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
graph.rs
use crate::{CommandEncoder, CommandEncoderOutput}; use generational_arena::Arena; use moonwave_resources::{BindGroup, Buffer, ResourceRc, SampledTexture, TextureView}; use multimap::MultiMap; use parking_lot::{RwLock, RwLockReadGuard}; use rayon::{prelude::*, ThreadPool}; use std::{ collections::HashMap, fmt::{Debu...
} device_host.get_queue().submit(buffers); } } } // Reset optick::event!("FrameGraph::reset"); self.reset(); } } #[derive(Clone)] pub enum FrameNodeValue { Buffer(ResourceRc<Buffer>), BindGroup(ResourceRc<BindGroup>), TextureView(ResourceRc<TextureView>), S...
{ buffers.push(buffer); }
conditional_block
signature_format.py
#!/usr/bin/python3 #-*- encoding: Utf-8 -*- from typing import Dict, List, Set, Sequence, Union, Any from base64 import b64decode, b64encode from math import log, exp, sqrt from binascii import crc32 from enum import IntEnum from io import BytesIO from ctypes import * DATA_URI_PREFIX = 'data:audio/vnd.shazam.sig;base6...
"_seconds": frequency_peak.get_seconds() } for frequency_peak in frequency_peaks ] for frequency_band, frequency_peaks in sorted(self.frequency_band_to_sound_peaks.items()) } } def encode_to_bina...
"fft_pass_number": frequency_peak.fft_pass_number, "peak_magnitude": frequency_peak.peak_magnitude, "corrected_peak_frequency_bin": frequency_peak.corrected_peak_frequency_bin, "_frequency_hz": frequency_peak.get_frequency_h...
random_line_split
signature_format.py
#!/usr/bin/python3 #-*- encoding: Utf-8 -*- from typing import Dict, List, Set, Sequence, Union, Any from base64 import b64decode, b64encode from math import log, exp, sqrt from binascii import crc32 from enum import IntEnum from io import BytesIO from ctypes import * DATA_URI_PREFIX = 'data:audio/vnd.shazam.sig;base6...
@classmethod def decode_from_uri(cls, uri : str): assert uri.startswith(DATA_URI_PREFIX) return cls.decode_from_binary(b64decode(uri.replace(DATA_URI_PREFIX, '', 1))) """ Encode the current object to a readable JSON format, for debugging purposes....
self = cls() buf = BytesIO(data) buf.seek(8) checksummable_data = buf.read() buf.seek(0) # Read and check the header header = RawSignatureHeader() buf.readinto(header) assert header.magic1 == 0xcafe2580 assert h...
identifier_body
signature_format.py
#!/usr/bin/python3 #-*- encoding: Utf-8 -*- from typing import Dict, List, Set, Sequence, Union, Any from base64 import b64decode, b64encode from math import log, exp, sqrt from binascii import crc32 from enum import IntEnum from io import BytesIO from ctypes import * DATA_URI_PREFIX = 'data:audio/vnd.shazam.sig;base6...
(self) -> float: return (self.fft_pass_number * 128) / self.sample_rate_hz # ^ Assume that new FFT bins are emitted every 128 samples, on a # standard 16 KHz sample rate basis. class DecodedMessage: sample_rate_hz : int = None number_samples : in...
get_seconds
identifier_name
signature_format.py
#!/usr/bin/python3 #-*- encoding: Utf-8 -*- from typing import Dict, List, Set, Sequence, Union, Any from base64 import b64decode, b64encode from math import log, exp, sqrt from binascii import crc32 from enum import IntEnum from io import BytesIO from ctypes import * DATA_URI_PREFIX = 'data:audio/vnd.shazam.sig;base6...
# Below, write the full message as a binary stream header.size_minus_header = len(contents_buf.getvalue()) + 8 buf = BytesIO() buf.write(bytes(header)) # We will rewrite it just after in order to include the final CRC-32 buf.write((0x...
peaks_buf = BytesIO() fft_pass_number = 0 # NOTE: Correctly filtering and sorting the peaks within the members # of "self.frequency_band_to_sound_peaks" is the responsability of the # caller for frequency_peak...
conditional_block
mp3.py
from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.wid...
def infinite_loop(self, url): iteration = 0 self.proc = subprocess.Popen(["mpg123","-o", "alsa", "-@", url], stderr=subprocess.PIPE, bufsize = 0) line = [] while True: if self.stop.is_set(): Logger.info("Player: stopping thread") self.stop.clear() return ...
Logger.info("Player: already playing")
conditional_block
mp3.py
from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.widg...
# self.ids['wlan_list'].bind(text=self.change_wlan_selection) def change_wlan_selection(self, spinner, args): Logger.info("WLAN: user selection %s" % args) # Logger.info("WLAN: current WLAN %s" % Network.ssid) # if args != Network.ssid: # Logger.info("WLAN: changing WLAN to %s" % args) # Netw...
# if net['ssid'] is Network.ssid: # self.ids['wlan_list'].text = net[Network.ssid] # self.ids['wlan_list'].values = networklist
random_line_split
mp3.py
from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.wid...
class MySettingsWithTabbedPanel(SettingsWithTabbedPanel): def on_close(self): Logger.info("main.py: MySettingsWithTabbedPanel.on_close") def on_config_change(self, config, section, key, value): if key == "playlist": Stations.no_data = True Logger.info( "main.py: MySettingsWithTabbedPanel...
global RootApp #print(Mp3PiAppClass) def do_GET(self): if self.path == "/": self.page = markup.page() self.page.init(title="Title") self.page.table(border="true") firstline = True for row in RootApp.search_results.adapter.data: if firstline is True: ...
identifier_body
mp3.py
from kivy.app import App from kivy.uix.scatter import Scatter from kivy.uix.label import Label from kivy.uix.floatlayout import FloatLayout from kivy.uix.textinput import TextInput from kivy.uix.boxlayout import BoxLayout from kivy.uix.button import Button from kivy.uix.scrollview import ScrollView from kivy.uix.wid...
(self): global ConfigObject connection = NMCLI.current_connection() while True: if self.statusthread_stop.is_set(): self.statusthread_stop.clear() return if not int(time.time()) % 5: connection = NMCLI.current_connection() ip = NMCLI.get_ip() ...
status_thread
identifier_name
base.py
import logging import os import re from collections import OrderedDict import numexpr as ne import numpy as np import pandas as pd import yaml from tardis import constants from astropy import units as u from pyne import nucname import tardis from tardis.io.util import get_internal_data_path k_B_cgs = constants.k_B.c...
(nu, T): """ Calculate the intensity of a black-body according to the following formula .. math:: I(\\nu, T) = \\frac{2h\\nu^3}{c^2}\frac{1} {e^{h\\nu \\beta_\\textrm{rad}} - 1} Parameters ---------- nu : float Frequency of light T : float Temperature in kel...
intensity_black_body
identifier_name
base.py
import logging import os import re from collections import OrderedDict import numexpr as ne import numpy as np import pandas as pd import yaml from tardis import constants from astropy import units as u from pyne import nucname import tardis from tardis.io.util import get_internal_data_path k_B_cgs = constants.k_B.c...
return (np.linspace(start.value, stop.to(start.unit).value, num, **kwargs) * start.unit) def convert_abundances_format(fname, delimiter=r'\s+'): """ Changes format of file containing abundances into data frame Parameters ---------- fname : file, str File or file name that...
raise ValueError('Both start and stop need to be quantities with a ' 'unit attribute')
random_line_split
base.py
import logging import os import re from collections import OrderedDict import numexpr as ne import numpy as np import pandas as pd import yaml from tardis import constants from astropy import units as u from pyne import nucname import tardis from tardis.io.util import get_internal_data_path k_B_cgs = constants.k_B.c...
def quantity_linspace(start, stop, num, **kwargs): """ Essentially the same input parameters as linspace, but calculated for an astropy quantity start and stop. Parameters ---------- start : ~astropy.Quantity Starting value of the sequence stop : ~astropy.Quantity End val...
""" Reformat the string so the first letter is uppercase and all subsequent letters lowercase. Parameters ---------- element_string : str Inputted element symbol Returns ------- str Returned reformatted element symbol """ return element_string[0].upper() + ele...
identifier_body
base.py
import logging import os import re from collections import OrderedDict import numexpr as ne import numpy as np import pandas as pd import yaml from tardis import constants from astropy import units as u from pyne import nucname import tardis from tardis.io.util import get_internal_data_path k_B_cgs = constants.k_B.c...
relevant_synpp_refs = radial1d_mdl.atom_data.synpp_refs[ radial1d_mdl.atom_data.synpp_refs['ref_log_tau'] > -50] with open(synpp_default_yaml_fname) as stream: yaml_reference = yaml.load(stream, Loader=yaml.CLoader) if lines_db is not None: yaml_reference['opacity']['line_dir'] ...
try: radial1d_mdl.atom_data.synpp_refs['ref_log_tau'].loc[key] = np.log10( radial1d_mdl.plasma.tau_sobolevs[0].loc[value['line_id']]) except KeyError: pass
conditional_block
profiling_data.go
// Copyright (C) 2019 Google 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 t...
{ counterTracksQueryResult, err := processor.Query(counterTracksQuery) if err != nil { return nil, log.Errf(ctx, err, "SQL query failed: %v", counterTracksQuery) } // t.id, name, unit, description, ts, value tracksColumns := counterTracksQueryResult.GetColumns() numTracksRows := counterTracksQueryResult.GetNumR...
identifier_body
profiling_data.go
// Copyright (C) 2019 Google 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 t...
(ctx context.Context, replayHandles *[]int64, replayHandleType string, handleMapping *map[uint64][]service.VulkanHandleMappingItem) { for i, v := range *replayHandles { handles, ok := (*handleMapping)[uint64(v)] if !ok { log.E(ctx, "%v not found in replay: %v", replayHandleType, v) continue } found := f...
extractTraceHandles
identifier_name
profiling_data.go
// Copyright (C) 2019 Google 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 t...
if !found { log.E(ctx, "Incorrect Handle type for %v: %v", replayHandleType, v) } } } func fixContextIds(contextIDs []int64) { // This is a workaround a QC bug(b/192546534) // that causes first deviceID to be zero after a // renderpass change in the same queue submit. // So, we fill the zero devices with...
{ if handle.HandleType == replayHandleType { (*replayHandles)[i] = int64(handle.TraceValue) found = true break } }
conditional_block
profiling_data.go
// Copyright (C) 2019 Google 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 t...
"github.com/google/gapid/gapis/perfetto" perfetto_service "github.com/google/gapid/gapis/perfetto/service" "github.com/google/gapid/gapis/service" "github.com/google/gapid/gapis/service/path" "github.com/google/gapid/gapis/trace/android/profile" "github.com/google/gapid/gapis/trace/android/utils" ) var ( slices...
random_line_split
config.js
/*global define */ /*jslint browser:true,sloppy:true */ /* | Copyright 2014 Esri | | 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 | ...
}, { Title: "Layout", WidgetPath: "widgets/layout/layout" }, { Title: "Sign In", WidgetPath: "widgets/portalSignin/portalSignin" }], // -------------------------------------------------------------------------------------------------------...
Title: "Info", WidgetPath: "widgets/info/info" }, { Title: "Sort By", WidgetPath: "widgets/sortby/sortby"
random_line_split
manager.go
package manager import ( "fmt" "log" "net" "os" "reflect" "strings" "sync" "time" "golang.org/x/net/context" "github.com/coreos/etcd/client" "github.com/samuelngs/axis/health" "github.com/samuelngs/axis/launcher" "github.com/samuelngs/axis/models" "github.com/samuelngs/axis/pkg/network" ) type ( // C...
for _, iface := range ifaces { if iface.Flags&net.FlagUp == 0 { continue // interface down } if iface.Flags&net.FlagLoopback != 0 { continue // loopback interface } addrs, err := iface.Addrs() if err != nil { return "" } for _, addr := range addrs { var ip net.IP switch v := addr.(type)...
{ return "" }
conditional_block
manager.go
package manager import ( "fmt" "log" "net" "os" "reflect" "strings" "sync" "time" "golang.org/x/net/context" "github.com/coreos/etcd/client" "github.com/samuelngs/axis/health" "github.com/samuelngs/axis/launcher" "github.com/samuelngs/axis/models" "github.com/samuelngs/axis/pkg/network" ) type ( // C...
// GetRunningNodes to get existed nodes func (c *Client) GetRunningNodes() []models.Node { dir := c.dir.Running res := []models.Node{} if c.client == nil { return res } resp, err := c.client.Get(context.Background(), dir, nil) if err != nil { return res } if !resp.Node.Dir { return res } for _, node :...
{ return models.SetupEnvironment( c.GetServiceHostname(), c.GetServiceIP(), c.GetRunningNodes(), ) }
identifier_body
manager.go
package manager import ( "fmt" "log" "net" "os" "reflect" "strings" "sync" "time" "golang.org/x/net/context" "github.com/coreos/etcd/client" "github.com/samuelngs/axis/health" "github.com/samuelngs/axis/launcher" "github.com/samuelngs/axis/models" "github.com/samuelngs/axis/pkg/network" ) type ( // C...
() error { endpoints := c.GetEndPoint() cfg := client.Config{ Endpoints: endpoints, Transport: client.DefaultTransport, HeaderTimeoutPerRequest: time.Second, } fmt.Printf("# connect to %v\n", endpoints) conn, err := client.New(cfg) if err != nil { return err } kapi := client....
Connect
identifier_name
manager.go
package manager import ( "fmt" "log" "net" "os" "reflect" "strings" "sync" "time" "golang.org/x/net/context" "github.com/coreos/etcd/client" "github.com/samuelngs/axis/health" "github.com/samuelngs/axis/launcher" "github.com/samuelngs/axis/models" "github.com/samuelngs/axis/pkg/network" ) type ( // C...
return "" } for _, addr := range addrs { var ip net.IP switch v := addr.(type) { case *net.IPNet: ip = v.IP case *net.IPAddr: ip = v.IP } if ip == nil || ip.IsLoopback() { continue } ip = ip.To4() if ip == nil { continue // not an ipv4 address } return ip.String()...
continue // loopback interface } addrs, err := iface.Addrs() if err != nil {
random_line_split
main.rs
use num_traits::PrimInt; use pest::Parser; use pest_derive::Parser; use std::{ collections::HashMap, error::Error, fmt, io::{self, Read}, str::FromStr, }; #[cfg(debug_assertions)] macro_rules! dbg_print { ($( $args:expr ),*) => { print!( $( $args ),* ); } } #[cfg(not(debug_assertions))] macro_rules! dbg_...
fn calc_hit(&self, enemy: &Group) -> u32 { match ( self.immunity.to(enemy.attack), self.weakness.to(enemy.attack), ) { (false, false) => enemy.effective_power(), (true, false) => 0, (false, true) => enemy.effective_power() * 2, (true, true) => unreachable!(), } } ...
fn is_alive(&self) -> bool { self.units > 0 }
random_line_split
main.rs
use num_traits::PrimInt; use pest::Parser; use pest_derive::Parser; use std::{ collections::HashMap, error::Error, fmt, io::{self, Read}, str::FromStr, }; #[cfg(debug_assertions)] macro_rules! dbg_print { ($( $args:expr ),*) => { print!( $( $args ),* ); } } #[cfg(not(debug_assertions))] macro_rules! dbg_...
} #[derive(Default, Clone)] struct Army<'a> { groups: Vec<Group>, name: &'a str, } impl Army<'_> { fn sort_for_attack(&self) -> Vec<u16> { let mut ids: Vec<u16> = (0..self.groups.len() as u16).collect(); ids.sort_by_key(|i| // descending sort ( !self.groups[*i as usize].is_alive(), ...
{ let org_units = self.units; let units_kill = points / self.hits; self.units = self.units.saturating_sub(units_kill); let units_lost = org_units - self.units; dbg_print!("Units lost: {}\n", units_lost); units_lost }
identifier_body
main.rs
use num_traits::PrimInt; use pest::Parser; use pest_derive::Parser; use std::{ collections::HashMap, error::Error, fmt, io::{self, Read}, str::FromStr, }; #[cfg(debug_assertions)] macro_rules! dbg_print { ($( $args:expr ),*) => { print!( $( $args ),* ); } } #[cfg(not(debug_assertions))] macro_rules! dbg_...
(&self) -> u32 { self.units * (self.damages as u32 + self.boost as u32) } fn is_alive(&self) -> bool { self.units > 0 } fn calc_hit(&self, enemy: &Group) -> u32 { match ( self.immunity.to(enemy.attack), self.weakness.to(enemy.attack), ) { (false, false) => enemy.effective_pow...
effective_power
identifier_name
types.ts
import type { AccountLimitsResponse, Authorize, ContractUpdate, DetailsOfEachMT5Loginid, GetAccountStatus, GetLimits, GetSettings, LandingCompany, LogOutResponse, Portfolio1, ProposalOpenContract, ResidenceList, SetFinancialAssessmentRequest, SetFinancialAssessmen...
}; type TContractStore = { getContractById: (id: number) => ProposalOpenContract; }; type TMenuStore = { attach: (item: TMenuItem) => void; update: (menu: TMenuItem, index: number) => void; }; type TNotificationStore = { addNotificationMessage: (message: TNotification) => void; addNotificationMes...
onClickCancel: (contract_id?: number) => void; onClickSell: (contract_id?: number) => void; onMount: () => void; positions: TPortfolioPosition[]; removePositionById: (id: number) => void;
random_line_split
socket.rs
// SPDX-License-Identifier: MIT use std::{ io::{Error, Result}, mem, os::unix::io::{AsRawFd, FromRawFd, RawFd}, }; use crate::SocketAddr; /// A netlink socket. /// /// # Example /// /// In this example we: /// /// 1. open a new socket /// 2. send a message to the kernel /// 3. read the reponse /// /// ``...
(&self, non_blocking: bool) -> Result<()> { let mut non_blocking = non_blocking as libc::c_int; let res = unsafe { libc::ioctl(self.0, libc::FIONBIO, &mut non_blocking) }; if res < 0 { return Err(Error::last_os_error()); } Ok(()) } /// Connect the socket to t...
set_non_blocking
identifier_name
socket.rs
// SPDX-License-Identifier: MIT use std::{ io::{Error, Result}, mem, os::unix::io::{AsRawFd, FromRawFd, RawFd}, }; use crate::SocketAddr; /// A netlink socket. /// /// # Example /// /// In this example we: /// /// 1. open a new socket /// 2. send a message to the kernel /// 3. read the reponse /// /// ``...
// a pointer to it. let addrlen_ptr = &mut addrlen as *mut usize as *mut libc::socklen_t; let chunk = buf.chunk_mut(); // Cast the *mut u8 into *mut void. // This is equivalent to casting a *char into *void // ...
// also a sockaddr_in, a sockaddr_in6, or even the generic sockaddr_storage that can store // any address. let mut addrlen = mem::size_of_val(&addr); // recvfrom does not take the address length by value (see [thread]), so we need to create
random_line_split
socket.rs
// SPDX-License-Identifier: MIT use std::{ io::{Error, Result}, mem, os::unix::io::{AsRawFd, FromRawFd, RawFd}, }; use crate::SocketAddr; /// A netlink socket. /// /// # Example /// /// In this example we: /// /// 1. open a new socket /// 2. send a message to the kernel /// 3. read the reponse /// /// ``...
// Most of the comments in this method come from a discussion on rust users forum. // [thread]: https://users.rust-lang.org/t/help-understanding-libc-call/17308/9 // /// Read a datagram from the socket and return the number of bytes that have been read and the address of the /// sender. The data b...
{ // FIXME: // // Event though for SOCK_DGRAM sockets there's no IO, if our socket is non-blocking, // connect() might return EINPROGRESS. In theory, the right way to treat EINPROGRESS would // be to ignore the error, and let the user poll the socket to check when it becomes ...
identifier_body
socket.rs
// SPDX-License-Identifier: MIT use std::{ io::{Error, Result}, mem, os::unix::io::{AsRawFd, FromRawFd, RawFd}, }; use crate::SocketAddr; /// A netlink socket. /// /// # Example /// /// In this example we: /// /// 1. open a new socket /// 2. send a message to the kernel /// 3. read the reponse /// /// ``...
else { 0 }; setsockopt(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS, value) } pub fn get_no_enobufs(&self) -> Result<bool> { let res = getsockopt::<libc::c_int>(self.0, libc::SOL_NETLINK, libc::NETLINK_NO_ENOBUFS)?; Ok(res == 1) } /// `NETLINK_LISTEN_ALL_NSID` (since Li...
{ 1 }
conditional_block
context.go
package terraform import ( "context" "fmt" "log" "sort" "strings" "sync" "github.com/hashicorp/terraform/tfdiags" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/version"...
// ShadowError returns any errors caught during a shadow operation. // // A shadow operation is an operation run in parallel to a real operation // that performs the same tasks using new logic on copied state. The results // are compared to ensure that the new logic works the same as the old logic. // The shadow neve...
{ if opts == nil { opts = &ContextGraphOpts{Validate: true} } log.Printf("[INFO] terraform: building graph: %s", typ) switch typ { case GraphTypeApply: return (&ApplyGraphBuilder{ Module: c.module, Diff: c.diff, State: c.state, Providers: c.components.ResourceProviders(), ...
identifier_body
context.go
package terraform import ( "context" "fmt" "log" "sort" "strings" "sync" "github.com/hashicorp/terraform/tfdiags" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/version"...
(k string, v interface{}) { c.variables[k] = v } func (c *Context) acquireRun(phase string) func() { // With the run lock held, grab the context lock to make changes // to the run context. c.l.Lock() defer c.l.Unlock() // Wait until we're no longer running for c.runCond != nil { c.runCond.Wait() } // Buil...
SetVariable
identifier_name
context.go
package terraform import ( "context" "fmt" "log" "sort" "strings" "sync" "github.com/hashicorp/terraform/tfdiags" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/version"...
// no value provided, so don't set the variable at all if value == "" { continue } decoded, err := parseVariableAsHCL(n, value, valueType) if err != nil { return err } if decoded != nil { c.variables[n] = decoded } } } if mode&InputModeProvider != 0 { // Build the graph ...
{ var err error value, err = c.uiInput.Input(&InputOpts{ Id: fmt.Sprintf("var.%s", n), Query: fmt.Sprintf("var.%s", n), Description: v.Description, }) if err != nil { return fmt.Errorf( "Error asking for %s: %s", n, err) } if value == "" && v.Required() ...
conditional_block
context.go
package terraform import ( "context" "fmt" "log" "sort" "strings" "sync" "github.com/hashicorp/terraform/tfdiags" "github.com/hashicorp/go-multierror" "github.com/hashicorp/hcl" "github.com/hashicorp/terraform/config" "github.com/hashicorp/terraform/config/module" "github.com/hashicorp/terraform/version"...
// With the run lock held, grab the context lock to make changes // to the run context. c.l.Lock() defer c.l.Unlock() // Wait until we're no longer running for c.runCond != nil { c.runCond.Wait() } // Build our lock c.runCond = sync.NewCond(&c.l) // Setup debugging dbug.SetPhase(phase) // Create a new...
func (c *Context) acquireRun(phase string) func() {
random_line_split
workshopSteps.py
#first we are going to import the libraries we need #OS library is used for operating system functionalities such as reading a file or using software/hardware products. #Math library is for math functions such as floor/ceiling #Sys library gives access to system only functions such as exit() #Random library allows us t...
#STEP 7 #Lets create a function to move the snake def move(self): #So we're going to calculate the length of the snake - 1, since arrays start from 0 the last index will be #the length of the snake - 1 lastCell = len(self.bodyStack) - 1 #We're going to write a while loop ...
self.x = x self.y = y self.direction = KEY["RIGHT"] #We're going to create a list to hold all the snakes body self.bodyStack = [] #adding the first snake cell to the list of cells self.bodyStack.append(self) #We're going to create an end cell to separate the bod...
identifier_body
workshopSteps.py
#first we are going to import the libraries we need #OS library is used for operating system functionalities such as reading a file or using software/hardware products. #Math library is for math functions such as floor/ceiling #Sys library gives access to system only functions such as exit() #Random library allows us t...
: def __init__(self,x,y): #So we initalize the snakes x and y location to the x and y passed in and #set the direction of the snake to right self.x = x self.y = y self.direction = KEY["RIGHT"] #We're going to create a list to hold all the snakes body self.bod...
Snake
identifier_name
workshopSteps.py
#first we are going to import the libraries we need #OS library is used for operating system functionalities such as reading a file or using software/hardware products. #Math library is for math functions such as floor/ceiling #Sys library gives access to system only functions such as exit() #Random library allows us t...
#We're going to write a function to draw the food #parameters are going to be self and a screen #lets draw a rect using the screen the self.color and the x, y coordinates and the food size and a 0 width def draw(self,screen): pygame.draw.rect(screen, self.color, (self.x, self.y, FOOD_SIZE, FOOD_...
random_line_split
workshopSteps.py
#first we are going to import the libraries we need #OS library is used for operating system functionalities such as reading a file or using software/hardware products. #Math library is for math functions such as floor/ceiling #Sys library gives access to system only functions such as exit() #Random library allows us t...
#If a key was pressed we try to change the direction of the snake then we move again if(keyPressed): snake.changeDirection(keyPressed) snake.move() #We fill the screen in again with the color screen.fill(background_color) #we check for all the food and if ...
spawnSingleFood(food, snake.bodyStack[0].x, snake.bodyStack[0].y) eaten_food = False
conditional_block
glove.py
import logging from collections import Counter from random import shuffle import numpy as np from math import log from matplotlib import pyplot as plt from scipy import sparse from scipy.spatial.distance import pdist from sklearn.decomposition import PCA class GloVe: def __init__(self, lists, learning_rate=0.05...
# indexing speed; we'll convert into a list later cooccurrences = sparse.lil_matrix((vocab_size, vocab_size), dtype=np.float64) for i, list_ in enumerate(self._lists): if i % 1000 == 0: self._logger.info("Building cooccurrenc...
vocab_size = len(self._vocabulary) # Collect cooccurrences internally as a sparse matrix for passable
random_line_split
glove.py
import logging from collections import Counter from random import shuffle import numpy as np from math import log from matplotlib import pyplot as plt from scipy import sparse from scipy.spatial.distance import pdist from sklearn.decomposition import PCA class GloVe: def __init__(self, lists, learning_rate=0.05...
test_lists = [ ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['owoce', 'szynka'], ['woda', 'chleb'], ['woda', 'chleb'], ['woda', 'c...
conditional_block
glove.py
import logging from collections import Counter from random import shuffle import numpy as np from math import log from matplotlib import pyplot as plt from scipy import sparse from scipy.spatial.distance import pdist from sklearn.decomposition import PCA class GloVe: def __init__(self, lists, learning_rate=0.05...
def fit(self): space = self._train() merged_space = self._merge_main_context(space) return merged_space def setup_logger(self, name_='GloVe'): # TODO redirect to file self._logger = logging.getLogger(name_) stream_logger = logging.StreamHandler() stre...
self.setup_logger() self.build_vocab() self.build_id2word()
identifier_body
glove.py
import logging from collections import Counter from random import shuffle import numpy as np from math import log from matplotlib import pyplot as plt from scipy import sparse from scipy.spatial.distance import pdist from sklearn.decomposition import PCA class GloVe: def __init__(self, lists, learning_rate=0.05...
(self): self.setup_logger() self.build_vocab() self.build_id2word() def fit(self): space = self._train() merged_space = self._merge_main_context(space) return merged_space def setup_logger(self, name_='GloVe'): # TODO redirect to file self._logg...
setup
identifier_name
printer.rs
use std::borrow::Cow; use std::io::{self, BufRead, BufReader, Read, Write}; use std::time::Instant; use encoding_rs::Encoding; use encoding_rs_io::DecodeReaderBytesBuilder; use mime::Mime; use reqwest::blocking::{Body, Request, Response}; use reqwest::cookie::CookieStore; use reqwest::header::{ HeaderMap, HeaderNa...
pub fn print_response_body( &mut self, response: &mut Response, encoding: Option<&'static Encoding>, mime: Option<&str>, ) -> anyhow::Result<()> { let starting_time = Instant::now(); let url = response.url().clone(); let content_type = mime.m...
{ let content_type = get_content_type(request.headers()); if let Some(body) = request.body_mut() { let body = body.buffer()?; if body.contains(&b'\0') { self.buffer.print(BINARY_SUPPRESSOR)?; } else { self.print_body_text(content_type, ...
identifier_body
printer.rs
use std::borrow::Cow; use std::io::{self, BufRead, BufReader, Read, Write}; use std::time::Instant; use encoding_rs::Encoding; use encoding_rs_io::DecodeReaderBytesBuilder; use mime::Mime; use reqwest::blocking::{Body, Request, Response}; use reqwest::cookie::CookieStore; use reqwest::header::{ HeaderMap, HeaderNa...
else { Some(text) } } /// Like [`decode_blob`], but without binary detection. fn decode_blob_unconditional<'a>( raw: &'a [u8], encoding: Option<&'static Encoding>, url: &Url, ) -> Cow<'a, str> { let encoding = encoding.unwrap_or_else(|| detect_encoding(raw, true, url)); encoding.decode...
{ None }
conditional_block
printer.rs
use std::borrow::Cow; use std::io::{self, BufRead, BufReader, Read, Write}; use std::time::Instant; use encoding_rs::Encoding; use encoding_rs_io::DecodeReaderBytesBuilder; use mime::Mime; use reqwest::blocking::{Body, Request, Response}; use reqwest::cookie::CookieStore; use reqwest::header::{ HeaderMap, HeaderNa...
(&self, headers: &HeaderMap, version: Version) -> String { let as_titlecase = match version { Version::HTTP_09 | Version::HTTP_10 | Version::HTTP_11 => true, Version::HTTP_2 | Version::HTTP_3 => false, _ => false, }; let mut headers: Vec<(&HeaderName, &HeaderV...
headers_to_string
identifier_name
printer.rs
use std::borrow::Cow; use std::io::{self, BufRead, BufReader, Read, Write}; use std::time::Instant; use encoding_rs::Encoding; use encoding_rs_io::DecodeReaderBytesBuilder; use mime::Mime; use reqwest::blocking::{Body, Request, Response}; use reqwest::cookie::CookieStore; use reqwest::header::{ HeaderMap, HeaderNa...
self.buffer.print("\n")?; } Err(err) if err.kind() == io::ErrorKind::InvalidData => { self.buffer.print(BINARY_SUPPRESSOR)?; } Err(err) => return Err(err.into()), } } else { let mut bu...
Ok(_) => {
random_line_split
graham_scan.py
""" Author: Ajinkya Shinde """ # Importing the necessary packages from Stack import Stack from math import atan2, sqrt, pi, cos, sin import numpy as np import matplotlib.pyplot as plt import time import random import os import csv def point_with_min_y(points): """Returns the point with minimum y co-ordinate and the ...
s.push(sorted_points[i]) end = time.time() #helper dictionary for generating plots input_choice_title = {1:'Random Scatter',2:'Circle',3:'Circle with min. hull pts %'} ##Call results function show_convex_hull(points,input_choice_title[int(choice_of_input)],round((end-start),6),str(per_min_pt),n,s.print_a...
s.pop()
conditional_block
graham_scan.py
""" Author: Ajinkya Shinde """ # Importing the necessary packages from Stack import Stack from math import atan2, sqrt, pi, cos, sin import numpy as np import matplotlib.pyplot as plt import time import random import os import csv def point_with_min_y(points): """Returns the point with minimum y co-ordinate and the ...
(n): """Returns random points for input choice 1 from menu screen Input:n(int) : size of input Output: points array """ return [(random.randint(0,n),random.randint(0,n)) for i in range(n)] def points_on_circumference(center=(0, 0), r=50, n=100): """ Returns points around the boundary of circle with random d...
create_random_points
identifier_name
graham_scan.py
""" Author: Ajinkya Shinde """ # Importing the necessary packages from Stack import Stack from math import atan2, sqrt, pi, cos, sin import numpy as np import matplotlib.pyplot as plt import time import random import os import csv def point_with_min_y(points): """Returns the point with minimum y co-ordinate and the ...
final_points.append(check_points[max_far_idx]) elif len(each) == 1: final_points.append(points[each.tolist()[0]]) return final_points def cross_product(p0,p1,p2): """Returns the cross product of points of p0,p1 and p2. The value returned is +ve, -ve or 0 """ return (((p1[0]-p0[0])*(p2[1]-p...
for j in i: check_points.append(points[j]) check_points_arr = np.asarray(check_points) max_far_idx = np.argmax(euclidean_distance(check_points,P0))
random_line_split
graham_scan.py
""" Author: Ajinkya Shinde """ # Importing the necessary packages from Stack import Stack from math import atan2, sqrt, pi, cos, sin import numpy as np import matplotlib.pyplot as plt import time import random import os import csv def point_with_min_y(points): """Returns the point with minimum y co-ordinate and the ...
def create_export_files(n,input_choice,timing,min_hull_per): """Creates folder analysis if not exists in current directory and creates results.csv file Input: n(int): size of input input_choice(int): choice of input from menu timing(decimal): Timing in sec of algo min_hull_per(int): perc...
""" Returns points around the boundary of circle with random distribution It is called when choice of input entered is 2 """ return [ ( center[0]+(cos(2 * pi / n * x) * r), center[1] + (sin(2 * pi / n * x) * r) ) for x in range(0, n + 1)]
identifier_body
dataset.py
import os,sys import inspect import tempfile import shutil from OpenVisus import * #in configure step I dont have numpy yet try: import numpy except: pass # ////////////////////////////////////////////////////////// def CreateIdx(**args): if not "url" in args: raise Exception("url not speci...
if not access: access=self.db.createAccess() def NoGenerator(): if not self.db.executeBoxQuery(access, query): raise Exception("query error {0}".format(query.errormsg)) # i cannot be sure how the numpy will be used outside or when the query will dealllocate the buffer data=Array.to...
raise Exception("begin query failed {0}".format(query.errormsg))
conditional_block
dataset.py
import os,sys import inspect import tempfile import shutil from OpenVisus import * #in configure step I dont have numpy yet try: import numpy except: pass # ////////////////////////////////////////////////////////// def CreateIdx(**args): if not "url" in args: raise Exception("url not speci...
# readBlock def readBlock(self, block_id, time=None, field=None, access=None, aborted=Aborted()): Assert(access) field=self.getField() if field is None else self.getField(field) time = self.getTime() if time is None else time read_block = self.db.createBlockQuery(block_id, field, time, ord('r'), abo...
return self.db.createAccess()
identifier_body
dataset.py
import os,sys import inspect import tempfile import shutil from OpenVisus import * #in configure step I dont have numpy yet try: import numpy except: pass # ////////////////////////////////////////////////////////// def CreateIdx(**args): if not "url" in args: raise Exception("url not speci...
(object): # constructor def __init__(self,db): self.db = db # __getattr__ def __getattr__(self,attr): return getattr(self.db, attr) # getPointDim def getPointDim(self): return self.db.getPointDim() # getMaxResolution def getMaxResolution(self): return self.db.getMaxResolution() ...
PyDataset
identifier_name
dataset.py
import os,sys import inspect import tempfile import shutil from OpenVisus import * #in configure step I dont have numpy yet try: import numpy except: pass # ////////////////////////////////////////////////////////// def CreateIdx(**args): if not "url" in args: raise Exception("url not speci...
query = self.db.createBoxQuery(logic_box, field , time , ord('w')) query.end_resolutions.push_back(self.getMaxResolution()) self.db.beginBoxQuery(query) if not query.isRunning(): raise Exception("begin query failed {0}".format(query.errormsg)) if not access: access=IdxDiskAccess.cre...
logic_box=BoxNi(PointNi(logic_box[0]),PointNi(logic_box[1]))
random_line_split
imitation_ddpg_model.py
import gym import tensorflow as tf from tensorflow.keras import layers import numpy as np import cv2 as cv import matplotlib.pyplot as plt import setup_path import airsim import time import os import pyautogui import pytesseract from PIL import Image import tracking physical_devices = tf.config.list_physical_devices...
action = policy(tf_prev_state, ou_noise) action = tf.squeeze(action) print('episode :', ep + 1, '|', 'brake :', round(float(action[0]), 3), '|', 'steering :', round(float(action[1]), 3), '|', 'throttle :', round(float(abs(action[2])), 3), '|', 'direction :', round(fl...
random_line_split
imitation_ddpg_model.py
import gym import tensorflow as tf from tensorflow.keras import layers import numpy as np import cv2 as cv import matplotlib.pyplot as plt import setup_path import airsim import time import os import pyautogui import pytesseract from PIL import Image import tracking physical_devices = tf.config.list_physical_devices...
# Takes (s,a,r,s') obervation tuple as input def record(self, obs_tuple): # Set index to zero if buffer_capacity is exceeded, # replacing old records index = self.buffer_counter % self.buffer_capacity self.state_buffer[index] = obs_tuple[0] self.action_buffer[index] = ...
self.buffer_capacity = buffer_capacity # Num of tuples to train on. self.batch_size = batch_size # Its tells us num of times record() was called. self.buffer_counter = 0 # Instead of list of tuples as the exp.replay concept go # We use different np.arrays for each tuple...
identifier_body
imitation_ddpg_model.py
import gym import tensorflow as tf from tensorflow.keras import layers import numpy as np import cv2 as cv import matplotlib.pyplot as plt import setup_path import airsim import time import os import pyautogui import pytesseract from PIL import Image import tracking physical_devices = tf.config.list_physical_devices...
()
lient, car_controls = sim_start() break prev_state = state ep_reward_list.append(episodic_reward) # Mean of last 40 episodes avg_reward = np.mean(ep_reward_list[-40:]) print("Episode * {} * Avg Reward is ==> {}".format(ep + 1, avg_reward)) avg_reward_list.append(avg_reward) ...
conditional_block
imitation_ddpg_model.py
import gym import tensorflow as tf from tensorflow.keras import layers import numpy as np import cv2 as cv import matplotlib.pyplot as plt import setup_path import airsim import time import os import pyautogui import pytesseract from PIL import Image import tracking physical_devices = tf.config.list_physical_devices...
(self): if self.x_initial is not None: self.x_prev = self.x_initial else: self.x_prev = np.zeros_like(self.mean) class Buffer: def __init__(self, buffer_capacity=100000, batch_size=64): # Number of "experiences" to store at max self.buffer_capacity = buffer_...
reset
identifier_name
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_has...
Ok(record_chunks) } /// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len() != sector_size(pieces_in_sector) { return Err(ReadingE...
{ return Err(ReadingError::WrongRecordSizeAfterDecoding { expected: Record::NUM_CHUNKS, actual: record_chunks.len(), }); }
conditional_block
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_has...
ReadingError::InvalidChunk { s_bucket, encoded_chunk_used, chunk_location, error, } })?); Ok::<_, ReadingError>(()) }, )?; let...
); } maybe_record_chunk.replace(Scalar::try_from(record_chunk).map_err(|error| {
random_line_split
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_has...
<PosTable>( piece_offset: PieceOffset, sector_id: &SectorId, sector_metadata: &SectorMetadataChecksummed, sector: &[u8], erasure_coding: &ErasureCoding, table_generator: &mut PosTable::Generator, ) -> Result<Piece, ReadingError> where PosTable: Table, { let pieces_in_sector = sector_meta...
read_piece
identifier_name
reading.rs
use crate::sector::{ sector_record_chunks_size, sector_size, RecordMetadata, SectorContentsMap, SectorContentsMapFromBytesError, SectorMetadataChecksummed, }; use parity_scale_codec::Decode; use rayon::prelude::*; use std::mem::ManuallyDrop; use std::simd::Simd; use subspace_core_primitives::crypto::{blake3_has...
/// Read metadata (commitment and witness) for record pub(crate) fn read_record_metadata( piece_offset: PieceOffset, pieces_in_sector: u16, sector: &[u8], ) -> Result<RecordMetadata, ReadingError> { if sector.len() != sector_size(pieces_in_sector) { return Err(ReadingError::WrongSectorSize { ...
{ // Restore source record scalars let record_chunks = erasure_coding .recover_source(sector_record_chunks) .map_err(|error| ReadingError::FailedToErasureDecodeRecord { piece_offset, error, })?; // Required for safety invariant below if record_chunks.len(...
identifier_body
api_op_UpdateMatchmakingConfiguration.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "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.c...
func addUpdateMatchmakingConfigurationResolveEndpointMiddleware(stack *middleware.Stack, options Options) error { return stack.Serialize.Insert(&opUpdateMatchmakingConfigurationResolveEndpointMiddleware{ EndpointResolver: options.EndpointResolverV2, BuiltInResolver: &builtInResolver{ Region: options.Reg...
{ if awsmiddleware.GetRequiresLegacyEndpoints(ctx) { return next.HandleSerialize(ctx, in) } req, ok := in.Request.(*smithyhttp.Request) if !ok { return out, metadata, fmt.Errorf("unknown transport type %T", in.Request) } if m.EndpointResolver == nil { return out, metadata, fmt.Errorf("expected endpoint re...
identifier_body
api_op_UpdateMatchmakingConfiguration.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "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.c...
(region string) *awsmiddleware.RegisterServiceMetadata { return &awsmiddleware.RegisterServiceMetadata{ Region: region, ServiceID: ServiceID, SigningName: "gamelift", OperationName: "UpdateMatchmakingConfiguration", } } type opUpdateMatchmakingConfigurationResolveEndpointMiddleware struct { End...
newServiceMetadataMiddleware_opUpdateMatchmakingConfiguration
identifier_name
api_op_UpdateMatchmakingConfiguration.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "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.c...
} if err = smithyhttp.AddErrorCloseResponseBodyMiddleware(stack); err != nil { return err } if err = smithyhttp.AddCloseResponseBodyMiddleware(stack); err != nil { return err } if err = addUpdateMatchmakingConfigurationResolveEndpointMiddleware(stack, options); err != nil { return err } if err = addOpUpda...
random_line_split
api_op_UpdateMatchmakingConfiguration.go
// Code generated by smithy-go-codegen DO NOT EDIT. package gamelift import ( "context" "errors" "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.c...
ctx = awsmiddleware.SetSigningName(ctx, signingName) ctx = awsmiddleware.SetSigningRegion(ctx, signingRegion) break case *internalauth.AuthenticationSchemeV4A: v4aScheme, _ := authScheme.(*internalauth.AuthenticationSchemeV4A) if v4aScheme.SigningName == nil { v4aScheme.SigningName = aws.String("g...
{ // The signer sets an equivalent value at client initialization time. // Setting this context value will cause the signer to extract it // and override the value set at client initialization time. ctx = internalauth.SetDisableDoubleEncoding(ctx, *v4Scheme.DisableDoubleEncoding) }
conditional_block
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colo...
(&mut self, d: RotateVec<f64>, s: &str, override_color: Option<usize>) { let c = if let Some(over) = override_color { Color::generate(over) } else { Color::generate(self.data.len() + 11) }; let l = gtk::Label::new(Some(s)); l.override_color(StateFlags::fro...
push
identifier_name
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colo...
pub fn invalidate(&self) { if let Some(t_win) = self.area.get_window() { let (x, y) = self.area.translate_coordinates(&self.area, 0, 0) .expect("translate_coordinates failed"); let rect = gdk::Rectangle { x: x, y: y, width: self.area....
}
random_line_split
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colo...
}
{ let s = self.clone(); if let Some(parent) = self.borrow().horizontal_layout.get_toplevel() { // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); ...
identifier_body
graph.rs
use cairo; use gtk::{self, BoxExt, ContainerExt, DrawingArea, ScrolledWindowExt, StateFlags, WidgetExt}; use std::cell::RefCell; use gdk::{self, WindowExt}; use std::rc::Rc; use std::time::Instant; use color::Color; use utils::RotateVec; const LEFT_WIDTH: f64 = 31.; pub struct Graph { elapsed: Instant, colo...
else { eprintln!("This method needs to be called *after* it has been put inside a window"); } } }
{ // TODO: ugly way to resize drawing area, I should find a better way parent.connect_configure_event(move |w, _| { let need_diff = s.borrow().initial_diff.is_none(); if need_diff { let mut s = s.borrow_mut(); let parent_wid...
conditional_block
train_and_deploy.py
import argparse from collections import OrderedDict import json import numpy as np import sys import os import pandas as pd import random from sklearn.metrics import accuracy_score from tqdm import tqdm import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import transfor...
torch.backends.cudnn.deterministic = True # Converting the lines to BERT format # Thanks to https://www.kaggle.com/httpwwwfszyc/bert-in-keras-taming def convert_lines(example, max_seq_length, tokenizer): max_seq_length -= 2 all_tokens = [] longer = 0 for text in tqdm(example): tokens_a = ...
torch.cuda.manual_seed(seed)
conditional_block
train_and_deploy.py
import argparse from collections import OrderedDict import json import numpy as np import sys import os import pandas as pd import random from sklearn.metrics import accuracy_score from tqdm import tqdm import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import transfor...
def train(train_loader, model, optimizer, is_distributed): model.train() avg_loss = 0. avg_accuracy = 0. tk0 = tqdm(enumerate(train_loader), total=len(train_loader), leave=False) optimizer.zero_grad() for i, (x_batch, y_batch) in tk0: y_pred = model(x_batch.to(DEVI...
size = float(dist.get_world_size()) for param in model.parameters(): dist.all_reduce(param.grad.data, op=dist.reduce_op.SUM) param.grad.data /= size
identifier_body
train_and_deploy.py
import argparse from collections import OrderedDict import json import numpy as np import sys import os import pandas as pd import random from sklearn.metrics import accuracy_score from tqdm import tqdm import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import transfor...
# Load pre-trained bert model model = BertForSequenceClassification.from_pretrained('cl-tohoku/bert-base-japanese-whole-word-masking', num_labels=1) model.zero_grad() model = model.to(DEVICE) param_optimizer = list(model.named_paramete...
random_line_split
train_and_deploy.py
import argparse from collections import OrderedDict import json import numpy as np import sys import os import pandas as pd import random from sklearn.metrics import accuracy_score from tqdm import tqdm import torch import torch.distributed as dist import torch.nn as nn import torch.nn.functional as F import transfor...
(train_loader, model, optimizer, is_distributed): model.train() avg_loss = 0. avg_accuracy = 0. tk0 = tqdm(enumerate(train_loader), total=len(train_loader), leave=False) optimizer.zero_grad() for i, (x_batch, y_batch) in tk0: y_pred = model(x_batch.to(DEVICE), ...
train
identifier_name
windows_aligned_file_reader.rs
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::sync::Arc; use std::time::Duration; use std::{ptr, thread}; use crossbeam::sync::ShardedLock; use hashbrown::HashMap; use once_cell::sync::Lazy; use platform::file_handle::{AccessMode, ShareMode}; use platf...
// Extract number of neighbors from the node_data let neighbors_num = u32::from_le_bytes( node_data[num_nbrs_start..nbrs_buf_start] .try_into() .unwrap(), ); let nbors_buf_end = ...
.chunks_exact(std::mem::size_of::<f32>()) .map(|chunk| f32::from_le_bytes(chunk.try_into().unwrap())) .collect();
random_line_split
windows_aligned_file_reader.rs
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::sync::Arc; use std::time::Duration; use std::{ptr, thread}; use crossbeam::sync::ShardedLock; use hashbrown::HashMap; use once_cell::sync::Lazy; use platform::file_handle::{AccessMode, ShareMode}; use platf...
() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.get_ctx(); assert!(result.is_ok()); } #[test] fn test_register_thread() { let reader = WindowsAlignedFileReader::new(TEST_INDEX_PATH).unwrap(); let result = reader.register...
test_get_ctx
identifier_name
windows_aligned_file_reader.rs
/* * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT license. */ use std::sync::Arc; use std::time::Duration; use std::{ptr, thread}; use crossbeam::sync::ShardedLock; use hashbrown::HashMap; use once_cell::sync::Lazy; use platform::file_handle::{AccessMode, ShareMode}; use platf...
} pub struct WindowsAlignedFileReader { file_name: String, // ctx_map is the mapping from thread id to io context. It is hashmap behind a sharded lock to allow concurrent access from multiple threads. // ShardedLock: shardedlock provides an implementation of a reader-writer lock that offers concurrent re...
{ self.aligned_buf }
identifier_body
sm2.go
/* 编写者:严志伟 编写时间:2018/08/01 公司:中国搜索信息科技股份有限公司 */ /* 椭圆曲线加解密及签名算法的技术原理及其Go语言实现:http://www.jeepyurongfu.net/blog/45309.html */ package sm2 import "C" import ( "bytes" "crypto" "crypto/elliptic" "crypto/rand" "encoding/asn1" "encoding/binary" "errors" "fmt" "github.com/chinaso/fabricGM/cryptopkg/golangGM/sm...
identifier_name
sm2.go
/* 编写者:严志伟 编写时间:2018/08/01 公司:中国搜索信息科技股份有限公司 */ /* 椭圆曲线加解密及签名算法的技术原理及其Go语言实现:http://www.jeepyurongfu.net/blog/45309.html */ package sm2 import "C" import ( "bytes" "crypto" "crypto/elliptic" "crypto/rand" "encoding/asn1" "encoding/binary" "errors" "fmt" "github.com/chinaso/fabricGM/cryptopkg/golangGM/sm...
*zr) Read(dst []byte) (n int, err error) { for i := range dst { dst[i] = 0 } return len(dst), nil } var zeroReader = &zr{} func getLastBit(a *big.Int) uint { return a.Bit(0) } func Compress(a *PublicKey) []byte { buf := []byte{} yp := getLastBit(a.Y) buf = append(buf, a.X.Bytes()...) if n := len(a.X.Bytes()...
eturn t, nil } type zr struct { io.Reader } func (z
conditional_block
sm2.go
/* 编写者:严志伟 编写时间:2018/08/01 公司:中国搜索信息科技股份有限公司 */ /* 椭圆曲线加解密及签名算法的技术原理及其Go语言实现:http://www.jeepyurongfu.net/blog/45309.html */ package sm2 import "C" import ( "bytes" "crypto" "crypto/elliptic" "crypto/rand" "encoding/asn1" "encoding/binary" "errors" "fmt" "github.com/chinaso/fabricGM/cryptopkg/golangGM/sm...
return t, nil } type zr struct { io.Reader } func (z *zr) Read(dst []byte) (n int, err error) { for i := range dst { dst[i] = 0 } return len(dst), nil } var zeroReader = &zr{} func getLastBit(a *big.Int) uint { return a.Bit(0) } func Compress(a *PublicKey) []byte { buf := []byte{} yp := getLastBit(a.Y) b...
tm = append(tm, y2Buf...) h := sm3.Sum(tm) if bytes.Compare(h, ciphertext[64:96]) != 0 { return t, errors.New("Decrypt: failed to decrypt") }
random_line_split
sm2.go
/* 编写者:严志伟 编写时间:2018/08/01 公司:中国搜索信息科技股份有限公司 */ /* 椭圆曲线加解密及签名算法的技术原理及其Go语言实现:http://www.jeepyurongfu.net/blog/45309.html */ package sm2 import "C" import ( "bytes" "crypto" "crypto/elliptic" "crypto/rand" "encoding/asn1" "encoding/binary" "errors" "fmt" "github.com/chinaso/fabricGM/cryptopkg/golangGM/sm...
byte, sign []byte) bool { var sm2Sign sm2Signature _, err := asn1.Unmarshal(sign, &sm2Sign) if err != nil { return false } return SM2Verify(pub, msg, nil, sm2Sign.R, sm2Sign.S) } // ---------------------------------------------------------------- // func (pub *PublicKey) Encrypt(data []byte) ([]byte, error)...
nil { return nil, err } return asn1.Marshal(sm2Signature{r, s}) } // ---------------------------------------------------------------- // func (pub *PublicKey) Verify(msg []
identifier_body
varausohjelmajs.js
// Kaikki javascripti joka liittyy adminsivuun ja redirectaamiseen // array johon kaikki lisatyt kaytajat tallennetaan var userArray = []; userArray[0] = "@ default default" // sessionstorage asettaa stringin, // aluksi muokataan array string-muotoon kayttamalla JSON.stringify jonka jalkeen // kaytetaan JSON:...
toggleShowRoom(0); function toggleTable(indexsi) { for (var i = 0; i < ataglist.length; i++) { var x = ataglist[i]; if (x.style.display === 'none') { x.style.display = 'block'; } else { x.style.display = 'none'; } } } //var lTable = docu...
for (var i = 0; i < ataglist.length; i++){ $( ataglist[i] ).removeClass("active"); } $( tablelist[room] ).toggle(true); $(tablelist[room]).siblings().toggle( false ); };
identifier_body
varausohjelmajs.js
// Kaikki javascripti joka liittyy adminsivuun ja redirectaamiseen // array johon kaikki lisatyt kaytajat tallennetaan var userArray = []; userArray[0] = "@ default default" // sessionstorage asettaa stringin, // aluksi muokataan array string-muotoon kayttamalla JSON.stringify jonka jalkeen // kaytetaan JSON:...
} function updateHTMLBlock(){ elokuvaBlokki = stringElementti1 + rowspanElementti + stringElementti2 + elokuvanNimi + stringElementti3 + sali + stringElementti4 + aika + stringElementti5; } var asda = document.getElementsByName function tarkistaKoko(){ if (parseInt(rowspanKokoSallija, 10) < (selectedT...
{ this.classList.add("selected"); $(this).addClass('selected') this.style.backgroundColor = "green"; }
conditional_block
varausohjelmajs.js
// Kaikki javascripti joka liittyy adminsivuun ja redirectaamiseen // array johon kaikki lisatyt kaytajat tallennetaan var userArray = []; userArray[0] = "@ default default" // sessionstorage asettaa stringin, // aluksi muokataan array string-muotoon kayttamalla JSON.stringify jonka jalkeen // kaytetaan JSON:...
elementti, arvo) { var arr = []; for (var i = 0; i < arvo; i++) { arr.push(elementti); } return arr; } //function getIndexAndWorkFromThere(){ //for (var i = 0, neljanNappiSetit = aNapit.children.length; i < len; i++){ // var aNapit = document.getElementById('nappiSetti'); // for (var i = 0...
illArray(
identifier_name
varausohjelmajs.js
// Kaikki javascripti joka liittyy adminsivuun ja redirectaamiseen // array johon kaikki lisatyt kaytajat tallennetaan var userArray = []; userArray[0] = "@ default default" // sessionstorage asettaa stringin, // aluksi muokataan array string-muotoon kayttamalla JSON.stringify jonka jalkeen // kaytetaan JSON:...
return true; } } function tarkistaKokoKonfliktit(){ while(selectedTimeIndex2 > 0) { if (!$(seuraavanLapsitdt2[rowspanKohta]).hasClass('no-events')){ alert("Asettamasi aika on konfliktissa toisen ajan kanssa"); return false; } seuraavanLapsitdt2 = seuraavanLapsitdt2[0].pa...
function tarkistaKoko(){ if (parseInt(rowspanKokoSallija, 10) < (selectedTimeIndex +1)) { return false; } else {
random_line_split
openfoodfacts.py
""" Ce module permet de récupérer les données du site web OpenFoodFacts ("https://fr.openfoodfacts.org/"). Le module contient une fonction de scraping de données récupérant diverses informations sur tous les produits recensés sur le site. Il est aussi accompagné d'une mesure du temps de computation vous indiquant en co...
r = re.compile('^Quan.*$') quantity = list(filter(r.match, infos))[0].split(':')[-1] except : quantity = error try : r = re.compile('^Conditionnement.*$') conditionnement = list(filter(r.match, infos))[0...
except: pass try :
conditional_block
openfoodfacts.py
""" Ce module permet de récupérer les données du site web OpenFoodFacts ("https://fr.openfoodfacts.org/"). Le module contient une fonction de scraping de données récupérant diverses informations sur tous les produits recensés sur le site. Il est aussi accompagné d'une mesure du temps de computation vous indiquant en co...
except : sucre = error try : sel = liste_repères_nutri[3] sel = [float(elt) for elt in sel.split() if elt.replace('.', '').isdigit()].pop() except : sel = error ...
sucre = liste_repères_nutri[2] sucre = [float(elt) for elt in sucre.split() if elt.replace('.', '').isdigit()].pop()
random_line_split
openfoodfacts.py
""" Ce module permet de récupérer les données du site web OpenFoodFacts ("https://fr.openfoodfacts.org/"). Le module contient une fonction de scraping de données récupérant diverses informations sur tous les produits recensés sur le site. Il est aussi accompagné d'une mesure du temps de computation vous indiquant en co...
git de la fonction principale du module. Cette dernière crée dans votre espace de travail un DataFrame Pandas contenant les informations scrapées sur le site OpenFoodFacts. L'argument "nb_pages" permet de régler le nombre de page à scraper. Veuillez ne pas trop l'augmenter afin que l'opération prenne un tem...
identifier_body
openfoodfacts.py
""" Ce module permet de récupérer les données du site web OpenFoodFacts ("https://fr.openfoodfacts.org/"). Le module contient une fonction de scraping de données récupérant diverses informations sur tous les produits recensés sur le site. Il est aussi accompagné d'une mesure du temps de computation vous indiquant en co...
= 50) : """ Il s'agit de la fonction principale du module. Cette dernière crée dans votre espace de travail un DataFrame Pandas contenant les informations scrapées sur le site OpenFoodFacts. L'argument "nb_pages" permet de régler le nombre de page à scraper. Veuillez ne pas trop l'augmenter afin que l'o...
foodfacts(nb_pages
identifier_name
hexformat.go
package anticipation import ( "bytes" "errors" "fmt" "log" ) //needs to be all 1s on right, can't be larger than 255 const FileXFerDataLineSize = uint16(0xff) type EncodeDecodeError struct { s string } func NewEncodeDecodeError(s string) error { return &EncodeDecodeError{s} } func (d *EncodeDecodeError) Error...
/////////////////////////////////////////////////////////////////////////////////// // ENCODING /////////////////////////////////////////////////////////////////////////////////// func EncodeDataBytes(raw []byte, offset uint16) string { if len(raw) > 255 { log.Fatalf("intel hex format only allows 2 hex characters...
{ i := int(index) total := uint8(0) switch buffer[i] { case '0': case '1': total += 16 * 1 case '2': total += 16 * 2 case '3': total += 16 * 3 case '4': total += 16 * 4 case '5': total += 16 * 5 case '6': total += 16 * 6 case '7': total += 16 * 7 case '8': total += 16 * 8 case '9': total ...
identifier_body
hexformat.go
package anticipation import ( "bytes" "errors" "fmt" "log" ) //needs to be all 1s on right, can't be larger than 255 const FileXFerDataLineSize = uint16(0xff) type EncodeDecodeError struct { s string } func NewEncodeDecodeError(s string) error { return &EncodeDecodeError{s} } func (d *EncodeDecodeError) Error...
(index uint16, buffer []byte) (uint8, bool) { i := int(index) total := uint8(0) switch buffer[i] { case '0': case '1': total += 16 * 1 case '2': total += 16 * 2 case '3': total += 16 * 3 case '4': total += 16 * 4 case '5': total += 16 * 5 case '6': total += 16 * 6 case '7': total += 16 * 7 cas...
bufferValue
identifier_name
hexformat.go
package anticipation import ( "bytes" "errors" "fmt" "log" ) //needs to be all 1s on right, can't be larger than 255 const FileXFerDataLineSize = uint16(0xff) type EncodeDecodeError struct { s string } func NewEncodeDecodeError(s string) error { return &EncodeDecodeError{s} } func (d *EncodeDecodeError) Error...
raw := []byte{byte(entry & 0xff000000 >> 24), byte(entry & 0x00ff0000 >> 16), byte(entry & 0x0000ff00 >> 8), byte(entry & 0x000000ff)} buf.WriteString(fmt.Sprintf(":040000%02X%08X", int(ExtensionBigEntryPoint), entry)) cs := createChecksum(raw, 0, ExtensionBigEntryPoint) buf.WriteString(fmt.Sprintf("%02X", cs)) ...
return buf.String() } func EncodeBigEntry(entry uint32) string { buf := bytes.Buffer{}
random_line_split
hexformat.go
package anticipation import ( "bytes" "errors" "fmt" "log" ) //needs to be all 1s on right, can't be larger than 255 const FileXFerDataLineSize = uint16(0xff) type EncodeDecodeError struct { s string } func NewEncodeDecodeError(s string) error { return &EncodeDecodeError{s} } func (d *EncodeDecodeError) Error...
converted := make([]byte, (l-1)/2) //skip first colon for i := uint16(1); i < l; i += 2 { v, ok := bufferValue(i, raw) if !ok { return nil // they already sent the error to the other side } converted[(i-1)/2] = v } return converted } // this hits buffer[i] and buffer[i+1] to convert an ascii byte // r...
{ print("!bad payload, expected even number of hex bytes but got:", l-1, "\n") return nil }
conditional_block
columnar.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
/// Finalize constructing a [ColumnarRecords]. pub fn finish(self) -> ColumnarRecords { let ret = ColumnarRecords { len: self.len, key_data: Buffer::from(self.key_data), key_offsets: OffsetsBuffer::try_from(self.key_offsets) .expect("constructed vali...
{ let ((key, val), ts, diff) = record; // Check size invariants ahead of time so we stay atomic when we can't // add the record. if !self.can_fit(key, val, KEY_VAL_DATA_MAX_LEN) { return false; } // NB: We should never hit the following expects because we ch...
identifier_body
columnar.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
key_data: self.key_data.as_slice(), key_offsets: self.key_offsets.as_slice(), val_data: self.val_data.as_slice(), val_offsets: self.val_offsets.as_slice(), timestamps: self.timestamps.as_slice(), diffs: self.diffs.as_slice(), }; deb...
/// Borrow Self as a [ColumnarRecordsRef]. fn borrow<'a>(&'a self) -> ColumnarRecordsRef<'a> { let ret = ColumnarRecordsRef { len: self.len,
random_line_split
columnar.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
(self) -> ColumnarRecords { let ret = ColumnarRecords { len: self.len, key_data: Buffer::from(self.key_data), key_offsets: OffsetsBuffer::try_from(self.key_offsets) .expect("constructed valid offsets"), val_data: Buffer::from(self.val_data), ...
finish
identifier_name
columnar.rs
// Copyright Materialize, Inc. and contributors. All rights reserved. // // Use of this software is governed by the Business Source License // included in the LICENSE file. // // As of the Change Date specified in that file, in accordance with // the Business Source License, use of this software will be governed // by ...
if let Some(first_val_offset) = self.val_offsets.first() { if first_val_offset.to_usize() != 0 { return Err(format!( "expected first val offset to be 0 got {}", first_val_offset.to_usize() )); } } if...
{ return Err(format!( "expected {} val_offsets got {}", self.len + 1, self.val_offsets.len() )); }
conditional_block
Transformer_prac.py
import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import matplotlib as plt dtype = torch.FloatTensor sentence =['ich mochte ein bier P', 'S i want a beer','i want a beer E'] # S : Symbol that shows starting point of decoding input # E : Symb...
.contiguous().view(-1)) print('Epoch:','%04d'%(epoch+1), 'cost = '.format(loss)) loss.backward() optimizer.step()
ut, enc_output, dec_self_attn_mask, dec_enc_attn_mask) dec_self_attn.append(dec_self_attn) dec_enc_attn.append(dec_enc_attn) return dec_output, dec_self_attn, dec_enc_attn, dec_enc_attn class Transformer(nn.Module): def __init__(self): super(Transformer, self).__init_...
identifier_body
Transformer_prac.py
import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import matplotlib as plt dtype = torch.FloatTensor sentence =['ich mochte ein bier P', 'S i want a beer','i want a beer E'] # S : Symbol that shows starting point of decoding input # E : Symb...
과 dim1이 서로 바꿘다 score.masked_fill_(att_mask, -1e9) # masked! # masked_fill_(mask, value) mask는 boolean으로, 마스크가 true인 곳에 value를 채움 attn = self.softmax(score) # attn = attention distribution context = torch.matmul(attn, V) return context, attn ###############################...
anpose: 주어진 dim0
identifier_name
Transformer_prac.py
import numpy as np import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import matplotlib as plt dtype = torch.FloatTensor sentence =['ich mochte ein bier P', 'S i want a beer','i want a beer E'] # S : Symbol that shows starting point of decoding input # E : Symb...
odel(enc_input, dec_input) loss = criterion(outputs, target_batch.contiguous().view(-1)) print('Epoch:','%04d'%(epoch+1), 'cost = '.format(loss)) loss.backward() optimizer.step()
parameters(), lr = 0.001) for epoch in range(20): optimizer.zero_grad() enc_input, dec_input, target_batch = make_batch(sentence) outputs, enc_self_attns, dec_self_attns, dec_enc_attns = m
conditional_block