query
large_stringlengths
4
15k
positive
large_stringlengths
5
289k
source
stringclasses
6 values
update a record via table api, kparams being the dict of PUT params to update. returns a SnowRecord obj.
def update(self,table, sys_id, **kparams): """ update a record via table api, kparams being the dict of PUT params to update. returns a SnowRecord obj. """ record = self.api.update(table, sys_id, **kparams) return record
csn
private void dumpMEtoMEConversations(final IncidentStream is) { if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.entry(this, tc, "dumpMEtoMEConversations", is); final ServerConnectionManager scm = ServerConnectionManager.getRef(); final List obc = scm.getActiveOutboundMEtoMEConversations(); is.writeLine("", ""); is.writeLine("\n------ ME to ME Conversation Dump ------ ", ">"); if (obc != null) { //Build a map of connection -> conversation so that we can output the //connection information once per set of conversations. final Map<Object, LinkedList<Conversation>> connectionToConversationMap = convertToMap(is, obc); //Go through the map and dump out a connection -
followed by its conversations for (final Iterator<Entry<Object,LinkedList<Conversation>>>i = connectionToConversationMap.entrySet().iterator(); i.hasNext();) { final Entry<Object, LinkedList<Conversation>>entry = i.next(); is.writeLine("\nOutbound connection:", entry.getKey()); final LinkedList conversationList = entry.getValue(); while(!conversationList.isEmpty()) { final Conversation c = (Conversation)conversationList.removeFirst(); is.writeLine("\nOutbound Conversation[" + c.getId() + "]: ", c.getFullSummary()); try { dumpMEtoMEConversation(is, c); } catch(Throwable t) { // No FFDC Code Needed is.writeLine("\nUnable to dump conversation", t); } } } } if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) SibTr.exit(this, tc, "dumpMEtoMEConversations"); }
csn_ccr
Calculates the maximum depth of the program tree.
def _depth(self): """Calculates the maximum depth of the program tree.""" terminals = [0] depth = 1 for node in self.program: if isinstance(node, _Function): terminals.append(node.arity) depth = max(len(terminals), depth) else: terminals[-1] -= 1 while terminals[-1] == 0: terminals.pop() terminals[-1] -= 1 return depth - 1
csn
def lock(self, session): """Lock the connection, ensuring that it is not busy and storing a weakref for the session. :param queries.Session session: The session to lock the connection with :raises: ConnectionBusyError """ if self.busy:
raise ConnectionBusyError(self) with self._lock: self.used_by = weakref.ref(session) LOGGER.debug('Connection %s locked', self.id)
csn_ccr
private function getModelId(EnvironmentInterface $environment) { $inputProvider = $environment->getInputProvider(); if ($inputProvider->hasParameter('id') && $inputProvider->getParameter('id')) { $modelId = ModelId::fromSerialized($inputProvider->getParameter('id')); } if (!(isset($modelId)
&& ($environment->getDataDefinition()->getName() === $modelId->getDataProviderName())) ) { return null; } return $modelId; }
csn_ccr
tieBreak method which will kick in when the comparator list generated an equality result for both sides. the tieBreak method will try best to make sure a stable result is returned.
protected boolean tieBreak(final T object1, final T object2) { if (null == object2) { return true; } if (null == object1) { return false; } return object1.hashCode() >= object2.hashCode(); }
csn
func signalReorg(d ReorgData) { if nodeClient == nil { log.Errorf("The daemon RPC client for signalReorg is not configured!") return } // Determine the common ancestor of the two chains, and get the full // list of blocks in each chain back to but not including the common // ancestor. ancestor, newChain, oldChain, err := rpcutils.CommonAncestor(nodeClient, d.NewChainHead, d.OldChainHead) if err != nil { log.Errorf("Failed to determine common ancestor. Aborting reorg.") return } fullData := &txhelpers.ReorgData{ CommonAncestor: *ancestor, NewChain: newChain, NewChainHead: d.NewChainHead, NewChainHeight: d.NewChainHeight, OldChain: oldChain, OldChainHead: d.OldChainHead, OldChainHeight: d.OldChainHeight, WG: d.WG, } // Send reorg data to stakedb's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanStakeDB <- fullData: default: d.WG.Done() } d.WG.Wait() // Send reorg data to dcrsqlite's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanWiredDB <- fullData:
default: d.WG.Done() } // Send reorg data to blockdata's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanBlockData <- fullData: default: d.WG.Done() } // Send reorg data to ChainDB's monitor. d.WG.Add(1) select { case NtfnChans.ReorgChanDcrpgDB <- fullData: default: d.WG.Done() } d.WG.Wait() // Ensure all the other chain reorgs are successful before initiating the // charts cache reorg. Send common ancestor reorg data to charts cache monitor. d.WG.Add(1) select { case NtfnChans.ReorgChartsCache <- fullData: default: d.WG.Done() } d.WG.Wait() // Update prevHash and prevHeight in collectionQueue. blockQueue.SetPreviousBlock(d.NewChainHead, int64(d.NewChainHeight)) }
csn_ccr
Return a sound playback callback. Parameters ---------- resampler The resampler from which samples are read. samplerate : float The sample rate. params : dict Parameters for FM generation.
def get_playback_callback(resampler, samplerate, params): """Return a sound playback callback. Parameters ---------- resampler The resampler from which samples are read. samplerate : float The sample rate. params : dict Parameters for FM generation. """ def callback(outdata, frames, time, _): """Playback callback. Read samples from the resampler and modulate them onto a carrier frequency. """ last_fmphase = getattr(callback, 'last_fmphase', 0) df = params['fm_gain'] * resampler.read(frames) df = np.pad(df, (0, frames - len(df)), mode='constant') t = time.outputBufferDacTime + np.arange(frames) / samplerate phase = 2 * np.pi * params['carrier_frequency'] * t fmphase = last_fmphase + 2 * np.pi * np.cumsum(df) / samplerate outdata[:, 0] = params['output_volume'] * np.cos(phase + fmphase) callback.last_fmphase = fmphase[-1] return callback
csn
def store_groups_in_session(sender, user, request, **kwargs): """ When a user logs in, fetch its groups and store them in the users session. This is required by ws4redis, since fetching groups accesses the database, which is a blocking operation and thus not
allowed from within the websocket loop. """ if hasattr(user, 'groups'): request.session['ws4redis:memberof'] = [g.name for g in user.groups.all()]
csn_ccr
private ServletHandler configureHandler(String servletClassName) { ServletHandler handler = new ServletHandler();
handler.addServletWithMapping(servletClassName, "/*"); return handler; }
csn_ccr
Reserves the given number of bytes to spill. If more than the maximum, throws an exception. @throws ExceededSpillLimitException
public synchronized ListenableFuture<?> reserve(long bytes) { checkArgument(bytes >= 0, "bytes is negative"); if ((currentBytes + bytes) >= maxBytes) { throw exceededLocalLimit(succinctBytes(maxBytes)); } currentBytes += bytes; return NOT_BLOCKED; }
csn
Stateless intermediate ops from LongStream
@Override public final DoubleStream asDoubleStream() { return new DoublePipeline.StatelessOp<Long>(this, StreamShape.LONG_VALUE, StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) { @Override public Sink<Long> opWrapSink(int flags, Sink<Double> sink) { return new Sink.ChainedLong<Double>(sink) { @Override public void accept(long t) { downstream.accept((double) t); } }; } }; }
csn
def run(xmin, ymin, xmax, ymax, step, range_, range_x, range_y, t): X,Y = t.shape pt = np.zeros((X,Y)) "omp parallel for" for i in range(X): for j in range(Y): for k in t: tmp = 6368.* np.arccos(
np.cos(xmin+step*i)*np.cos( k[0] ) * np.cos((ymin+step*j)-k[1])+ np.sin(xmin+step*i)*np.sin(k[0])) if tmp < range_: pt[i][j]+=k[2] / (1+tmp) return pt
csn_ccr
def merged(self, other): """Returns the merged result of two requirements. Two requirements can be in conflict and if so, this function returns None. For example, requests for "foo-4" and "foo-6" are in conflict, since both cannot be satisfied with a single version of foo. Some example successful requirements merges are: - "foo-3+" and "!foo-5+" == "foo-3+<5" - "foo-1" and "foo-1.5" == "foo-1.5" - "!foo-2" and "!foo-5" == "!foo-2|5" """ if self.name_ != other.name_: return None # cannot merge across object names def _r(r_): r = Requirement(None) r.name_ = r_.name_ r.negate_ = r_.negate_ r.conflict_ = r_.conflict_ r.sep_ = r_.sep_ return r if self.range is None: return other elif other.range is None: return self elif self.conflict: if other.conflict: r = _r(self) r.range_ = self.range_ | other.range_ r.negate_ = (self.negate_ and other.negate_ and not r.range_.is_any()) return r else: range_ = other.range - self.range if range_ is None: return None
else: r = _r(other) r.range_ = range_ return r elif other.conflict: range_ = self.range_ - other.range_ if range_ is None: return None else: r = _r(self) r.range_ = range_ return r else: range_ = self.range_ & other.range_ if range_ is None: return None else: r = _r(self) r.range_ = range_ return r
csn_ccr
// MakeRequest initiates a request to the remote host, returning a response and // possible error.
func (c Client) MakeRequest(req Request) (Response, error) { if req.AcceptableStatusCodes == nil { panic("acceptable status codes for this request were not set") } request, err := c.buildRequest(req) if err != nil { return Response{}, err } var resp *http.Response transport := buildTransport(c.config.SkipVerifySSL) if req.DoNotFollowRedirects { resp, err = transport.RoundTrip(request) } else { client := &http.Client{Transport: transport} resp, err = client.Do(request) } if err != nil { return Response{}, newRequestHTTPError(err) } defer resp.Body.Close() responseBody, err := ioutil.ReadAll(resp.Body) if err != nil { return Response{}, newResponseReadError(err) } return c.handleResponse(req, Response{ Code: resp.StatusCode, Body: responseBody, Headers: resp.Header, }) }
csn
public static String resolveFunction(String functionString, TestContext context) { String functionExpression = VariableUtils.cutOffVariablesPrefix(functionString); if (!functionExpression.contains("(") || !functionExpression.endsWith(")") || !functionExpression.contains(":")) { throw new InvalidFunctionUsageException("Unable to resolve function: " + functionExpression); } String functionPrefix = functionExpression.substring(0, functionExpression.indexOf(':') + 1); String parameterString = functionExpression.substring(functionExpression.indexOf('(') + 1, functionExpression.length() - 1); String function = functionExpression.substring(functionPrefix.length(), functionExpression.indexOf('('));
FunctionLibrary library = context.getFunctionRegistry().getLibraryForPrefix(functionPrefix); parameterString = VariableUtils.replaceVariablesInString(parameterString, context, false); parameterString = replaceFunctionsInString(parameterString, context); String value = library.getFunction(function).execute(FunctionParameterHelper.getParameterList(parameterString), context); if (value == null) { return ""; } else { return value; } }
csn_ccr
public function groups() { if ($this->groups === null) { $ident = $this->ident(); $metadata = $this->adminSecondaryMenu(); $this->groups = []; if (isset($metadata[$ident]['groups'])) { $groups = $metadata[$ident]['groups'];
if (is_array($groups)) { $this->setGroups($groups); } } } return $this->groups; }
csn_ccr
protected function _compile($part, ValueBinder $generator) { if ($part instanceof ExpressionInterface) { $part = $part->sql($generator); } elseif (is_array($part)) { $placeholder = $generator->placeholder('param');
$generator->bind($placeholder, $part['value'], $part['type']); $part = $placeholder; } return $part; }
csn_ccr
public JBBPTextWriter Byte(final byte[] array, int off, int len) throws IOException { ensureValueMode();
while (len-- > 0) { Byte(array[off++]); } return this; }
csn_ccr
Parses all settings form the main configuration file. @param root The root element of the configuration.
private final void parseSettings (final Element root) { if (root == null) { throw new NullPointerException(); } clear(); parseGlobalSettings(root); parseTargetSpecificSettings(root); }
csn
Initialmethode, wird aufgerufen um den internen Zustand des Objektes zu setzten. @param fld Function Libraries zum validieren der Funktionen @param cfml CFML Code der transfomiert werden soll.
protected Data init(Data data) { if (JSON_ARRAY == null) JSON_ARRAY = getFLF(data, "_literalArray"); if (JSON_STRUCT == null) JSON_STRUCT = getFLF(data, "_literalStruct"); if (GET_STATIC_SCOPE == null) GET_STATIC_SCOPE = getFLF(data, "_getStaticScope"); if (GET_SUPER_STATIC_SCOPE == null) GET_SUPER_STATIC_SCOPE = getFLF(data, "_getSuperStaticScope"); return data; }
csn
please add timezone info to timestamps python
def parse_timestamp(timestamp): """Parse ISO8601 timestamps given by github API.""" dt = dateutil.parser.parse(timestamp) return dt.astimezone(dateutil.tz.tzutc())
cosqa
// arePodVolumesBound returns true if all volumes are fully bound
func (b *volumeBinder) arePodVolumesBound(pod *v1.Pod) bool { for _, vol := range pod.Spec.Volumes { if isBound, _, _ := b.isVolumeBound(pod.Namespace, &vol); !isBound { // Pod has at least one PVC that needs binding return false } } return true }
csn
// signMessage signs the given message with the private key for the given // address
func signMessage(icmd interface{}, w *wallet.Wallet) (interface{}, error) { cmd := icmd.(*btcjson.SignMessageCmd) addr, err := decodeAddress(cmd.Address, w.ChainParams()) if err != nil { return nil, err } privKey, err := w.PrivKeyForAddress(addr) if err != nil { return nil, err } var buf bytes.Buffer wire.WriteVarString(&buf, 0, "Bitcoin Signed Message:\n") wire.WriteVarString(&buf, 0, cmd.Message) messageHash := chainhash.DoubleHashB(buf.Bytes()) sigbytes, err := btcec.SignCompact(btcec.S256(), privKey, messageHash, true) if err != nil { return nil, err } return base64.StdEncoding.EncodeToString(sigbytes), nil }
csn
Sets configuration options from raw DirectAdmin data. @param UserContext $context Owning user context @param array $config An array of settings
private function setConfig(UserContext $context, array $config) { $this->domainName = $config['domain']; // Determine owner if ($config['username'] === $context->getUsername()) { $this->owner = $context->getContextUser(); } else { throw new DirectAdminException('Could not determine relationship between context user and domain'); } // Parse plain options $bandwidths = array_map('trim', explode('/', $config['bandwidth'])); $this->bandwidthUsed = floatval($bandwidths[0]); $this->bandwidthLimit = !isset($bandwidths[1]) || ctype_alpha($bandwidths[1]) ? null : floatval($bandwidths[1]); $this->diskUsage = floatval($config['quota']); $this->aliases = array_filter(explode('|', $config['alias_pointers'])); $this->pointers = array_filter(explode('|', $config['pointers'])); }
csn
public Geometry createGeometry(Geometry geometry) { if (geometry instanceof Point) { return createPoint(geometry.getCoordinate()); } else if (geometry instanceof LinearRing) { return createLinearRing(geometry.getCoordinates()); } else if (geometry instanceof LineString) { return createLineString(geometry.getCoordinates()); } else if (geometry instanceof Polygon) { Polygon polygon = (Polygon) geometry; LinearRing exteriorRing = createLinearRing(polygon.getExteriorRing().getCoordinates()); LinearRing[] interiorRings = new LinearRing[polygon.getNumInteriorRing()]; for (int n = 0; n < polygon.getNumInteriorRing(); n++) { interiorRings[n] = createLinearRing(polygon.getInteriorRingN(n).getCoordinates()); } return new Polygon(srid, precision, exteriorRing, interiorRings); } else if (geometry instanceof MultiPoint) { Point[] clones = new Point[geometry.getNumGeometries()]; for (int n = 0; n < geometry.getNumGeometries(); n++) { clones[n] = createPoint(geometry.getGeometryN(n).getCoordinate()); } return new MultiPoint(srid, precision, clones); } else if (geometry instanceof MultiLineString) {
LineString[] clones = new LineString[geometry.getNumGeometries()]; for (int n = 0; n < geometry.getNumGeometries(); n++) { clones[n] = createLineString(geometry.getGeometryN(n).getCoordinates()); } return new MultiLineString(srid, precision, clones); } else if (geometry instanceof MultiPolygon) { Polygon[] clones = new Polygon[geometry.getNumGeometries()]; for (int n = 0; n < geometry.getNumGeometries(); n++) { clones[n] = (Polygon) createGeometry(geometry.getGeometryN(n)); } return new MultiPolygon(srid, precision, clones); } return null; }
csn_ccr
// startListening on the network addresses
func startListening(host p2phost.Host, cfg *config.Config) error { listenAddrs, err := listenAddresses(cfg) if err != nil { return err } // Actually start listening: if err := host.Network().Listen(listenAddrs...); err != nil { return err } // list out our addresses addrs, err := host.Network().InterfaceListenAddresses() if err != nil { return err } log.Infof("Swarm listening at: %s", addrs) return nil }
csn
Reads a single byte from the input stream.
private int read() { int curByte = 0; try { curByte = rawData.get() & 0xFF; } catch (Exception e) { header.status = GifDecoder.STATUS_FORMAT_ERROR; } return curByte; }
csn
Resolve services, factories, callables by given token @param string $name @return mixed
public function tokenResolve($name) { if(strpos($name, 'self.callable') === 0) $name = str_replace('self.callable.', 'callable.', $name); if(strpos($name, 'self.factory') === 0) $name = str_replace('self.factory.', 'factory.', $name); switch($name) { case 'self': return $this; break; default: $split = explode('.', $name, 2); if(isset($split[1])) { switch($split[0]) { case 'self': return $this->{$split[1]}; break; case 'service': return $this->get($split[1]); break; case 'factory': return $this->create($split[1]); break; case 'callable': return $this->__call($split[1]); break; default: return $this->{$arg}; break; } } else { return $this->get($name); } break; } }
csn
This is a private message handler method. It is a message handler for analog messages. :param data: message data :returns: None - but saves the data in the pins structure
async def _analog_message(self, data): """ This is a private message handler method. It is a message handler for analog messages. :param data: message data :returns: None - but saves the data in the pins structure """ pin = data[0] value = (data[PrivateConstants.MSB] << 7) + data[PrivateConstants.LSB] # if self.analog_pins[pin].current_value != value: self.analog_pins[pin].current_value = value # append pin number, pin value, and pin type to return value and return as a list message = [pin, value, Constants.ANALOG] if self.analog_pins[pin].cb: if self.analog_pins[pin].cb_type: await self.analog_pins[pin].cb(message) else: loop = self.loop loop.call_soon(self.analog_pins[pin].cb, message) # is there a latch entry for this pin? key = 'A' + str(pin) if key in self.latch_map: await self._check_latch_data(key, message[1])
csn
Eighth-grader Vova is on duty today in the class. After classes, he went into the office to wash the board, and found on it the number n. He asked what is this number and the teacher of mathematics Inna Petrovna answered Vova that n is the answer to the arithmetic task for first-graders. In the textbook, a certain positive integer x was given. The task was to add x to the sum of the digits of the number x written in decimal numeral system. Since the number n on the board was small, Vova quickly guessed which x could be in the textbook. Now he wants to get a program which will search for arbitrary values of the number n for all suitable values of x or determine that such x does not exist. Write such a program for Vova. -----Input----- The first line contains integer n (1 ≤ n ≤ 10^9). -----Output----- In the first line print one integer k — number of different values of x satisfying the condition. In next k lines print these values in ascending order. -----Examples----- Input 21 Output 1 15 Input 20 Output 0 -----Note----- In the first test case x = 15 there is only one variant: 15 + 1 + 5 = 21. In the second test case there are no such x.
n=int(input()) q=[] for i in range(max(0,n-100),n+1): j=i res=i while j: res+=j%10 j//=10 if res==n: q.append(i) print(len(q)) for i in q: print(i)
apps
Show device model.
def get_device_model(self) -> str: '''Show device model.''' output, _ = self._execute( '-s', self.device_sn, 'shell', 'getprop', 'ro.product.model') return output.strip()
csn
public void writeit(String strTemp) { String strTabs = ""; int i = 0; for (i = 0; i < m_iTabs; i++) { strTabs += "\t"; } if (m_bTabOnNextLine) if ((strTemp.length() > 0) && (strTemp.charAt(0) != '\n')) strTemp = strTabs + strTemp; m_bTabOnNextLine = false; int iIndex = 0; int iIndex2; while (iIndex != -1) { iIndex = strTemp.indexOf('\n', iIndex); if ((iIndex != -1) && (iIndex < strTemp.length() - 1)) { iIndex2 = iIndex + 1; if (iIndex > 1) if (strTemp.charAt(iIndex) == '\r') iIndex--; strTemp = strTemp.substring(0, iIndex+1) + strTabs + strTemp.substring(iIndex2, strTemp.length()); iIndex = iIndex + 2; } else
iIndex = -1; } iIndex = 0; while (iIndex != -1) { iIndex = strTemp.indexOf('\r', iIndex); if (iIndex != -1) strTemp = strTemp.substring(0, iIndex) + strTemp.substring(iIndex + 1, strTemp.length()); } strTemp = this.tabsToSpaces(strTemp); this.print(strTemp); if (strTemp.length() > 0) if (strTemp.charAt(strTemp.length() - 1) == '\n'); m_bTabOnNextLine = true; }
csn_ccr
function getPropertyValue(obj, path, useGetter) { // if (arguments.length < 3) { // useGetter = false; // } path = path.trim(); if (path === undefined || path.length === 0) { throw new Error("Invalid field path: '" + path + "'"); } // if (obj === undefined || obj === null) { // throw new Error("Undefined target object"); // } var paths = null, m = null, p = null; if (path.indexOf('.') > 0) { paths = path.split('.'); for(var i = 0; i < paths.length; i++) { p = paths[i]; if (obj !== undefined && obj !== null && ((useGetter === true && (m = getPropertyGetter(obj, p))) || obj.hasOwnProperty(p))) {
if (useGetter === true && m !== null) { obj = m.call(obj); } else { obj = obj[p]; } } else { return undefined; } } } else if (path === '*') { var res = {}; for (var k in obj) { if (k[0] !== '$' && obj.hasOwnProperty(k)) { res[k] = getPropertyValue(obj, k, useGetter === true); } } return res; } else { if (useGetter === true) { m = getPropertyGetter(obj, path); if (m !== null) { return m.call(obj); } } if (obj.hasOwnProperty(path) === true) { obj = obj[path]; } else { return undefined; } } // detect object value factory if (obj !== null && obj !== undefined && obj.$new !== undefined) { return obj.$new(); } else { return obj; } }
csn_ccr
public void setSelectionType(MaterialDatePickerType selectionType) { this.selectionType = selectionType; switch (selectionType) { case MONTH_DAY: options.selectMonths = true; break; case YEAR_MONTH_DAY: options.selectYears = yearsToDisplay; options.selectMonths = true;
break; case YEAR: options.selectYears = yearsToDisplay; options.selectMonths = false; break; } }
csn_ccr
// CloseDevTools closes the dev tools
func (w *Window) CloseDevTools() (err error) { if err = w.isActionable(); err != nil { return } return w.w.write(Event{Name: EventNameWindowCmdWebContentsCloseDevTools, TargetID: w.id}) }
csn
public static String encodeECC200(String codewords, SymbolInfo symbolInfo) { if (codewords.length() != symbolInfo.getDataCapacity()) { throw new IllegalArgumentException( "The number of codewords does not match the selected symbol"); } StringBuilder sb = new StringBuilder(symbolInfo.getDataCapacity() + symbolInfo.getErrorCodewords()); sb.append(codewords); int blockCount = symbolInfo.getInterleavedBlockCount(); if (blockCount == 1) { String ecc = createECCBlock(codewords, symbolInfo.getErrorCodewords()); sb.append(ecc); } else { sb.setLength(sb.capacity()); int[] dataSizes = new int[blockCount]; int[] errorSizes = new int[blockCount]; for (int i = 0; i < blockCount; i++) { dataSizes[i] = symbolInfo.getDataLengthForInterleavedBlock(i + 1); errorSizes[i] = symbolInfo.getErrorLengthForInterleavedBlock(i + 1); }
for (int block = 0; block < blockCount; block++) { StringBuilder temp = new StringBuilder(dataSizes[block]); for (int d = block; d < symbolInfo.getDataCapacity(); d += blockCount) { temp.append(codewords.charAt(d)); } String ecc = createECCBlock(temp.toString(), errorSizes[block]); int pos = 0; for (int e = block; e < errorSizes[block] * blockCount; e += blockCount) { sb.setCharAt(symbolInfo.getDataCapacity() + e, ecc.charAt(pos++)); } } } return sb.toString(); }
csn_ccr
public static ImageRequestBuilder fromRequest(ImageRequest imageRequest) { return ImageRequestBuilder.newBuilderWithSource(imageRequest.getSourceUri()) .setImageDecodeOptions(imageRequest.getImageDecodeOptions()) .setBytesRange(imageRequest.getBytesRange()) .setCacheChoice(imageRequest.getCacheChoice()) .setLocalThumbnailPreviewsEnabled(imageRequest.getLocalThumbnailPreviewsEnabled())
.setLowestPermittedRequestLevel(imageRequest.getLowestPermittedRequestLevel()) .setPostprocessor(imageRequest.getPostprocessor()) .setProgressiveRenderingEnabled(imageRequest.getProgressiveRenderingEnabled()) .setRequestPriority(imageRequest.getPriority()) .setResizeOptions(imageRequest.getResizeOptions()) .setRequestListener(imageRequest.getRequestListener()) .setRotationOptions(imageRequest.getRotationOptions()) .setShouldDecodePrefetches(imageRequest.shouldDecodePrefetches()); }
csn_ccr
Populate data from this array as if it was in local file data. @param data an array of bytes @param offset the start offset @param length the number of bytes in the array from offset @since 1.1 @throws ZipException on error
public void parseFromLocalFileData(byte[] data, int offset, int length) throws ZipException { long givenChecksum = ZipLong.getValue(data, offset); byte[] tmp = new byte[length - WORD]; System.arraycopy(data, offset + WORD, tmp, 0, length - WORD); crc.reset(); crc.update(tmp); long realChecksum = crc.getValue(); if (givenChecksum != realChecksum) { throw new ZipException("bad CRC checksum " + Long.toHexString(givenChecksum) + " instead of " + Long.toHexString(realChecksum)); } int newMode = ZipShort.getValue(tmp, 0); // CheckStyle:MagicNumber OFF byte[] linkArray = new byte[(int) ZipLong.getValue(tmp, 2)]; uid = ZipShort.getValue(tmp, 6); gid = ZipShort.getValue(tmp, 8); if (linkArray.length == 0) { link = ""; } else { System.arraycopy(tmp, 10, linkArray, 0, linkArray.length); link = new String(linkArray); // Uses default charset - see class Javadoc } // CheckStyle:MagicNumber ON setDirectory((newMode & DIR_FLAG) != 0); setMode(newMode); }
csn
private function okToDelete(PhingFile $d) { $list = $d->listDir(); if ($list === null) { return false; // maybe io error? } foreach ($list as $s) {
$f = new PhingFile($d, $s); if ($f->isDirectory()) { if (!$this->okToDelete($f)) { return false; } } else { // found a file return false; } } return true; }
csn_ccr
def update_feature_value(host_name, client_name, client_pass, user_twitter_id, feature_name, feature_score): """ Updates a single topic score, for a single user. Inputs: - host_name: A string containing the address of the machine where the PServer instance is hosted. - client_name: The PServer client name. - client_pass: The PServer client's password. - user_twitter_id: A Twitter user identifier. - feature_name: A specific PServer feature name. - feature_score: The corresponding score. """ username = str(user_twitter_id) feature_value = "{0:.2f}".format(feature_score) joined_ftr_value = "ftr_" + feature_name + "=" + str(feature_value) values = "usr=%s&%s" % (username, joined_ftr_value) # Construct
request. request = construct_request(model_type="pers", client_name=client_name, client_pass=client_pass, command="setusr", values=values) # Send request. send_request(host_name, request)
csn_ccr
function normalizeOptions(options, include) { _.forEach(options, function (v,k) { if(!_.contains(include, k))
delete options[k]; }); return options; }
csn_ccr
"I don't have any fancy quotes." - vijju123 Chef was reading some quotes by great people. Now, he is interested in classifying all the fancy quotes he knows. He thinks that all fancy quotes which contain the word "not" are Real Fancy; quotes that do not contain it are regularly fancy. You are given some quotes. For each quote, you need to tell Chef if it is Real Fancy or just regularly fancy. -----Input----- - The first line of the input contains a single integer $T$ denoting the number of test cases. The description of $T$ test cases follows. - The first and only line of each test case contains a single string $S$ denoting a quote. -----Output----- For each test case, print a single line containing the string "Real Fancy" or "regularly fancy" (without quotes). -----Constraints----- - $1 \le T \le 50$ - $1 \le |S| \le 100$ - each character of $S$ is either a lowercase English letter or a space -----Subtasks----- Subtask #1 (100 points): original constraints -----Example Input----- 2 i do not have any fancy quotes when nothing goes right go left -----Example Output----- Real Fancy regularly fancy -----Explanation----- Example case 1: "i do not have any fancy quotes" Example case 2: The word "not" does not appear in the given quote.
# cook your dish here import re t=int(input()) while(t>0): s=list(input().split(' ')) if("not" in s): print("Real Fancy") else: print("regularly fancy") t=t-1
apps
public function get_admin_config() { if ($this->adminconfig) { return $this->adminconfig; }
$this->adminconfig = get_config('assign'); return $this->adminconfig; }
csn_ccr
public static function get($refundId) { $api = new Api\Info(); $api->setRefundId($refundId); $result = $api->doRequest();
$result['refundId'] = $refundId; return new Result\Refund($result); }
csn_ccr
def on(cls, event, handler_func=None): """ Registers a handler function whenever an instance of the model emits the given event. This method can either called directly, passing a function reference: MyModel.on('did_save', my_function) ...or as a decorator of the function to be registered. @MyModel.on('did_save') def myfunction(my_model): pass
""" if handler_func: cls.handler_registrar().register(event, handler_func) return def register(fn): cls.handler_registrar().register(event, fn) return fn return register
csn_ccr
2) Returns CredentialEmailModel @param Request $request @return CredentialEmailModel
public function getCredentials(Request $request) { $post = json_decode($request->getContent(), true); return new CredentialEmailModel($post[self::EMAIL_FIELD], $post[self::PASSWORD_FIELD]); }
csn
// AllowMissingKeys allows a caller to specify whether they want an error if a field or map key // cannot be located, or simply an empty result. The receiver is returned for chaining.
func (j *JSONPath) AllowMissingKeys(allow bool) *JSONPath { j.allowMissingKeys = allow return j }
csn
channel user prefixes
def _parse_PREFIX(value): "channel user prefixes" channel_modes, channel_chars = value.split(')') channel_modes = channel_modes[1:] return collections.OrderedDict(zip(channel_chars, channel_modes))
csn
Sets and prepares the rows. The rows are stored in groups in a dictionary. A group is a list of rows with the same pseudo key. The key in the dictionary is a tuple with the values of the pseudo key. :param list[dict] rows: The rows
def prepare_data(self, rows): """ Sets and prepares the rows. The rows are stored in groups in a dictionary. A group is a list of rows with the same pseudo key. The key in the dictionary is a tuple with the values of the pseudo key. :param list[dict] rows: The rows """ self._rows = dict() for row in copy.copy(rows) if self.copy else rows: pseudo_key = self._get_pseudo_key(row) if pseudo_key not in self._rows: self._rows[pseudo_key] = list() self._rows[pseudo_key].append(row) # Convert begin and end dates to integers. self._date_type = None for pseudo_key, rows in self._rows.items(): self._rows_date2int(rows)
csn
func pushCommit(ref *github.Reference, tree *github.Tree) (err error) { // Get the parent commit to attach the commit to. parent, _, err := client.Repositories.GetCommit(ctx, *sourceOwner, *sourceRepo, *ref.Object.SHA) if err != nil { return err } // This is not always populated, but is needed. parent.Commit.SHA = parent.SHA // Create the commit using the
tree. date := time.Now() author := &github.CommitAuthor{Date: &date, Name: authorName, Email: authorEmail} commit := &github.Commit{Author: author, Message: commitMessage, Tree: tree, Parents: []github.Commit{*parent.Commit}} newCommit, _, err := client.Git.CreateCommit(ctx, *sourceOwner, *sourceRepo, commit) if err != nil { return err } // Attach the commit to the master branch. ref.Object.SHA = newCommit.SHA _, _, err = client.Git.UpdateRef(ctx, *sourceOwner, *sourceRepo, ref, false) return err }
csn_ccr
function createErrorHandler(opts, transform) { return err => { if ('emit' === opts.error) { transform.emit('error', err) } else if ('function' === typeof opts.error) { opts.error(err) } else { const message = colors.red(err.name) + '\n' + err.toString()
.replace(/(ParseError.*)/, colors.red('$1')) log(message) } transform.emit('end') if (opts.callback) { opts.callback(through2()) } } }
csn_ccr
// UpdateIngressStatus updates an Ingress with a provided status.
func (c *clientWrapper) UpdateIngressStatus(namespace, name, ip, hostname string) error { if !c.isWatchedNamespace(namespace) { return fmt.Errorf("failed to get ingress %s/%s: namespace is not within watched namespaces", namespace, name) } ing, err := c.factoriesKube[c.lookupNamespace(namespace)].Extensions().V1beta1().Ingresses().Lister().Ingresses(namespace).Get(name) if err != nil { return fmt.Errorf("failed to get ingress %s/%s: %v", namespace, name, err) } if len(ing.Status.LoadBalancer.Ingress) > 0 { if ing.Status.LoadBalancer.Ingress[0].Hostname == hostname && ing.Status.LoadBalancer.Ingress[0].IP == ip { // If status is already set, skip update log.Debugf("Skipping status update on ingress %s/%s", ing.Namespace, ing.Name) return nil } } ingCopy := ing.DeepCopy() ingCopy.Status = extensionsv1beta1.IngressStatus{LoadBalancer: corev1.LoadBalancerStatus{Ingress: []corev1.LoadBalancerIngress{{IP: ip, Hostname: hostname}}}} _, err = c.csKube.ExtensionsV1beta1().Ingresses(ingCopy.Namespace).UpdateStatus(ingCopy) if err != nil { return fmt.Errorf("failed to update ingress status %s/%s: %v", namespace, name, err) } log.Infof("Updated status on ingress %s/%s", namespace, name) return nil }
csn
// LogURIs returns the URIs of all logs currently in the logCache
func (c *logCache) LogURIs() []string { c.RLock() defer c.RUnlock() var uris []string for _, l := range c.logs { uris = append(uris, l.uri) } return uris }
csn
Compute a set of summary metrics from the input value expression Parameters ---------- arg : value expression exact_nunique : boolean, default False Compute the exact number of distinct values (slower) prefix : string, default None String prefix for metric names Returns ------- summary : (count, # nulls, nunique)
def _generic_summary(arg, exact_nunique=False, prefix=None): """ Compute a set of summary metrics from the input value expression Parameters ---------- arg : value expression exact_nunique : boolean, default False Compute the exact number of distinct values (slower) prefix : string, default None String prefix for metric names Returns ------- summary : (count, # nulls, nunique) """ metrics = [arg.count(), arg.isnull().sum().name('nulls')] if exact_nunique: unique_metric = arg.nunique().name('uniques') else: unique_metric = arg.approx_nunique().name('uniques') metrics.append(unique_metric) return _wrap_summary_metrics(metrics, prefix)
csn
public function prevUrl() { $prev = $this->current() -
1; return ($prev > 0 && $prev < $this->pages()) ? $this->parseUrl($prev) : ""; }
csn_ccr
func (b byTime) Less(i, j int) bool { if b[i].Next.IsZero() { return false } if b[j].Next.IsZero() {
return true } return b[i].Next.Before(b[j].Next) }
csn_ccr
function drawTurnInfo(pdata) { var my_game = $.cookie("game"); var my_player = pdata[$.cookie("player")]; $(PIECES).empty(); $(ADDPIECE).show(); // allow player to end his turn if (my_player.has_turn) { $(ENDTURN).removeAttr('disabled'); $(TURN).html("It's your turn! You have " + "<span id='countdown'>0m 0s</span> left."); $(ENDTURN)[0].onclick = function() { $.post("/games/" + enc(my_game) + "/players", {end_turn: true}, function() {
getPlayers(); /* Typically we let HAVETURN get updated from the server * in onGetPlayers(), but if there is only one player this * doesn't work very well (the player has to refresh manually). * So we force it to false here in this special case. */ if (Object.keys(pdata).length === 1) { HAVETURN = false; clearTimeout(COUNTDOWNTID); } }); }; } else { $(ENDTURN).attr('disabled', ''); $(TURN).html("It's not your turn."); } getPiecesLeft(); getBoard(); getMyPieces(my_player); }
csn_ccr
func Col(text string, colType ColumnType) Column { return
Column{Text: text, Type: colType} }
csn_ccr
@SuppressWarnings("unchecked") public <T> T convertElement(ConversionContext context, Object source, TypeReference<T> destinationType) throws ConverterException {
return (T) elementConverter.convert(context, source, destinationType); }
csn_ccr
Call `load` method with `centerings` filtered to keys in `self.filter_`.
def load(self, df, centerings): """Call `load` method with `centerings` filtered to keys in `self.filter_`.""" return super().load( df, {key: value for key, value in centerings.items() if key in self.filter_} )
csn
def register_on_medium_changed(self, callback): """Set the callback function to consume on medium changed events. Callback receives a IMediumChangedEvent
object. Returns the callback_id """ event_type = library.VBoxEventType.on_medium_changed return self.event_source.register_callback(callback, event_type)
csn_ccr
python compress leading whitespace
def clean_whitespace(string, compact=False): """Return string with compressed whitespace.""" for a, b in (('\r\n', '\n'), ('\r', '\n'), ('\n\n', '\n'), ('\t', ' '), (' ', ' ')): string = string.replace(a, b) if compact: for a, b in (('\n', ' '), ('[ ', '['), (' ', ' '), (' ', ' '), (' ', ' ')): string = string.replace(a, b) return string.strip()
cosqa
Serialize additionalProperties to JSON @param JsonSerializationVisitor $visitor Visitor @param SchemaAdditionalProperties $additionalProperties properties @param array $type Type @param Context $context Context @return string|null
public function serializeSchemaAdditionalPropertiesToJson( JsonSerializationVisitor $visitor, SchemaAdditionalProperties $additionalProperties, array $type, Context $context ) { $properties = $additionalProperties->getProperties(); // case for v4 schema if (is_bool($properties)) { return $visitor->visitBoolean($properties, [], $context); } // case for schema inside additionalProperties, swagger exclusive if ($properties instanceof Schema) { return $visitor->getNavigator()->accept( $properties, ['name' => 'Graviton\SchemaBundle\Document\Schema'], $context ); } }
csn
// Release implements util.Releaser. // It also close the file if it is an io.Closer.
func (r *Reader) Release() { r.mu.Lock() defer r.mu.Unlock() if closer, ok := r.reader.(io.Closer); ok { closer.Close() } if r.indexBlock != nil { r.indexBlock.Release() r.indexBlock = nil } if r.filterBlock != nil { r.filterBlock.Release() r.filterBlock = nil } r.reader = nil r.cache = nil r.bpool = nil r.err = ErrReaderReleased }
csn
public static void store(Explanation<OWLAxiom> explanation, OutputStream os) throws IOException { try { OWLOntologyManager manager = OWLManager.createOWLOntologyManager(); OWLOntology ontology = manager.createOntology(explanation.getAxioms()); OWLDataFactory df = manager.getOWLDataFactory(); OWLAnnotationProperty entailmentMarkerAnnotationProperty = df.getOWLAnnotationProperty(ENTAILMENT_MARKER_IRI); OWLAnnotation entailmentAnnotation = df.getOWLAnnotation(entailmentMarkerAnnotationProperty, df.getOWLLiteral(true)); OWLAxiom annotatedEntailment = explanation.getEntailment().getAnnotatedAxiom(Collections.singleton(entailmentAnnotation)); manager.addAxiom(ontology, annotatedEntailment);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(os); OWLXMLDocumentFormat justificationOntologyFormat = new OWLXMLDocumentFormat(); manager.saveOntology(ontology, justificationOntologyFormat, bufferedOutputStream); } catch (OWLOntologyStorageException | OWLOntologyCreationException e) { throw new RuntimeException(e); } }
csn_ccr
def _issubclass_Union_rec(subclass, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check): """Helper for _issubclass_Union. """ # this function is partly based on code from typing module 3.5.2.2 super_args = get_Union_params(superclass) if super_args is None: return is_Union(subclass) elif is_Union(subclass): sub_args = get_Union_params(subclass) if sub_args is None: return False return all(_issubclass(c, superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) \ for c in (sub_args)) elif isinstance(subclass, TypeVar): if subclass in super_args:
return True if subclass.__constraints__: return _issubclass(Union[subclass.__constraints__], superclass, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) return False else: return any(_issubclass(subclass, t, bound_Generic, bound_typevars, bound_typevars_readonly, follow_fwd_refs, _recursion_check) \ for t in super_args)
csn_ccr
Get a ResponsiveImageClass by it's name @param string $classname @return ResponsiveImageClass
public function getClass($classname) { if ((string) $classname == '' || !array_key_exists($classname, $this->classes)) { throw new ImageClassNotRegisteredException($classname); } return $this->classes[$classname]; }
csn
An helper method to build and throw a SQL Exception when a property cannot be set. @param cause the cause @param theType the type of the property @param value the value of the property @throws SQLException the SQL Exception
public static void throwSQLException(Exception cause, String theType, String value) throws SQLException { throw new SQLException("Invalid " + theType + " value: " + value, cause); }
csn
Your company, [Congo Pizza](http://interesting-africa-facts.com/Africa-Landforms/Congo-Rainforest-Facts.html), is the second-largest online frozen pizza retailer. You own a number of international warehouses that you use to store your frozen pizzas, and you need to figure out how many crates of pizzas you can store at each location. Congo recently standardized its storage containers: all pizzas fit inside a *cubic crate, 16-inchs on a side*. The crates are super tough so you can stack them as high as you want. Write a function `box_capacity()` that figures out how many crates you can store in a given warehouse. The function should take three arguments: the length, width, and height of your warehouse (in feet) and should return an integer representing the number of boxes you can store in that space. For example: a warehouse 32 feet long, 64 feet wide, and 16 feet high can hold 13,824 boxes because you can fit 24 boxes across, 48 boxes deep, and 12 boxes high, so `box_capacity(32, 64, 16)` should return `13824`.
def box_capacity(length, width, height): return (length * 12 // 16) * (width * 12 // 16) * (height * 12 // 16)
apps
Synchronize between the file in the file system and the field record
def sync(self, force=None): """Synchronize between the file in the file system and the field record""" try: if force: sd = force else: sd = self.sync_dir() if sd == self.SYNC_DIR.FILE_TO_RECORD: if force and not self.exists(): return None self.fs_to_record() elif sd == self.SYNC_DIR.RECORD_TO_FILE: self.record_to_fs() else: return None self._dataset.config.sync[self.file_const][sd] = time.time() return sd except Exception as e: self._bundle.rollback() self._bundle.error("Failed to sync '{}': {}".format(self.file_const, e)) raise
csn
protected function getDividend($row) { $currentValue = $row->getColumn($this->columnValueToRead); // if the site this is for doesn't support ecommerce & this is for the revenue_evolution column, // we don't add the new column if ($currentValue === false && $this->isRevenueEvolution && !Site::isEcommerceEnabledFor($row->getColumn('label')) ) { return false; } $pastRow =
$this->getPastRowFromCurrent($row); if ($pastRow) { $pastValue = $pastRow->getColumn($this->columnValueToRead); } else { $pastValue = 0; } return $currentValue - $pastValue; }
csn_ccr
computing distance matrix in python
def get_distance_matrix(x): """Get distance matrix given a matrix. Used in testing.""" square = nd.sum(x ** 2.0, axis=1, keepdims=True) distance_square = square + square.transpose() - (2.0 * nd.dot(x, x.transpose())) return nd.sqrt(distance_square)
cosqa
Loads all data for zones that belong to provided layout.
public function loadLayoutZonesData(Layout $layout): array { $query = $this->getZoneSelectQuery(); $query->where( $query->expr()->eq('layout_id', ':layout_id') ) ->setParameter('layout_id', $layout->id, Type::INTEGER) ->orderBy('identifier', 'ASC'); $this->applyStatusCondition($query, $layout->status); return $query->execute()->fetchAll(PDO::FETCH_ASSOC); }
csn
func (c *Chunk) NumRows() int { if c.NumCols() == 0 {
return c.numVirtualRows } return c.columns[0].length }
csn_ccr
int size() { int res = m_subscriptions.size(); for (TreeNode child : m_children) { res
+= child.size(); } return res; }
csn_ccr
func (_class PBDClass) GetSR(sessionID SessionRef, self PBDRef) (_retval SRRef, _err error) { _method := "PBD.get_SR" _sessionIDArg, _err := convertSessionRefToXen(fmt.Sprintf("%s(%s)", _method, "session_id"), sessionID) if
_err != nil { return } _selfArg, _err := convertPBDRefToXen(fmt.Sprintf("%s(%s)", _method, "self"), self) if _err != nil { return } _result, _err := _class.client.APICall(_method, _sessionIDArg, _selfArg) if _err != nil { return } _retval, _err = convertSRRefToGo(_method + " -> ", _result.Value) return }
csn_ccr
Asks for a single choice out of multiple items. Given those items, and a prompt to ask the user with
def get_choice(prompt, choices): """ Asks for a single choice out of multiple items. Given those items, and a prompt to ask the user with """ print() checker = [] for offset, choice in enumerate(choices): number = offset + 1 print("\t{}): '{}'\n".format(number, choice)) checker.append(str(number)) response = get_input(prompt, tuple(checker) + ('',)) if not response: print("Exiting...") exit() offset = int(response) - 1 selected = choices[offset] return selected
csn
func (c *Client) FromString(targetPath, content string) (resource.Resource, error) { return c.rs.ResourceCache.GetOrCreate(resources.CACHE_OTHER, targetPath, func() (resource.Resource, error) { return c.rs.NewForFs( c.rs.FileCaches.AssetsCache().Fs, resources.ResourceSourceDescriptor{ LazyPublish: true,
OpenReadSeekCloser: func() (hugio.ReadSeekCloser, error) { return hugio.NewReadSeekerNoOpCloserFromString(content), nil }, RelTargetFilename: filepath.Clean(targetPath)}) }) }
csn_ccr
private function selectRestVersion($channelXml, $supportedVersions) { $channelXml->registerXPathNamespace('ns', self::CHANNEL_NS); foreach ($supportedVersions as $version) { $xpathTest = "ns:servers/ns:primary/ns:rest/ns:baseurl[@type='{$version}']"; $testResult = $channelXml->xpath($xpathTest);
if (count($testResult) > 0) { return array('version' => $version, 'baseUrl' => (string) $testResult[0]); } } return null; }
csn_ccr
Runs Sonar. @throws IOException @return the json file containing the results.
public File run() throws IOException { Map<String, String> props = loadBaseProperties(); setAdditionalProperties(props); sonarEmbeddedScanner.addGlobalProperties(props); log.info("Sonar configuration: {}", props.toString()); sonarEmbeddedScanner.start(); sonarEmbeddedScanner.execute(new HashMap<String, String>()); return new File(OUTPUT_DIR, OUTPUT_FILE); }
csn
Calculate reasonable canvas height and width for tree given N tips
def get_dims_from_tree_size(self): "Calculate reasonable canvas height and width for tree given N tips" ntips = len(self.ttree) if self.style.orient in ("right", "left"): # height is long tip-wise dimension if not self.style.height: self.style.height = max(275, min(1000, 18 * ntips)) if not self.style.width: self.style.width = max(350, min(500, 18 * ntips)) else: # width is long tip-wise dimension if not self.style.height: self.style.height = max(275, min(500, 18 * ntips)) if not self.style.width: self.style.width = max(350, min(1000, 18 * ntips))
csn
Set the hotspots that define the choices that are to be ordered by the candidate. @param \qtism\data\content\interactions\HotspotChoiceCollection $hotspotChoices A collection of HotspotChoice objects. @throws \InvalidArgumentException If the given $hotspotChoices collection is empty.
public function setHotspotChoices(HotspotChoiceCollection $hotspotChoices) { if (count($hotspotChoices) > 0) { $this->hotspotChoices = $hotspotChoices; } else { $msg = "A GraphicOrderInteraction must contain at least 1 hotspotChoice object. None given."; throw new InvalidArgumentException($msg); } }
csn
def add_color(self, name, model, description): r"""Add a color that can be used throughout the document. Args ---- name: str Name to set for the color model: str The color model to use when defining the color description: str The values to use to define the color """ if self.color is False: self.packages.append(Package("color"))
self.color = True self.preamble.append(Command("definecolor", arguments=[name, model, description]))
csn_ccr
def create(self, name, url, description=None, extra=None, is_public=None, is_protected=None): """Create a Job Binary. :param dict extra: authentication info needed for some job binaries, containing the keys `user` and `password` for job binary in Swift or the keys `accesskey`, `secretkey`, and `endpoint` for job binary in S3 """ data = { "name":
name, "url": url } self._copy_if_defined(data, description=description, extra=extra, is_public=is_public, is_protected=is_protected) return self._create('/job-binaries', data, 'job_binary')
csn_ccr
Explain the libxml errors encountered. @param string $filename The name of the file to which the errors are related. @return string[]
public static function explainLibXmlErrors($filename = '') { $errors = libxml_get_errors(); $result = array(); if (empty($errors)) { $result[] = 'Unknown libxml error'; } else { foreach ($errors as $error) { switch ($error->level) { case LIBXML_ERR_WARNING: $level = 'Warning'; break; case LIBXML_ERR_ERROR: $level = 'Error'; break; case LIBXML_ERR_FATAL: $level = 'Fatal error'; break; default: $level = 'Unknown error'; break; } $description = $level.' '.trim($error->message); if (!empty($filename)) { $description .= "\n File: $filename"; } $description .= "\n Line: {$error->line}"; $description .= "\n Code: {$error->code}"; $result[] = $description; } } return $result; }
csn
matrix csv write python
def csv_matrix_print(classes, table): """ Return matrix as csv data. :param classes: classes list :type classes:list :param table: table :type table:dict :return: """ result = "" classes.sort() for i in classes: for j in classes: result += str(table[i][j]) + "," result = result[:-1] + "\n" return result[:-1]
cosqa
Classes annotated with DBObject gain persistence methods.
def DBObject(table_name, versioning=VersioningTypes.NONE): """Classes annotated with DBObject gain persistence methods.""" def wrapped(cls): field_names = set() all_fields = [] for name in dir(cls): fld = getattr(cls, name) if fld and isinstance(fld, Field): fld.name = name all_fields.append(fld) field_names.add(name) def add_missing_field(name, default='', insert_pos=None): if name not in field_names: fld = Field(default=default) fld.name = name all_fields.insert( len(all_fields) if insert_pos is None else insert_pos, fld ) add_missing_field('id', insert_pos=0) add_missing_field('_create_date') add_missing_field('_last_update') if versioning == VersioningTypes.DELTA_HISTORY: add_missing_field('_version_hist', default=list) # Things we count on as part of our processing cls.__table_name__ = table_name cls.__versioning__ = versioning cls.__fields__ = all_fields # Give them a ctor for free - but make sure we aren't clobbering one if not ctor_overridable(cls): raise TypeError( 'Classes with user-supplied __init__ should not be decorated ' 'with DBObject. Use the setup method' ) cls.__init__ = _auto_init # Duck-type the class for our data methods cls.get_table_name = classmethod(_get_table_name) cls.get_id = _get_id cls.set_id = _set_id cls.to_data = _to_data cls.from_data = classmethod(_from_data) cls.index_names = classmethod(_index_names) cls.indexes = _indexes # Bonus methods they get for using gludb.simple cls.get_version_hist = _get_version_hist # Register with our abc since we actually implement all necessary # functionality Storable.register(cls) # And now that we're registered, we can also get the database # read/write functionality for free cls = DatabaseEnabled(cls) if versioning == VersioningTypes.DELTA_HISTORY: cls.save = _delta_save(cls.save) return cls return wrapped
csn
public static <T extends Field> ImmutableMap<String, T> getFieldsForType( Descriptor descriptor, Set<FieldDescriptor> extensions, Factory<T> factory) { ImmutableMap.Builder<String, T> fields = ImmutableMap.builder(); for (FieldDescriptor fieldDescriptor : descriptor.getFields()) { if (ProtoUtils.shouldJsIgnoreField(fieldDescriptor)) { continue; } T field = factory.create(fieldDescriptor); fields.put(field.getName(), field); } SetMultimap<String, T> extensionsBySoyName = MultimapBuilder.hashKeys().hashSetValues().build(); for (FieldDescriptor extension : extensions) { T field = factory.create(extension); extensionsBySoyName.put(field.getName(), field); } for (Map.Entry<String, Set<T>> group : Multimaps.asMap(extensionsBySoyName).entrySet()) { Set<T> ambiguousFields = group.getValue(); String fieldName = group.getKey(); if (ambiguousFields.size() == 1) {
fields.put(fieldName, Iterables.getOnlyElement(ambiguousFields)); } else { T value = factory.createAmbiguousFieldSet(ambiguousFields); logger.severe( "Proto " + descriptor.getFullName() + " has multiple extensions with the name \"" + fieldName + "\": " + fullFieldNames(ambiguousFields) + "\nThis field will not be accessible from soy"); fields.put(fieldName, value); } } return fields.build(); }
csn_ccr
Set a default Acl of this group. @param int Acl ID.
public function setDefaultAcl($aclId) { // set no default to siblings Database::run('UPDATE `acl` SET `is_default` = 0 WHERE `group_id` = ? AND `id` <> ?', [$this->id, $aclId]); // set default to this Database::run('UPDATE `acl` SET `is_default` = 1 WHERE `group_id` = ? AND `id` = ?', [$this->id, $aclId]); }
csn
Handle log level request === Parameters options(Hash):: Command line options === Return true:: Always return true
def manage(options) # Initialize configuration directory setting AgentConfig.cfg_dir = options[:cfg_dir] # Determine command level = options[:level] command = { :name => (level ? 'set_log_level' : 'get_log_level') } command[:level] = level.to_sym if level # Determine candidate agents agent_names = if options[:agent_name] [options[:agent_name]] else AgentConfig.cfg_agents end fail("No agents configured") if agent_names.empty? # Perform command for each agent count = 0 agent_names.each do |agent_name| count += 1 if request_log_level(agent_name, command, options) end puts("No agents running") if count == 0 true end
csn
func Pty() (*os.File, *os.File, error) { ptm, err := open_pty_master() if err != nil { return nil, nil, err } sname, err := Ptsname(ptm) if err != nil { return nil, nil, err } err = grantpt(ptm) if err != nil { return nil, nil, err } err = unlockpt(ptm) if err != nil { return nil, nil, err }
pts, err := open_device(sname) if err != nil { return nil, nil, err } return os.NewFile(uintptr(ptm), "ptm"), os.NewFile(uintptr(pts), sname), nil }
csn_ccr
In computer science and discrete mathematics, an [inversion](https://en.wikipedia.org/wiki/Inversion_%28discrete_mathematics%29) is a pair of places in a sequence where the elements in these places are out of their natural order. So, if we use ascending order for a group of numbers, then an inversion is when larger numbers appear before lower number in a sequence. Check out this example sequence: ```(1, 2, 5, 3, 4, 7, 6)``` and we can see here three inversions ```5``` and ```3```; ```5``` and ```4```; ```7``` and ```6```. You are given a sequence of numbers and you should count the number of inversions in this sequence. ```Input```: A sequence as a tuple of integers. ```Output```: The inversion number as an integer. Example: ```python count_inversion((1, 2, 5, 3, 4, 7, 6)) == 3 count_inversion((0, 1, 2, 3)) == 0 ```
def count_inversion(nums): return sum(a > b for i, a in enumerate(nums) for b in nums[i + 1:])
apps
def watch_command(context, backend, config, poll): """ Watch for change on your Sass project sources then compile them to CSS. Watched events are: \b * Create: when a new source file is created; * Change: when a source is changed; * Delete: when a source is deleted; * Move: When a source file is moved in watched dirs. Also occurs with editor transition file; Almost all errors occurring during compile won't break watcher, so you can resolve them and watcher will try again to compile once a new event occurs. You can stop watcher using key combo "CTRL+C" (or CMD+C on MacOSX). """ logger = logging.getLogger("boussole") logger.info("Watching project") # Discover settings file try: discovering = Discover(backends=[SettingsBackendJson, SettingsBackendYaml]) config_filepath, config_engine = discovering.search( filepath=config, basedir=os.getcwd(), kind=backend ) project = ProjectBase(backend_name=config_engine._kind_name) settings = project.backend_engine.load(filepath=config_filepath) except BoussoleBaseException as e: logger.critical(six.text_type(e)) raise click.Abort() logger.debug(u"Settings file: {} ({})".format( config_filepath, config_engine._kind_name)) logger.debug(u"Project sources directory: {}".format( settings.SOURCES_PATH)) logger.debug(u"Project destination directory: {}".format( settings.TARGET_PATH)) logger.debug(u"Exclude patterns: {}".format( settings.EXCLUDES)) # Watcher settings watcher_templates_patterns = { 'patterns': ['*.scss'],
'ignore_patterns': ['*.part'], 'ignore_directories': False, 'case_sensitive': True, } # Init inspector instance shared through all handlers inspector = ScssInspector() if not poll: logger.debug(u"Using Watchdog native platform observer") observer = Observer() else: logger.debug(u"Using Watchdog polling observer") observer = PollingObserver() # Init event handlers project_handler = WatchdogProjectEventHandler(settings, inspector, **watcher_templates_patterns) lib_handler = WatchdogLibraryEventHandler(settings, inspector, **watcher_templates_patterns) # Observe source directory observer.schedule(project_handler, settings.SOURCES_PATH, recursive=True) # Also observe libraries directories for libpath in settings.LIBRARY_PATHS: observer.schedule(lib_handler, libpath, recursive=True) # Start watching logger.warning(u"Launching the watcher, use CTRL+C to stop it") observer.start() try: while True: time.sleep(1) except KeyboardInterrupt: logger.warning(u"CTRL+C used, stopping..") observer.stop() observer.join()
csn_ccr
Doctrine table data loader @param int $page @param int $limit @return SimpleTableData
public function dataLoader($page, $limit) { if ($limit > 0) { $this->getQueryBuilder()->setMaxResults($limit); $this->getQueryBuilder()->setFirstResult(($page - 1) * $limit); } $paginator = new Paginator($this->getQueryBuilder()); $tableData = new SimpleTableData(); $tableData->setTotalResults(count($paginator)); $tableData->setResults(iterator_to_array($paginator->getIterator())); return $tableData; }
csn
func (bb *Builder) SetSigner(signer blob.Ref)
*Builder { bb.m["camliSigner"] = signer.String() return bb }
csn_ccr
def convert_from_gps_time(gps_time, gps_week=None): """ Convert gps time in ticks to standard time. """ converted_gps_time = None gps_timestamp = float(gps_time) if gps_week != None: # image date converted_gps_time = GPS_START + datetime.timedelta(seconds=int(gps_week) * SECS_IN_WEEK + gps_timestamp) else: # TAI scale with 1970-01-01 00:00:10 (TAI) epoch os.environ['TZ'] = 'right/UTC' # by definition gps_time_as_gps = GPS_START + \ datetime.timedelta(seconds=gps_timestamp) # constant offset
gps_time_as_tai = gps_time_as_gps + \ datetime.timedelta(seconds=19) tai_epoch_as_tai = datetime.datetime(1970, 1, 1, 0, 0, 10) # by definition tai_timestamp = (gps_time_as_tai - tai_epoch_as_tai).total_seconds() converted_gps_time = ( datetime.datetime.utcfromtimestamp(tai_timestamp)) # "right" timezone is in effect return converted_gps_time
csn_ccr
public function publish(Message $message): ChannelInformation { $response = $this->client->post( new Request( $this->channelUrl, [ 'Accept' => 'application/json', 'Content-Type' => $message->contentType(), 'X-EventSource-Event' => $message->name() ], $message->content() ) ); if (!in_array($response->statusCode(), [Response::CREATED, Response::ACCEPTED])) {
throw new NchanException( sprintf( 'Unable to publish to channel. Maybe the channel does not exists. HTTP status code was %s.', $response->statusCode() ) ); } return ChannelInformation::fromJson($response->body()); }
csn_ccr
Given a 2MASS position, look up the epoch when it was observed. This function uses the CDS Vizier web service to look up information in the 2MASS point source database. Arguments are: tmra The source's J2000 right ascension, in radians. tmdec The source's J2000 declination, in radians. debug If True, the web server's response will be printed to :data:`sys.stdout`. The return value is an MJD. If the lookup fails, a message will be printed to :data:`sys.stderr` (unconditionally!) and the :data:`J2000` epoch will be returned.
def get_2mass_epoch (tmra, tmdec, debug=False): """Given a 2MASS position, look up the epoch when it was observed. This function uses the CDS Vizier web service to look up information in the 2MASS point source database. Arguments are: tmra The source's J2000 right ascension, in radians. tmdec The source's J2000 declination, in radians. debug If True, the web server's response will be printed to :data:`sys.stdout`. The return value is an MJD. If the lookup fails, a message will be printed to :data:`sys.stderr` (unconditionally!) and the :data:`J2000` epoch will be returned. """ import codecs try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen postdata = b'''-mime=csv -source=2MASS -out=_q,JD -c=%.6f %.6f -c.eq=J2000''' % (tmra * R2D, tmdec * R2D) jd = None for line in codecs.getreader('utf-8')(urlopen (_vizurl, postdata)): line = line.strip () if debug: print_ ('D: 2M >>', line) if line.startswith ('1;'): jd = float (line[2:]) if jd is None: import sys print_ ('warning: 2MASS epoch lookup failed; astrometry could be very wrong!', file=sys.stderr) return J2000 return jd - 2400000.5
csn
Returns all the database columns in SHOW COLUMN format @return array
public function columns() { if (!isset($this->_columns)) { $this->_columns = array(); foreach ($this->_connection->execute("SHOW COLUMNS FROM ".$this->_name->quoted()) as $c) { $column = $c['Field']; unset($c['Field']); $this->_columns[$column] = $c; } } return $this->_columns; }
csn