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
mole.go
KeepAliveInterval time.Duration `json:"keep-alive-interval" mapstructure:"keep-alive-interva" toml:"keep-alive-interval"` ConnectionRetries int `json:"connection-retries" mapstructure:"connection-retries" toml:"connection-retries"` WaitAndRetry time.Duration `json:"wait-and-retry" mapstructur...
t, err := createTunnel(c.Conf) if err != nil { log.WithFields(log.Fields{ "id": c.Conf.Id, }).WithError(err).Error("error creating tunnel") return err } c.Tunnel = t if err = c.Tunnel.Start(); err != nil { log.WithFields(log.Fields{ "tunnel": c.Tunnel.String(), }).WithError(err).Error("error whi...
random_line_split
cliches.go
(match string) *BadTerm { return &BadTerm{match, "'%s' is a cliche. Avoid it like the plague."} } // ShouldNotCliche returns a slice of BadTerm's, none of which should be in the // a text (case insensitive). See existence_checks.go for details of BadTerms. func ShouldNotCliche() []TextCheck { return []TextCheck{ c...
cliche
identifier_name
cliches.go
// ShouldNotCliche returns a slice of BadTerm's, none of which should be in the // a text (case insensitive). See existence_checks.go for details of BadTerms. func ShouldNotCliche() []TextCheck { return []TextCheck{ cliche("all hell broke loose"), cliche("american as apple pie"), cliche("hobson's choice"), c...
{ return &BadTerm{match, "'%s' is a cliche. Avoid it like the plague."} }
identifier_body
cliches.go
"), cliche("cry like a baby"), cliche("cry me a river"), cliche("cry over spilt milk"), cliche("crystal clear"), cliche("crystal clear"), cliche("curiosity killed the cat"), cliche("cut and dried"), cliche("cut through the red tape"), cliche("cut to the chase"), cliche("cute as a bugs ear"), clich...
cliche("dime a dozen"), cliche("divide and conquer"), cliche("dog and pony show"), cliche("dog days"), cliche("dog eat dog"), cliche("dog tired"), cliche("don't burn your bridges"), cliche("don't count your chickens"), cliche("don't look a gift horse in the mouth"), cliche("don't rock the boat"), ...
cliche("day in, day out"), cliche("dead as a doornail"), cliche("decision-making process"), cliche("devil is in the details"),
random_line_split
spi_host.rs
0 => istate_clr: ReadWrite<u32, ISTATE_CLR::Register>), (0x0014 => _reserved), (0x1000 => tx_fifo: [WriteOnly<u8>; 128]), (0x1080 => rx_fifo: [ReadOnly<u8>; 128]), (0x1100 => @END), } } register_bitfields![u32, CTRL [
CSBSU OFFSET(2) NUMBITS(4) [], /// CSB from SCK hold time in SCK cycles + 1 (defined with respect to /// the last SCK edge) CSBHLD OFFSET(6) NUMBITS(4) [], /// SPI Clk Divider. Actual divider is IDIV+1. A value of 0 gives divide /// by 1 clock, 1 gives divide by 2 etc. ...
/// CPOL setting CPOL OFFSET(0) NUMBITS(1) [], /// CPHA setting CPHA OFFSET(1) NUMBITS(1) [], /// CSB to SCK setup time in SCK cycles + 1.5
random_line_split
spi_host.rs
(24) NUMBITS(1) [], /// Order in which received bits are packed into byte. /// 0: first bit received is bit0 1: last bit received is bit 0 RXBITOR OFFSET(25) NUMBITS(1) [], /// Order in which received bytes are packed into word. /// 0: first byte received is byte 0 1: first byte ...
{ panic!("set_rate is not implemented"); }
identifier_body
spi_host.rs
byte received is byte 0 1: first byte received is byte 3 RXBYTOR OFFSET(26) NUMBITS(1) [], /// SPI Passthrough Mode. 0: Disable, 1: Enable. This is the host side /// control of whether passthrough is allowed. In order for full /// passthrough functionality, both the host and device pass...
set_phase
identifier_name
spi_host.rs
_reserved), (0x1000 => tx_fifo: [WriteOnly<u8>; 128]), (0x1080 => rx_fifo: [ReadOnly<u8>; 128]), (0x1100 => @END), } } register_bitfields![u32, CTRL [ /// CPOL setting CPOL OFFSET(0) NUMBITS(1) [], /// CPHA setting CPHA OFFSET(1) NUMBITS(1) [], /...
{ CTRL::ENPASSTHRU::CLEAR }
conditional_block
campaign-gant-chart.js
rendering performance for large charts. g.setShowComp(0); g.setShowTaskInfoLink(0); g.setShowTaskInfoRes(0); g.setShowTaskInfoComp(0); g.setFormatArr('Day', 'Week', 'Month', 'Quarter'); // Even with setUseSingleCell using Hour format on such a large chart can cause issues in some browsers //(pID, pNa...
"gtaskpurple", '#', 0, content, 0, 0, stageId, 0, dependency, '', table, g)); } } } g.Draw(); } else { alert("Error, unable to create Gantt Chart"); } } function previewChart(divName){ element = $("#"+divName); /*$("#downloadChart").show();*/ $("#chartPreviewContainer").show(); $...
var taskStyleIndex = Math.floor(Math.random() * (taskStyle.length - 1)) + 0; var content = campaignSubstage.connectType == 0 ? campaignSubstage.contentId : campaignSubstage.connectUrl; g.AddTaskItem(new JSGantt.TaskItem(substageId, campaignSubstage.campaignSubStageName, startDateString, ...
random_line_split
campaign-gant-chart.js
MM < 10 ? ("0" + startDateMM) : startDateMM) + "-" + (startDateDD < 10 ? ("0" + startDateDD) : startDateDD); endDate = new Date(parseFloat(campaignStage.endDate)); endDateMM = endDate.getMonth() + 1; endDateDD = endDate.getDate(); endDateString = endDate.getFullYear() + "-" + (endDateMM < 10 ? ("0" ...
{ console.log("Loading"); showLoader(); previewChart(divName); setTimeout(function () { print("chartPreviewContainer"); hideLoader(); }, 3500); $("#chartPreviewContainer").hide(); }
identifier_body
campaign-gant-chart.js
TaskItem(new JSGantt.TaskItem(campaignId, campaign.campaignName, startDateString, endDateString, 'ggroupblack', '#', 0, '-', 0, 1, 0, 0, '', '', '', g)); //populate campaignStages for (var j = 0; j < campaign.campaignStagesSet.length; j++) { var campaignStage = campaign.campaignStagesSet[j...
expandAllFolders
identifier_name
adc.rs
MHz, >5k @ ADCK < 4MHz) /// inputs. Long = 1, } /// Adc Clock Divisors /// /// Note 1/16 divisor is only usable for the Bus clock pub enum ClockDivisor { /// Source / 1, No divison _1 = 0, /// Source / 2 _2 = 1, /// Source / 4 _4 = 2, /// Source / 8 _8 = 3, /// Source / 16 ...
return_vref_h
identifier_name
adc.rs
_freq.integer() / req_adc_freq.integer()) as u8; let mut output: u8 = 1; let mut err: i8 = (denom - output) as i8; let mut err_old: i8 = err; let max_divisor = match self.clock_source { AdcClocks::Bus => 16, _ => 8, }; while output < max_divisor {...
// Don't start a conversion (set channel to DummyDisable) self.peripheral.sc1.modify(|_, w| w.adch()._11111());
random_line_split
adc.rs
2bit = 2, } /// Adc sample time pub enum AdcSampleTime { /// Sample for 3.5 ADC clock (ADCK) cycles. Short = 0, /// Sample for 23.5 ADC clock (ADCK) cycles. /// /// Required for high impedence (>2k @ADCK > 4MHz, >5k @ ADCK < 4MHz) /// inputs. Long = 1, } /// Adc Clock Divisors /// /// Not...
{ self.bandgap.replace(inst); }
identifier_body
adc.rs
_analog] method. /// Once measurements from that pin are completed it will be returned to an /// Output that is set high by calling the [Analog::outof_analog] method. /// /// ```rust /// let pta0 = gpioa.pta0.into_push_pull_output(); /// pta0.set_high(); /// let mut pta0 = pta0.into_analog(); // pta0 is hi-Z /// let va...
{ None }
conditional_block
TimeSeries.js
//append each month in the time series as a new object pair to the data variable for(i=0; i<Object.keys(dates).length; i++){ var new_entry = {}; new_entry.date = dates[i]; new_entry.price = Object.values(crude_prices)[i]; data.push(new_entry); } //set up the x and y values - may need to parse dates from ...
for(i=0; i<Object.keys(dates).length; i++){ var new_entry = {}; new_entry.date = dates[i]; new_entry.imports = Object.values(import_data)[i]; data.push(new_entry); } var imports_x = d3.scaleTime() .domain(d3.extent(dates)) .range([0, width]); var imports_scale = d3.scaleLinear() .do...
var data =[]; //append each month in the time series as a new object pair to the data variable
random_line_split
TimeSeries.js
append each month in the time series as a new object pair to the data variable for(i=0; i<Object.keys(dates).length; i++){ var new_entry = {}; new_entry.date = dates[i]; new_entry.price = Object.values(crude_prices)[i]; data.push(new_entry); } //set up the x and y values - may need to parse dates from YY...
}); var dates = Object.keys(crude_prices).map(function(date){ return parse_dates(date); }); dates = dates.slice(0,dates.length-6); var data =[]; //append each month in the time series as a new object pair to the data variable for(i=0; i<Object.keys(dates).length; i++){ var new_entry = {}; new_entry.date ...
{ import_data = circle.circle.Imports; }
conditional_block
installed.rs
where T: AsRef<str> + 'a, I: IntoIterator<Item = &'a T> { let mut url = String::new(); let mut scopes_string = scopes.into_iter().fold(String::new(), |mut acc, sc| { acc.push_str(sc.as_ref()); acc.push_str(" "); acc }); // Remove last space scopes_string.pop();...
{ // We use a fake URL because the redirect goes to a URL, meaning we // can't use the url form decode (because there's slashes and hashes and stuff in // it). let url = hyper::Url::parse(&format!("http://example.com{}", path)); if url.is_...
conditional_block
installed.rs
T, I>(auth_uri: &str, client_id: &str, scopes: I, redirect_uri: Option<String>) -> String where T: AsRef<str> + 'a, I: In...
impl server::Handler for InstalledFlowHandler { fn handle(&self, rq: server::Request, mut rp: server::Response) { match rq.uri { uri::RequestUri::AbsolutePath(path) => { // We use a fake URL because the redirect goes to a URL, meaning we // can't use the url form ...
struct InstalledFlowHandler { auth_code_snd: Mutex<Sender<String>>, }
random_line_split
installed.rs
, I>(auth_uri: &str, client_id: &str, scopes: I, redirect_uri: Option<String>) -> String where T: AsRef<str> + 'a, I: Into...
match listening { Result::Err(_) => default, Result::Ok(listening) => { InstalledFlow { client: default.client, server: Some(listening)...
{ let default = InstalledFlow { client: client, server: None, port: None, auth_code_rcv: None, }; match method { None => default, Some(InstalledFlowReturnMethod::Interactive) => default, // Start server on localh...
identifier_body
installed.rs
T, I>(auth_uri: &str, client_id: &str, scopes: I, redirect_uri: Option<String>) -> String where T: AsRef<str> + 'a, I: In...
{ /// Involves showing a URL to the user and asking to copy a code from their browser /// (default) Interactive, /// Involves spinning up a local HTTP server and Google redirecting the browser to /// the server with a URL containing the code (preferred, but not as reliable). The /// parameter i...
InstalledFlowReturnMethod
identifier_name
types.go
Group of cluster type const ( STATIC_CLUSTER ClusterType = "STATIC" SIMPLE_CLUSTER ClusterType = "SIMPLE" DYNAMIC_CLUSTER ClusterType = "DYNAMIC" EDS_CLUSTER ClusterType = "EDS" ) // LbType type LbType string // Group of load balancer type const ( LB_RANDOM LbType = "LB_RANDOM" LB_ROUNDROBIN LbType =...
// TCPProxy type TCPProxy struct { StatPrefix string `json:"stat_prefix,omitempty"` Cluster string `json:"cluster,omitempty"` IdleTimeout *time.Duration `json:"idle_timeout,omitempty"` MaxConnectAttempts uint32 `json:"max_connect_attempts,omitempty"` Routes ...
} // Implements of filter config
random_line_split
server.go
() continue } latest := kv.configs[len(kv.configs)-1] kv.mu.RUnlock() config := kv.masters.Query(latest.Num + 1) if latest.Num < config.Num { kv.rf.Start(config) } } } } func (kv *ShardKV) migrationChecker() { t := time.NewTicker(100 * time.Millisecond) start := time.Now() for { sele...
{ shard := kv.database.GetShard(shardNum) shard.Append(op.Key, op.Value, op.ClientId, op.OpId) kv.lastOpId[op.ClientId] = op.OpId kv.saveShardKVState(false) }
conditional_block
server.go
("ShardKV %d (gid = %d) CheckMigrateShard ok = %v args = %+v reply = %+v\n", kv.me, kv.gid, ok, args, reply) }*/ if ok && reply.Result == OK { kv.rf.Start(reply) return } } }(servers, args) } } kv.mu.RUnlock() } } } func (kv *ShardKV) migrationHelper() { t ...
} // remove shard from kv.Database and store in waitClean kv.waitClean.StoreCleanData(kv.database) if !kv.waitMigration.IsEmpty() { go kv.migrationHelper()
random_line_split
server.go
KV { // call labgob.Register on structures you want // Go's RPC library to marshall/unmarshall. kv := new(ShardKV) kv.me = me kv.maxraftstate = maxraftstate kv.make_end = make_end kv.gid = gid kv.masters = shardmaster.MakeClerk(masters) kv.applyCh = make(chan raft.ApplyMsg) kv.applyWait = NewWait() kv.persis...
Result: ErrWaitCleanTimeOut, }) } else { for gid, shardNums := range gidShards { servers := config.Groups[gid] args := CheckMigrateShardArgs{ config.Num, gid, shardNums, } go func(servers []string, args CheckMigrateShardArgs) { for si := 0; si < len(servers...
{ t := time.NewTicker(100 * time.Millisecond) start := time.Now() for { select { case <-kv.ctx.Done(): return case <-t.C: kv.mu.RLock() if kv.waitClean.IsEmpty() { kv.mu.RUnlock() return } gidShards := kv.waitClean.GetGidShard() config := kv.waitClean.GetConfig() if time.Now().Sub...
identifier_body
server.go
KV { // call labgob.Register on structures you want // Go's RPC library to marshall/unmarshall. kv := new(ShardKV) kv.me = me kv.maxraftstate = maxraftstate kv.make_end = make_end kv.gid = gid kv.masters = shardmaster.MakeClerk(masters) kv.applyCh = make(chan raft.ApplyMsg) kv.applyWait = NewWait() kv.persis...
(force bool) { shouldSave := kv.maxraftstate != -1 && (force || kv.persister.RaftStateSize() > kv.maxraftstate) if shouldSave { w := new(bytes.Buffer) e := labgob.NewEncoder(w) e.Encode(kv.lastApplied) e.Encode(kv.database) e.Encode(kv.lastOpId) e.Encode(kv.configs) e.Encode(kv.waitClean) e.Encode(kv....
saveShardKVState
identifier_name
xor.go
<input type="search" id="codesearchQuery" value="" size="30" onkeydown="return codesearchKeyDown(event);"/> <form method="GET" action="http://www.google.com/codesearch" id="codesearch" class="search" onsubmit="return codeSearchSubmit();" style="display:inline;"> <input type="hidden" name=...
<span style="color: red">(TODO: remove for now?)</span> </form> </td> </tr> <tr> <td> <span style="color: gray;">(e.g. &ldquo;pem&rdquo; or &ldquo;xml&rdquo;)</span> </td> </tr> </table> --> </td>...
<input type="submit" value="Code search" />
random_line_split
app.js
Chase & Co'], ['McDonald\'s Corporation'], ['Merck & Co., Inc.'], ['Microsoft Corporation'], ['Pfizer Inc'], ['The Coca-Cola Company'], ['The Home Depot, Inc.'], ['The Procter & Gamble Company'], ['United Technologies Corporation'], ['Verizon Communications'], ['Wal-Mart Stores, Inc.']]; for (var i = 0, l = myData.l...
} else if (record.get("price") < 25) { metaData.style = "background-color:red;"; return '<span style="font-weight:bolder;">' + value + '</span>'; } else { metaData.style = "background-color:blue;"; } return '<span style="font-weight:bolder;color:white;">' + value + '</span>'; } }, { ...
dataIndex : 'company', renderer : function(value, metaData, record, rowIndex, colIndex, store, view) { if (record.get("price") > 50) { metaData.style = "background-color:green;"; return '<span style="font-weight:bolder;">' + value + '</span>';
random_line_split
app.js
var bd = Ext.getBody(), form = false, rec = false, selectedStoreItem = false, //performs the highlight of an item in the bar series selectItem = function(storeItem) { var name = storeItem.get('company'), series = barChart.series.get(0), i, items, l; series.highlight = true; series.unHighlightItem(); serie...
{ if (value > 50) { metaData.style = ""; return '<span style="color:green;font-weight:bolder;">' + Ext.util.Format.number(value, '0.00 %') + '</span>'; } else if (value < 25) { return '<span style="color:red;font-weight:bolder;">' + Ext.util.Format.number(value, '0.00 %') + '</span>'; } return '<span s...
identifier_body
app.js
series.highlight = false; }, //updates a record modified via the form updateRecord = function(rec) { var name, series, i, l, items, json = [{ 'Name' : 'Price', 'Data' : rec.get('price') }, { 'Name' : 'Revenue %', 'Data' : rec.get('revenue %') }, { 'Name' : 'Growth %', 'Data' : rec.get('gro...
{ if (name == items[i].storeItem.get('company')) { selectedStoreItem = items[i].storeItem; series.highlightItem(items[i]); break; } }
conditional_block
app.js
(value, metaData, record, rowIndex, colIndex, store, view) { if (value > 50) { metaData.style = ""; return '<span style="color:green;font-weight:bolder;">' + Ext.util.Format.number(value, '0.00 %') + '</span>'; } else if (value < 25) { return '<span style="color:red;font-weight:bolder;">' + Ext.util.Format...
perc
identifier_name
voice_recognition.py
1.03, -0.50], 'right': [0.08, -1.0, 1.19, 1.94, -0.67, 1.03, 0.50] } } self._collide_lsub = rospy.Subscriber( 'robot/limb/left/collision_avoidance_state', CollisionAvoidanceState, ...
speak('Ready to work!, sir.') Tuck_arms(False)
conditional_block
voice_recognition.py
self._limbs = ('left', 'right') self._arms = { 'left': baxter_interface.Limb('left'), 'right': baxter_interface.Limb('right'), } self._tuck = tuck_cmd self._tuck_rate = rospy.Rate(20.0) # Hz self._tuck_threshold = 0.2 # radians self....
else: rospy.loginfo("Untucking: Arms already Untucked;" " Moving to neutral position.") self._check_arm_state() suppress = deepcopy(self._arm_state['flipped']) actions = {'left': 'untuck', 'right': 'untuck'} ...
actions = {'left': 'untuck', 'right': 'untuck'} self._move_to(actions, suppress) self._done = True return # If arms already untucked, move to neutral location
random_line_split
voice_recognition.py
self._limbs = ('left', 'right') self._arms = { 'left': baxter_interface.Limb('left'), 'right': baxter_interface.Limb('right'), } self._tuck = tuck_cmd self._tuck_rate = rospy.Rate(20.0) # Hz self._tuck_threshold = 0.2 # radians self._...
def _check_arm_state(self): """ Check for goals and behind collision field. If s1 joint is over the peak, collision will need to be disabled to get the arm around the head-arm collision force-field. """ diff_check = lambda a, b: abs(a - b) <= self._tuck_threshold ...
self._arm_state['collide'][limb] = len(data.collision_object) > 0 self._check_arm_state()
identifier_body
voice_recognition.py
{ 'tuck': { 'left': [-1.0, -2.07, 3.0, 2.55, 0.0, 0.01, 0.0], 'right': [1.0, -2.07, -3.0, 2.55, -0.0, 0.01, 0.0] }, 'untuck': { 'left': [-0.08, -1.0, -1.19, 1.94, 0.67, 1.03, -0.50], ...
handler
identifier_name
_criticizer_base.py
.") @property def inputs(self): self.assert_sampled() return self._inputs @property def representations_full(self) -> tfd.Distribution: return self._representations_full @property def latents_full(self) -> tfd.Distribution: return self._representations_full @property def factors_full...
(self, inputs, mask=None, sample_shape=()): r""" Encode inputs to latent codes Arguments: inputs : a single Tensor or list of Tensor Returns: `tensorflow_probability.Distribution`, q(z|x) the latent distribution """ inputs = tf.nest.flatten(inputs)[:len(self._vae.encoder.inputs)] l...
encode
identifier_name
_criticizer_base.py
representations.") @property def inputs(self): self.assert_sampled() return self._inputs @property def representations_full(self) -> tfd.Distribution: return self._representations_full @property def latents_full(self) -> tfd.Distribution: return self._representations_full @property ...
for z in tf.nest.flatten(latents): assert isinstance(z, tfd.Distribution), \ "The latent code return from `vae.encode` must be instance of " + \ "tensorflow_probability.Distribution, but returned: %s" % \ str(z) return latents def decode(self, latents, mask=None, sample_sh...
# only support single returned latent variable now
random_line_split
_criticizer_base.py
.") @property def inputs(self): self.assert_sampled() return self._inputs @property def representations_full(self) -> tfd.Distribution:
@property def latents_full(self) -> tfd.Distribution: return self._representations_full @property def factors_full(self) -> tf.Tensor: return self._factors_full @property def original_factors_full(self) -> tf.Tensor: return self._original_factors_full @property def representations(self)...
return self._representations_full
identifier_body
_criticizer_base.py
# main arguments self._inputs = None self._factors = None self._original_factors = None self._factor_names = None self._representations = None self._reconstructions = None # concatenated train and test self._representations_full = None self._factors_full = None self._origina...
random_state = np.random.RandomState(seed=random_state)
conditional_block
patterns.rs
8..71 'any': fn any<&str>() -> &str 68..73 'any()': &str 74..76 '{}': () 81..100 'if let...y() {}': () 88..89 '1': i32 88..89 '1': i32 92..95 'any': fn any<i32>() -> i32 92..97 'any()': i32 98..100 '{}': () 105..127 'if let...y() {}': () 112..116 '1u32': u32 112..116 '1u32': ...
); } #[test] fn infer_pattern_match_ergonomics() { assert_snapshot!( infer(r#" struct A<T>(T); fn test() { let A(n) = &A(1); let A(n) = &mut A(1); } "#), @r###" 28..79 '{ ...(1); }': () 38..42 'A(n)': A<i32> 40..41 'n': &i32 45..50 '&A(1)': &A<i32> 46..47 'A': A<i3...
{ assert_snapshot!( infer_with_mismatches(r#" fn test(x: &i32) { if let 1..76 = 2u32 {} if let 1..=76 = 2u32 {} } "#, true), @r###" 9..10 'x': &i32 18..76 '{ ...2 {} }': () 24..46 'if let...u32 {}': () 31..36 '1..76': u32 39..43 '2u32': u32 44..46 '{}': () 51....
identifier_body
patterns.rs
8..71 'any': fn any<&str>() -> &str 68..73 'any()': &str 74..76 '{}': () 81..100 'if let...y() {}': () 88..89 '1': i32 88..89 '1': i32 92..95 'any': fn any<i32>() -> i32 92..97 'any()': i32 98..100 '{}': () 105..127 'if let...y() {}': () 112..116 '1u32': u32 112..116 '1u32': ...
() { mark::check!(match_ergonomics_ref); assert_snapshot!( infer(r#" fn test() { let v = &(1, &2); let (_, &w) = v; } "#), @r###" 11..57 '{ ...= v; }': () 21..22 'v': &(i32, &i32) 25..33 '&(1, &2)': &(i32, &i32) 26..33 '(1, &2)': (i32, &i32) 27..28 '1': i32 30..32...
infer_pattern_match_ergonomics_ref
identifier_name
patterns.rs
let (c, d) = (1, "hello"); for (e, f) in some_iter { let g = e; } if let [val] = opt { let h = val; } let lambda = |a: u64, b, c: i32| { a + b; c }; let ref ref_to_x = x; let mut mut_x = x; let ref mut mut_ref_to_x = x; let k = mut_ref_to_x; } "#), @r#...
infer(r#" fn test(x: &i32) { let y = x; let &z = x; let a = z;
random_line_split
dual_encoder.py
(filename, vocab): """ Load glove vectors from a .txt file. Optionally limit the vocabulary to save memory. `vocab` should be a set. """ dct = {} vectors = array.array('d') current_idx = 0 with codecs.open(filename, "r", encoding="utf-8") as f: for _, line in enumerate(f): ...
logits = self.inference() probs = tf.sigmoid(logits, name="probs_op") losses = tf.nn.sigmoid_cross_entropy_with_logits(logits=logits, labels=tf.to_float(self.targets), name="CrossEntropy") mean_loss = tf.reduce_mean(losses, name="Mean_CE_Loss") train_op = tf.contrib.layers.opt...
def __init__(self, hparams): self.hparams = hparams self.global_step = tf.Variable(0, trainable=False, name='global_step') self.learning_rate = tf.train.exponential_decay( self.hparams.learning_rate, # Base learning rate. self.global_step, # Current index into the dat...
identifier_body
dual_encoder.py
VE(filename, vocab): """ Load glove vectors from a .txt file. Optionally limit the vocabulary to save memory. `vocab` should be a set. """ dct = {} vectors = array.array('d') current_idx = 0 with codecs.open(filename, "r", encoding="utf-8") as f: for _, line in enumerate(f): ...
self.hparams.learning_rate, # Base learning rate. self.global_step, # Current index into the dataset. self.hparams.decay_step, # Decay step. self.hparams.decay_rate, # Decay rate. staircase=self.hparams.staircase, name="learning_rate_decay") self....
self.learning_rate = tf.train.exponential_decay(
random_line_split
dual_encoder.py
return [vocab, dct] def loadGLOVE(filename, vocab): """ Load glove vectors from a .txt file. Optionally limit the vocabulary to save memory. `vocab` should be a set. """ dct = {} vectors = array.array('d') current_idx = 0 with codecs.open(filename, "r", encoding="utf-8") as f: ...
dct[word] = idx
conditional_block
dual_encoder.py
vectors = array.array('d') current_idx = 0 with codecs.open(filename, "r", encoding="utf-8") as f: for _, line in enumerate(f): tokens = line.split(" ") word = tokens[0] entries = tokens[1:] if not vocab or word in vocab: dct[word] = curre...
validate
identifier_name
list_view.rs
parent_base_ref = baseref_from_parent(parent); let opts = ListViewOpts::define_ctrl_id(opts); let ctrl_id = opts.ctrl_id; let context_menu = opts.context_menu; let new_self = Self( Arc::new( Obj { base: BaseNativeControl::new(parent_base_ref), opts_id: OptsId::Wnd(opts), events...
match &self.0.opts_id { OptsId::Wnd(opts) => { let mut pos = opts.position; let mut sz = opts.size; multiply_dpi(Some(&mut pos), Some(&mut sz))?; self.0.base.create_window( // may panic "SysListView32", None, pos, sz, opts.ctrl_id, opts.window_ex_style, opts...
|| -> WinResult<()> {
random_line_split
list_view.rs
let parent_base_ref = baseref_from_parent(parent); let opts = ListViewOpts::define_ctrl_id(opts); let ctrl_id = opts.ctrl_id; let context_menu = opts.context_menu; let new_self = Self( Arc::new( Obj { base: BaseNativeControl::new(parent_base_ref), opts_id: OptsId::Wnd(opts), ev...
(&self, set: bool, ex_style: co::LVS_EX) { self.hwnd().SendMessage(lvm::SetExtendedListViewStyle { mask: ex_style, style: if set { ex_style } else { co::LVS_EX::NoValue }, }); } fn show_context_menu(&self, follow_cursor: bool, has_ctrl: bool, has_shift: bool) -> WinResult<()> { let hmenu = m...
toggle_extended_style
identifier_name
list_view.rs
.unwrap_or_else(|err| PostQuitMessage(err)); } else if lvnk.wVKey == co::VK::APPS { // context menu key me.show_context_menu(false, has_ctrl, has_shift).unwrap(); } None } }); parent_base_ref.privileged_events_ref().add_nfy(ctrl_id, co::NM::RCLICK.into(), { let me = self.clone(); ...
{ self.ctrl_id = auto_ctrl_id(); }
conditional_block
main.rs
32, String) { let mut score = 0; let mut mutations = "".to_string(); let mut n = 1; for (i, j) in seq1.chars().zip(seq2.chars()) { if i != j { score += 1; if score == 1 { mutations = mutations + &format!("{}{}", n, i); } else { ...
() { let args : Vec<String> = env::args().collect(); let file1 = fastq::Reader::from_file(&args[1]).unwrap(); let file2 = fastq::Reader::from_file(&args[2]).unwrap(); let mut num_records = 0; let mut num_duplicates = 0; let mut num_qual_skip = 0; let mut results : HashMap<String, (String, ...
main
identifier_name
main.rs
// distance += 1; // } // } // else { // distance += 1; // } // index += 1; // } // (distance, dif) // } fn hamming(seq1: &str, seq2: &str) -> u32 { let mut score = 0; for (i, j) in seq1.chars().zip(seq2.chars()) { if i != ...
// if i != j { // dif.push((index, i, j));
random_line_split
main.rs
fn ham_mutations(seq1: &str, seq2: &str) -> (u32, String) { let mut score = 0; let mut mutations = "".to_string(); let mut n = 1; for (i, j) in seq1.chars().zip(seq2.chars()) { if i != j { score += 1; if score == 1 { mutations = mutations + &format!("{}...
{ let mut score = 0; for (i, j) in seq1.chars().zip(seq2.chars()) { if i != j { score += 1; } } score }
identifier_body
get.go
]string Vars []string } // Clone clones the config options func (co *ConfigOptions) Clone() (*ConfigOptions, error) { out, err := yaml.Marshal(co) if err != nil { return nil, err } newCo := &ConfigOptions{} err = yaml.Unmarshal(out, newCo) if err != nil { return nil, err } return newCo, nil } // ...
{ cwd, err := os.Getwd() if err != nil { return false, err } originalCwd := cwd homedir, err := homedir.Dir() if err != nil { return false, err } lastLength := 0 for len(cwd) != lastLength { if cwd != homedir { configExists := configExistsInPath(cwd) if configExists { // Change working direct...
identifier_body
get.go
, newCo) if err != nil { return nil, err } return newCo, nil } // GetBaseConfig returns the config func GetBaseConfig(options *ConfigOptions) (*latest.Config, error) { return loadConfigOnce(options, false) } // GetConfig returns the config merged with all potential overwrite files func GetConfig(options *Confi...
{ configExists := configExistsInPath(cwd) if configExists { // Change working directory err = os.Chdir(cwd) if err != nil { return false, err } // Notify user that we are not using the current working directory if originalCwd != cwd { log.Infof("Using devspace config in %s", fil...
conditional_block
get.go
var getConfigOnce sync.Once var getConfigOnceErr error var getConfigOnceMutex sync.Mutex // ConfigExists checks whether the yaml file for the config exists or the configs.yaml exists func ConfigExists() bool { return configExistsInPath(".") } // configExistsInPath checks wheter a devspace configuration exists at a ...
(generatedConfig *generated.Config, basePath string, options *ConfigOptions, log log.Logger) (*latest.Config, error) { if options == nil { options = &ConfigOptions{} } configPath := filepath.Join(basePath, constants.DefaultConfigPath) // Check devspace.yaml _, err := os.Stat(configPath) if err != nil { // C...
GetConfigFromPath
identifier_name
get.go
var getConfigOnce sync.Once var getConfigOnceErr error var getConfigOnceMutex sync.Mutex // ConfigExists checks whether the yaml file for the config exists or the configs.yaml exists func ConfigExists() bool { return configExistsInPath(".") } // configExistsInPath checks wheter a devspace configuration exists at a ...
if err != nil { return nil, err } rawMap := map[interface{}]interface{}{} err = yaml.Unmarshal(fileContent, &rawMap) if err != nil { return nil, err } return rawMap, nil } // GetConfigFromPath loads the config from a given base path func GetConfigFromPath(generatedConfig *generated.Config, basePath string...
func GetRawConfig(configPath string) (map[interface{}]interface{}, error) { fileContent, err := ioutil.ReadFile(configPath)
random_line_split
charm.py
ATION_NAME = "legend-db" LEGEND_GITLAB_RELATION_NAME = "legend-sdlc-gitlab" LEGEND_STUDIO_RELATION_NAME = "legend-sdlc" SDLC_SERVICE_URL_FORMAT = "%(schema)s://%(host)s:%(port)s%(path)s" SDLC_CONFIG_FILE_CONTAINER_LOCAL_PATH = "/sdlc-config.yaml" SDLC_MAIN_GITLAB_REDIRECT_URL = "%(base_url)s/auth/callback" SDLC_GITLAB...
legend_db_uri = legend_db_credentials["uri"] legend_db = legend_db_credentials["database"] # Check gitlab-related options: gitlab_project_visibility = GITLAB_PROJECT_VISIBILITY_PRIVATE if self.model.config["gitlab-create-new-projects-as-public"]: gitlab_project_visi...
return model.WaitingStatus("no legend db info present in relation yet")
conditional_block
charm.py
j/login/callback", ] TRUSTSTORE_PASSPHRASE = "Legend SDLC" TRUSTSTORE_CONTAINER_LOCAL_PATH = "/truststore.jks" APPLICATION_CONNECTOR_PORT_HTTP = 7070 APPLICATION_ADMIN_CONNECTOR_PORT_HTTP = 7076 APPLICATION_ROOT_PATH = "/api" APPLICATION_LOGGING_FORMAT = "%d{yyyy-MM-dd HH:mm:ss.SSS} %-5p [%thread] %c - %m%n" GITLAB...
_on_studio_relation_joined
identifier_name
charm.py
_RELATION_NAME = "legend-db" LEGEND_GITLAB_RELATION_NAME = "legend-sdlc-gitlab" LEGEND_STUDIO_RELATION_NAME = "legend-sdlc" SDLC_SERVICE_URL_FORMAT = "%(schema)s://%(host)s:%(port)s%(path)s" SDLC_CONFIG_FILE_CONTAINER_LOCAL_PATH = "/sdlc-config.yaml" SDLC_MAIN_GITLAB_REDIRECT_URL = "%(base_url)s/auth/callback" SDLC_GI...
def _get_workload_service_names(cls): return [SDLC_SERVICE_NAME] @classmethod def _get_workload_pebble_layers(cls): return { "sdlc": { "summary": "SDLC layer.", "description": "Pebble config layer for FINOS Legend SDLC.", "services...
random_line_split
charm.py
ATION_NAME = "legend-db" LEGEND_GITLAB_RELATION_NAME = "legend-sdlc-gitlab" LEGEND_STUDIO_RELATION_NAME = "legend-sdlc" SDLC_SERVICE_URL_FORMAT = "%(schema)s://%(host)s:%(port)s%(path)s" SDLC_CONFIG_FILE_CONTAINER_LOCAL_PATH = "/sdlc-config.yaml" SDLC_MAIN_GITLAB_REDIRECT_URL = "%(base_url)s/auth/callback" SDLC_GITLAB...
def _get_sdlc_service_url(self): ip_address = legend_operator_base.get_ip_address() return SDLC_SERVICE_URL_FORMAT % ( { # NOTE(aznashwan): we always return the plain HTTP endpoint: "schema": "http", "host": ip_address, "p...
return LEGEND_DB_RELATION_NAME
identifier_body
run_test.go
Conn) sshAgent.Add(key) } func removeKeyfromSSHAgent(key ssh.PublicKey) { aConn, _ := net.Dial("unix", sshAgentSocket) sshAgent := agent.NewClient(aConn) sshAgent.Remove(key) } func startSSHServer() { done := make(chan bool, 1) go func(done chan<- bool) { glssh.Handle(func(s glssh.Session) { authorizedKey ...
t.Errorf("Value received: %v expected %v", returned, tt.expected) }
conditional_block
run_test.go
aConn, _ := net.Dial("unix", sshAgentSocket) sshAgent := agent.NewClient(aConn) sshAgent.Remove(key) } func startSSHServer() { done := make(chan bool, 1) go func(done chan<- bool) { glssh.Handle(func(s glssh.Session) { authorizedKey := ssh.MarshalAuthorizedKey(s.PublicKey()) io.WriteString(s, fmt.Sprintf(...
}
random_line_split
run_test.go
[string]ssh.PublicKey sshAgentSocket string ) func init() { var err error n := len(testdata.PEMBytes) testSigners = make(map[string]ssh.Signer, n) testPrivateKeys = make(map[string]interface{}, n) testPublicKeys = make(map[string]ssh.PublicKey, n) for t, k := range testdata.PEMBytes { testPrivateKeys[t], e...
t *testing.T) { tests := []struct { name string key mockSSHKey expected ssh.Signer }{ {name: "Basic key signer with valid rsa key", key: mockSSHKey{ keyname: "/tmp/mockkey", content: testdata.PEMBytes["rsa"], }, expected: testSigners["rsa"], }, {name: "Basic key signer with valid...
estMakeSigner(
identifier_name
run_test.go
(func(ctx glssh.Context, key glssh.PublicKey) bool { for _, pubk := range testPublicKeys { if glssh.KeysEqual(key, pubk) { return true } } return false }) fmt.Println("starting ssh server on port 2222...") done <- true panic(glssh.ListenAndServe(":2222", nil, publicKeyOption)) }(done) <...
tests := []struct { name string id string }{ {name: "Teardown SSH Agent", id: "sshAgentTdown"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if tt.id == "sshAgentTdown" { os.Remove(sshAgentSocket) } }) } }
identifier_body
main.rs
window::WindowBuilder::new() .with_title("starframe test") .with_inner_size(winit::dpi::LogicalSize { width: 800.0, height: 600.0, }), ); let state = State::init(&game.renderer.device); game.run(state); microprofile::shutdown!(); } //...
{ graph: graph::Graph, l_pose: graph::Layer<m::Pose>, l_collider: graph::Layer<phys::Collider>, l_body: graph::Layer<phys::RigidBody>, l_shape: graph::Layer<gx::Shape>, l_player: graph::Layer<player::Player>, l_evt_sink: sf::event::EventSinkLayer<MyGraph>, } impl MyGraph { pub fn new() ...
MyGraph
identifier_name
main.rs
window::WindowBuilder::new() .with_title("starframe test") .with_inner_size(winit::dpi::LogicalSize { width: 800.0, height: 600.0, }), ); let state = State::init(&game.renderer.device); game.run(state); microprofile::shutdown!(); } //...
distr::Uniform::from(-5.0..5.0).sample(&mut rng), distr::Uniform::from(-5.0..5.0).sample(&mut rng), ] }; let mut rng = rand::thread_rng(); if game.input.is_key_pressed(Key::S, Some(0)) { Recipe::DynamicBlock(recipes::Block { ...
let random_vel = || { let mut rng = rand::thread_rng(); [
random_line_split
main.rs
{ #[clap(long)] labels: bool, #[clap(long)] statement_counts: bool, #[clap(short, long, default_value = "0")] skip: u64, #[clap(short, long)] threads: Option<usize>, #[clap(required = true)] paths: Vec<String>, } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum Extra<'a> {...
Opts
identifier_name
main.rs
.get(7) .map(|lang| Extra::Lang(lang.as_str())) .or_else(|| { captures .get(8) .map(|data_type| Extra::Type(data_type.as_str())) }) .unwrap_or(Extra::None); Obj...
} }, _ => { panic!("invalid escape {}{} at {} in {}", c, c2, idx, s); } }); continue; } }; } res.push(c); ...
}, 'U' => match parse_unicode(&mut chars, 8) { Ok(c3) => c3, Err(err) => { panic!("invalid escape {}{} at {} in {}: {}", c, c2, idx, s, err);
random_line_split
main.rs
continue; } }; } res.push(c); } res } fn parse_unicode<I>(chars: &mut I, count: usize) -> Result<char, String> where I: Iterator<Item = (usize, char)>, { let unicode_seq: String = chars.take(count).map(|(_, c)| c).collect(); u32::from_str_radix(&unico...
{ let dir = env!("CARGO_MANIFEST_DIR"); let mut in_path = PathBuf::from(dir); in_path.push("test.in.rdf"); let in_path = in_path.as_os_str().to_str().unwrap(); let mut out_path = PathBuf::from(dir); out_path.push("test.out.rdf"); let out_path = out_path.as_os_st...
identifier_body
lease_status.pb.go
i = encodeVarintLeaseStatus(dAtA, i, uint64(m.Lease.Size())) n1, err := m.Lease.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n1 dAtA[i] = 0x12 i++ i = encodeVarintLeaseStatus(dAtA, i, uint64(m.Timestamp.Size())) n2, err := m.Timestamp.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += ...
var l int _ = l dAtA[i] = 0xa i++
random_line_split
lease_status.pb.go
() (dAtA []byte, err error) { size := m.Size() dAtA = make([]byte, size) n, err := m.MarshalTo(dAtA) if err != nil { return nil, err } return dAtA[:n], nil } func (m *LeaseStatus) MarshalTo(dAtA []byte) (int, error) { var i int _ = i var l int _ = l dAtA[i] = 0xa i++ i = encodeVarintLeaseStatus(dAtA, i,...
Marshal
identifier_name
lease_status.pb.go
.Size())) n2, err := m.Timestamp.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 if m.State != 0 { dAtA[i] = 0x18 i++ i = encodeVarintLeaseStatus(dAtA, i, uint64(m.State)) } if m.Liveness != nil { dAtA[i] = 0x22 i++ i = encodeVarintLeaseStatus(dAtA, i, uint64(m.Liveness.Size())) n3, e...
b := dAtA[iNdEx] iNdEx++ length |= (int(b) & 0x7F) << shift if b < 0x80 { break } } iNdEx += length if length < 0 { return 0, ErrInvalidLengthLeaseStatus } return iNdEx, nil case
{ return 0, io.ErrUnexpectedEOF }
conditional_block
lease_status.pb.go
.Size())) n2, err := m.Timestamp.MarshalTo(dAtA[i:]) if err != nil { return 0, err } i += n2 if m.State != 0 { dAtA[i] = 0x18 i++ i = encodeVarintLeaseStatus(dAtA, i, uint64(m.State)) } if m.Liveness != nil { dAtA[i] = 0x22 i++ i = encodeVarintLeaseStatus(dAtA, i, uint64(m.Liveness.Size())) n3, e...
fieldNum := int32(wire >> 3) wireType := int(wire & 0x7) if wireType == 4 { return fmt.Errorf("proto: LeaseStatus: wiretype end group for non-group") } if fieldNum <= 0 { return fmt.Errorf("proto: LeaseStatus: illegal tag %d (wire type %d)", fieldNum, wire) } switch fieldNum { case 1: if wireTy...
{ l := len(dAtA) iNdEx := 0 for iNdEx < l { preIndex := iNdEx var wire uint64 for shift := uint(0); ; shift += 7 { if shift >= 64 { return ErrIntOverflowLeaseStatus } if iNdEx >= l { return io.ErrUnexpectedEOF } b := dAtA[iNdEx] iNdEx++ wire |= (uint64(b) & 0x7F) << shift if b <...
identifier_body
writer.rs
(&mut self, arch: Arch) { self.arch = arch; } /// Sets the debug identifier of this SymCache. pub fn set_debug_id(&mut self, debug_id: DebugId) { self.debug_id = debug_id; } // Methods processing symbolic-debuginfo [`ObjectLike`] below: // Feel free to move these to a separate ...
set_arch
identifier_name
writer.rs
let mut callee_call_locations = Vec::new(); // Iterate over the line records. while let Some(line) = next_line.take() { let line_range_start = line.address as u32; let line_range_end = (line.address + line.size.unwrap_or(1)) as u32; // Find the call location...
let mut writer = Writer::new(writer); // Insert a trailing sentinel source location in case we have a definite end addr if let Some(last_addr) = self.last_addr { // TODO: to be extra safe, we might check that `last_addr` is indeed larger than // the largest range at some...
identifier_body
writer.rs
#[tracing::instrument(skip_all, fields(object.debug_id = %object.debug_id().breakpad()))] pub fn process_object<'d, 'o, O>(&mut self, object: &'o O) -> Result<(), Error> where O: ObjectLike<'d, 'o>, O::Error: std::error::Error + Send + Sync + 'static, { let session = object ...
let language = function.name.language(); let mut function = transform::Function { name: function.name.as_str().into(), comp_dir: comp_dir.map(Into::into), }; for transformer in &mut self.transformers.0 { function = transform...
} else { function.address as u32 }; let function_idx = {
random_line_split
CAPM_ab.py
def get_indexReturns(self): index = self.Sindex # The index ind_ret = self.pf.symbols[index].TDs[self.period].get_timeSeriesReturn() return ind_ret def get_indexMeanReturn(self): ind_ret = self.get_indexReturns() ind_ret = np.mean(ind_ret) return ind_ret def get_symbol_ab(self, ...
if (type(symbol_index) == type(-1)): # If we are given nothing or a number # We just stablish the first one symbol_index = self.pf.symbols.keys()[0] self.Sindex = symbol_index
identifier_body
CAPM_ab.py
self.get_indexReturns() ind_ret = np.mean(ind_ret) return ind_ret def get_symbol_ab(self, symbol): ## This function outputs the alpha beta a symbol index = self.Sindex # The index sym_ret = self.pf.symbols[symbol].TDs[self.period].get_timeSeriesReturn() ind_ret = self.get_indexReturns() ...
hist, bin_edges = np.histogram(residual, density=True) gl.bar(bin_edges[:-1], hist, labels = ["Distribution","Return", "Probability"], legend = [symbol], alpha = 0.5, nf = nf) ## Lets get some statistics using stats m, v, s, k = stats.t.stats(10, moments...
random_line_split
CAPM_ab.py
self.Sindex = symbol_index def get_indexReturns(self): index = self.Sindex # The index ind_ret = self.pf.symbols[index].TDs[self.period].get_timeSeriesReturn() return ind_ret def get_indexMeanReturn(self): ind_ret = self.get_indexReturns() ind_ret = np.mean(ind_ret) retu...
symbol_index = self.pf.symbols.keys()[0]
conditional_block
CAPM_ab.py
self.get_indexReturns() ind_ret = np.mean(ind_ret) return ind_ret def get_symbol_ab(self, symbol): ## This function outputs the alpha beta a symbol index = self.Sindex # The index sym_ret = self.pf.symbols[symbol].TDs[self.period].get_timeSeriesReturn() ind_ret = self.get_indexReturns() ...
(self,symbol, nf = 1): ## This function tests that the residuals behaves properly. ## That is, that the alpha (how we behave compared to the market) ## has a nice gaussian distribution. ## Slide 7 index = self.Sindex # The index sym_ret = self.pf.symbols[symbol].TDs[self.period].get_timeSerie...
test_symbol_ab
identifier_name
TableauViz.js
url, options); } function exportPDF() { viz.showExportPDFDialog(); $('.tab-dialog')[0].animate({ 'marginLeft': "-=50px" }); } function exportData() { viz.showExportDataDialog(); } function resetViz() { viz.revertAllAsync(); } function showVizButtons() { var sheets = workbook.getPublishedSheetsI...
var fixedCloseLabel = ""; var changeFromPriorClose = 0; var changeFromPriorCloseLabel = ""; var date = ""; for (var markIndex = 0; markIndex < marks.length; markIndex++) { //getPairs gets tuples of data for the mark. one mark has multiple tuples var pair...
// If selection has been cleared, no need to show a message if (marks.length == 0) { $('#eventBox').hide(600); return; } // Save selected marks in memory so they can be submitted later selectedMarks = marks; $('#eventPanel').html(""); $('#eventBox').show(600); // Logi...
identifier_body
TableauViz.js
url, options); } function exportPDF() { viz.showExportPDFDialog(); $('.tab-dialog')[0].animate({ 'marginLeft': "-=50px" }); } function exportData() { viz.showExportDataDialog(); } function resetViz() { viz.revertAllAsync(); } function showVizButtons() { var sheets = workbook.getPublishedSheetsI...
{ // Adjust UI: Hide Buttons & navigation menu, increase size for edit mode $('#VizToolbar').hide(); $('body').addClass("sidebar-collapse"); $(".content-wrapper").css("height","1200px"); $("#tableauViz").hide(); // If the URL happens to have a ticket on it, clean it up before loading the edit...
unch_edit()
identifier_name
TableauViz.js
Filters</button>'); divIndividualButtons.append('<button type="button" onclick="exportPDF()" class="btn btn-primary" style="min-width:135px; margin-right: 5px; margin-top: 5px;">Export PDF</button>'); divIndividualButtons.append('<button type="button" onclick="exportData()" class="btn btn-primary" style="min-w...
url_parts = url.split('#/site/'); url = url_parts[0] + "t/" + url_parts[1]; vizUrlForWebEdit = url; console.log("URL updated in iframe_change: " + url); }
conditional_block
TableauViz.js
function exportPDF() { viz.showExportPDFDialog(); $('.tab-dialog')[0].animate({ 'marginLeft': "-=50px" }); } function exportData() { viz.showExportDataDialog(); } function resetViz() { viz.revertAllAsync(); } function showVizButtons() { var sheets = workbook.getPublishedSheetsInfo(); var divI...
viz = new tableau.Viz(placeholderDiv, url, options); }
random_line_split
__init__.py
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import six __author__ = 'xepa4ep, a@toukmanov.ru' import re from ..exceptions import Error, RequiredArgumentIsNotPassed, MethodDoesNotExist from ..rules.contexts import Value, ContextNotFound from ..rules.case import DummyCase f...
return options['escape'] return True def escape_if_needed(text, options): """ Escape string if it needed Agrs: text (string): text to escape options (dict): tranlation options (if key safe is True - do not escape) Returns: text """ if hasattr(...
if 'escape' in options:
random_line_split
__init__.py
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import six __author__ = 'xepa4ep, a@toukmanov.ru' import re from ..exceptions import Error, RequiredArgumentIsNotPassed, MethodDoesNotExist from ..rules.contexts import Value, ContextNotFound from ..rules.case import DummyCase f...
@classmethod def validate(cls, text, language): m = cls.IS_TOKEN.match(text) if m: return MethodToken(m.group(1), m.group(2)) class RulesToken(AbstractVariableToken): """ Token which execute some rules on variable {count|token, tokens}: count = 1 -> token ...
""" Fetch variable""" return super(VariableToken, self).fetch(data)
identifier_body
__init__.py
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import six __author__ = 'xepa4ep, a@toukmanov.ru' import re from ..exceptions import Error, RequiredArgumentIsNotPassed, MethodDoesNotExist from ..rules.contexts import Value, ContextNotFound from ..rules.case import DummyCase f...
if text[0] != '{': return TextToken(text) def __str__(self): return "TextToken[%s]" % self.text class AbstractVariableToken(AbstractToken): IS_VARIABLE = '([\$\d\w]+)' IS_METHOD = '([\$\d\w])' REGEXP_TOKEN = '^\{%s\}$' def __init__(self, name): self.name = n...
return TextToken(text)
conditional_block
__init__.py
OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import absolute_import import six __author__ = 'xepa4ep, a@toukmanov.ru' import re from ..exceptions import Error, RequiredArgumentIsNotPassed, MethodDoesNotExist from ..rules.contexts import Value, ContextNotFound from ..rules.case import DummyCase f...
(RulesMethodToken): IS_TOKEN = re.compile(AbstractVariableToken.REGEXP_TOKEN % ( AbstractVariableToken.IS_VARIABLE + MethodToken.HAS_METHOD + '\:\:(.*)')) def __init__(self, name, method_name, case, language): self.token = MethodToken(name, method_name) self.case = language.cases.get(st...
CaseMethodToken
identifier_name
FindPoints.py
point[1]<150: continue if point[0]>(height-150): continue if point[1]>(width-150): continue temp_centers.append(point) min_distance = 300 cgroup = [] ## Average centers that...
if match==[]: #new_group.append(point) top, bottom, left, right = control_edge(point, dim, dim) try: npoint = local_Kmeans(mask[top:bottom,left:right])[0] npoint = local_center_of_mass(mask[top:bottom,left:right]) except: ...
match = centre
conditional_block
FindPoints.py
<min_distance: cgroup = [tcenter, tcenter2] min_distance = dist if cgroup==[]: for tcenter in temp_centers: centers.append(tcenter) else: ncenter = findCentre(cgroup) centers.appe...
top, bottom, left, right = control_edge(point, dim, dim) img = img[top:bottom,left:right] labmask = LABMaskImage(img) hsvmask = HSVMaskImage(img) mask = combinemasks(labmask, hsvmask) blackpixels = np.where(mask==0) blackpixels = np.matrix(blackpixels) return blackpixels.shape[1]
identifier_body
FindPoints.py
(filename, mask, potsize=500): f = open(filename) centers = [] for line in f: info = line.split(" ")[2:] center = info[2] center = center.split(",") center[0] = int(round(float(center[0]))) center[1] = int(round(float(center[1]))) center = center[::-1] ...
loadcenters
identifier_name
FindPoints.py
center = info[2] center = center.split(",") center[0] = int(round(float(center[0]))) center[1] = int(round(float(center[1]))) center = center[::-1] if center[0]<150 or center[1]<150: print "Centre on the edge, and will therefore be removed" contin...
centers = [] for line in f: info = line.split(" ")[2:]
random_line_split
provider_validation.go
_, pc := range mod.ProviderConfigs { name := providerName(pc.Name, pc.Alias) // Validate the config against an empty schema to see if it's empty. _, pcConfigDiags := pc.Config.Content(&hcl.BodySchema{}) if pcConfigDiags.HasErrors() || pc.Version.Required != nil { configured[name] = pc.DeclRange } else { ...
if !(localName || configAlias || emptyConfig) { // we still allow default configs, so switch to a warning if the incoming provider is a default if providerAddr.Provider.IsDefault() { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagWarning, Summary: "Reference to undefined provider", ...
_, emptyConfig := emptyConfigs[name]
random_line_split
provider_validation.go
// those providers will have a configuration at runtime. This way we can // direct users where to add the missing configuration, because the runtime // error is only "missing provider X". for _, modCall := range mod.ModuleCalls { for _, passed := range modCall.Providers { // aliased providers are handled more s...
{ if sourceAddr.Equals(parentAddr.Provider) { otherLocalName = localName break } }
conditional_block
provider_validation.go
providerAddr.Provider.ForDisplay(), name, name, ), Subject: &parentCall.DeclRange, }) } // You cannot pass in a provider that cannot be used for name, passed := range passedIn { childTy := passed.InChild.providerType // get a default type if there was none set if childTy.IsZero() { // This mean...
{ if alias != "" { name = name + "." + alias } return name }
identifier_body
provider_validation.go
(parentCall *ModuleCall, cfg *Config, noProviderConfigRange *hcl.Range) (diags hcl.Diagnostics) { mod := cfg.Module for name, child := range cfg.Children { mc := mod.ModuleCalls[name] childNoProviderConfigRange := noProviderConfigRange // if the module call has any of count, for_each or depends_on, // provid...
validateProviderConfigs
identifier_name
sup.rs
(no_version)] Status { /// A package identifier (ex: core/redis, core/busybox-static/1.42.2) #[structopt(name = "PKG_IDENT")] pkg_ident: Option<PackageIdent>, #[structopt(flatten)] remote_sup: RemoteSup, }, /// Gracefully terminate the Habitat Supervisor and all of i...
(#[serde(with = "serde_string")] NatsAddress); impl fmt::Display for EventStreamAddress { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl FromStr for EventStreamAddress { type Err = RantsError; fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(EventStreamAdd...
EventStreamAddress
identifier_name
sup.rs
(no_version)] Status { /// A package identifier (ex: core/redis, core/busybox-static/1.42.2) #[structopt(name = "PKG_IDENT")] pkg_ident: Option<PackageIdent>, #[structopt(flatten)] remote_sup: RemoteSup, }, /// Gracefully terminate the Habitat Supervisor and all of i...
/// run --ring myring) #[structopt(name = "RING", long = "ring", short = "r", env = RING_ENVVAR, conflicts_with = "RING_KEY")] ring: String, /// The contents of the ring key when running with wire encryption. (Note: This option is /// e...
#[structopt(flatten)] cache_key_path: CacheKeyPath, /// The name of the ring used by the Supervisor when running with wire encryption. (ex: hab sup
random_line_split
texture.rs
Interaction, dstdx: &mut Vector2f, dstdy: &mut Vector2f) -> Point2f { let st = self.sphere(&si.p); // Compute texture coordinate differentials for sphere (u, v) mapping let delta = 0.1; let st_deltax = self.sphere(&(si.p + si.dpdx.get() * delta)); *dstdx = (st_deltax ...
{ -v }
conditional_block
texture.rs
ay = self.cylinder(&(si.p + si.dpdy.get() * delta)); *dstdy = (st_deltay - st) / delta; // Handle sphere mapping discontinuity for coordinate differentials if dstdx[1] > 0.5 { dstdx[1] = 1.0 - dstdx[1]; } else if (*dstdx)[1] < -0.5 { (*dstdx)[1] = -((*dstdx)[1] + 1.0); } if dstd...
smooth_step(0.3, 0.7, npartial), 0.2, noisep(*p * lambda).abs());
random_line_split