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
trainer.rs
(&self, word_counts: &[Sentence]) -> HashSet<String> { word_counts .iter() .flat_map(|(s, _count)| s.chars()) .chain(self.initial_alphabet.iter().copied()) .map(|c| c.to_string()) .collect() } fn make_seed_sentence_pieces( &self, ...
required_chars
identifier_name
trainer.rs
self, sentences: &[Sentence], _progress: &Option<ProgressBar>, ) -> Vec<SentencePiece> { // Put all sentences in a string, separated by \0 let total: usize = sentences .iter() .map(|(s, _)| s.chars().count()) .sum::<usize>() + sentences...
f /= vsum; // normalizes by all sentence frequency. let logprob_sp = freq[id].ln() - logsum; // After removing the sentencepiece[i], its frequency freq[i] is // re-assigned to alternatives. // new_sum = current_sum - freq[i] + freq[i] * a...
{ // new_pieces.push((token.to_string(), *score)); continue; }
conditional_block
dense_matop.go
retVal.AP = transform retVal.old = t.AP.Clone() retVal.transposeWith = axes return } // Transpose() actually transposes the data. // This is a generalized version of the inplace matrix transposition algorithm from Wikipedia: // https://en.wikipedia.org/wiki/In-place_matrix_transposition func (t *Dense) Transpose(...
Concat
identifier_name
dense_matop.go
(t *Dense) SetMaskAtIndex(v bool, i int) error { if !t.IsMasked() { return nil } t.mask[i] = v return nil } // SetMaskAt sets the mask value at the given coordinate func (t *Dense) SetMaskAt(v bool, coords ...int) error { if !t.IsMasked() { return nil } if len(coords) != t.Dims() { return errors.Errorf(d...
return t.Concat(0, others...) }
random_line_split
dense_matop.go
t *Dense) SetMaskAtIndex(v bool, i int) error { if !t.IsMasked() { return nil } t.mask[i] = v return nil } // SetMaskAt sets the mask value at the given coordinate func (t *Dense) SetMaskAt(v bool, coords ...int) error { if !t.IsMasked() { return nil } if len(coords) != t.Dims() { return errors.Errorf(dim...
{ // check that everything is at least 2D if t.Dims() < 2 { return nil, errors.Errorf(atleastDims, 2) } for _, d := range others { if d.Dims() < 2 { return nil, errors.Errorf(atleastDims, 2) } } return t.Concat(0, others...) }
identifier_body
dense_matop.go
(coords) != t.Dims() { return nil, errors.Errorf(dimMismatch, t.Dims(), len(coords)) } at, err := t.at(coords...) if err != nil { return nil, errors.Wrap(err, "At()") } return t.Get(at), nil } // MaskAt returns the value of the mask at a given coordinate // returns false (valid) if not tensor is not masked ...
{ v.reshape(v.shape[0], 1) }
conditional_block
main.go
{ geometry.faces = append(geometry.faces, poly) } } else { poly := make(faceType, 0) for i := 0; i < len(geometry.vertices)/3; i++ { offset := i * 3 p := vertexType{geometry.vertices[offset+0], geometry.vertices[offset+1], geometry.vertices[offset+2]} ...
{ return fmt.Sprintf("<vertex(%f, %f, %f)>", p[0], p[1], p[2]) }
identifier_body
main.go
.GetY()*10)) } fmt.Println("</g></svg>") } type vertexType [3]float64 type edgeType [2]vertexType type faceType []vertexType func (a vertexType) Equals(b vertexType) bool { return number.FloatEquals(a[0], b[0]) && number.FloatEquals(a[1], b[1]) && number.FloatEquals(a[2], b[2]) } func (p vertexType) String() str...
{ fmt.Println(err) return mapcontainer.MapPolygon{} }
conditional_block
main.go
strings.Split(geometry.name, "\x00")[0] var children3 []marshChild json.Unmarshal(child2.Children, &children3) for _, child3 := range children3 { if child3.Name == "Vertices" { json.Unmarshal(child3.Properties[0].Value, &geometry.vertices) } if child3.Name == "PolygonVertexIn...
(polygon []vector.Vector2) { fmt.Println("<svg height='700' width='500'><g transform='translate(700,350)
debugPolygonSVG
identifier_name
main.go
strings.Split(geometry.name, "\x00")[0] var children3 []marshChild json.Unmarshal(child2.Children, &children3) for _, child3 := range children3 { if child3.Name == "Vertices" { json.Unmarshal(child3.Properties[0].Value, &geometry.vertices) }
if len(geometry.indices) > 0 { poly := make(faceType, 0) for _, geometryIndex := range geometry.indices { endPoly := false if geometryIndex < 0 { // https://www.scratchapixel.com/lessons/3d-basic-rendering/introduction-polygon-mesh/polygon-mesh-file-formats ...
if child3.Name == "PolygonVertexIndex" { json.Unmarshal(child3.Properties[0].Value, &geometry.indices)
random_line_split
symptoms.js
<li> {" "} Mantenha a cabeça elevada à noite, usando travesseiros extras ou levantando a cabeceira da cama com calços; </li> <li> Mantenha os ambientes bem ventilados;</li> <li> {" "} Aumente o teor de umidade do ar com umidifica...
<li>Doenças neurológicas;</li> <li>Medicamentos;</li> <li> Entre outras que levam a incapacidade do sangue carrear o oxigênio pelo corpo, como na anemia grave, sangramentos e doenças
random_line_split
symptoms.js
aumenta o volume de muco produzido pelos brônquios; causa irritação física e química das mucosas; destrói os cílios que cobrem o revestimento interno dos brônquios; facilita o acúmulo de material estranho às vias aéreas. Outras causas importantes são a sinusite, principalmente em crianç...
=> setModalShow(false)} /> </> ); } //quarta const Four = (props) => ( <Modal {...props} size="lg" aria-labelledby="contained-modal-title-vcenter" centered > <Modal.Header closeButton> <Modal.Title id="contained-modal-title-vcenter"
identifier_body
symptoms.js
ariamente pode levar à cefaleia tensional crônica. </p> </Modal.Body> <Modal.Footer> <Button onClick={props.onHide}>Close</Button> </Modal.Footer> </Modal> ); function AppCe() { const [modalShow, setModalShow] = React
tate(false); return ( <> <button onClick={() => setModalShow(true)} className="icons__symptoms"> Cefalea </button> <One show={modalShow} onHide={() => setModalShow(false)} /> </> ); } //segundo item de opção const Tow = (props) => ( <Modal {...props} size="lg" aria...
.useS
identifier_name
Data visualization_Trump Winning Rate.py
Define the date format date_form = DateFormatter("%m-%d") ax.xaxis.set_major_formatter(date_form) # Ensure a major tick for each week using (interval=1) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.legend() plt.show() # * Trump's winning rate has a declining trend and the winning rate gap betwe...
# * The correlation is the lowest in KY: Trump is more likely to win the national election if he lost in KY. # ## 4. Comovement between Trump's Winning Rate and Economic Indicators # In[21]: ei = pd.read_csv('economic_index.csv') ei['date'] = ei['modeldate'].apply(lambda x: datetime.datetime(int(x.split('/')[2]),in...
# * The correlation is the highest in PA, UT, CO: If Trump wins these three states, he is likely to win the national election.
random_line_split
Data visualization_Trump Winning Rate.py
the date format date_form = DateFormatter("%m-%d") ax.xaxis.set_major_formatter(date_form) # Ensure a major tick for each week using (interval=1) ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1)) plt.legend() plt.show() # * Trump's winning rate has a declining trend and the winning rate gap between Bide...
# * From the above graphs, we can see the Trump's winning rates by state and month # * The winning rates are particularly low in Northeast and West coast while higher in the middle states # ### 3.2 States with the Largest Uncertainties # In[15]: pst_cat = pst[['date','winstate_inc','code']] datevar = pst_cat['da...
pst_sub = pst_cat[pst_cat['date'] == date] fig = go.Figure(data=go.Choropleth( locations=pst_sub['code'], # Spatial coordinates z = pst_sub['winstate_inc'].astype(float), # Data to be color-coded locationmode = 'USA-states', # set of locations match entries in `locations` colorscale = 'Reds', co...
conditional_block
MLP.py
()) else: self.hidden_layer.neurons[h].weights.append(hidden_layer_weights[weight_num]) weight_num += 1 def init_weights_from_hidden_layer_neurons_to_output_layer_neurons(self, output_layer_weights): weight_num = 0 for o in range(len(self.output_l...
sh(self.calculate_total_net_input()) return self.output def calculate_total_net_input(self): # z=W(n)x+b total = 0 for i in range(len(self.inputs)): total += self.inputs[i]*self.weights[i] return total + self.bias # Use the sigmoid function as the activit...
s = inputs self.output = self.squa
identifier_body
MLP.py
()) else: self.hidden_layer.neurons[h].weights.append(hidden_layer_weights[weight_num]) weight_num += 1 def
(self, output_layer_weights): weight_num = 0 for o in range(len(self.output_layer.neurons)): for h in range(len(self.hidden_layer.neurons)): # hidden layer if not output_layer_weights: # if no output_layer_weight---randomly pick a value ...
init_weights_from_hidden_layer_neurons_to_output_layer_neurons
identifier_name
MLP.py
()) else: self.hidden_layer.neurons[h].weights.append(hidden_layer_weights[weight_num]) weight_num += 1 def init_weights_from_hidden_layer_neurons_to_output_layer_neurons(self, output_layer_weights): weight_num = 0 for o in range(len(self.output_l...
# Use the sigmoid function as the activition function, which is the definition of the sigmoid function. def squash(self, total_net_input): return 1/(1 + math.exp(-total_net_input)) # δ = ∂E/∂zⱼ = ∂E/∂yⱼ * dyⱼ/dzⱼ 关键key def calculate_pd_error_wrt_total_net_input(self, target_output): ...
return total + self.bias
random_line_split
MLP.py
else: self.hidden_layer.neurons[h].weights.append(hidden_layer_weights[weight_num]) weight_num += 1 def init_weights_from_hidden_layer_neurons_to_output_layer_neurons(self, output_layer_weights): weight_num = 0 for o in range(len(self.output_layer...
o in range(len(self.output_layer.neurons)): for w_ho in range(len(self.output_layer.neurons[o].weights)): # ∂Eⱼ/∂wᵢⱼ = ∂E/∂zⱼ * ∂zⱼ/∂wᵢⱼ pd_error_wrt_weight = pd_errors_wrt_output_neuron_total_net_input[o]*self.output_layer.neurons[ o].calculate_pd_total_...
for o in range(len(self.output_layer.neurons)): d_error_wrt_hidden_neuron_output += pd_errors_wrt_output_neuron_total_net_input[o]* \ self.output_layer.neurons[o].weights[h] # ∂E/∂zⱼ = dE/dyⱼ * ∂zⱼ/∂ pd_errors_wrt_hidden...
conditional_block
propose-vote-enact-market.py
_url = helpers.check_wallet_url(wallet_server_url) ############################################################################### # W A L L E T S E R V I C E # ############################################################################### print(f"Logging into wallet...
# https://docs.testnet.vega.xyz/docs/api-howtos/create-market/ # __prepare_propose_market: # Compose a governance proposal for a new market proposal_ref = f"{pubkey}-{uuid.uuid4()}" # Set closing/enactment and validation timestamps to valid time offsets # from the current Vega blockchain time closing_time = blockchai...
random_line_split
propose-vote-enact-market.py
_url = helpers.check_wallet_url(wallet_server_url) ############################################################################### # W A L L E T S E R V I C E # ############################################################################### print(f"Logging into wallet...
assert proposal_id != "" ############################################################################### # V O T E O N M A R K E T # ############################################################################### # STEP 2 - Let's vote on the market proposal # IMP...
if n["proposal"]["reference"] == proposal_ref: proposal_id = n["proposal"]["id"] print() print("Your proposal has been accepted by the network") print(n) done = True break
conditional_block
integration.py
', default=str(int(today[0])), help='end year to crawl from') parser.add_argument('-sm', '--START_MONTH', default=today[1], help='start month to crawl from') parser.add_argument('-em', '--END_MONTH', default=str(int(today[1])), help='end month to crawl from') parser.add_argument('-sd', '--START_DAY', default...
(): tags = [] url_root = 'https://medium.com/tag/' url_xpath = '//div[@class=\'postArticle-readMore\']/a' with open('./top_tags_by_blogs_with_linked_papers.json') as f: content = json.load(f) # crawl top 100 tags top_tags = collections.OrderedDict(sorted(content.items(), key=lambda x: x[1], reverse=True)).ke...
crawl_medium
identifier_name
integration.py
for day in range(START_DAY, END_DAY + 1): day_str = convert_number_to_str(day) # check if the day exists path = url_root + '/archive/' + year_str + '/' + month_str + '/' + day_str if check_redirect(path): continue crawl_by_day(url_root + '/archive/', url_xpath, year_str, month_...
r = Rake() # Uses stopwords for english from NLTK, and all puntuation characters. r.extract_keywords_from_text(text) return r.get_ranked_phrases() # To get keyword phrases ranked highest to lowest.
identifier_body
integration.py
', '--START_MONTH', default=today[1], help='start month to crawl from') parser.add_argument('-em', '--END_MONTH', default=str(int(today[1])), help='end month to crawl from') parser.add_argument('-sd', '--START_DAY', default=today[2], help='start day to crawl from') parser.add_argument('-ed', '--END_DAY', def...
arxiv_id = arxiv_id[:len(arxiv_id) - 1]
conditional_block
integration.py
prefs = {'profile.managed_default_content_settings.images':2} chrome_options.add_experimental_option("prefs", prefs) def main(): parser = ArgumentParser() #default is crawl daily blogs today = str(date.today()).split('-') parser.add_argument('-sy', '--START_YEAR', default=today[0], help='start year to crawl fro...
chrome_options.add_argument("--headless") chrome_options.add_argument('--disable-extensions') chrome_options.add_argument('--disable-gpu') chrome_options.add_argument('--no-sandbox')
random_line_split
window.py
) un boton con etiqueta "examinar" en el dialogo self.file_chooser_button = gtk.Button("Examinar") self.file_chooser_button.connect("clicked",self.open_file) self.hBox_botones.pack_end(self.file_chooser_button,gtk.FALSE,gtk.FALSE,0) # meter boton en hbox # crear un buffer para el TextView (text_area) self....
\t"+i.get_machinecode(self.tabop)+"\t\t"+line[j]+"\n") if i.get_label()!=None: self.tb
conditional_block
window.py
# insertar items al item "archivo" self.menu = gtk.Menu() self.menu_item = gtk.MenuItem("Abrir _archivo...") self.menu.append(self.menu_item) self.menu_item.connect("activate",self.open_file) self.menu_item_file.set_submenu(self.menu) self.menu_item = gtk.MenuItem("_Guardar") self.menu.append(self....
__init__(self,title,type=gtk.WINDOW_TOPLEVEL): # crear, fijar titulo, fijar tamaño y conectar señal de la ventana self.window = gtk.Window(type) # atributo window recibe objeto ventana del tipo 'type' self.window.set_title(title) # se fija titulo recibido en el constructor self.window.set_default_size(400,3...
identifier_body
window.py
") self.menu.append(self.menu_item) self.menu_item.connect("activate",self.save_file) self.menu_item = gtk.MenuItem("_Cerrar") self.menu.append(self.menu_item) self.menu_item.connect("activate",self.close) self.menu_separator = gtk.SeparatorMenuItem() # crear un separador para un menu self.menu.append...
=None): # se crean los iteradores para marcar el inicio y final del buffer, para guardar el archivo file_start = self.text_buffer.get_start_iter() file_end = self.text_buffer.get_end_iter() try: self.file = open(self.namefile,'w+') self.file.write(self.text_buffer.get_text(file_start,file_end)) ...
dget,data
identifier_name
window.py
Guardar") self.menu.append(self.menu_item) self.menu_item.connect("activate",self.save_file) self.menu_item = gtk.MenuItem("_Cerrar") self.menu.append(self.menu_item) self.menu_item.connect("activate",self.close) self.menu_separator = gtk.SeparatorMenuItem() # crear un separador para un menu self.menu...
file_end = self.text_buffer.get_end_iter() cont = self.text_buffer.get_text(file_start,file_end) if self.text_buffer.get_modified(): message = "El Archivo ha sido modificado\n¿Desea guardar cambios?" result_dialog = gtk.MessageDialog(self.window, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT, ...
def close(self,widget,data=None): # método llamado desde el menu "archivo -> cerrar" print "Ctrl + W" file_start = self.text_buffer.get_start_iter()
random_line_split
manager.rs
send but are only used internally. impl<A, L> Manager<A, L> where A: Asset<L>, L: Loader, { /// Construct a new, empty `Manager`. /// /// The function does not allocate and the returned Managers main storage will have no /// capacity until `insert` is called. pub(crate) fn new( loa...
} } pub fn strong_count<P: AsRef<Path>>(&mut self, path: P) -> Option<usize> { Some(Arc::strong_count( self.asset_handles.get(path.as_ref())?.get()?,
random_line_split
manager.rs
(optional default:off). pub struct
<A, L> where A: Asset<L>, L: Loader, { drop: bool, unload: bool, loader_id: usize, load_send: Sender<(usize, PathBuf, L::TransferSupplement)>, load_recv: Receiver<(PathBuf, <L::Source as Source>::Output)>, asset_handles: HashMap<PathBuf, AssetHandle<A, L>>, loaded_once: Vec<PathBuf>,...
Manager
identifier_name
manager.rs
(optional default:off). pub struct Manager<A, L> where A: Asset<L>, L: Loader, { drop: bool, unload: bool, loader_id: usize, load_send: Sender<(usize, PathBuf, L::TransferSupplement)>, load_recv: Receiver<(PathBuf, <L::Source as Source>::Output)>, asset_handles: HashMap<PathBuf, AssetHan...
else { a.status = LoadStatus::Loading; let package = (self.loader_id, path.as_ref().into(), supp); self .load_send .send(package) .map_err(|e| std::io::Error::new( ErrorKind::ConnectionReset, for...
{ Err(std::io::Error::new( ErrorKind::AlreadyExists, format!("Image already loading! {:?}", path.as_ref()), )) }
conditional_block
manager.rs
usize, PathBuf, L::TransferSupplement)>, load_recv: Receiver<(PathBuf, <L::Source as Source>::Output)>, data: A::ManagerSupplement, ) -> Self { Self { drop: false, unload: false, loader_id, load_send, load_recv, asset_ha...
{ self.asset_handles .iter() .next() .map(|(_, a)| a.get().map(|a| a.clone())) }
identifier_body
api_op_StartJobRun.go
class. // The standard execution-class is ideal for time-sensitive workloads that require // fast job startup and dedicated resources. The flexible execution class is // appropriate for time-insensitive jobs whose start and completion times may vary. // Only jobs with Glue version 3.0 and above and command type gl...
newServiceMetadataMiddleware_opStartJobRun
identifier_name
api_op_StartJobRun.go
your own Job arguments, see the // Calling Glue APIs in Python (https://docs.aws.amazon.com/glue/latest/dg/aws-glue-programming-python-calling.html) // topic in the developer guide. For information about the arguments you can // provide to this field when configuring Spark jobs, see the Special Parameters // Used ...
if err = awsmiddleware.AddRawResponseToMetadata(stack); err != nil { return err } if err = awsmiddleware.AddRecordResponseTiming(stack); err != nil { return err } if err = addClientUserAgent(stack, options); err != nil { return err } if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != n...
{ return err }
conditional_block
api_op_StartJobRun.go
3.0 and above and command type glueetl will be // allowed to set ExecutionClass to FLEX . The flexible execution class is // available for Spark jobs. ExecutionClass types.ExecutionClass // The ID of a previous JobRun to retry. JobRunId *string // For Glue version 1.0 or earlier jobs, using the standard worker ...
{ return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "glue", OperationName: "StartJobRun", } }
identifier_body
api_op_StartJobRun.go
"fmt" "github.com/aws/aws-sdk-go-v2/aws" awsmiddleware "github.com/aws/aws-sdk-go-v2/aws/middleware" "github.com/aws/aws-sdk-go-v2/aws/signer/v4" internalauth "github.com/aws/aws-sdk-go-v2/internal/auth" "github.com/aws/aws-sdk-go-v2/service/glue/types" smithyendpoints "github.com/aws/smithy-go/endpoints" "gith...
"errors"
random_line_split
metadata.rs
[`SerializedPackage`]( * https://github.com/rust-lang/cargo/blob/0.40.0/src/cargo/core/package.rs#L32-L50) */ #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] pub struct Package { pub name: String, pub version: String, pub id: PackageId, pub license: Option<String>, pub license_file: Option<S...
source: serde_json::to_string(&dependency.source_id()).unwrap(), req: dependency.version_req().to_string(), kind: match dependency.kind() { CargoKind::Normal => None, CargoKind::Development => Some("dev".to_owned()), CargoKind::Build => Some(...
name: dependency.package_name().to_string(), // UNWRAP: It's cargo's responsibility to ensure a serializable source_id
random_line_split
metadata.rs
}; let ws = Workspace::new(&manifest, &self.cargo_config)?; let specs = Packages::All.to_package_id_specs(&ws)?; let root_name = specs.iter().next().unwrap().name(); let resolve_opts = ResolveOpts::new(true, &[], false, false); let (resolved_packages, cargo_resolve) = ops::resolve_ws_with_opts(...
{ let dir = TempDir::new("test_cargo_raze_metadata_dir").unwrap(); let toml_path = { let path = dir.path().join("Cargo.toml"); let mut toml = File::create(&path).unwrap(); toml.write_all(b"hello").unwrap(); path }; let files = CargoWorkspaceFiles { lock_path_opt: None, ...
identifier_body
metadata.rs
_name().unwrap()); fs::copy(lock_path, new_lock_path)?; } dir }; // Shell out to cargo let exec_output = Command::new("cargo") .current_dir(cargo_tempdir.path()) .args(&["metadata", "--format-version", "1"]) .output()?; // Handle command errs let stdout_str =...
test_cargo_subcommand_metadata_fetcher_works_with_lock
identifier_name
socks5.go
} auth.Ver = b[0] nmethods := b[1] if auth.Ver != 5 { return fmt.Errorf("ver %v is incorrect", auth.Ver) } b = buf[:uint8(nmethods)] if _, err := io.ReadFull(r, b); err != nil { return fmt.Errorf("failed to read socks5 auth methods, %v", err) } methods := make([]Socks5AuthMethodType, len(b)) for i := r...
return nil } func WriteAuth(w io.Writer, auth *Socks5AuthPack) error { if auth == nil { return fmt.Errorf("auth is nil") } return auth.Write(w) } func ReadSocks5AuthR(r io.Reader) (*Socks5AuthRPack, error) { ar := Socks5AuthRPack{} err := ar.Read(r) if err != nil { return nil, err } return &ar, err } f...
if _, err := w.Write(buf); err != nil { return fmt.Errorf("w.write,%v", err) }
random_line_split
socks5.go
} auth.Ver = b[0] nmethods := b[1] if auth.Ver != 5 { return fmt.Errorf("ver %v is incorrect", auth.Ver) } b = buf[:uint8(nmethods)] if _, err := io.ReadFull(r, b); err != nil { return fmt.Errorf("failed to read socks5 auth methods, %v", err) } methods := make([]Socks5AuthMethodType, len(b)) for i := ra...
er) (*Socks5AuthRPack, error) { ar := Socks5AuthRPack{} err := ar.Read(r) if err != nil { return nil, err } return &ar, err } func (ar *Socks5AuthRPack) Read(r io.Reader) error { buf := mempool.Get(1024) defer mempool.Put(buf) buf = buf[:2] if _, err := io.ReadFull(r, buf); err != nil { return err } a...
io.Read
identifier_name
socks5.go
Socks5CmdType(buf[1]) cmd.Rsv = buf[2] cmd.Atyp = Socks5AtypType(buf[3]) if cmd.Ver != 5 { return fmt.Errorf("unexpected protocol version %v ", cmd.Ver) } /* 这个不应该由这里判断。 if cmd.Cmd != 0x01 && cmd.Cmd != 0x02 && cmd.Cmd != 0x03 { return nil, fmt.Errorf("未知的命令,cmd:%v。", cmd.Cmd) }*/ /*if cmd.atyp ==...
f) buf = buf[:2] if _, err := io.ReadFull(r, buf); err != nil { return err } pr.Ver = buf[0] pr.Status = Socks5AuthPasswordRStatusType(buf[1]) if pr.Ver != 1 { return fmt.Errorf("unexpected protocol version %v", pr.Ver) } return nil } func WriteSocks5AuthPasswordR(w io.Writer, r *Socks5AuthPasswordRPack...
identifier_body
socks5.go
} auth.Ver = b[0] nmethods := b[1] if auth.Ver != 5 { return fmt.Errorf("ver %v is incorrect", auth.Ver) } b = buf[:uint8(nmethods)] if _, err := io.ReadFull(r, b); err != nil { return fmt.Errorf("failed to read socks5 auth methods, %v", err) } methods := make([]Socks5AuthMethodType, len(b)) for i := ra...
..) default: return fmt.Errorf("unknown atyp %v type", cmd.Atyp) } buf = append(buf, port[0], port[1]) if _, err := w.Write(buf); err != nil { return fmt.Errorf("w.write, %v", err) } return nil } func ReadSocks5Cmd(r io.Reader) (*Socks5CmdPack, error) { cmd := Socks5CmdPack{} err := cmd.Read(r) if err !...
buf = append(buf, []byte(cmd.Host).
conditional_block
base_redash_preview_client.py
= 2 # (executing) SUCCESS = 3 FAILURE = 4 CANCELLED = 5 class BaseRedashPreviewClient(BasePreviewClient): """ Generic client for using Redash as a preview client backend. Redash does not allow arbitrary queries to be submitted but it does allow the creation of templated queries that can...
query_result_id = self._wait_for_query_finish(job_id=query_results['job']['id']) query_results = self._get_query_results(query_result_id=query_result_id)
conditional_block
base_redash_preview_client.py
= '{redash_host}/api/queries/{query_id}/results' REDASH_TRACK_JOB_ENDPOINT = '{redash_host}/api/jobs/{job_id}' REDASH_QUERY_RESULTS_ENDPOINT = '{redash_host}/api/query_results/{query_result_id}' class RedashApiKeyNotProvidedException(Exception): pass class RedashQueryCouldNotCompleteException(Exception): p...
(Enum): PENDING = 1 # (waiting to be executed) STARTED = 2 # (executing) SUCCESS = 3 FAILURE = 4 CANCELLED = 5 class BaseRedashPreviewClient(BasePreviewClient): """ Generic client for using Redash as a preview client backend. Redash does not allow arbitrary queries to be submitted b...
RedashApiResponse
identifier_name
base_redash_preview_client.py
= '{redash_host}/api/queries/{query_id}/results' REDASH_TRACK_JOB_ENDPOINT = '{redash_host}/api/jobs/{job_id}' REDASH_QUERY_RESULTS_ENDPOINT = '{redash_host}/api/query_results/{query_result_id}' class RedashApiKeyNotProvidedException(Exception): pass class RedashQueryCouldNotCompleteException(Exception): p...
def __init__(self, redash_host: str, user_api_key: Optional[str] = None) -> None: self.redash_host = redash_host self.user_api_key: Optional[str] = user_api_key self.headers: Optional[Dict] = None self.default_query_limit = 50 self.max_redash_cache_age = 86400 # One day ...
The template values in the Redash query will be filled by the `build_redash_query_params` function. """
random_line_split
base_redash_preview_client.py
= '{redash_host}/api/queries/{query_id}/results' REDASH_TRACK_JOB_ENDPOINT = '{redash_host}/api/jobs/{job_id}' REDASH_QUERY_RESULTS_ENDPOINT = '{redash_host}/api/query_results/{query_result_id}' class RedashApiKeyNotProvidedException(Exception): pass class RedashQueryCouldNotCompleteException(Exception): p...
LOGGER.debug('Response from redash query: %s', resp_json) # When submitting a query, Redash can return 2 distinct payloads. One if the # query result has been cached by Redash and one if the query was submitted # to be executed. The 'job' object is returned if the query is not cached. ...
""" Starts a query in Redash. Returns a job ID that can be used to poll for the job status. :param query_id: The ID of the query in the Redash system. This can be retrieved by viewing the URL for your query template in the Redash GUI. :param query_params: A dicti...
identifier_body
p-register-xsell-from-chat.js
OnValidatedUserInput(input, isValid, toNextStep); }, function() { var input = elements.passwordContainer.find('input'); function isValid() { return !elements.passwordContainer.is('.error') && input.is('.set') && Number(elements.passwordContainer.find('label.error').css('...
else { /* Just in case validation hasn't happened yet or the input was never focused on by the user at all (eg auto-populated by browser), force trigger validation. `isValid` is expected to return false when validation hasn't happened yet. */ input.trigger('blur'); di...
{ nextAction(); }
conditional_block
p-register-xsell-from-chat.js
OnValidatedUserInput(input, isValid, toNextStep); }, function() { var input = elements.passwordContainer.find('input'); function isValid()
triggerNextActionOnValidatedUserInput(input, isValid, createAccount); } ]; function swapNextButtonHandler() { ++currentStep; elements.nextButton .off('click') .on('click', nextButtonHandlers[currentStep]); } function triggerNextActionOnValidatedUserInput(input, isValid, nextAct...
{ return !elements.passwordContainer.is('.error') && input.is('.set') && Number(elements.passwordContainer.find('label.error').css('opacity')) === 0; }
identifier_body
p-register-xsell-from-chat.js
OnValidatedUserInput(input, isValid, toNextStep); }, function() { var input = elements.passwordContainer.find('input'); function isValid() { return !elements.passwordContainer.is('.error') &&
triggerNextActionOnValidatedUserInput(input, isValid, createAccount); } ]; function swapNextButtonHandler() { ++currentStep; elements.nextButton .off('click') .on('click', nextButtonHandlers[currentStep]); } function triggerNextActionOnValidatedUserInput(input, isValid, nextActi...
input.is('.set') && Number(elements.passwordContainer.find('label.error').css('opacity')) === 0; }
random_line_split
p-register-xsell-from-chat.js
OnValidatedUserInput(input, isValid, toNextStep); }, function() { var input = elements.passwordContainer.find('input'); function
() { return !elements.passwordContainer.is('.error') && input.is('.set') && Number(elements.passwordContainer.find('label.error').css('opacity')) === 0; } triggerNextActionOnValidatedUserInput(input, isValid, createAccount); } ]; function swapNextButtonHandler() { +...
isValid
identifier_name
full_heap.go
Cost int64 } const Inf = 1e18 type Graph struct { Size int edges map[GNode][]IntPair } func (g *Graph) AddEdge(e Edge) { if g.Size == 0 || g.edges == nil { g.init() } if g.edges[e.From] == nil { g.edges[e.From] = make([]IntPair, 0) } if g.edges[e.To] == nil { g.edges[e.To] = make([]IntPair, 0) } g....
else { newNode := &Node{x, nil, nil, f.min, f.min.right, 0, false} //Create a new node f.min.right.left = newNode f.min.right = newNode f.updateMin(newNode) f.nodes[x] = newNode } f.size++ } //ExtractMin deletes the minimum value of the heap and returns it //If heap is empty there comes an error //Impleme...
{ f.init() f.min.key = x f.min.left, f.min.right = f.min, f.min f.nodes[x] = f.min }
conditional_block
full_heap.go
Cost int64 } const Inf = 1e18 type Graph struct { Size int edges map[GNode][]IntPair } func (g *Graph) AddEdge(e Edge) { if g.Size == 0 || g.edges == nil { g.init() } if g.edges[e.From] == nil { g.edges[e.From] = make([]IntPair, 0) } if g.edges[e.To] == nil { g.edges[e.To] = make([]IntPair, 0) } g....
() (Value, error) { if f.IsEmpty() { return nil, errors.New("unable to get minimum from an empty heap") } res := f.min.key delete(f.nodes, f.min.key) if f.GetSize() == 1 { //If it was the only node return f.min = nil f.size = 0 return res, nil } f.cutChildren(f.min, f.min.child) f.min.left.right = f.min...
ExtractMin
identifier_name
full_heap.go
//and hashmap (value, pointer to node with that value) //THAT MEANS TO USE DECREASE CORRECTLY YOU NEED UNIQUE ENTIES //It could be done with some sort of hashes in your structure type FibonacciHeap struct { min *Node size int nodes map[Value]*Node } //Decrease method accepts old and new value and changes that in...
{ return f.size == 0 }
identifier_body
full_heap.go
of child ren marked bool //If we already cut this node's child } //FibonacciHeap is represented with pointer to minimum, size //and hashmap (value, pointer to node with that value) //THAT MEANS TO USE DECREASE CORRECTLY YOU NEED UNIQUE ENTIES //It could be done with some sort of hashes in your structure type Fibonac...
//GetSize returns current size of the heap (number of nodes) func (f *FibonacciHeap) GetSize() int { return f.size }
random_line_split
non_copy_const.rs
ParamEnv` where every generic params and assoc types are `Freeze`is another option; // but I'm not sure whether it's a decent way, if possible. cx.tcx.layout_of(cx.param_env.and(ty)).is_ok() && !ty.is_freeze(cx.tcx.at(DUMMY_SP), cx.param_env) } fn is_value_unfrozen_raw<'tcx>( cx: &LateContext<'tcx>, re...
{ if let ImplItemKind::Const(hir_ty, body_id) = &impl_item.kind { let item_hir_id = cx.tcx.hir().get_parent_node(impl_item.hir_id()); let item = cx.tcx.hir().expect_item(item_hir_id); match &item.kind { ItemKind::Impl(Impl { of_trait: Some...
identifier_body
non_copy_const.rs
'static Lint, &'static str, Span) { match self { Self::Item { item } | Self::Assoc { item, .. } => ( DECLARE_INTERIOR_MUTABLE_CONST, "a `const` item should never be interior mutable", *item, ), Self::Expr { expr } => ( ...
{ cx.typeck_results().expr_ty(dereferenced_expr) }
conditional_block
non_copy_const.rs
/// static STATIC_ATOM: AtomicUsize = AtomicUsize::new(15); /// STATIC_ATOM.store(9, SeqCst); /// assert_eq!(STATIC_ATOM.load(SeqCst), 9); // use a `static` item to refer to the same instance /// ``` #[clippy::version = "pre 1.29.0"] pub DECLARE_INTERIOR_MUTABLE_CONST, style, "declaring `co...
<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { // Ignore types whose layout is unknown since `is_freeze` reports every generic types as `!Freeze`, // making it indistinguishable from `UnsafeCell`. i.e. it isn't a tool to prove a type is // 'unfrozen'. However, this code causes a false negative in wh...
is_unfrozen
identifier_name
non_copy_const.rs
/// /// The `const` should better be replaced by a `static` item if a global /// variable is wanted, or replaced by a `const fn` if a constructor is wanted. /// /// ### Known problems /// A "non-constant" const item is a legacy way to supply an /// initialized value to downstream `static` it...
/// Consts are copied everywhere they are referenced, i.e., /// every time you refer to the const a fresh instance of the `Cell` or `Mutex` /// or `AtomicXxxx` will be created, which defeats the whole purpose of using /// these types in the first place.
random_line_split
lib.rs
888888K. 888 8888888 "Y888b. 8888888P" 888 888 d88P 888 888 d88P 888 888 "Y88b 888 888 "Y88b. 888 T88b 888888 888 888 d88P 888 888 d88P 888 888 888 888 888 "888 888 T88b 888 .d88P d8888888888 888 d8888888888 888 d88P 888...
} } } } #[allow(non_snake_case)] #[derive(Debug, Clone)] pub struct DataTableQuery { pub draw: i32, /* Stands for the n-th time that we're drawing */ pub columns: Vec<( Option<i32>, Option<String>, Option<bool>, Option<bool>, Option<String>, ...
random_line_split
lib.rs
888888K. 888 8888888 "Y888b. 8888888P" 888 888 d88P 888 888 d88P 888 888 "Y88b 888 888 "Y88b. 888 T88b 888888 888 888 d88P 888 888 d88P 888 888 888 888 888 "888 888 T88b 888 .d88P d8888888888 888 d8888888888 888 d88P 888...
"start" if start.is_none() => { let decoded = item.value.url_decode().map_err(|_| ())?; start = Some(match decoded.parse::<i32>() { Ok(item_val) => item_val, Err(_err_msg) => 0, }); ...
{ let decoded = item.value.url_decode().map_err(|_| ())?; draw = Some(match decoded.parse::<i32>() { Ok(item_val) => item_val, Err(_err_msg) => 0, }); }
conditional_block
lib.rs
888888K. 888 8888888 "Y888b. 8888888P" 888 888 d88P 888 888 d88P 888 888 "Y88b 888 888 "Y88b. 888 T88b 888888 888 888 d88P 888 888 d88P 888 888 888 888 888 "888 888 T88b 888 .d88P d8888888888 888 d8888888888 888 d88P 888...
) }) .collect::<String>(); self.query = Some( format!("{} {}", self.query.to_owned().unwrap(), stmt.to_owned()).to_owned(), ); self.to_owned() } None => self.to_...
{ /* # How this works? ## We will match the existing needing of appending the "join statement" or not As well we do on other self sql generators functions, we'll opt to not do an if stmt for seeking the "last" target and doing a exactly cut for the string to append. ...
identifier_body
lib.rs
888888K. 888 8888888 "Y888b. 8888888P" 888 888 d88P 888 888 d88P 888 888 "Y88b 888 888 "Y88b. 888 T88b 888888 888 888 d88P 888 888 d88P 888 888 888 888 888 "888 888 T88b 888 .d88P d8888888888 888 d8888888888 888 d88P 888...
<'a> { pub origin: (&'a str, &'a str), /* From */ pub fields: Vec<&'a str>, /* Fields to seek for */ pub join_targets: Option<Vec<(&'a str, (&'a str, &'a str), (&'a str, &'a str))>>, /* Join Targets explained over here */ pub datatables_post_query: DataTableQuery, /* Incoming Query */ pub quer...
Tables
identifier_name
plot_3d.py
.0): lamb_str='0' else: lamb_str='%.2e'%(lamb) a=lamb_str.split('e') power=a[1] lamb_str=a[0] if (power[0]=='-'): sign='-' else: sign='' power=power[1:] if (power[0]=='0'): power=power[1:] ...
get_pow_str
identifier_name
plot_3d.py
z0 = FrankeFunction(x, y) if (verbosity>0): print('') print('#############################################') print('') if (not (var_check and diff_noise)): if (sigma>0.0): noise=np.random.normal(0.0,sigma,size=(n,n)) z=z0+noise else: ...
x = np.arange(0, 1.0001, 1.0/(n-1)) y = np.arange(0, 1.0001, 1.0/(n-1)) x, y = np.meshgrid(x,y)
random_line_split
plot_3d.py
betak*1.0 bvs[:,i*k:(i+1)*k]=bv*1.0 bv_sum+=np.mean(bv,axis=1) #get the mean of the estimated var beta_mean=np.mean(betas,axis=1) bv_mean=bv_sum/m be_std=np.sqrt(bv_mean) for i in range(m*k): for j in range(n_p): bv_calc[j]+=(betas[...
elif (model=='ols'): if (plt_title): plt.title(r'OLS, $p=$ %i'%(deg)) filename='ols' if (noise): filename+='_noise' if (colbar): filename+='_cbar' filename+='_p%i'%(deg)+fig_format elif (model=='ridge'): if (plt_title): ...
if (plt_title): plt.title('Franke function') filename='franke_function' if (noise): filename+='_noise' if (colbar): filename+='_cbar' filename+=fig_format
conditional_block
plot_3d.py
xv,yv,fv=init_xy_vectors(n,rand,rearr=True,x=x,y=y,z=z) if (var_check): #check the variance terms of beta vs. the equation from lecture notes # Var[beta_j]=sigma^2 * ((X.T@X)^-1)_jj if (verbosity>0): print('Variance check, lambda %.2e'%lamb[0]) if (di...
n2=n**2 np.random.seed(seed) x = np.arange(0, 1.0001, 1.0/(n-1)) y = np.arange(0, 1.0001, 1.0/(n-1)) x, y = np.meshgrid(x,y) z0 = FrankeFunction(x, y) if (verbosity>0): print('') print('#############################################') print('') if (not (var...
identifier_body
daemon.go
select { case fch <- struct{}{}: default: glg.Warn("failure queue already full") } } case <-ticker.C: if err := p.Update(ctx); err != nil { ech <- errors.Wrap(err, "error update policy") select { case fch <- struct{}{}: default: glg.Warn("failure queue alr...
{ asss = append(r.([]*Assertion), a) }
conditional_block
daemon.go
make(chan struct{}, 1) if err := p.Update(ctx); err != nil { glg.Debugf("Error initialize policy data, err: %v", err) ech <- errors.Wrap(err, "error update policy") fch <- struct{}{} } go func() { defer close(fch) defer close(ech) p.etagCache.StartExpired(ctx, p.etagFlushDur) ticker := time.NewTicke...
{ eg := errgroup.Group{} assm := new(sync.Map) // assertion map // simplify signed policy cache for _, policy := range sp.DomainSignedPolicyData.SignedPolicyData.PolicyData.Policies { pol := policy eg.Go(func() error { for _, ass := range pol.Assertions { select { case <-ctx.Done(): return ctx....
identifier_body
daemon.go
) error CheckPolicy(ctx context.Context, domain string, roles []string, action, resource string) error GetPolicyCache(context.Context) map[string]interface{} } type policyd struct { expireMargin time.Duration // expire margin force update policy when the policy expire time hit the margin rolePolicies ...
(ctx context.Context, g gache.Gache, dom string) error { spd, upd, err := p.fetchPolicy(ctx, dom) if err != nil { glg.Debugf("fetch policy failed, err: %v", err) return errors.Wrap(err, "error fetch policy") } glg.DebugFunc(func() string { rawpol, _ := json.Marshal(spd) return fmt.Sprintf("fetched policy d...
fetchAndCachePolicy
identifier_name
daemon.go
.Context) error CheckPolicy(ctx context.Context, domain string, roles []string, action, resource string) error GetPolicyCache(context.Context) map[string]interface{} } type policyd struct { expireMargin time.Duration // expire margin force update policy when the policy expire time hit the margin rolePolic...
// www.athenz.com/zts/v1 athenzURL string athenzDomains []string client *http.Client } type etagCache struct { eTag string sp *SignedPolicy } // New represent the constructor of Policyd func New(opts ...Option) (Daemon, error) { p := &policyd{ rolePolicies: gache.New(), etagCache: gache.New(), }...
etagFlushDur time.Duration etagExpTime time.Duration
random_line_split
_debug_alg.py
-emphasise the prediction model for the unknown nodes. prediction_model_emphasis = 1.0 # read METIS file G = shared.read_metis(DATA_FILENAME) # Alpha value used in prediction model prediction_model_alpha = G.number_of_edges() * (num_partitions / G.number_of_nodes()**2) # Order of nodes arriving arrival_order = list(...
# preserve original node/edge weight if graph_modification_functions: node_weights = {n[0]: n[1]['
for edge in G.edges_iter(data=True): left = edge[0] right = edge[1] edge_weight = edge[2]['weight_orig'] # new edge weight edge[2]['weight'] = (float(G.node[left]['weight']) * edge_weight) * (float(G.node[right]['weight']) * edge_weight) if left in nodes_arrived or righ...
identifier_body
_debug_alg.py
de-emphasise the prediction model for the unknown nodes. prediction_model_emphasis = 1.0 # read METIS file G = shared.read_metis(DATA_FILENAME) # Alpha value used in prediction model prediction_model_alpha = G.number_of_edges() * (num_partitions / G.number_of_nodes()**2) # Order of nodes arriving arrival_order = li...
fennelModel = {} fennelModel['assignments'] = np.repeat(np.int32(UNMAPPED), G.number_of_nodes()) fennelModel['fixed'] = np.repeat(np.int32(UNMAPPED), G.number_of_nodes()) predictionModels[config.Partitioners.FENNEL] = fennelModel scotchModel = {} scotchModel['assignments'] = np.repeat(np.int32...
random_line_split
_debug_alg.py
-emphasise the prediction model for the unknown nodes. prediction_model_emphasis = 1.0 # read METIS file G = shared.read_metis(DATA_FILENAME) # Alpha value used in prediction model prediction_model_alpha = G.number_of_edges() * (num_partitions / G.number_of_nodes()**2) # Order of nodes arriving arrival_order = list(...
def edge_expansion(G): # Update edge weights for nodes that have an assigned probability of displacement for edge in G.edges_iter(data=True): left = edge[0] right = edge[1] edge_weight = edge[2]['weight_orig'] # new edge weight edge[2]['weight'] = (float(G.node[left]['...
print("Assigning in batches of {}".format(restream_batches)) print("--------------------------------\n")
conditional_block
_debug_alg.py
-emphasise the prediction model for the unknown nodes. prediction_model_emphasis = 1.0 # read METIS file G = shared.read_metis(DATA_FILENAME) # Alpha value used in prediction model prediction_model_alpha = G.number_of_edges() * (num_partitions / G.number_of_nodes()**2) # Order of nodes arriving arrival_order = list(...
(G): # Update edge weights for nodes that have an assigned probability of displacement for edge in G.edges_iter(data=True): left = edge[0] right = edge[1] edge_weight = edge[2]['weight_orig'] # new edge weight edge[2]['weight'] = (float(G.node[left]['weight']) * edge_wei...
edge_expansion
identifier_name
main.rs
crate failure; const CONFIG_FILE_OPT: &str = "config"; const CONFIG_DIR_OPT: &str = "conf-dir"; const CONFIG_FILE_EXT: &str = "toml"; const DEFAULT_CONFIG_FILE: &str = "example_config.toml"; fn build_app() -> App<'static> { App::new("alis-bot-rs") .version("1.0") .about("alis-unofficial IRC bot")...
async fn run_instance(config: &PathBuf) -> irc::error::Result<()> { let config = Config::load(&config)?; let mut client = Client::from_config(config.clone()).await?; client.identify()?; let mut stream = client.stream()?; if let Some(server) = config.server { info!("Connected to {}", server...
{ let path = match config_file_is_valid(PathBuf::from(DEFAULT_CONFIG_FILE)) { Ok(p) => p, Err(e) => return Err(e), }; info!( "Using default configuration file: {}", path.as_path().display().to_string() ); Ok(vec![path]) }
identifier_body
main.rs
crate failure; const CONFIG_FILE_OPT: &str = "config"; const CONFIG_DIR_OPT: &str = "conf-dir"; const CONFIG_FILE_EXT: &str = "toml"; const DEFAULT_CONFIG_FILE: &str = "example_config.toml"; fn build_app() -> App<'static> { App::new("alis-bot-rs") .version("1.0") .about("alis-unofficial IRC bot")...
Ok(paths) } fn config_file_is_valid(path: PathBuf) -> Result<PathBuf, Error> { let error; if let Ok(config) = Config::load(&path) { if let Some(_server) = config.server { return Ok(path); } else { error = format_err!( "Configuration file: {}, no ser...
{ return Err(format_err!("No valid configuration files found")); }
conditional_block
main.rs
crate failure; const CONFIG_FILE_OPT: &str = "config"; const CONFIG_DIR_OPT: &str = "conf-dir"; const CONFIG_FILE_EXT: &str = "toml"; const DEFAULT_CONFIG_FILE: &str = "example_config.toml"; fn build_app() -> App<'static> { App::new("alis-bot-rs") .version("1.0") .about("alis-unofficial IRC bot")...
"/tmp/test/1_file.toml", "/tmp/test/2_file.toml", "/tmp/test/error_file.toml", ] .iter(); let matches = build_app().get_matches_from(cmd); let result = get_config_paths_from_cli(matches).unwrap(); assert_eq!(result, expected); } #[test]...
"-c",
random_line_split
main.rs
crate failure; const CONFIG_FILE_OPT: &str = "config"; const CONFIG_DIR_OPT: &str = "conf-dir"; const CONFIG_FILE_EXT: &str = "toml"; const DEFAULT_CONFIG_FILE: &str = "example_config.toml"; fn build_app() -> App<'static> { App::new("alis-bot-rs") .version("1.0") .about("alis-unofficial IRC bot")...
() { let cmd = ["alis-bot-rs", "-d", "/unaccessible/path"].iter(); let matches =
directory_failures_errors
identifier_name
sql_webshell.py
shell', shell_obj ) return [shell_obj, ] raise w3afException('No exploitable vulnerabilities found.') def getAttackType(self): ''' @return: The type of exploit, SHELL, PROXY, etc. ''' return 'shell' de...
return False
conditional_block
sql_webshell.py
httpPostDataRequest.httpPostDataRequest() elif self._method == 'GET': freq = httpQsRequest.httpQsRequest() else: raise w3afException('Method not supported.') freq.setURL( self._url ) freq.setDc( parse_qs( self._data ) ) ...
(self, driver, vuln_obj): ''' First, upload any file to the target webroot. Once I've found the target webroot (or any other location inside the webroot where I can write a file) try to upload a webshell and test for execution. @parameter driver: The database dr...
_upload_webshell
identifier_name
sql_webshell.py
are exploiting. @return: The webshell URL if the webshell was uploaded, or None if the process failed. ''' upload_success = False # First, we test if we can upload a file into a directory we can access: webroot_dirs = get_webroot_dirs( vuln_obj.getURL().getDoma...
''' This method is called when a user writes a command in the shell and hits enter. Before calling this method, the framework calls the generic_user_input method from the shell class. @parameter command: The command to handle ( ie. "read", "exec", etc ). @return: The re...
identifier_body
sql_webshell.py
httpPostDataRequest.httpPostDataRequest() elif self._method == 'GET': freq = httpQsRequest.httpQsRequest() else: raise w3afException('Method not supported.') freq.setURL( self._url ) freq.setDc( parse_qs( self._data ) ) ...
raise w3afException('No exploitable vulnerabilities found.') def getAttackType(self): ''' @return: The type of exploit, SHELL, PROXY, etc. ''' return 'shell' def getExploitableVulns(self): vulns = kb.kb.getData( '...
random_line_split
remote.py
easily add cluster mode to 2.0. class RemoteMixin(object): "A mix-in class to turn local nodes into remote nodes" # ssh base command # -q: don't print stupid diagnostic messages # BatchMode yes: don't ask for password # ForwardAgent yes: forward authentication credentials sshbase = ['ssh', '-...
(RemoteNode): "A RemoteHost is simply a RemoteNode" pass class RemoteOVSSwitch(RemoteMixin, OVSSwitch): "Remote instance of Open vSwitch" OVSVersions = {} def __init__(self, *args, **kwargs): # No batch startup yet kwargs.update(batch=True) super(RemoteOVSSwitch, self).__...
RemoteHost
identifier_name
remote.py
= popen.poll() result += decode(popen.stdout.read()) if poll is not None: break return result @staticmethod def _ignoreSignal(): "Detach from process group to ignore all signals" os.setpgrp() def _popen(self, cmd, sudo=True, tt=True, **param...
if not addr: result = node.cmd('ip link set tap9 name', intf) else: result = node.cmd('ip link set tap9 name', intf, 'address', addr) if result: raise Exception('error renaming %s: %s' % (intf, result))
conditional_block
remote.py
easily add cluster mode to 2.0. class RemoteMixin(object): "A mix-in class to turn local nodes into remote nodes" # ssh base command # -q: don't print stupid diagnostic messages # BatchMode yes: don't ask for password # ForwardAgent yes: forward authentication credentials sshbase = ['ssh', '-...
server: remote server (optional) user: user on remote server (optional) controlPath: specify shared ssh control path (optional) splitInit: split initialization? **kwargs: see Node()""" # We connect to servers by IP address self.server = server if se...
controlPath=False, splitInit=False, **kwargs): """Instantiate a remote node name: name of remote node
random_line_split
remote.py
easily add cluster mode to 2.0. class RemoteMixin(object): "A mix-in class to turn local nodes into remote nodes" # ssh base command # -q: don't print stupid diagnostic messages # BatchMode yes: don't ask for password # ForwardAgent yes: forward authentication credentials sshbase = ['ssh', '-...
def addIntf(self, *args, **kwargs): "Override: use RemoteLink.moveIntf" # kwargs.update( moveIntfFn=RemoteLink.moveIntf ) # pylint: disable=useless-super-delegation return super(RemoteMixin, self).addIntf(*args, **kwargs) class RemoteNode(RemoteMixin, Node): "A node on a remo...
"Override: disable -tt" return super(RemoteMixin, self).popen(*args, tt=False, **kwargs)
identifier_body
SPComponentLoader.js
LogKillswtichActivated, isDisable3PCodeKillswitchActivated, isOptimsticPreloadFilteredToViewPortKillswitchActivated } from '../common/killSwitches';
* SPFx component loader. * * @public */ var SPComponentLoader = /** @class */ (function () { function SPComponentLoader(loaderArgs) { var bundledComponents = loaderArgs.bundledComponents, ctor = loaderArgs.ctor, _a = loaderArgs.debugData, debugLoader = _a.debugLoader, debugManifests = _a.debugManifests,...
import { normalizeComponentId } from '../common/normalize'; import { startApplication } from '../common/platformLoader'; /**
random_line_split
SPComponentLoader.js
KillswtichActivated, isDisable3PCodeKillswitchActivated, isOptimsticPreloadFilteredToViewPortKillswitchActivated } from '../common/killSwitches'; import { normalizeComponentId } from '../common/normalize'; import { startApplication } from '../common/platformLoader'; /** * SPFx component loader. * * @public */ var S...
}; /** * {@inheritdoc ISPComponentLoader._unloadComponents} * * @internal */ SPComponentLoader.prototype._unloadComponents = function () { for (var _i = 0, _a = ManifestStore.instance.getRegisteredManifests(); _i < _a.length; _i++) { var m = _a[_i]; Compo...
{ ManifestStore.instance.getRegisteredManifests(true).forEach(function (manifest) { // We don't need to care if these succeed or fail here, and are just focused on starting the load. _this.loadComponent(manifest); // tslint:disable-line:no-floating-promises }); ...
conditional_block
SPComponentLoader.js
KillswtichActivated, isDisable3PCodeKillswitchActivated, isOptimsticPreloadFilteredToViewPortKillswitchActivated } from '../common/killSwitches'; import { normalizeComponentId } from '../common/normalize'; import { startApplication } from '../common/platformLoader'; /** * SPFx component loader. * * @public */ var S...
if (debugManifests) { if (!registerAsNonDebug && !isDangerouslyEnableDebugKSActivated()) { ManifestStore.instance.registerDebugManifests(debugManifests); } else { ManifestStore.instance.registerManifests(debugManifests, registerAsNonDebug); ...
{ var bundledComponents = loaderArgs.bundledComponents, ctor = loaderArgs.ctor, _a = loaderArgs.debugData, debugLoader = _a.debugLoader, debugManifests = _a.debugManifests, registerAsNonDebug = _a.registerAsNonDebug, preloadedData = loaderArgs.preloadedData, serviceScope = loaderArgs.serviceScope, useSecondaryC...
identifier_body
SPComponentLoader.js
KillswtichActivated, isDisable3PCodeKillswitchActivated, isOptimsticPreloadFilteredToViewPortKillswitchActivated } from '../common/killSwitches'; import { normalizeComponentId } from '../common/normalize'; import { startApplication } from '../common/platformLoader'; /** * SPFx component loader. * * @public */ var S...
(loaderArgs) { var bundledComponents = loaderArgs.bundledComponents, ctor = loaderArgs.ctor, _a = loaderArgs.debugData, debugLoader = _a.debugLoader, debugManifests = _a.debugManifests, registerAsNonDebug = _a.registerAsNonDebug, preloadedData = loaderArgs.preloadedData, serviceScope = loaderArgs.serviceScope, ...
SPComponentLoader
identifier_name
imageUploader.js
easier comparison for(var i = 0; i < arr.length; i++) { header += arr[i].toString(16); } var mimeType = evaluateFileSignature(header); callback(mimeType); // retrieve mimeType for evaluation via evaluateMimeType() }; fileReader.readAsArrayBuffer(file); // asynchronous function call }...
// message with photo upload status $("#upload_status").html("Your photos have successfully uploaded.<br>Please note that it will take a moment to process them.").show(); updateButtons(); } } // POST the photo name and data to /queue_photos route via an AJAX reque...
{ cells[i].onclick = null; cells[i].removeChild(cells[i].childNodes[3]); }
conditional_block
imageUploader.js
easier comparison for(var i = 0; i < arr.length; i++) { header += arr[i].toString(16); } var mimeType = evaluateFileSignature(header); callback(mimeType); // retrieve mimeType for evaluation via evaluateMimeType() }; fileReader.readAsArrayBuffer(file); // asynchronous function call }...
(file, index, length) { $.ajax({ url: "/queue_photos", type: 'POST', data: {filename: file.filename, data: file.data}, success: function(data, status, xhr) {}, complete: function(data, status, xhr) { if (index + 1 === length) { // if t...
queuePhotos
identifier_name
imageUploader.js
easier comparison for(var i = 0; i < arr.length; i++) { header += arr[i].toString(16); } var mimeType = evaluateFileSignature(header); callback(mimeType); // retrieve mimeType for evaluation via evaluateMimeType() }; fileReader.readAsArrayBuffer(file); // asynchronous function call }...
// Trigger /upload_photos route to start processing photo data from photo queue function uploadPhotos() { $.ajax({ url: "/upload_photos", type: 'POST', data: {photoUploadStatus: "OK"}, success: function(data, status, xhr) {} }); } // I...
{ $.ajax({ url: "/queue_photos", type: 'POST', data: {filename: file.filename, data: file.data}, success: function(data, status, xhr) {}, complete: function(data, status, xhr) { if (index + 1 === length) { // if this is the last photo ...
identifier_body
imageUploader.js
var slice = byteCharacters.slice(offset, offset + sliceSize); var byteNumbers = new Array(slice.length); for (var i = 0; i < slice.length; i++) { byteNumbers[i] = slice.charCodeAt(i); } var byteArray = new Uint8Array(byteNumbers); byteArrays.push(byteArray); ...
// Hide "You didn't upload any photos..." message if it is showing after clicking Select Photo button
random_line_split
encode.rs
32 }; let value: u8 = bitreader.read(num_bits_to_read).unwrap(); if use_shuffle { utils::shuffle_char_value_map(rng, char_to_value_map); } value_vec.push(value); num_bits_remain -= num_bits_to_read as usize; } value_vec } pub fn get_value_vec( bit_to_char_map: &mut HashMap<us...
encode
identifier_name
encode.rs
_map: &mut HashMap<usize, char>, unique_words: &Vec<&str>, total_words: f64, consecutive_skips: usize, depth_skip_threshold: usize, use_shuffle: bool, ) -> Result<String, String> { let mut char_to_bit_map = HashMap::new(); let mut num_bits = 0; for bit_val in bit_to_char_map.keys() { num_bits += 1; ...
{ let mut cursor = Cursor::new(&file_contents); let mut num_bits_remain = file_contents.len() * 8; let mut bitreader = BitReader::endian(&mut cursor, BigEndian); let mut sorted_keys = vec![]; let mut value_vec = vec![]; for byte_val in bit_to_char_map.keys() { sorted_keys.push(*byte_val); } sorted_...
identifier_body
encode.rs
str>, usize>, usable_words: &Vec<&'a str>, current_words: &Vec<&str>, n: usize, total_words: f64, ) -> (&'a str, usize) { let mut all_p_zero = true; let mut use_n = n; let mut max_p_index = 0; while all_p_zero { let mut ngram_slice = vec![]; let mut counter = 1; for word in current_words.it...
use_shuffle: bool, rng: &mut StdRng, char_to_value_map: &mut HashMap<char, usize>, ) -> Vec<u8> {
random_line_split
BratsCRFNeighborWhole.py
import Counter from CRFUtils import * from BratsCheckPredictions import * import math from math import * train_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_training_t1_t1c_hist_match" test_path="/media/bmi/MyPassport/new_n4/Recon_2013_data/N4_zscore_testing_t1_t1c_hist_match" #train_path="/media/b...
testLayers = np.array( [x.reshape((sliceShape[0]*sliceShape[1],n_features)) for x in testLayers] ) testTruth = np.array( [x.reshape((sliceShape[0]*sliceShape[1],)).astype(int) for x in testTruth] ) asdfTest = zip(testLayers,GTest) predTest = svm.predict(asdfTest) ...
GTest = [edges for x in testLayers]
random_line_split