text
stringlengths
27
775k
/* * Copyright 2020 The Android Open stream Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.rxjava2 import androidx.compose.runtime.Composable import androidx.compose.runtime.State import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue import androidx.test.filters.MediumTest import androidx.ui.test.createComposeRule import com.google.common.truth.Truth.assertThat import io.reactivex.BackpressureStrategy import io.reactivex.Maybe import io.reactivex.MaybeEmitter import io.reactivex.MaybeOnSubscribe import io.reactivex.Single import io.reactivex.SingleEmitter import io.reactivex.SingleOnSubscribe import io.reactivex.subjects.BehaviorSubject import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.junit.runners.Parameterized import java.util.concurrent.CountDownLatch import java.util.concurrent.TimeUnit @MediumTest @RunWith(Parameterized::class) class RxJava2AdapterTest(private val factory: () -> Stream) { companion object { @JvmStatic @Parameterized.Parameters(name = "{0}") fun initParameters(): Array<() -> Stream> = arrayOf( ObservableStream(), FlowableStream(), SingleStream(), MaybeStream() ) } @get:Rule val rule = createComposeRule() @Test fun whenValueIsNotSetWeGotNull() { val stream = factory() var realValue: String? = "to-be-updated" rule.setContent { realValue = stream.subscribeAsState(null).value } assertThat(realValue).isNull() } @Test fun weGotInitialValue() { val stream = factory() stream.onNext("value") var realValue: String? = null rule.setContent { realValue = stream.subscribeAsState(null).value } assertThat(realValue).isEqualTo("value") } @Test fun weReceiveValueSubmittedLater() { val stream = factory() var realValue: String? = null rule.setContent { realValue = stream.subscribeAsState(null).value } rule.runOnIdle { stream.onNext("value") } rule.runOnIdle { assertThat(realValue).isEqualTo("value") } } @Test fun weReceiveSecondValue() { val stream = factory() if (!stream.supportMultipleValues()) return stream.onNext("value") var realValue: String? = null rule.setContent { realValue = stream.subscribeAsState(null).value } rule.runOnIdle { stream.onNext("value2") } rule.runOnIdle { assertThat(realValue).isEqualTo("value2") } } @Test fun noUpdatesAfterDispose() { val stream = factory() var emit by mutableStateOf(true) var realValue: String? = "to-be-updated" rule.setContent { if (emit) { realValue = stream.subscribeAsState(null).value } } rule.runOnIdle { emit = false } rule.runOnIdle { stream.onNext("value") } rule.runOnIdle { assertThat(realValue).isNull() } } @Test fun testObservableWithInitialValue() { val stream = factory() var realValue: String? = "to-be-updated" rule.setContent { realValue = stream.subscribeAsState("value").value } assertThat(realValue).isEqualTo("value") } @Test fun weReceiveValueSubmittedOnBackgroundThread() { val stream = factory() val latch = CountDownLatch(1) var realValue: String? = null rule.setContent { realValue = stream.subscribeAsState(null).value if (realValue != null) { latch.countDown() } } Thread( Runnable { stream.onNext("value") } ).start() assertThat(latch.await(5, TimeUnit.SECONDS)).isTrue() rule.runOnUiThread { assertThat(realValue).isEqualTo("value") } } } interface Stream { fun onNext(value: String) @Composable fun subscribeAsState(initial: String?): State<String?> fun supportMultipleValues(): Boolean } private class ObservableStream : () -> Stream { override fun invoke(): Stream { return object : Stream { val subject = BehaviorSubject.create<String>() override fun onNext(value: String) = subject.onNext(value) @Composable override fun subscribeAsState(initial: String?) = subject.subscribeAsState(initial) override fun supportMultipleValues(): Boolean = true } } override fun toString() = "Observable" } private class FlowableStream : () -> Stream { override fun invoke(): Stream { return object : Stream { val subject = BehaviorSubject.create<String>() val flowable = subject.toFlowable(BackpressureStrategy.LATEST) override fun onNext(value: String) = subject.onNext(value) @Composable override fun subscribeAsState(initial: String?) = flowable.subscribeAsState(initial) override fun supportMultipleValues(): Boolean = true } } override fun toString() = "Flowable" } private class SingleStream : () -> Stream { override fun invoke(): Stream { return object : Stream, SingleOnSubscribe<String> { var value: String? = null val emmiters = mutableListOf<SingleEmitter<String>>() val single = Single.create(this) override fun onNext(value: String) { require(this.value == null) this.value = value emitAll() } private fun emitAll() { if (value != null) { emmiters.forEach { if (!it.isDisposed) { it.onSuccess(value!!) } } } } override fun subscribe(p0: SingleEmitter<String>) { emmiters.add(p0) emitAll() } @Composable override fun subscribeAsState(initial: String?) = single.subscribeAsState(initial) override fun supportMultipleValues(): Boolean = false } } override fun toString() = "Single" } private class MaybeStream : () -> Stream { override fun invoke(): Stream { return object : Stream, MaybeOnSubscribe<String> { val emmiters = mutableListOf<MaybeEmitter<String>>() var value: String? = null val maybe = Maybe.create<String>(this) override fun onNext(value: String) { require(this.value == null) this.value = value emitAll() } private fun emitAll() { if (value != null) { emmiters.forEach { if (!it.isDisposed) { it.onSuccess(value!!) } } } } override fun subscribe(p0: MaybeEmitter<String>) { emmiters.add(p0) emitAll() } @Composable override fun subscribeAsState(initial: String?) = maybe.subscribeAsState(initial) override fun supportMultipleValues(): Boolean = false } } override fun toString() = "Maybe" }
package com.rarible.protocol.nftorder.api.client import com.rarible.protocol.client.AbstractApiClientFactory import com.rarible.protocol.client.ApiServiceUriProvider import com.rarible.protocol.nftorder.api.ApiClient import org.springframework.boot.web.reactive.function.client.WebClientCustomizer open class NftOrderApiClientFactory( uriProvider: ApiServiceUriProvider, webClientCustomizer: WebClientCustomizer ) : AbstractApiClientFactory(uriProvider, webClientCustomizer) { fun createNftOrderOwnershipApiClient(blockchain: String): NftOrderOwnershipControllerApi { return NftOrderOwnershipControllerApi(createApiClient(blockchain)) } fun createNftOrderItemApiClient(blockchain: String): NftOrderItemControllerApi { return NftOrderItemControllerApi(createApiClient(blockchain)) } fun createNftOrderActivityApiClient(blockchain: String): NftOrderActivityControllerApi { return NftOrderActivityControllerApi(createApiClient(blockchain)) } fun createNftOrderLazyMintControllerApi(blockchain: String): NftOrderLazyMintControllerApi { return NftOrderLazyMintControllerApi(createApiClient(blockchain)) } fun createNftOrderCollectionControllerApi(blockchain: String): NftOrderCollectionControllerApi { return NftOrderCollectionControllerApi(createApiClient(blockchain)) } private fun createApiClient(blockchain: String): ApiClient { return ApiClient(webClientCustomizer) .setBasePath(getBasePath(blockchain)) } }
import 'package:flutter/material.dart'; import 'package:flutter/widgets.dart'; class ApiController { getJsonNfeDataFromAssets({ @required BuildContext context, @required Widget destination, }) { openScreenDestination(context, destination); } openScreenDestination(BuildContext context, Widget destination) { Navigator.push( context, MaterialPageRoute(builder: (BuildContext context) { return destination; }), ); } /// Assumes the given path is a text-file-asset. Future<dynamic> getFileData(BuildContext context, String path) async { var result = await DefaultAssetBundle.of(context).loadString(path); return result; } }
--- description: "Learn more about: NMAKE Fatal Error U1086" title: "NMAKE Fatal Error U1086" ms.date: "11/04/2016" f1_keywords: ["U1086"] helpviewer_keywords: ["U1086"] ms.assetid: 6d3cd68a-ead6-4a6d-a205-01324785de7e --- # NMAKE Fatal Error U1086 **inference rule cannot have dependents** The colon (**:**) in an inference rule must be followed by one of these: - Newline character - Semicolon (**;**), which can be followed by a command - Number sign (**#**), which can be followed by a comment
using System; using System.Collections.Generic; using System.Text.RegularExpressions; using Microsoft.Extensions.Options; using CatenaX.NetworkServices.Mailing.Template.Model; namespace CatenaX.NetworkServices.Mailing.Template { public class TemplateManager : ITemplateManager { private readonly TemplateSettings _Templates; public TemplateManager(IOptions<TemplateSettings> templateSettings) { _Templates = templateSettings.Value; } Mail ITemplateManager.ApplyTemplate(string id, IDictionary<string, string> parameters) { try { var Template = _Templates[id]; return new Mail( replaceValues(Template.Subject,parameters), replaceValues(Template.Body,parameters), Template.html ); } catch(ArgumentNullException) { throw new NoSuchTemplateException(id); } catch(KeyNotFoundException) { throw new NoSuchTemplateException(id); } } private string replaceValues(string template, IDictionary<string,string> parameters) { return Regex.Replace( template, @"\{(\w+)\}", //replaces any text surrounded by { and } m => { string value; return parameters.TryGetValue(m.Groups[1].Value, out value) ? value : "null"; } ); } } }
const { join } = require("path"); const SwiftFormatOfficial = require("../../../src/linters/swift-format-official"); const testName = "swift-format-official"; const linter = SwiftFormatOfficial; const commandPrefix = ""; const extensions = ["swift"]; function getLintParams(dir) { const warning1 = `${join(dir, "file2.swift")}:2:22: warning: [DoNotUseSemicolons]: remove ';'`; const warning2 = `${join(dir, "file1.swift")}:3:35: warning: [RemoveLine]: remove line break`; const warning3 = `${join( dir, "file1.swift", )}:7:1: warning: [Indentation] replace leading whitespace with 2 spaces`; const warning4 = `${join(dir, "file1.swift")}:7:23: warning: [Spacing]: add 1 space`; return { // Expected output of the linting function. cmdOutput: { status: 1, stderrParts: [warning1, warning2, warning3, warning4], stderr: `${warning1}\n${warning2}\n${warning3}\n${warning4}`, }, // Expected output of the parsing function. lintResult: { isSuccess: false, error: [ { path: "file2.swift", firstLine: 2, lastLine: 2, message: "[DoNotUseSemicolons]: remove ';'", }, { path: "file1.swift", firstLine: 3, lastLine: 3, message: "[RemoveLine]: remove line break", }, { path: "file1.swift", firstLine: 7, lastLine: 7, message: "[Indentation] replace leading whitespace with 2 spaces", }, { path: "file1.swift", firstLine: 7, lastLine: 7, message: "[Spacing]: add 1 space", }, ], warning: [], }, }; } function getFixParams(dir) { return { // Expected output of the linting function. cmdOutput: { status: 0, stderr: "", }, // Expected output of the parsing function. lintResult: { isSuccess: true, warning: [], error: [], }, }; } module.exports = [testName, linter, commandPrefix, extensions, getLintParams, getFixParams];
#!/usr/bin/env bash #:title: Divine.dotfiles FreeBSD adapter #:author: Grove Pyree #:email: grayarea@protonmail.ch #:revdate: 2019.11.30 #:revremark: Rewrite all Github references to point to new repo location #:created_at: 2019.08.08 ## Part of Divine.dotfiles <https://github.com/divine-dotfiles/divine-dotfiles> # ## An adapter is a set of functions that, when implemented, allow framework to #. support FreeBSD OS distribution # ## For reference, see lib/templates/adapters/distro.adp.sh # # Marker and dependencies readonly D__ADD_FREEBSD=loaded d__load util workflow # Implement detection mechanism for package manager d__detect_os_pkgmgr() { # Check if apt-get is available pkg --version &>/dev/null || return 1 # Set marker variable d__os_pkgmgr='pkg' # Implement wrapper function d__os_pkgmgr() { case "$1" in update) d__require_sudo pkg; sudo pkg update; sudo pkg upgrade -y;; has) pkg rquery %n "$2" &>/dev/null;; check) pkg info "$2" &>/dev/null;; install) d__require_sudo pkg; sudo pkg install -y "$2";; remove) d__require_sudo pkg; sudo pkg delete -y "$2" ;; *) return 1;; esac } }
package fr.rss.download.api.utils; import java.util.ArrayList; public class AllDebridUtils { public static boolean isFolder(String link) { link = link.replaceAll("(\\r|\\n)", "").replaceAll("^https?://(www\\.)?", ""); ArrayList<String> redirectorsRegexp = new ArrayList<>(); redirectorsRegexp.add("^(zytpirwai.net/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(linkbucks.com/([0-9a-zA-Z.-]+))$"); redirectorsRegexp.add("^(adf.ly/[0-9]+/(.+))$"); redirectorsRegexp.add("^(adf.ly/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(bit.ly/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(tinyurl.com/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(safelinking.net/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(extreme-protect.net/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(ed-protect.org/[0-9a-zA-Z.-]+)$"); redirectorsRegexp.add("^(dl-protecte.com/[0-9a-zA-Z.-]+)"); redirectorsRegexp.add("^(dl-protect1.com/[0-9a-zA-Z.-]+)"); redirectorsRegexp.add("^(dl-protecte.org/[0-9a-zA-Z.-]+)"); redirectorsRegexp.add("^(liencaptcha.com/lien.php?idupload=[0-9]+&ad=[0-9]+&pos=[0-9]+&link=[0-9]+)"); redirectorsRegexp.add("^(protect.ddl-island.su/[0-9a-zA-Z.-]+)$"); for (String regexp : redirectorsRegexp) { if (link.matches(regexp)) { return true; } } return false; } }
/* * This file is part of AceQL Client SDK. * AceQL Client SDK: Remote JDBC access over HTTP with AceQL HTTP. * Copyright (C) 2020, KawanSoft SAS * (http://www.kawansoft.com). All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kawanfw.driver.jdbc.abstracts; import java.sql.BatchUpdateException; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.Statement; /** * Statement Wrapper. <br> * Implements all the Statement methods. Usage is exactly the same as a * Statement. * */ public class AbstractStatement implements Statement { /** The Statement */ private Statement statement = null; /** Flag that says the caller is ConnectionHttp */ private boolean isConnectionHttp = false; /** * Set to true if the user has closed the connection by a explicit call to * close() */ private boolean isClosed = false; /** * Void Constructor * * Needed for HTTP usage because there is no real JDBC Connection */ public AbstractStatement() { isConnectionHttp = true; } /** * Constructor * * @param statement * actual statement in use to wrap */ public AbstractStatement(Statement statement) throws SQLException { this.statement = statement; } /** * Will throw a SQL Exception if calling method is not authorized **/ private void verifyCallAuthorization(String methodName) throws SQLException { if (isClosed) { throw new SQLException("Statement is closed."); } if (isConnectionHttp) { throw new SQLException( AbstractConnection.FEATURE_NOT_SUPPORTED_IN_THIS_VERSION + methodName); } } /** * Executes the given SQL statement, which returns a single * <code>ResultSet</code> object. * * @param sql * an SQL statement to be sent to the database, typically a * static SQL <code>SELECT</code> statement * @return a <code>ResultSet</code> object that contains the data produced * by the given query; never <code>null</code> * @exception SQLException * if a database access error occurs or the given SQL * statement produces anything other than a single * <code>ResultSet</code> object */ @Override public ResultSet executeQuery(String sql) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.executeQuery(sql); } /** * Executes the given SQL statement, which may be an <code>INSERT</code>, * <code>UPDATE</code>, or <code>DELETE</code> statement or an SQL statement * that returns nothing, such as an SQL DDL statement. * * @param sql * an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns * nothing * @return either the row count for <code>INSERT</code>, <code>UPDATE</code> * or <code>DELETE</code> statements, or <code>0</code> for SQL * statements that return nothing * @exception SQLException * if a database access error occurs or the given SQL * statement produces a <code>ResultSet</code> object */ @Override public int executeUpdate(String sql) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.executeUpdate(sql); } /** * Releases this <code>Statement</code> object's database and JDBC resources * immediately instead of waiting for this to happen when it is * automatically closed. It is generally good practice to release resources * as soon as you are finished with them to avoid tying up database * resources. * <P> * Calling the method <code>close</code> on a <code>Statement</code> object * that is already closed has no effect. * <P> * <B>Note:</B> A <code>Statement</code> object is automatically closed when * it is garbage collected. When a <code>Statement</code> object is closed, * its current <code>ResultSet</code> object, if one exists, is also closed. * * @exception SQLException * if a database access error occurs */ @Override public void close() throws SQLException { isClosed = true; } // ---------------------------------------------------------------------- /** * Retrieves the maximum number of bytes that can be returned for character * and binary column values in a <code>ResultSet</code> object produced by * this <code>Statement</code> object. This limit applies only to * <code>BINARY</code>, <code>VARBINARY</code>, <code>LONGVARBINARY</code>, * <code>CHAR</code>, <code>VARCHAR</code>, and <code>LONGVARCHAR</code> * columns. If the limit is exceeded, the excess data is silently discarded. * * @return the current column size limit for columns storing character and * binary values; zero means there is no limit * @exception SQLException * if a database access error occurs * @see #setMaxFieldSize */ @Override public int getMaxFieldSize() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getMaxFieldSize(); } /** * Sets the limit for the maximum number of bytes in a * <code>ResultSet</code> column storing character or binary values to the * given number of bytes. This limit applies only to <code>BINARY</code>, * <code>VARBINARY</code>, <code>LONGVARBINARY</code>, <code>CHAR</code>, * <code>VARCHAR</code>, and <code>LONGVARCHAR</code> fields. If the limit * is exceeded, the excess data is silently discarded. For maximum * portability, use values greater than 256. * * @param max * the new column size limit in bytes; zero means there is no * limit * @exception SQLException * if a database access error occurs or the condition max >= * 0 is not satisfied * @see #getMaxFieldSize */ @Override public void setMaxFieldSize(int max) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setMaxFieldSize(max); } /** * Retrieves the maximum number of rows that a <code>ResultSet</code> object * produced by this <code>Statement</code> object can contain. If this limit * is exceeded, the excess rows are silently dropped. * * @return the current maximum number of rows for a <code>ResultSet</code> * object produced by this <code>Statement</code> object; zero means * there is no limit * @exception SQLException * if a database access error occurs * @see #setMaxRows */ @Override public int getMaxRows() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getMaxRows(); } /** * Sets the limit for the maximum number of rows that any * <code>ResultSet</code> object can contain to the given number. If the * limit is exceeded, the excess rows are silently dropped. * * @param max * the new max rows limit; zero means there is no limit * @exception SQLException * if a database access error occurs or the condition max >= * 0 is not satisfied * @see #getMaxRows */ @Override public void setMaxRows(int max) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setMaxRows(max); } /** * Sets escape processing on or off. If escape scanning is on (the default), * the driver will do escape substitution before sending the SQL statement * to the database. * * Note: Since prepared statements have usually been parsed prior to making * this call, disabling escape processing for * <code>PreparedStatements</code> objects will have no effect. * * @param enable * <code>true</code> to enable escape processing; * <code>false</code> to disable it * @exception SQLException * if a database access error occurs */ @Override public void setEscapeProcessing(boolean enable) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setEscapeProcessing(enable); } /** * Retrieves the number of seconds the driver will wait for a * <code>Statement</code> object to execute. If the limit is exceeded, a * <code>SQLException</code> is thrown. * * @return the current query timeout limit in seconds; zero means there is * no limit * @exception SQLException * if a database access error occurs * @see #setQueryTimeout */ @Override public int getQueryTimeout() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getQueryTimeout(); } /** * Sets the number of seconds the driver will wait for a * <code>Statement</code> object to execute to the given number of seconds. * If the limit is exceeded, an <code>SQLException</code> is thrown. * * @param seconds * the new query timeout limit in seconds; zero means there is no * limit * @exception SQLException * if a database access error occurs or the condition seconds * >= 0 is not satisfied * @see #getQueryTimeout */ @Override public void setQueryTimeout(int seconds) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setQueryTimeout(seconds); } /** * Cancels this <code>Statement</code> object if both the DBMS and driver * support aborting an SQL statement. This method can be used by one thread * to cancel a statement that is being executed by another thread. * * @exception SQLException * if a database access error occurs */ @Override public void cancel() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.cancel(); } /** * Retrieves the first warning reported by calls on this * <code>Statement</code> object. Subsequent <code>Statement</code> object * warnings will be chained to this <code>SQLWarning</code> object. * * <p> * The warning chain is automatically cleared each time a statement is * (re)executed. This method may not be called on a closed * <code>Statement</code> object; doing so will cause an * <code>SQLException</code> to be thrown. * * <P> * <B>Note:</B> If you are processing a <code>ResultSet</code> object, any * warnings associated with reads on that <code>ResultSet</code> object will * be chained on it rather than on the <code>Statement</code> object that * produced it. * * @return the first <code>SQLWarning</code> object or <code>null</code> if * there are no warnings * @exception SQLException * if a database access error occurs or this method is called * on a closed statement */ @Override public SQLWarning getWarnings() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getWarnings(); } /** * Clears all the warnings reported on this <code>Statement</code> object. * After a call to this method, the method <code>getWarnings</code> will * return <code>null</code> until a new warning is reported for this * <code>Statement</code> object. * * @exception SQLException * if a database access error occurs */ @Override public void clearWarnings() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.clearWarnings(); } /** * Sets the SQL cursor name to the given <code>String</code>, which will be * used by subsequent <code>Statement</code> object <code>execute</code> * methods. This name can then be used in SQL positioned update or delete * statements to identify the current row in the <code>ResultSet</code> * object generated by this statement. If the database does not support * positioned update/delete, this method is a noop. To insure that a cursor * has the proper isolation level to support updates, the cursor's * <code>SELECT</code> statement should have the form * <code>SELECT FOR UPDATE</code>. If <code>FOR UPDATE</code> is not * present, positioned updates may fail. * * <P> * <B>Note:</B> By definition, the execution of positioned updates and * deletes must be done by a different <code>Statement</code> object than * the one that generated the <code>ResultSet</code> object being used for * positioning. Also, cursor names must be unique within a connection. * * @param name * the new cursor name, which must be unique within a connection * @exception SQLException * if a database access error occurs */ @Override public void setCursorName(String name) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setCursorName(name); } // ----------------------- Multiple Results -------------------------- /** * Executes the given SQL statement, which may return multiple results. In * some (uncommon) situations, a single SQL statement may return multiple * result sets and/or update counts. Normally you can ignore this unless you * are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates * the form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the * result, and <code>getMoreResults</code> to move to any subsequent * result(s). * * @param sql * any SQL statement * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no results * @exception SQLException * if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults */ @Override public boolean execute(String sql) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.execute(sql); } /** * Retrieves the current result as a <code>ResultSet</code> object. This * method should be called only once per result. * * @return the current result as a <code>ResultSet</code> object or * <code>null</code> if the result is an update count or there are * no more results * @exception SQLException * if a database access error occurs * @see #execute */ @Override public ResultSet getResultSet() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getResultSet(); } /** * Retrieves the current result as an update count; if the result is a * <code>ResultSet</code> object or there are no more results, -1 is * returned. This method should be called only once per result. * * @return the current result as an update count; -1 if the current result * is a <code>ResultSet</code> object or there are no more results * @exception SQLException * if a database access error occurs * @see #execute */ @Override public int getUpdateCount() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getUpdateCount(); } /** * Moves to this <code>Statement</code> object's next result, returns * <code>true</code> if it is a <code>ResultSet</code> object, and * implicitly closes any current <code>ResultSet</code> object(s) obtained * with the method <code>getResultSet</code>. * * <P> * There are no more results when the following is true: * * <PRE> * <code>(!getMoreResults() && (getUpdateCount() == -1)</code> * </PRE> * * @return <code>true</code> if the next result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no more results * @exception SQLException * if a database access error occurs * @see #execute */ @Override public boolean getMoreResults() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getMoreResults(); } // --------------------------JDBC 2.0----------------------------- /** * Gives the driver a hint as to the direction in which rows will be * processed in <code>ResultSet</code> objects created using this * <code>Statement</code> object. The default value is * <code>ResultSet.FETCH_FORWARD</code>. * <P> * Note that this method sets the default fetch direction for result sets * generated by this <code>Statement</code> object. Each result set has its * own methods for getting and setting its own fetch direction. * * @param direction * the initial direction for processing rows * @exception SQLException * if a database access error occurs or the given direction * is not one of <code>ResultSet.FETCH_FORWARD</code>, * <code>ResultSet.FETCH_REVERSE</code>, or * <code>ResultSet.FETCH_UNKNOWN</code> * @since 1.2 * @see #getFetchDirection */ @Override public void setFetchDirection(int direction) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setFetchDirection(direction); } /** * Retrieves the direction for fetching rows from database tables that is * the default for result sets generated from this <code>Statement</code> * object. If this <code>Statement</code> object has not set a fetch * direction by calling the method <code>setFetchDirection</code>, the * return value is implementation-specific. * * @return the default fetch direction for result sets generated from this * <code>Statement</code> object * @exception SQLException * if a database access error occurs * @since 1.2 * @see #setFetchDirection */ @Override public int getFetchDirection() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getFetchDirection(); } /** * Gives the JDBC driver a hint as to the number of rows that should be * fetched from the database when more rows are needed. The number of rows * specified affects only result sets created using this statement. If the * value specified is zero, then the hint is ignored. The default value is * zero. * * @param rows * the number of rows to fetch * @exception SQLException * if a database access error occurs, or the condition 0 <= * <code>rows</code> <= <code>this.getMaxRows()</code> is not * satisfied. * @since 1.2 * @see #getFetchSize */ @Override public void setFetchSize(int rows) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.setFetchSize(rows); } /** * Retrieves the number of result set rows that is the default fetch size * for <code>ResultSet</code> objects generated from this * <code>Statement</code> object. If this <code>Statement</code> object has * not set a fetch size by calling the method <code>setFetchSize</code>, the * return value is implementation-specific. * * @return the default fetch size for result sets generated from this * <code>Statement</code> object * @exception SQLException * if a database access error occurs * @since 1.2 * @see #setFetchSize */ @Override public int getFetchSize() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getFetchSize(); } /** * Retrieves the result set concurrency for <code>ResultSet</code> objects * generated by this <code>Statement</code> object. * * @return either <code>ResultSet.CONCUR_READ_ONLY</code> or * <code>ResultSet.CONCUR_UPDATABLE</code> * @exception SQLException * if a database access error occurs * @since 1.2 */ @Override public int getResultSetConcurrency() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getResultSetConcurrency(); } /** * Retrieves the result set type for <code>ResultSet</code> objects * generated by this <code>Statement</code> object. * * @return one of <code>ResultSet.TYPE_FORWARD_ONLY</code>, * <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or * <code>ResultSet.TYPE_SCROLL_SENSITIVE</code> * @exception SQLException * if a database access error occurs * @since 1.2 */ @Override public int getResultSetType() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getResultSetType(); } /** * Adds the given SQL command to the current list of commmands for this * <code>Statement</code> object. The commands in this list can be executed * as a batch by calling the method <code>executeBatch</code>. * <P> * <B>NOTE:</B> This method is optional. * * @param sql * typically this is a static SQL <code>INSERT</code> or * <code>UPDATE</code> statement * @exception SQLException * if a database access error occurs, or the driver does not * support batch updates * @see #executeBatch * @since 1.2 */ @Override public void addBatch(String sql) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.addBatch(sql); } /** * Empties this <code>Statement</code> object's current list of SQL * commands. * <P> * <B>NOTE:</B> This method is optional. * * @exception SQLException * if a database access error occurs or the driver does not * support batch updates * @see #addBatch * @since 1.2 */ @Override public void clearBatch() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); this.statement.clearBatch(); } /** * Submits a batch of commands to the database for execution and if all * commands execute successfully, returns an array of update counts. The * <code>int</code> elements of the array that is returned are ordered to * correspond to the commands in the batch, which are ordered according to * the order in which they were added to the batch. The elements in the * array returned by the method <code>executeBatch</code> may be one of the * following: * <OL> * <LI>A number greater than or equal to zero -- indicates that the command * was processed successfully and is an update count giving the number of * rows in the database that were affected by the command's execution * <LI>A value of <code>SUCCESS_NO_INFO</code> -- indicates that the command * was processed successfully but that the number of rows affected is * unknown * <P> * If one of the commands in a batch update fails to execute properly, this * method throws a <code>BatchUpdateException</code>, and a JDBC driver may * or may not continue to process the remaining commands in the batch. * However, the driver's behavior must be consistent with a particular DBMS, * either always continuing to process commands or never continuing to * process commands. If the driver continues processing after a failure, the * array returned by the method * <code>BatchUpdateException.getUpdateCounts</code> will contain as many * elements as there are commands in the batch, and at least one of the * elements will be the following: * <P> * <LI>A value of <code>EXECUTE_FAILED</code> -- indicates that the command * failed to execute successfully and occurs only if a driver continues to * process commands after a command fails * </OL> * <P> * A driver is not required to implement this method. The possible * implementations and return values have been modified in the Java 2 SDK, * Standard Edition, version 1.3 to accommodate the option of continuing to * proccess commands in a batch update after a * <code>BatchUpdateException</code> obejct has been thrown. * * @return an array of update counts containing one element for each command * in the batch. The elements of the array are ordered according to * the order in which commands were added to the batch. * @exception SQLException * if a database access error occurs or the driver does not * support batch statements. Throws * {@link BatchUpdateException} (a subclass of * <code>SQLException</code>) if one of the commands sent to * the database fails to execute properly or attempts to * return a result set. * @since 1.3 */ @Override public int[] executeBatch() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.executeBatch(); } /** * Retrieves the <code>Connection</code> object that produced this * <code>Statement</code> object. * * @return the connection that produced this statement * @exception SQLException * if a database access error occurs * @since 1.2 */ @Override public Connection getConnection() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getConnection(); } // --------------------------JDBC 3.0----------------------------- /** * The constant indicating that the current <code>ResultSet</code> object * should be closed when calling <code>getMoreResults</code>. * * @since 1.4 */ public int CLOSE_CURRENT_RESULT = 1; /** * The constant indicating that the current <code>ResultSet</code> object * should not be closed when calling <code>getMoreResults</code>. * * @since 1.4 */ public int KEEP_CURRENT_RESULT = 2; /** * The constant indicating that all <code>ResultSet</code> objects that have * previously been kept open should be closed when calling * <code>getMoreResults</code>. * * @since 1.4 */ public int CLOSE_ALL_RESULTS = 3; /** * The constant indicating that a batch statement executed successfully but * that no count of the number of rows it affected is available. * * @since 1.4 */ public int SUCCESS_NO_INFO = -2; /** * The constant indicating that an error occured while executing a batch * statement. * * @since 1.4 */ public int EXECUTE_FAILED = -3; /** * The constant indicating that generated keys should be made available for * retrieval. * * @since 1.4 */ public int RETURN_GENERATED_KEYS = 1; /** * The constant indicating that generated keys should not be made available * for retrieval. * * @since 1.4 */ public int NO_GENERATED_KEYS = 2; /** * Moves to this <code>Statement</code> object's next result, deals with any * current <code>ResultSet</code> object(s) according to the instructions * specified by the given flag, and returns <code>true</code> if the next * result is a <code>ResultSet</code> object. * * <P> * There are no more results when the following is true: * * <PRE> * <code>(!getMoreResults() && (getUpdateCount() == -1)</code> * </PRE> * * @param current * one of the following <code>Statement</code> constants * indicating what should happen to current * <code>ResultSet</code> objects obtained using the method * <code>getResultSet</code: <code>CLOSE_CURRENT_RESULT</code>, * <code>KEEP_CURRENT_RESULT</code>, or * <code>CLOSE_ALL_RESULTS</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no more results * @exception SQLException * if a database access error occurs * @since 1.4 * @see #execute */ @Override public boolean getMoreResults(int current) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getMoreResults(current); } /** * Retrieves any auto-generated keys created as a result of executing this * <code>Statement</code> object. If this <code>Statement</code> object did * not generate any keys, an empty <code>ResultSet</code> object is * returned. * * @return a <code>ResultSet</code> object containing the auto-generated * key(s) generated by the execution of this <code>Statement</code> * object * @exception SQLException * if a database access error occurs * @since 1.4 */ @Override public ResultSet getGeneratedKeys() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getGeneratedKeys(); } /** * Executes the given SQL statement and signals the driver with the given * flag about whether the auto-generated keys produced by this * <code>Statement</code> object should be made available for retrieval. * * @param sql * must be an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns * nothing * @param autoGeneratedKeys * a flag indicating whether auto-generated keys should be made * available for retrieval; one of the following constants: * <code>Statement.RETURN_GENERATED_KEYS</code> * <code>Statement.NO_GENERATED_KEYS</code> * @return either the row count for <code>INSERT</code>, <code>UPDATE</code> * or <code>DELETE</code> statements, or <code>0</code> for SQL * statements that return nothing * @exception SQLException * if a database access error occurs, the given SQL statement * returns a <code>ResultSet</code> object, or the given * constant is not one of those allowed * @since 1.4 */ @Override public int executeUpdate(String sql, int autoGeneratedKeys) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.executeUpdate(sql, autoGeneratedKeys); } /** * Executes the given SQL statement and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. The driver will ignore the array if the SQL statement is * not an <code>INSERT</code> statement. * * @param sql * an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns * nothing, such as an SQL DDL statement * @param columnIndexes * an array of column indexes indicating the columns that should * be returned from the inserted row * @return either the row count for <code>INSERT</code>, <code>UPDATE</code> * , or <code>DELETE</code> statements, or 0 for SQL statements that * return nothing * @exception SQLException * if a database access error occurs or the SQL statement * returns a <code>ResultSet</code> object * @since 1.4 */ @Override public int executeUpdate(String sql, int[] columnIndexes) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.executeUpdate(sql, columnIndexes); } /** * Executes the given SQL statement and signals the driver that the * auto-generated keys indicated in the given array should be made available * for retrieval. The driver will ignore the array if the SQL statement is * not an <code>INSERT</code> statement. * * @param sql * an SQL <code>INSERT</code>, <code>UPDATE</code> or * <code>DELETE</code> statement or an SQL statement that returns * nothing * @param columnNames * an array of the names of the columns that should be returned * from the inserted row * @return either the row count for <code>INSERT</code>, <code>UPDATE</code> * , or <code>DELETE</code> statements, or 0 for SQL statements that * return nothing * @exception SQLException * if a database access error occurs * * @since 1.4 */ @Override public int executeUpdate(String sql, String[] columnNames) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.executeUpdate(sql, columnNames); } /** * Executes the given SQL statement, which may return multiple results, and * signals the driver that any auto-generated keys should be made available * for retrieval. The driver will ignore this signal if the SQL statement is * not an <code>INSERT</code> statement. * <P> * In some (uncommon) situations, a single SQL statement may return multiple * result sets and/or update counts. Normally you can ignore this unless you * are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates * the form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the * result, and <code>getMoreResults</code> to move to any subsequent * result(s). * * @param sql * any SQL statement * @param autoGeneratedKeys * a constant indicating whether auto-generated keys should be * made available for retrieval using the method * <code>getGeneratedKeys</code>; one of the following constants: * <code>Statement.RETURN_GENERATED_KEYS</code> or * <code>Statement.NO_GENERATED_KEYS</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no results * @exception SQLException * if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * * @since 1.4 */ @Override public boolean execute(String sql, int autoGeneratedKeys) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.execute(sql, autoGeneratedKeys); } /** * Executes the given SQL statement, which may return multiple results, and * signals the driver that the auto-generated keys indicated in the given * array should be made available for retrieval. This array contains the * indexes of the columns in the target table that contain the * auto-generated keys that should be made available. The driver will ignore * the array if the given SQL statement is not an <code>INSERT</code> * statement. * <P> * Under some (uncommon) situations, a single SQL statement may return * multiple result sets and/or update counts. Normally you can ignore this * unless you are (1) executing a stored procedure that you know may return * multiple results or (2) you are dynamically executing an unknown SQL * string. * <P> * The <code>execute</code> method executes an SQL statement and indicates * the form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the * result, and <code>getMoreResults</code> to move to any subsequent * result(s). * * @param sql * any SQL statement * @param columnIndexes * an array of the indexes of the columns in the inserted row * that should be made available for retrieval by a call to the * method <code>getGeneratedKeys</code> * @return <code>true</code> if the first result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no results * @exception SQLException * if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * * @since 1.4 */ @Override public boolean execute(String sql, int[] columnIndexes) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.execute(sql, columnIndexes); } /** * Executes the given SQL statement, which may return multiple results, and * signals the driver that the auto-generated keys indicated in the given * array should be made available for retrieval. This array contains the * names of the columns in the target table that contain the auto-generated * keys that should be made available. The driver will ignore the array if * the given SQL statement is not an <code>INSERT</code> statement. * <P> * In some (uncommon) situations, a single SQL statement may return multiple * result sets and/or update counts. Normally you can ignore this unless you * are (1) executing a stored procedure that you know may return multiple * results or (2) you are dynamically executing an unknown SQL string. * <P> * The <code>execute</code> method executes an SQL statement and indicates * the form of the first result. You must then use the methods * <code>getResultSet</code> or <code>getUpdateCount</code> to retrieve the * result, and <code>getMoreResults</code> to move to any subsequent * result(s). * * @param sql * any SQL statement * @param columnNames * an array of the names of the columns in the inserted row that * should be made available for retrieval by a call to the method * <code>getGeneratedKeys</code> * @return <code>true</code> if the next result is a <code>ResultSet</code> * object; <code>false</code> if it is an update count or there are * no more results * @exception SQLException * if a database access error occurs * @see #getResultSet * @see #getUpdateCount * @see #getMoreResults * @see #getGeneratedKeys * * @since 1.4 */ @Override public boolean execute(String sql, String[] columnNames) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.execute(sql, columnNames); } /** * Retrieves the result set holdability for <code>ResultSet</code> objects * generated by this <code>Statement</code> object. * * @return either <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or * <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code> * @exception SQLException * if a database access error occurs * * @since 1.4 */ @Override public int getResultSetHoldability() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return this.statement.getResultSetHoldability(); } /** * @return * @throws SQLException * @see java.sql.Statement#isClosed() */ @Override public boolean isClosed() throws SQLException { return isClosed; } /** * @return * @throws SQLException * @see java.sql.Statement#isPoolable() */ @Override public boolean isPoolable() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return statement.isPoolable(); } /** * @param arg0 * @return * @throws SQLException * @see java.sql.Wrapper#isWrapperFor(java.lang.Class) */ @Override public boolean isWrapperFor(Class<?> arg0) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return statement.isWrapperFor(arg0); } /** * @param arg0 * @throws SQLException * @see java.sql.Statement#setPoolable(boolean) */ @Override public void setPoolable(boolean arg0) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); statement.setPoolable(arg0); } /** * @param <T> * @param arg0 * @return * @throws SQLException * @see java.sql.Wrapper#unwrap(java.lang.Class) */ @Override public <T> T unwrap(Class<T> arg0) throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return statement.unwrap(arg0); } /////////////////////////////////////////////////////////// // JAVA 7 METHOD EMULATION // /////////////////////////////////////////////////////////// // @Override do not override for Java 6 compatibility @Override public void closeOnCompletion() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); } // @Override do not override for Java 6 compatibility @Override public boolean isCloseOnCompletion() throws SQLException { String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); verifyCallAuthorization(methodName); return false; } }
package com.xicks.fibonacciserver import com.typesafe.config.ConfigFactory object Environment { val env = ConfigFactory.systemEnvironment() val hoconConfig = ConfigFactory.load().resolve()!! fun getOrDefault(fromEnv: String?, fromConfig: String?, default: String) : String { return listOf(env to fromEnv, hoconConfig to fromConfig) .asSequence() .mapNotNull { (config, property) -> if (property != null && config.hasPath(property)) { config.getString(property) } else null }.firstOrNull() ?: default } }
class CreateZipCodes < ActiveRecord::Migration def change create_table :zip_codes do |t| t.string :zip_code t.string :city t.belongs_to :state, index: true t.integer :district_count t.boolean :on_house_gov t.datetime :last_checked t.timestamps null: false end add_foreign_key :zip_codes, :states add_index :zip_codes, :zip_code, unique: true end end
// Copyright (c) to owners found in https://github.com/arlm/WinApi/blob/master/COPYRIGHT.md. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. using System.Runtime.InteropServices; namespace Sandbox { [StructLayout(LayoutKind.Sequential)] public struct DisplayData { // DWORD->unsigned int public uint dmDisplayFixedOutput; // DWORD->unsigned int public uint dmDisplayOrientation; // POINTL->_POINTL public PInvoke.POINT dmPosition; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Buffers.Binary; using System.IO; using System.Text; namespace Microsoft.Spark.Interop.Ipc { /// <summary> /// Enums with which Worker communicates with Spark. /// See spark/core/src/main/scala/org/apache/spark/api/python/PythonRunner.scala. /// </summary> internal enum SpecialLengths : int { /// <summary> /// Flag to indicate the end of data section /// </summary> END_OF_DATA_SECTION = -1, /// <summary> /// Flag to indicate an exception thrown from .NET side /// </summary> PYTHON_EXCEPTION_THROWN = -2, /// <summary> /// Flag to indicate a timing data /// </summary> TIMING_DATA = -3, /// <summary> /// Flag to indicate the end of stream /// </summary> END_OF_STREAM = -4, /// <summary> /// Flag to indicate non-defined type /// </summary> NULL = -5, /// <summary> /// Flag used by PySpark only. /// </summary> START_ARROW_STREAM = -6 } // TODO: When targeting .NET Core 2.1+ or .NET Standard 2.1+, all of this code can be simplified // using stackalloc'd spans and Stream.Read/Write(span). /// <summary> /// Serialization and Deserialization of data types between JVM and CLR /// </summary> internal class SerDe { [ThreadStatic] private static byte[] s_threadLocalBuffer; /// <summary> /// Reads a boolean from a stream. /// </summary> /// <param name="s">The stream to read</param> /// <returns>The boolean value read from the stream</returns> public static bool ReadBool(Stream s) => Convert.ToBoolean(s.ReadByte()); /// <summary> /// Reads an integer from a stream. /// </summary> /// <param name="s">The stream to be read</param> /// <returns>The integer read from stream</returns> public static int ReadInt32(Stream s) { byte[] buffer = GetThreadLocalBuffer(sizeof(int)); TryReadBytes(s, buffer, sizeof(int)); return BinaryPrimitives.ReadInt32BigEndian(buffer); } /// <summary> /// Reads a long integer from a stream. /// </summary> /// <param name="s">The stream to be read</param> /// <returns>The long integer read from stream</returns> public static long ReadInt64(Stream s) { byte[] buffer = GetThreadLocalBuffer(sizeof(long)); TryReadBytes(s, buffer, sizeof(long)); return BinaryPrimitives.ReadInt64BigEndian(buffer); } /// <summary> /// Reads a double from a stream. /// </summary> /// <param name="s">The stream to be read</param> /// <returns>The double read from stream</returns> public static double ReadDouble(Stream s) { byte[] buffer = GetThreadLocalBuffer(sizeof(long)); TryReadBytes(s, buffer, sizeof(long)); return BitConverter.Int64BitsToDouble(BinaryPrimitives.ReadInt64BigEndian(buffer)); } /// <summary> /// Reads a string from a stream /// </summary> /// <param name="s">The stream to be read</param> /// <returns>The string read from stream</returns> public static string ReadString(Stream s) { byte[] buffer = GetThreadLocalBuffer(sizeof(int)); if (!TryReadBytes(s, buffer, sizeof(int))) { return null; } return ReadString(s, BinaryPrimitives.ReadInt32BigEndian(buffer)); } /// <summary> /// Reads a string with a given length from a stream /// </summary> /// <param name="s">The stream to be read</param> /// <param name="length">The length to be read</param> /// <returns>The string read from stream</returns> public static string ReadString(Stream s, int length) { if (length == (int)SpecialLengths.NULL) { return null; } byte[] buffer = GetThreadLocalBuffer(length); TryReadBytes(s, buffer, length); return Encoding.UTF8.GetString(buffer, 0, length); } /// <summary> /// Reads a byte array with a given length from a stream /// </summary> /// <param name="s">The stream to be read</param> /// <param name="length">The length to be read</param> /// <returns>The a byte array read from stream</returns> /// <exception cref="ArgumentOutOfRangeException"> /// An ArgumentOutOfRangeException thrown if the given length is negative /// </exception> /// <exception cref="ArgumentException"> /// An ArgumentException if the actual read length is less than the given length /// </exception> public static byte[] ReadBytes(Stream s, int length) { if (length < 0) { throw new ArgumentOutOfRangeException(nameof(length), length, "length can't be negative."); } var buffer = new byte[length]; if (length > 0) { int bytesRead; int totalBytesRead = 0; do { bytesRead = s.Read(buffer, totalBytesRead, length - totalBytesRead); totalBytesRead += bytesRead; } while ((totalBytesRead < length) && (bytesRead > 0)); // The stream is closed, return null to notify function caller. if (totalBytesRead == 0) { return null; } if (totalBytesRead < length) { throw new ArgumentException( $"Incomplete bytes read: {totalBytesRead}, expected: {length}"); } } return buffer; } public static bool TryReadBytes(Stream s, byte[] buffer, int length) { if (length > 0) { int bytesRead; int totalBytesRead = 0; do { bytesRead = s.Read(buffer, totalBytesRead, length - totalBytesRead); totalBytesRead += bytesRead; } while ((totalBytesRead < length) && (bytesRead > 0)); // The stream is closed, return false to notify function caller. if (totalBytesRead == 0) { return false; } if (totalBytesRead < length) { throw new ArgumentException( $"Incomplete bytes read: {totalBytesRead}, expected: {length}"); } } return true; } public static int? ReadBytesLength(Stream s) { byte[] lengthBuffer = ReadBytes(s, sizeof(int)); if (lengthBuffer == null) { return null; } int length = BinaryPrimitives.ReadInt32BigEndian(lengthBuffer); if (length == (int)SpecialLengths.NULL) { return null; } return length; } /// <summary> /// Reads a byte array from a stream. The first 4 bytes indicate the length of a byte array. /// </summary> /// <param name="s">The stream to be read</param> /// <returns>The byte array read from stream</returns> public static byte[] ReadBytes(Stream s) { int? length = ReadBytesLength(s); if (length == null) { return null; } return ReadBytes(s, length.GetValueOrDefault()); } private static byte[] GetThreadLocalBuffer(int minSize) { const int DefaultMinSize = 256; byte[] buffer = s_threadLocalBuffer; if (buffer == null || buffer.Length < minSize) { s_threadLocalBuffer = buffer = new byte[Math.Max(DefaultMinSize, minSize)]; } return buffer; } /// <summary> /// Writes a byte to a stream /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The byte to write</param> public static void Write(Stream s, byte value) => s.WriteByte(value); /// <summary> /// Writes a byte array to a stream /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The byte array to write</param> public static void Write(Stream s, byte[] value) => Write(s, value, value.Length); /// <summary> /// Writes a byte array to a stream /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The byte array to write</param> /// <param name="count">The number of bytes in the array to write.</param> public static void Write(Stream s, byte[] value, int count) => s.Write(value, 0, count); /// <summary> /// Writes a boolean to a stream /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The boolean value to write</param> public static void Write(Stream s, bool value) => Write(s, Convert.ToByte(value)); /// <summary> /// Writes an integer to a stream (big-endian). /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The integer to write</param> public static void Write(Stream s, int value) { byte[] buffer = GetThreadLocalBuffer(sizeof(int)); BinaryPrimitives.WriteInt32BigEndian(buffer, value); Write(s, buffer, sizeof(int)); } /// <summary> /// Writes a long integer to a stream (big-endian). /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The long integer to write</param> public static void Write(Stream s, long value) { byte[] buffer = GetThreadLocalBuffer(sizeof(long)); BinaryPrimitives.WriteInt64BigEndian(buffer, value); Write(s, buffer, sizeof(long)); } /// <summary> /// Writes a double to a stream (big-endian). /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The double to write</param> public static void Write(Stream s, double value) => Write(s, BitConverter.DoubleToInt64Bits(value)); /// <summary> /// Writes a string to a stream. /// </summary> /// <param name="s">The stream to write</param> /// <param name="value">The string to write</param> public static void Write(Stream s, string value) { byte[] buffer = GetThreadLocalBuffer( sizeof(int) + Encoding.UTF8.GetMaxByteCount(value.Length)); int len = Encoding.UTF8.GetBytes(value, 0, value.Length, buffer, sizeof(int)); BinaryPrimitives.WriteInt32BigEndian(buffer, len); Write(s, buffer, sizeof(int) + len); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.netbeans.modules.spring.beans.wizards; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.swing.ListSelectionModel; import javax.swing.event.TableModelListener; import javax.swing.table.TableModel; import org.netbeans.modules.spring.api.beans.ConfigFileGroup; /** * * @author Rohan Ranade (Rohan.Ranade@Sun.COM) */ public class SpringXMLConfigGroupVisual extends javax.swing.JPanel { /** Creates new form SpringXMLConfigGroupVisual */ public SpringXMLConfigGroupVisual(List<ConfigFileGroup> configFileGroups) { initComponents(); groupsTable.getParent().setBackground(groupsTable.getBackground()); groupsTable.setModel(new ConfigGroupSelectionTableModel(configFileGroups)); groupsTable.getColumnModel().getColumn(0).setMaxWidth(0); groupsTable.getSelectionModel().setSelectionMode(ListSelectionModel.SINGLE_SELECTION); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { groupsScrollPane = new javax.swing.JScrollPane(); groupsTable = new javax.swing.JTable(); groupsLabel = new javax.swing.JLabel(); groupsTable.setIntercellSpacing(new java.awt.Dimension(0, 0)); groupsTable.setShowHorizontalLines(false); groupsTable.setShowVerticalLines(false); groupsTable.setTableHeader(null); groupsScrollPane.setViewportView(groupsTable); groupsLabel.setText(org.openide.util.NbBundle.getMessage(SpringXMLConfigGroupVisual.class, "LBL_Config_File_Selection")); // NOI18N javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(groupsLabel) .addContainerGap(152, Short.MAX_VALUE)) .addComponent(groupsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 431, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(groupsLabel) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(groupsScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 193, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel groupsLabel; private javax.swing.JScrollPane groupsScrollPane; private javax.swing.JTable groupsTable; // End of variables declaration//GEN-END:variables public Set<ConfigFileGroup> getSelectedConfigFileGroups() { return ((ConfigGroupSelectionTableModel)groupsTable.getModel()).getSelectedGroups(); } private static final class ConfigGroupSelectionTableModel implements TableModel { private List<ConfigFileGroup> groups; private boolean[] selected; public ConfigGroupSelectionTableModel(List<ConfigFileGroup> groups) { this.groups = groups; selected = new boolean[groups.size()]; } public int getRowCount() { return groups.size(); } public int getColumnCount() { return 2; } public String getColumnName(int columnIndex) { return ""; // NOI18N } public Class<?> getColumnClass(int columnIndex) { return (columnIndex == 0) ? Boolean.class : ConfigFileGroup.class; } public boolean isCellEditable(int rowIndex, int columnIndex) { return columnIndex == 0; } public Object getValueAt(int rowIndex, int columnIndex) { return (columnIndex == 0) ? selected[rowIndex] : groups.get(rowIndex).getName(); } public void setValueAt(Object aValue, int rowIndex, int columnIndex) { selected[rowIndex] = (Boolean)aValue; } public void addTableModelListener(TableModelListener l) { } public void removeTableModelListener(TableModelListener l) { } public Set<ConfigFileGroup> getSelectedGroups() { Set<ConfigFileGroup> selectedGroups = new HashSet<ConfigFileGroup>(groups.size()); for (int i = 0; i < groups.size(); i++) { if (selected[i]) { selectedGroups.add(groups.get(i)); } } return selectedGroups; } } }
#!/bin/sh echo 's x 1 s y 2 s z 3 w a.txt q '|./db 2>&1 >/dev/null echo 'l a.txt w b.txt q '|./db 2>&1 >/dev/null diff a.txt b.txt x=$? rm a.txt b.txt exit $x
(ns com.sixsq.slipstream.db.utils.acl) (defn- rule-of-type? [type rule] (= type (:type rule))) (def user-rule? (partial rule-of-type? "USER")) (def role-rule? (partial rule-of-type? "ROLE")) (def ^:const acl-users :_acl-users) (def ^:const acl-roles :_acl-roles) (defn- rules-with-owner [acl] (let [owner-rule (some-> acl :owner (assoc :right "ALL"))] (->> acl :rules (cons owner-rule) (into #{}) vec))) (defn- extract-by-type [acl type-pred] (->> (rules-with-owner acl) (filter type-pred) (map :principal))) (defn- extract-users [acl] (extract-by-type acl user-rule?)) (defn- extract-roles [acl] (extract-by-type acl role-rule?)) (defn denormalize-acl "Denormalize doc by exploding :acl in :_acl-users and :_acl-roles in a form easily searchable by Elastic Search" [doc] (-> doc (assoc acl-users (-> doc :acl extract-users)) (assoc acl-roles (-> doc :acl extract-roles)))) (defn normalize-acl "Dissoc denormalized field from doc" [doc] (dissoc doc acl-users acl-roles)) (defn force-admin-role-right-all [data] (update-in data [:acl :rules] #(vec (set (conj % {:type "ROLE" :principal "ADMIN" :right "ALL"})))))
# SecuconnectJsSdk.SecupayTransactionDTOExternalInvoicePdf ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **updateExisting** | **Boolean** | Update existing invoice PDF | [optional]
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.Collections.Generic; using Azure.Core; using Azure.Search.Documents.Models; namespace Azure.Search.Documents { /// <summary> /// Options for <see cref="SearchClient.AutocompleteAsync"/> that /// allow specifying autocomplete behaviors, like fuzzy matching. /// </summary> [CodeGenModel("AutocompleteRequest")] [CodeGenSuppress(nameof(AutocompleteOptions), typeof(string), typeof(string))] public partial class AutocompleteOptions : SearchRequestOptions { /// <summary> /// Initializes new instance of <see cref="AutocompleteOptions"/> /// </summary> public AutocompleteOptions() { } /// <summary> /// The search text on which to base autocomplete results. /// </summary> [CodeGenMember("search")] internal string SearchText { get; set; } /// <summary> /// The name of the suggester as specified in the suggesters collection /// that's part of the index definition. /// </summary> [CodeGenMember("suggesterName")] internal string SuggesterName { get; set; } /// <summary> /// Specifies the mode for Autocomplete. The default is /// <see cref="AutocompleteMode.OneTerm"/>. Use /// <see cref="AutocompleteMode.TwoTerms"/> to get shingles and /// <see cref="AutocompleteMode.OneTermWithContext"/> to use the /// current context while producing auto-completed terms. /// </summary> [CodeGenMember("autocompleteMode")] public AutocompleteMode? Mode { get; set; } /// <summary> /// An OData expression that filters the documents used to produce /// completed terms for the Autocomplete result. You can use /// <see cref="SearchFilter.Create(FormattableString)"/> to help /// construct the filter expression. /// </summary> [CodeGenMember("filter")] public string Filter { get; set; } /// <summary> /// The number of auto-completed terms to retrieve. This must be a /// value between 1 and 100. The default is 5. /// </summary> [CodeGenMember("top")] public int? Size { get; set; } /// <summary> /// The list of field names to consider when querying for /// auto-completed terms. Target fields must be included in the /// specified suggester. /// </summary> public IList<string> SearchFields { get; internal set; } = new List<string>(); #pragma warning disable CA1822 // Only (unused but required) setters are static /// <summary> /// Join SearchFields so it can be sent as a comma separated string. /// </summary> [CodeGenMember("searchFields")] internal string SearchFieldsRaw { get => SearchFields.CommaJoin(); set => throw new InvalidOperationException($"Cannot deserialize {nameof(AutocompleteOptions)}."); } #pragma warning restore CA1822 /// <summary> /// Creates a shallow copy of the AutocompleteOptions. /// </summary> /// <returns>The cloned AutocompleteOptions.</returns> internal AutocompleteOptions Clone() => new AutocompleteOptions { SearchText = SearchText, SuggesterName = SuggesterName, Mode = Mode, Filter = Filter, Size = Size, SearchFields = SearchFields, HighlightPostTag = HighlightPostTag, HighlightPreTag = HighlightPreTag, MinimumCoverage = MinimumCoverage, UseFuzzyMatching = UseFuzzyMatching, ClientRequestId = ClientRequestId }; } }
{-# LANGUAGE MagicHash #-} {-# LANGUAGE PolyKinds #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE UnboxedTuples #-} module RepPolyTupleSection where import GHC.Exts foo :: forall (r :: RuntimeRep) (a :: TYPE r). a -> (# Int#, a #) foo = (# 3#, #)
extern crate cluExtIO; use std::io::Write; use cluExtIO::analytics::CounterIOWrite; use std::io; fn main() -> Result<(), io::Error> { let out = io::stdout(); let mut counter = CounterIOWrite::from(out.lock()); for _a in 0..3 { counter.write(b"11")?; } counter.flush()?; println!(); println!("#Debug out:"); counter.write_stat(&mut out.lock())?; Ok( () ) }
#!/bin/bash # # Copyright (c) 2017, UT-BATTELLE, LLC # All rights reserved. # # This software is released under the BSD license detailed # in the LICENSE file in the top level a-prime directory # #PBS -q acme #PBS -l nodes=1 #PBS -l walltime=01:00:00 #PBS -A ACME #PBS -N aprime_ocnice_diags #PBS -o aprime_ocnice_diags.o$PBS_JOBID #PBS -e aprime_ocnice_diags.e$PBS_JOBID #PBS -V cd $PBS_O_WORKDIR export command_prefix="" unset LD_LIBRARY_PATH soft add +acme-unified-1.1.1-x ./bash_scripts/aprime_ocnice_diags.bash echo echo "**** The following batch job will be submitted to cp files to www_dir *if* the ocn/ice diags are completed" echo "**** jobID:" batch_script="./bash_scripts/batch_update_wwwdir.$machname.bash" qsub -W depend=afterok:$PBS_JOBID $batch_script
using CompAnalytics.X9.Records; using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace CompAnalytics.X9.Document { [DataContract] [Serializable] public class X9DepositItemImage : X9DocumentComponent { [DataMember] public ImageViewDetailRecord ImageViewDetail { get; set; } [DataMember] public ImageViewDataRecord ImageViewData { get; set; } public override List<X9Record> GetRecords() { return new List<X9Record> { this.ImageViewData, this.ImageViewDetail }; } } }
module Hearsay module Railties module ActionCableExtension module Subscribe extend ActiveSupport::Concern included do Hearsay.subscribe! /perform_action.action_cable$/i do |event| payload = { channel_class: event.payload[:channel_class], action: event.payload[:action], start_time: event.time, end_time: event.end, data: event.payload[:data] } Hearsay::Publisher.push 'cable', payload end end end module Payload def perform_action(data) #add more data then pass it in if respond_to?(:hearsay_attributes) # request_data[:custom_attributes] = request.controller_instance.hearsay_attributes Thread.current[:hearsay_custom_attributes] = hearsay_attributes end super_data = data # super_data = data.merge({current_user: current_user.id, current_provider: current_provider.try(:id)}) super super_data end end end end end ActiveSupport.on_load(:action_cable) do class ActionCable::Channel::Base include Hearsay::Railties::ActionCableExtension::Subscribe prepend Hearsay::Railties::ActionCableExtension::Payload end end
# -*- coding: utf-8 -*- """ Editor: Zhao Xinlu School: BUPT Date: 2018-03-27 算法思想:设置矩阵0 """ class Solution(object): def setZeroes(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ m = len(matrix) n = len(matrix[0]) row = [False for i in range(m)] colum = [False for j in range(n)] for i in range(m): for j in range(n): if matrix[i][j] == 0: row[i] = True colum[j] = True for i in range(m): for j in range(n): if row[i] or colum[j]: matrix[i][j] = 0
import { combineReducers, createStore } from 'redux' import { userReducer } from './User/User.reducer' const rootReducer = combineReducers({ userData: userReducer }) export const store = createStore( rootReducer, window._REDUX_DEVTOOLS_EXTENSION_ && window._REDUX_DEVTOOLS_EXTENSION_() )
package delta_test import ( "testing" "github.com/GeoNet/delta/meta" ) var testGains = map[string]func([]meta.Gain) func(t *testing.T){ "check for gain installation overlaps": func(installed []meta.Gain) func(t *testing.T) { return func(t *testing.T) { installs := make(map[string]meta.GainList) for _, s := range installed { for _, c := range s.Gains() { installs[c.Id()] = append(installs[c.Id()], c) } } for _, v := range installs { for i := 0; i < len(v); i++ { for j := i + 1; j < len(v); j++ { if v[i].End.Before(v[j].Start) { continue } if v[i].Start.After(v[j].End) { continue } if v[i].End.Equal(v[j].Start) { continue } if v[i].Start.Equal(v[j].End) { continue } t.Errorf("gain %s/%s has component %s overlap between %s and %s", v[i].Station, v[i].Location, v[i].Channel, v[i].Start.Format(meta.DateTimeFormat), v[i].End.Format(meta.DateTimeFormat)) } } } } }, } var testGainsSites = map[string]func([]meta.Gain, []meta.Site) func(t *testing.T){ "check for missing sites": func(installed []meta.Gain, sites []meta.Site) func(t *testing.T) { return func(t *testing.T) { for _, s := range installed { var found bool for _, a := range sites { if a.Station != s.Station { continue } if a.Location != s.Location { continue } found = true } if found { continue } t.Errorf("unable to find gain site: %s [%s]", s.Station, s.Location) } } }, } func TestGains(t *testing.T) { var installed meta.GainList loadListFile(t, "../install/gains.csv", &installed) for k, fn := range testGains { t.Run(k, fn(installed)) } } func TestGains_Sites(t *testing.T) { var installed meta.GainList loadListFile(t, "../install/gains.csv", &installed) var sites meta.SiteList loadListFile(t, "../network/sites.csv", &sites) for k, fn := range testGainsSites { t.Run(k, fn(installed, sites)) } }
export default interface CabinetAlterer { createSection(sectionName: string, destId?: string): Promise<void>; createPage(pageName: string, destId?: string): Promise<string>; renameElement(id: string, newName: string): Promise<void>; moveElement(id: string, destId: string): Promise<void>; deleteElement(id: string): Promise<void>; }
use std::collections::HashSet; use std::fmt; use std::iter::FromIterator; /// Someone living in the housing unit /// /// A wrapper around the name of someone financially responsible for charges #[derive(Hash, PartialEq, Clone, Debug)] pub struct Roommate(String); impl Roommate { /// Creates a new `Roommate` /// /// # Examples /// ``` /// use roommates::Roommate; /// /// let bob = Roommate::new("Bob"); /// assert_eq!(format!("{}", bob), "Bob"); /// ``` pub fn new(name: &str) -> Self { Roommate(String::from(name)) } } impl fmt::Display for Roommate { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } } impl Eq for Roommate {} /// A collection of [`Roommate`]s /// /// [`Roommate`]: struct.Roommate.html pub struct RoommateGroup(HashSet<Roommate>); impl RoommateGroup { /// Returns the number of `Roommate`s in the `RoommateGroup` /// /// # Examples /// ``` /// use roommates::RoommateGroup; /// /// let group: RoommateGroup = vec!["Bob", "Joe"].into_iter().collect(); /// assert_eq!(group.count(), 2); /// ``` pub fn count(&self) -> u32 { self.0.len() as u32 } /// Returns an iterator that visits each `Roommate` in the group pub fn iter(&self) -> impl Iterator<Item = &Roommate> { self.0.iter() } /// Returns a reference to a roommate with the given name /// /// # Examples /// ``` /// use roommates::{Roommate, RoommateGroup}; /// /// let group: RoommateGroup = vec!["Bob", "Joe"].into_iter().collect(); /// assert_eq!(group.borrow_by_name("Bob"), Some(&Roommate::new("Bob"))); /// assert_eq!(group.borrow_by_name("Steve"), None); /// ``` pub fn borrow_by_name(&self, name: &str) -> Option<&Roommate> { self.0.iter().find(|r| r.0 == name) } } impl<'a> FromIterator<&'a str> for RoommateGroup { fn from_iter<I: IntoIterator<Item = &'a str>>(names: I) -> Self { RoommateGroup(names.into_iter().map(|n| Roommate::new(n)).collect()) } }
#pragma once #include "definitions.h" #include "options.h" class Serial { public: Serial(Options& inOptions) : options(inOptions) {} auto read() const -> u8; void write(u8 byte); void write_control(u8 byte) const; private: Options& options; u8 data; };
package com.doge.client.module.modules.movement; import com.doge.api.setting.settings.NumberSetting; import com.doge.client.module.Category; import com.doge.client.module.Module; import org.lwjgl.input.Keyboard; public class Step extends Module { public NumberSetting stepHeight = new NumberSetting("Step Height", this, 2, 1, 5, 1); public Step() { super("Step", "Changes your step height.", Category.MOVEMENT); this.addSetting(stepHeight); } @Override public void onUpdate() { if (mc.player == null || mc.world == null) { return; } mc.player.stepHeight = (float) stepHeight.getNumber(); } @Override public void onDisable() { mc.player.stepHeight = 0.5f; } @Override public void onEnable() { } }
/* * This file is part of Buttermilk(TM) * Copyright 2013-2015 David R. Smith for cryptoregistry.com * */ package com.cryptoregistry.client.security; import java.io.File; import com.cryptoregistry.formats.simplereader.JSONSymmetricKeyReader; import com.cryptoregistry.passwords.Password; import com.cryptoregistry.passwords.SensitiveBytes; import com.cryptoregistry.symmetric.SymmetricKeyContents; /** * Creates and loads key needed for securing the key vault. This basic manager just loads a symmetric key. * * @author Dave * */ public class BasicKeyManager implements KeyManager { final SymmetricKeyContents key; public BasicKeyManager(File path, Password password) { JSONSymmetricKeyReader reader = new JSONSymmetricKeyReader(path,password); key = reader.parse(); password.selfDestruct(); } @Override public SensitiveBytes loadKey() { return new SensitiveBytes(key.getBytes()); } }
<?php return array ( 'singular' => 'ipcontaip_14_dadosfatura', 'plural' => 'ipcontaip_14_dadosfaturas', 'fields' => array ( 'id' => 'Id', 'idcidade' => 'Idcidade', 'tipo_reg' => 'Tipo Reg', 'cnpj' => 'Cnpj', 'cod_cliente' => 'Cod Cliente', 'cod_contrato' => 'Cod Contrato', 'num_medidor' => 'Num Medidor', 'cod_multiservico' => 'Cod Multiservico', 'num_doc_pag_coletiva' => 'Num Doc Pag Coletiva', 'num_fatura' => 'Num Fatura', 'cod_conceito' => 'Cod Conceito', 'qtd_conceito' => 'Qtd Conceito', 'preco_conceito' => 'Preco Conceito', 'sinal_do_valor_conceitos' => 'Sinal Do Valor Conceitos', 'valor_final_com_imposto' => 'Valor Final Com Imposto', 'descricao_conceito' => 'Descricao Conceito', 'contaipano' => 'Contaipano', 'contaipmes' => 'Contaipmes', 'segmento' => 'Segmento', 'created_at' => 'Created At', 'updated_at' => 'Updated At', 'deleted_at' => 'Deleted At', ), );
{-# LANGUAGE FlexibleContexts #-} {-# LANGUAGE BangPatterns #-} {-# LANGUAGE ViewPatterns #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeApplications #-} {-# LANGUAGE ScopedTypeVariables #-} module Main where import Control.Monad import Data.Bits import Data.Char import Data.List import Data.List.Split import qualified Data.Map.Strict as M import Data.Maybe import Debug.Trace import Text.Read main :: IO () main = day4 day4 :: IO () day4 = do putStrLn "day 4" ls <- lines <$> readFile "day4.txt" let newLines = fmap (intercalate " ") (splitOn [""] ls) print $ day4pt1 newLines print $ day4pt2 newLines day4pt1 :: [String] -> Int day4pt1 = solve4 (const mempty) day4pt2 :: [String] -> Int day4pt2 = solve4 $ \m -> [ validByr (m M.! "byr") && validIyr (m M.! "iyr") && validEyr (m M.! "eyr") && validHgt (m M.! "hgt") && validHcl (m M.! "hcl") && validEcl (m M.! "ecl") && validPid (m M.! "pid") ] solve4 :: (M.Map String String -> [Bool]) -> [String] -> Int solve4 validationRules = foldl' countValidPassports 0 where countValidPassports :: Int -> String -> Int countValidPassports acc line = do let fillMap m word | [k,v] <- splitOn ":" word = M.insert k v m m = foldl' fillMap mempty (words line) allFound = isJust (traverse (`M.lookup` m) day4Keys) if allFound && and (validationRules m) then acc + 1 else acc day4Keys = [ "byr" , "iyr" , "eyr" , "hgt" , "hcl" , "ecl" , "pid" ] ranged :: (Int,Int) -> String -> Bool ranged (x',y') str = case readMaybe str of Nothing -> False Just (x :: Int) -> x >= x' && x <= y' validHgt :: String -> Bool validHgt xs = case readMaybe @Int (takeWhile isDigit xs) of Nothing -> False Just num -> case reverse (take 2 (reverse xs)) of "cm" -> ranged (150,193) (takeWhile isDigit xs) "in" -> ranged (59,76) (takeWhile isDigit xs) _ -> False validHcl :: String -> Bool validHcl ('#':str) | and [ length str == 6 , all (\x -> x `elem` ['0'..'9'] || x `elem` ['a'..'f']) str ] = True validHcl _ = False validEcl :: String -> Bool validEcl xs = xs `elem` ["amb", "blu","brn","gry","grn","hzl","oth"] validPid :: String -> Bool validPid xs = length (takeWhile isDigit xs) == 9 validByr, validIyr, validEyr :: String -> Bool validByr = ranged (1920,2002) validIyr = ranged (2010,2020) validEyr = ranged (2020,2030)
namespace Incoding.CQRS { #region << Using >> using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using Incoding.Block; using Incoding.Data; using Incoding.Quality; using JetBrains.Annotations; #endregion public class GetEntityByIdQuery<T> : QueryBase<T> where T : class, IEntity, new() { #region Constructors [UsedImplicitly, Obsolete(ObsoleteMessage.SerializeConstructor), ExcludeFromCodeCoverage] public GetEntityByIdQuery() { } ////ncrunch: no coverage start public GetEntityByIdQuery(object id) { Id = id; } #endregion ////ncrunch: no coverage end #region Properties public object Id { get; set; } #endregion #region Override protected override T ExecuteResult() { return Repository.GetById<T>(Id); } #endregion } }
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: MIT-0 import React, { useContext } from "react"; import { Hub } from "@aws-amplify/core"; import { Text, View, SwitchField } from "@aws-amplify/ui-react"; import { AppContext, RoutingModesEnum } from "../../AppContext"; // Component: AvoidanceOptions - Renders the options for the avoidance routing mode const AvoidanceOptions = () => { const context = useContext(AppContext); const defaultChecked = {}; // Set defaults based on the current routing mode if (context.routingMode === RoutingModesEnum.CAR) { defaultChecked.AvoidFerries = context.carOptions.AvoidFerries; defaultChecked.AvoidTolls = context.carOptions.AvoidTolls; } else if (context.routingMode === RoutingModesEnum.TRUCK) { defaultChecked.AvoidFerries = context.truckOptions.AvoidFerries; defaultChecked.AvoidTolls = context.truckOptions.AvoidTolls; } // Handler for the avoidances changes const handleAvoidanceChanges = (id, value) => { console.debug(`${id} changed to`, value); Hub.dispatch( "Routing", { event: "changeAvoidances", data: { key: id, value: value, }, }, context.routingMode ); }; return ( <> <Text fontSize="small">Avoid</Text> <View key={`${context.routingMode}AvoidFerries`}> <SwitchField isDisabled={false} label="Ferries" isLabelHidden={false} labelPosition="end" trackColor="var(--amplify-colors-background-secondary)" trackCheckedColor="var(--amplify-colors-brand-primary)" onChange={(e) => handleAvoidanceChanges("AvoidFerries", e.target.checked) } defaultChecked={defaultChecked.AvoidFerries} /> </View> <View key={`${context.routingMode}AvoidTolls`} title="Avoid tolls when calculating routes" > <SwitchField isDisabled={false} label="Tolls" isLabelHidden={false} labelPosition="end" trackColor="var(--amplify-colors-background-secondary)" trackCheckedColor="var(--amplify-colors-brand-primary)" onChange={(e) => handleAvoidanceChanges("AvoidTolls", e.target.checked) } defaultChecked={defaultChecked.AvoidTolls} /> </View> </> ); }; export default AvoidanceOptions;
<?php namespace App\Support; use InvalidArgumentException; final class Percentage extends Number { protected $suffix = '%'; public function __construct($amount) { if ($amount < 0 || $amount > 100) { throw new InvalidArgumentException('Amount must be between 0 and 100'); } parent::__construct($amount); $this->amount = $amount; } }
package typingsSlinky.ipfsHttpServer import typingsSlinky.ipfsHttpServer.anon.Handler import typingsSlinky.ipfsHttpServer.anon.HandlerOptions import typingsSlinky.ipfsHttpServer.anon.Typeof_import import typingsSlinky.ipfsHttpServer.anon.Typeof_new import typingsSlinky.ipfsHttpServer.anon.Typeofadd import typingsSlinky.ipfsHttpServer.anon.TypeofaddDefault import typingsSlinky.ipfsHttpServer.anon.TypeofaddHandler import typingsSlinky.ipfsHttpServer.anon.Typeofaddrs import typingsSlinky.ipfsHttpServer.anon.Typeofbw import typingsSlinky.ipfsHttpServer.anon.Typeofcat import typingsSlinky.ipfsHttpServer.anon.Typeofconnect import typingsSlinky.ipfsHttpServer.anon.Typeofdata import typingsSlinky.ipfsHttpServer.anon.Typeofdisconnect import typingsSlinky.ipfsHttpServer.anon.TypeoffindPeer import typingsSlinky.ipfsHttpServer.anon.TypeoffindProvs import typingsSlinky.ipfsHttpServer.anon.Typeofgc import typingsSlinky.ipfsHttpServer.anon.Typeofgen import typingsSlinky.ipfsHttpServer.anon.Typeofget import typingsSlinky.ipfsHttpServer.anon.TypeofgetHandler import typingsSlinky.ipfsHttpServer.anon.TypeofgetOptions import typingsSlinky.ipfsHttpServer.anon.TypeofgetOptions4 import typingsSlinky.ipfsHttpServer.anon.TypeofgetOrSet import typingsSlinky.ipfsHttpServer.anon.Typeofimport import typingsSlinky.ipfsHttpServer.anon.Typeoflinks import typingsSlinky.ipfsHttpServer.anon.Typeoflist import typingsSlinky.ipfsHttpServer.anon.TypeoflocalAddrs import typingsSlinky.ipfsHttpServer.anon.Typeofls import typingsSlinky.ipfsHttpServer.anon.TypeoflsHandler import typingsSlinky.ipfsHttpServer.anon.TypeoflsOptions4 import typingsSlinky.ipfsHttpServer.anon.Typeofnew import typingsSlinky.ipfsHttpServer.anon.TypeofpatchAddLink import typingsSlinky.ipfsHttpServer.anon.TypeofpatchAppendData import typingsSlinky.ipfsHttpServer.anon.TypeofpatchRmLink import typingsSlinky.ipfsHttpServer.anon.TypeofpatchSetData import typingsSlinky.ipfsHttpServer.anon.Typeofpeers import typingsSlinky.ipfsHttpServer.anon.TypeofpeersHandler import typingsSlinky.ipfsHttpServer.anon.Typeofprofiles import typingsSlinky.ipfsHttpServer.anon.Typeofprovide import typingsSlinky.ipfsHttpServer.anon.Typeofpublish import typingsSlinky.ipfsHttpServer.anon.TypeofpublishHandler import typingsSlinky.ipfsHttpServer.anon.Typeofpubsub import typingsSlinky.ipfsHttpServer.anon.Typeofput import typingsSlinky.ipfsHttpServer.anon.TypeofputHandler import typingsSlinky.ipfsHttpServer.anon.TypeofputOptions2 import typingsSlinky.ipfsHttpServer.anon.TypeofputOptions8 import typingsSlinky.ipfsHttpServer.anon.Typeofquery import typingsSlinky.ipfsHttpServer.anon.Typeofrefs import typingsSlinky.ipfsHttpServer.anon.TypeofrefsLocal import typingsSlinky.ipfsHttpServer.anon.Typeofrename import typingsSlinky.ipfsHttpServer.anon.Typeofreplace import typingsSlinky.ipfsHttpServer.anon.Typeofresolve import typingsSlinky.ipfsHttpServer.anon.TypeofresolveHandler import typingsSlinky.ipfsHttpServer.anon.Typeofrm import typingsSlinky.ipfsHttpServer.anon.TypeofrmAll import typingsSlinky.ipfsHttpServer.anon.TypeofrmHandler import typingsSlinky.ipfsHttpServer.anon.TypeofrmHandler1 import typingsSlinky.ipfsHttpServer.anon.Typeofshow import typingsSlinky.ipfsHttpServer.anon.Typeofstat import typingsSlinky.ipfsHttpServer.anon.TypeofstatHandler import typingsSlinky.ipfsHttpServer.anon.TypeofstatOptions2 import typingsSlinky.ipfsHttpServer.anon.Typeofsubscribe import typingsSlinky.ipfsHttpServer.anon.Typeofunwant import typingsSlinky.ipfsHttpServer.anon.Typeofversion import typingsSlinky.ipfsHttpServer.anon.Typeofwantlist import typingsSlinky.ipfsHttpServer.anon.Validate import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object resourcesMod { object bitswap { @JSImport("ipfs-http-server/dist/src/api/resources", "bitswap.stat") @js.native val stat: TypeofstatOptions2 = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "bitswap.unwant") @js.native val unwant: Typeofunwant = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "bitswap.wantlist") @js.native val wantlist: Typeofwantlist = js.native } object block { @JSImport("ipfs-http-server/dist/src/api/resources", "block.get") @js.native val get: TypeofgetHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "block.put") @js.native val put: TypeofputHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "block.rm") @js.native val rm: TypeofrmHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "block.stat") @js.native val stat: TypeofstatHandler = js.native } object bootstrap { @JSImport("ipfs-http-server/dist/src/api/resources", "bootstrap.add") @js.native val add: Typeofadd = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "bootstrap.addDefault") @js.native val addDefault: TypeofaddDefault = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "bootstrap.list") @js.native val list: Typeoflist = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "bootstrap.rm") @js.native val rm: Typeofrm = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "bootstrap.rmAll") @js.native val rmAll: TypeofrmAll = js.native } object config { @JSImport("ipfs-http-server/dist/src/api/resources", "config.get") @js.native val get: Typeofget = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "config.getOrSet") @js.native val getOrSet: TypeofgetOrSet = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "config.profiles") @js.native val profiles: Typeofprofiles = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "config.replace") @js.native val replace: Typeofreplace = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "config.show") @js.native val show: Typeofshow = js.native } object dag { @JSImport("ipfs-http-server/dist/src/api/resources", "dag.get") @js.native val get: TypeofgetOptions = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dag.put") @js.native val put: TypeofputOptions2 = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dag.resolve") @js.native val resolve: Typeofresolve = js.native } object dht { @JSImport("ipfs-http-server/dist/src/api/resources", "dht.findPeer") @js.native val findPeer: TypeoffindPeer = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dht.findProvs") @js.native val findProvs: TypeoffindProvs = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dht.get") @js.native val get: TypeofgetOptions4 = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dht.provide") @js.native val provide: Typeofprovide = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dht.put") @js.native val put: TypeofputOptions8 = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dht.query") @js.native val query: Typeofquery = js.native } object dns { @JSImport("ipfs-http-server/dist/src/api/resources", "dns") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dns.handler") @js.native def handler(request: js.Any, h: js.Any): js.Promise[_] = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "dns.options") @js.native def options: Validate = js.native @scala.inline def options_=(x: Validate): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("options")(x.asInstanceOf[js.Any]) } object files { @JSImport("ipfs-http-server/dist/src/api/resources", "files") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "files.chmod") @js.native def chmod: Handler = js.native @scala.inline def chmod_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("chmod")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.cp") @js.native def cp: Handler = js.native @scala.inline def cp_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("cp")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.flush") @js.native def flush: Handler = js.native @scala.inline def flush_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("flush")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.ls") @js.native def ls: Handler = js.native @scala.inline def ls_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("ls")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.mkdir") @js.native def mkdir: Handler = js.native @scala.inline def mkdir_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("mkdir")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.mv") @js.native def mv: Handler = js.native @scala.inline def mv_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("mv")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.read") @js.native def read: Handler = js.native @scala.inline def read_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("read")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.rm") @js.native def rm: Handler = js.native @scala.inline def rm_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("rm")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.stat") @js.native def stat: Handler = js.native @scala.inline def stat_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("stat")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.touch") @js.native def touch: Handler = js.native @scala.inline def touch_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("touch")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "files.write") @js.native def write: HandlerOptions = js.native @scala.inline def write_=(x: HandlerOptions): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("write")(x.asInstanceOf[js.Any]) } object filesRegular { @JSImport("ipfs-http-server/dist/src/api/resources", "filesRegular.add") @js.native val add: TypeofaddHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "filesRegular.cat") @js.native val cat: Typeofcat = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "filesRegular.get") @js.native val get: Typeofget = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "filesRegular.ls") @js.native val ls: TypeoflsHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "filesRegular.refs") @js.native val refs: Typeofrefs = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "filesRegular.refsLocal") @js.native val refsLocal: TypeofrefsLocal = js.native } object id { @JSImport("ipfs-http-server/dist/src/api/resources", "id") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "id.handler") @js.native def handler(request: js.Any, h: js.Any): js.Promise[_] = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "id.options") @js.native def options: Validate = js.native @scala.inline def options_=(x: Validate): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("options")(x.asInstanceOf[js.Any]) } object key { @JSImport("ipfs-http-server/dist/src/api/resources", "key._import") @js.native val _import: Typeof_import = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "key.gen") @js.native val gen: Typeofgen = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "key.list") @js.native val list: Typeoflist = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "key.rename") @js.native val rename: Typeofrename = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "key.rm") @js.native val rm: TypeofrmHandler1 = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "key.import") @js.native val `import`: Typeofimport = js.native } object name { @JSImport("ipfs-http-server/dist/src/api/resources", "name.publish") @js.native val publish: TypeofpublishHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "name.pubsub") @js.native val pubsub: Typeofpubsub = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "name.resolve") @js.native val resolve: TypeofresolveHandler = js.native } object pin { @JSImport("ipfs-http-server/dist/src/api/resources", "pin.add") @js.native val add: Typeofadd = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "pin.ls") @js.native val ls: Typeofls = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "pin.rm") @js.native val rm: TypeofrmHandler = js.native } object ping { @JSImport("ipfs-http-server/dist/src/api/resources", "ping") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "ping.handler") @js.native def handler(request: js.Any, h: js.Any): js.Promise[_] = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "ping.options") @js.native def options: Validate = js.native @scala.inline def options_=(x: Validate): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("options")(x.asInstanceOf[js.Any]) } object pubsub { @JSImport("ipfs-http-server/dist/src/api/resources", "pubsub.ls") @js.native val ls: TypeoflsOptions4 = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "pubsub.peers") @js.native val peers: TypeofpeersHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "pubsub.publish") @js.native val publish: Typeofpublish = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "pubsub.subscribe") @js.native val subscribe: Typeofsubscribe = js.native } object repo { @JSImport("ipfs-http-server/dist/src/api/resources", "repo.gc") @js.native val gc: Typeofgc = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "repo.stat") @js.native val stat: Typeofstat = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "repo.version") @js.native val version: Typeofversion = js.native } object resolve { @JSImport("ipfs-http-server/dist/src/api/resources", "resolve") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "resolve.handler") @js.native def handler(request: js.Any, h: js.Any): js.Promise[_] = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "resolve.options") @js.native def options: Validate = js.native @scala.inline def options_=(x: Validate): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("options")(x.asInstanceOf[js.Any]) } object shutdown { @JSImport("ipfs-http-server/dist/src/api/resources", "shutdown.handler") @js.native def handler(_request: js.Any, h: js.Any): js.Any = js.native } object stats { @JSImport("ipfs-http-server/dist/src/api/resources", "stats") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "stats.bitswap") @js.native def bitswap: Handler = js.native @scala.inline def bitswap_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("bitswap")(x.asInstanceOf[js.Any]) @JSImport("ipfs-http-server/dist/src/api/resources", "stats.bw") @js.native val bw: Typeofbw = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "stats.repo") @js.native def repo: Handler = js.native @scala.inline def repo_=(x: Handler): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("repo")(x.asInstanceOf[js.Any]) } object swarm { @JSImport("ipfs-http-server/dist/src/api/resources", "swarm.addrs") @js.native val addrs: Typeofaddrs = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "swarm.connect") @js.native val connect: Typeofconnect = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "swarm.disconnect") @js.native val disconnect: Typeofdisconnect = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "swarm.localAddrs") @js.native val localAddrs: TypeoflocalAddrs = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "swarm.peers") @js.native val peers: Typeofpeers = js.native } object version { @JSImport("ipfs-http-server/dist/src/api/resources", "version") @js.native val ^ : js.Any = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "version.handler") @js.native def handler(request: js.Any, h: js.Any): js.Promise[_] = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "version.options") @js.native def options: Validate = js.native @scala.inline def options_=(x: Validate): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("options")(x.asInstanceOf[js.Any]) } object `object` { @JSImport("ipfs-http-server/dist/src/api/resources", "object._new") @js.native val _new: Typeof_new = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.data") @js.native val data: Typeofdata = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.get") @js.native val get: Typeofget = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.links") @js.native val links: Typeoflinks = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.patchAddLink") @js.native val patchAddLink: TypeofpatchAddLink = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.patchAppendData") @js.native val patchAppendData: TypeofpatchAppendData = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.patchRmLink") @js.native val patchRmLink: TypeofpatchRmLink = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.patchSetData") @js.native val patchSetData: TypeofpatchSetData = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.put") @js.native val put: Typeofput = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.stat") @js.native val stat: TypeofstatHandler = js.native @JSImport("ipfs-http-server/dist/src/api/resources", "object.new") @js.native val `new`: Typeofnew = js.native } }
package com.xenoage.utils.promise; import static com.xenoage.utils.promise.Calculator.Op.Div; import static com.xenoage.utils.promise.Calculator.Op.Plus; /** * A helper class for {@link PromiseTest}, performing simple calculations. * * @author Andreas Wenger */ public class Calculator { public enum Op { Plus, Div; } /** * Returns the result asynchronously. */ public static Promise<Integer> calc(int value1, Op op, int value2) { Promise<Integer> ret = new Promise<>(r -> { //Plus returns immediately if (op == Plus) { r.resolve(value1 + value2); } //Simulate more time with Div else if (op == Div) { //new Timer().schedule(new TimerTask() { // @Override public void run() { if (value2 == 0) r.reject(new ArithmeticException()); else r.resolve(value1 / value2); // } //},500); } else { r.reject(new UnsupportedOperationException()); } }); return ret; } }
package net.miririt.maldives.compat import android.content.Context import android.net.Uri import android.webkit.JavascriptInterface import androidx.documentfile.provider.DocumentFile import net.miririt.maldives.appendUri import org.json.JSONArray import java.io.* class FileSystemInterface(var context: Context, private val workDir: DocumentFile) { private val workUri: Uri = workDir.uri private val resolver = context.contentResolver private fun getFilename(path: String): String { return path.substring(path.lastIndexOf('/') + 1) } private fun getParentFilename(path: String): String { val parentPath = path.substring(0, path.lastIndexOf('/')) return parentPath.substring(parentPath.lastIndexOf('/') + 1) } private fun getParentPath(path: String): String { return path.substring(0, path.lastIndexOf('/')) } private fun resolvePath(startDir : DocumentFile, path: String) : DocumentFile { var currentPath = startDir val segments = path.split('/') for(dirName in segments) { if(dirName != "" && dirName != ".") currentPath = currentPath.findFile(dirName)!! } return currentPath } private fun touchFile(path : String) : Boolean { return try { val targetFile = DocumentFile.fromSingleUri(context, appendUri(workUri, path)) if(targetFile != null && targetFile.exists()) { return true } val parentFile = try { resolvePath(workDir, getParentPath(path)) } catch(e : Exception) { mkdirSync(getParentPath(path), true) resolvePath(workDir, getParentPath(path)) } val createdFile = parentFile.createFile("", getFilename(path)) if(createdFile != null && createdFile.exists() && createdFile.name == getFilename(path)) { true } else if(createdFile == null || !createdFile.exists()) { false } else { createdFile.renameTo(getFilename(path)) } } catch(e : Exception) { false } } @JavascriptInterface fun existsSync(path: String?): Boolean { if(path == null) return false return try { resolver.openFileDescriptor(appendUri(workUri, path), "r")!!.close() true } catch (ignore: Exception) { false } } @JavascriptInterface fun readFileSync(path: String?, encoding: String?): String { if(path == null) return "" return try { val fis = resolver.openInputStream(appendUri(workUri, path)) val baos = ByteArrayOutputStream() val buffer = ByteArray(1024 * 256) var length: Int while (fis!!.read(buffer).also { length = it } > 0) { baos.write(buffer, 0, length) } fis.close() baos.toString(encoding ?: "utf8") } catch (ignore: Exception) { "" } } @JavascriptInterface fun writeFileSync( path: String?, data: String?, encoding: String? ): Boolean { if(path == null) return false return try { touchFile(path) val fos = resolver.openOutputStream(appendUri(workUri, path)) fos!!.write(data?.toByteArray(charset(encoding!!))) fos.close() true } catch (e: Exception) { false } } @JavascriptInterface fun appendFileSync( path: String?, data: String?, encoding: String? ): Boolean { if(path == null) return false return try { touchFile(path) val fos = resolver.openOutputStream(appendUri(workUri, path), "wa") fos!!.write(data?.toByteArray(charset(encoding!!))) fos.close() true } catch (e: Exception) { false } } @JavascriptInterface fun copyFileSync(src: String?, dst: String?, mode: Int): Boolean { if(src == null || dst == null) return false val fis: InputStream? val fos: OutputStream? try { fis = resolver.openInputStream(appendUri(workUri, src)) touchFile(dst) fos = resolver.openOutputStream(appendUri(workUri, dst)) } catch (ignore: Exception) { return false } try { val buffer = ByteArray(1024 * 256) var length: Int while (fis!!.read(buffer).also { length = it } > 0) { fos?.write(buffer, 0, length) } fis.close() fos?.close() } catch (e: Exception) { return false } return true } @JavascriptInterface fun unlinkSync(path : String?) : Boolean { if(path == null) return false return try { val targetFile = DocumentFile.fromSingleUri(context, appendUri(workUri, path)) targetFile!!.delete() } catch(e : Exception) { false } } @JavascriptInterface fun mkdirSync(path: String?, recursive: Boolean): Boolean { if(path == null) return false val parentPath = getParentFilename(path) return try { if (!recursive) { val parentFile = DocumentFile.fromTreeUri(context, appendUri(workUri, parentPath)) if (!parentFile!!.exists()) false else parentFile.createDirectory(getFilename(path)) != null } else { val parentFile = DocumentFile.fromTreeUri(context, appendUri(workUri, parentPath)) if (!parentFile!!.exists()) mkdirSync(parentPath, true) parentFile.createDirectory(getFilename(path)) != null } } catch(e: Exception) { false } } @JavascriptInterface fun readdirSync(path: String?): String { if(path == null) return "[]" return try { val jsonFileList = JSONArray() val dir = DocumentFile.fromTreeUri(context, appendUri(workUri, path)) val fileList = dir!!.listFiles() for(file in fileList) { jsonFileList.put(file.name) } jsonFileList.toString() } catch(e : java.lang.Exception) { "[]" } } @JavascriptInterface fun isFile(path: String?): Boolean { if(path == null) return false return try { val targetFile = DocumentFile.fromTreeUri(context, appendUri(workUri, path)) targetFile!!.isFile } catch(e: Exception) { false } } @JavascriptInterface fun isDirectory(path: String?): Boolean { if(path == null) return false return try { val targetFile = DocumentFile.fromTreeUri(context, appendUri(workUri, path)) targetFile!!.isDirectory } catch(e: Exception) { false } } @JavascriptInterface fun fileSize(path: String?): Long { if(path == null) return 0L return try { val targetFile = DocumentFile.fromTreeUri(context, appendUri(workUri, path)) if(!targetFile!!.isFile) 0L else targetFile.length() } catch(e: Exception) { 0L } } }
<?php /** * Description of Supply * @author Euler Nuñez */ // module/Provision/src/Provision/Model/Entity/Supply.php namespace Provision\Model\Entity; class Supply { protected $id; protected $inicio; protected $cliente; protected $sede; protected $servicio; protected $solicitante; protected $asunto; protected $linea; protected $midas; protected $tramitador; protected $lote; protected $peticion; protected $descripcion; protected $odinvoz; protected $bj; protected $odindatos; protected $sg; protected $atlas; protected $visord; protected $estado; public function __construct(array $options = null) { if (is_array($options)) { $this->setOptions($options); } } public function __set($name, $value) { $method = 'set' . $name; if (!method_exists($this, $method)) { throw new Exception('Invalid Method'); } $this->$method($value); } public function __get($name) { $method = 'get' . $name; if (!method_exists($this, $method)) { throw new Exception('Invalid Method'); } return $this->$method(); } public function setOptions(array $options) { $methods = get_class_methods($this); foreach ($options as $key => $value) { $method = 'set' . ucfirst($key); if (in_array($method, $methods)) { $this->$method($value); } } return $this; } public function getId() { return $this->id; } public function setId($id) { $this->id = $id; return $this; } public function getInicio() { return $this->inicio; } public function setInicio($inicio) { $this->inicio = $inicio; return $this; } public function getCliente() { return $this->cliente; } public function setCliente($cliente) { $this->cliente = $cliente; return $this; } public function getSede() { return $this->sede; } public function setSede($sede) { $this->sede = $sede; return $this; } public function getServicio() { return $this->servicio; } public function setServicio($servicio) { $this->servicio = $servicio; return $this; } public function getSolicitante() { return $this->solicitante; } public function setSolicitante($solicitante) { $this->solicitante = $solicitante; return $this; } public function getAsunto() { return $this->asunto; } public function setAsunto($asunto) { $this->asunto = $asunto; return $this; } public function getLinea() { return $this->linea; } public function setLinea($linea) { $this->linea = $linea; return $this; } public function getMidas() { return $this->midas; } public function setMidas($midas) { $this->midas = $midas; return $this; } public function getTramitador() { return $this->tramitador; } public function setTramitador($tramitador) { $this->tramitador = $tramitador; return $this; } public function getLote() { return $this->lote; } public function setLote($lote) { $this->lote = $lote; return $this; } public function getPeticion() { return $this->peticion; } public function setPeticion($peticion) { $this->peticion = $peticion; return $this; } public function getDescripcion() { return $this->descripcion; } public function setDescripcion($descripcion) { $this->descripcion = $descripcion; return $this; } public function getOdinvoz() { return $this->odinvoz; } public function setOdinvoz($odinvoz) { $this->odinvoz = $odinvoz; return $this; } public function getBj() { return $this->bj; } public function setBj($bj) { $this->bj = $bj; return $this; } public function getOdindatos() { return $this->odindatos; } public function setOdindatos($odindatos) { $this->odindatos = $odindatos; return $this; } public function getSg() { return $this->sg; } public function setSg($sg) { $this->sg = $sg; return $this; } public function getAtlas() { return $this->atlas; } public function setAtlas($atlas) { $this->atlas = $atlas; return $this; } public function getVisord() { return $this->visord; } public function setVisord($visord) { $this->visord = $visord; return $this; } public function getEstado() { return $this->estado; } public function setEstado($estado) { $this->estado = $estado; return $this; } }
package com.pedrolge.mlflow.api.model.modelVersion import com.pedrolge.mlflow.api.model.{MLFlowFormatter, ModelVersion} import play.api.libs.json.{Json, OFormat} object Response { case class CreateModelVersionResponse( modelVersion: ModelVersion ) object CreateModelVersionResponse extends MLFlowFormatter { implicit val format: OFormat[CreateModelVersionResponse] = Json.format } case class GetModelVersionResponse( modelVersion: ModelVersion ) object GetModelVersionResponse extends MLFlowFormatter { implicit val format: OFormat[GetModelVersionResponse] = Json.format } case class UpdateModelVersionResponse( modelVersion: ModelVersion ) object UpdateModelVersionResponse extends MLFlowFormatter { implicit val format: OFormat[UpdateModelVersionResponse] = Json.format } case class SearchModelVersionResponse( modelVersions: List[ModelVersion] ) object SearchModelVersionResponse extends MLFlowFormatter { implicit val format: OFormat[SearchModelVersionResponse] = Json.format } case class GetModelVersionDownloadUriResponse( artifactUri: String ) object GetModelVersionDownloadUriResponse extends MLFlowFormatter { implicit val format: OFormat[GetModelVersionDownloadUriResponse] = Json.format } case class TransitionModelVersionStageResponse( modelVersion: ModelVersion ) object TransitionModelVersionStageResponse extends MLFlowFormatter { implicit val format: OFormat[TransitionModelVersionStageResponse] = Json.format } }
```js <NavBar active='user' count={2} onPress={console.log} /> ```
# coding: utf-8 __author__ = 'Catarina Silva' __version__ = '0.1' __email__ = 'c.alexandracorreia@ua.pt' __status__ = 'Development' import xml.etree.ElementTree as ET def info_cursos_xml(xml_file: str): lista = [] tree = ET.parse(xml_file) root = tree.getroot() for curso in root.findall('curso'): lista.append(curso.find('nome').text) return lista def info_cursos_xml_dic(xml_file: str, a: str, b:str, c: str): dic = {} tree = ET.parse(xml_file) root = tree.getroot() for curso in root.findall(a): dic.update({curso.find(b).text : curso.find(c).text}) return dic print(info_cursos_xml_dic('cursos.xml'))
package trello type Session struct { Board *Board List *List Card *Card }
package com.baeldung.scala.doobie import cats.effect.{IO, IOApp} import doobie.{Fragment, Transactor} import doobie.implicits._ object DoobieFragments extends IOApp.Simple { override def run: IO[Unit] = { val transactor: Transactor[IO] = Transactor.fromDriverManager[IO]( "org.postgresql.Driver", "jdbc:postgresql://localhost:5432/world-db", "world", "world123" ) import doobie.Fragments._ val optionalCityNameParam: Option[String] = Some("%Pol%") val optionalCityNameFragment: Option[Fragment] = optionalCityNameParam.map(name => fr"name like $name") val limitFragment = fr"limit 5" (for { selectedCities <- (fr"select name from city" ++ whereAndOpt(optionalCityNameFragment)).query[String].to[List] selectedLimitedCities <- (fr"select name from city" ++ limitFragment).query[String].to[List] } yield (selectedCities, selectedLimitedCities)).transact(transactor).map { tuple => println(s"fragment results: $tuple") } } }
// The idea of the code came from CamanJs with some modifications. // You can check for the original code @ https://github.com/meltingice/CamanJS import Renderer from "./renderer"; import Calculate from "./calculate"; import Convert from "./convert"; class Caman { static Filter: typeof import("./filter").default; static renderer = new Renderer(); static Calculate = new Calculate(); static Convert = new Convert(); process(name, processFn) { Caman.renderer.add({ type: Caman.Filter.Type.Single, name, processFn, }); return this; } } declare global { interface Window { Caman: any; } } export default Caman;
%% %% %CopyrightBegin% %% %% Copyright Ericsson AB 2000-2011. All Rights Reserved. %% %% The contents of this file are subject to the Erlang Public License, %% Version 1.1, (the "License"); you may not use this file except in %% compliance with the License. You should have received a copy of the %% Erlang Public License along with this software. If not, it can be %% retrieved online at http://www.erlang.org/. %% %% Software distributed under the License is distributed on an "AS IS" %% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See %% the License for the specific language governing rights and limitations %% under the License. %% %% %CopyrightEnd% %% -module(bs_match_bin_SUITE). -author('bjorn@erix.ericsson.se'). -export([all/0, suite/0,groups/0,init_per_group/2,end_per_group/2, init_per_testcase/2,end_per_testcase/2, init_per_suite/1,end_per_suite/1, byte_split_binary/1,bit_split_binary/1]). -include_lib("test_server/include/test_server.hrl"). suite() -> [{ct_hooks,[ts_install_cth]}]. all() -> cases(). groups() -> []. init_per_group(_GroupName, Config) -> Config. end_per_group(_GroupName, Config) -> Config. cases() -> [byte_split_binary, bit_split_binary]. init_per_testcase(_Case, Config) -> test_lib:interpret(?MODULE), Dog = test_server:timetrap(?t:minutes(1)), [{watchdog,Dog}|Config]. end_per_testcase(_Case, Config) -> Dog = ?config(watchdog, Config), ?t:timetrap_cancel(Dog), ok. init_per_suite(Config) when is_list(Config) -> ?line test_lib:interpret(?MODULE), ?line true = lists:member(?MODULE, int:interpreted()), Config. end_per_suite(Config) when is_list(Config) -> ok. byte_split_binary(doc) -> "Tries to split a binary at all byte-aligned positions."; byte_split_binary(suite) -> []; byte_split_binary(Config) when list(Config) -> ?line L = lists:seq(0, 57), ?line B = mkbin(L), ?line byte_split(L, B, size(B)). byte_split(L, B, Pos) when Pos >= 0 -> ?line Sz1 = Pos, ?line Sz2 = size(B) - Pos, ?line <<B1:Sz1/binary,B2:Sz2/binary>> = B, ?line B1 = list_to_binary(lists:sublist(L, 1, Pos)), ?line B2 = list_to_binary(lists:nthtail(Pos, L)), ?line byte_split(L, B, Pos-1); byte_split(_L, _B, _) -> ok. bit_split_binary(doc) -> "Tries to split a binary at all positions."; bit_split_binary(suite) -> []; bit_split_binary(Config) when list(Config) -> Fun = fun(Bin, List, SkipBef, N) -> ?line SkipAft = 8*size(Bin) - N - SkipBef, io:format("~p, ~p, ~p", [SkipBef,N,SkipAft]), ?line <<_I1:SkipBef,OutBin:N/binary-unit:1,_I2:SkipAft>> = Bin, ?line OutBin = make_bin_from_list(List, N) end, ?line bit_split_binary1(Fun, erlang:md5(<<1,2,3>>)), ok. bit_split_binary1(Action, Bin) -> BitList = bits_to_list(binary_to_list(Bin), 16#80), bit_split_binary2(Action, Bin, BitList, 0). bit_split_binary2(Action, Bin, [_|T]=List, Bef) -> bit_split_binary3(Action, Bin, List, Bef, size(Bin)*8), bit_split_binary2(Action, Bin, T, Bef+1); bit_split_binary2(_Action, _Bin, [], _Bef) -> ok. bit_split_binary3(Action, Bin, List, Bef, Aft) when Bef =< Aft -> Action(Bin, List, Bef, (Aft-Bef) div 8 * 8), bit_split_binary3(Action, Bin, List, Bef, Aft-8); bit_split_binary3(_, _, _, _, _) -> ok. make_bin_from_list(_List, 0) -> mkbin([]); make_bin_from_list(List, N) -> list_to_binary([make_int(List, 8, 0), make_bin_from_list(lists:nthtail(8, List), N-8)]). make_int(_List, 0, Acc) -> Acc; make_int([H|T], N, Acc) -> make_int(T, N-1, Acc bsl 1 bor H). bits_to_list([_H|T], 0) -> bits_to_list(T, 16#80); bits_to_list([H|_]=List, Mask) -> [case H band Mask of 0 -> 0; _ -> 1 end|bits_to_list(List, Mask bsr 1)]; bits_to_list([], _) -> []. mkbin(L) when list(L) -> list_to_binary(L).
# encoding: utf-8 require_relative "../spec_helper" require "nake/rule" describe Nake::Rule do before(:each) do Nake::Rule.rules.clear end describe "[]" do it "should find rule with given name if the name is a symbol" it "should find rule with given name if the name is a string" it "should find rule with given alias if the alias is a symbol" it "should find rule with given alias if the alias is a string" end describe "[]=" do it "should add the rule into the Nake::Rule.rules hash with stringified key" end describe ".rules" do end describe ".new" do it "should returns already existing rule object if this object exists" do rule = Nake::Rule.new(:release) Nake::Rule.new(:release).object_id.should eql(rule.object_id) end end it "should take name as a first argument" do Nake::Rule.new("name").name.should eql(:name) end it "should take name as a first argument" do Nake::Rule.new(:name).name.should eql(:name) end describe "#define" do it "should puts block into the rule.blocks collection" do rule = Nake::Rule.new(:name) -> { rule.define { "a block" } }.should change { rule.blocks.length }.by(1) end end describe "#hidden?" do it "should not be hidden by default" do rule = Nake::Rule.new(:name) rule.should_not be_hidden end it "should be true if the rule is hidden" do Nake::Rule.new(:name).tap do |rule| rule.hidden = true rule.should be_hidden end end it "should be false if the rule isn't hidden" do Nake::Rule.new(:name).tap do |rule| rule.hidden = false rule.should_not be_hidden end end end describe "#call" do it "should call all dependencies" it "should call all blocks of the given rule" end end
package watch.craft.storage import com.google.cloud.storage.Blob import com.google.cloud.storage.Bucket import com.google.cloud.storage.Bucket.BlobTargetOption import com.google.cloud.storage.Bucket.BlobTargetOption.doesNotExist import com.google.cloud.storage.Storage import com.google.cloud.storage.Storage.BlobListOption.prefix import com.google.cloud.storage.StorageException import com.nhaarman.mockitokotlin2.* import kotlinx.coroutines.runBlocking import org.junit.jupiter.api.Assertions.assertArrayEquals import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test import org.junit.jupiter.api.assertThrows import org.mockito.Mockito.RETURNS_DEEP_STUBS import watch.craft.FatalScraperException import java.net.SocketTimeoutException class GcsObjectStoreTest { private val bucket = mock<Bucket>(defaultAnswer = RETURNS_DEEP_STUBS) private val storage = mock<Storage> { on { get(NICE_BUCKET) } doReturn bucket } private val store = GcsObjectStore(NICE_BUCKET, storage) @Nested inner class Write { @Test fun `writes data to GCS if not already present`() { write() verify(bucket).create(NICE_KEY, NICE_DATA, doesNotExist()) } @Test fun `throws if file already present`() { whenever(bucket.create(any(), any(), any<BlobTargetOption>())) doThrow ALREADY_EXISTS_EXCEPTION assertThrows<FileExistsException> { write() } } @Test fun `throws without retries if unexpected error`() { whenever(bucket.create(any(), any(), any<BlobTargetOption>())) doThrow AUTH_EXCEPTION assertThrows<FatalScraperException> { write() } verify(bucket, times(1)).create(any(), any(), any<BlobTargetOption>()) } @Test fun `retries if error cause is a timeout`() { whenever(bucket.create(any(), any(), any<BlobTargetOption>())) doThrow TIMEOUT_EXCEPTION assertThrows<FatalScraperException> { write() } verify(bucket, times(5)).create(any(), any(), any<BlobTargetOption>()) } private fun write() = runBlocking { store.write(NICE_KEY, NICE_DATA) } } @Nested inner class Read { @Test fun `reads data if present`() { val blob = mock<Blob> { on { getContent() } doReturn NICE_DATA } whenever(bucket.get(NICE_KEY)) doReturn blob assertArrayEquals(NICE_DATA, read()) } @Test fun `throws if file not present`() { whenever(bucket.get(NICE_KEY)) doReturn null assertThrows<FileDoesntExistException> { read() } } @Test fun `throws without retries if unexpected error`() { whenever(bucket.get(NICE_KEY)) doThrow AUTH_EXCEPTION assertThrows<FatalScraperException> { read() } verify(bucket, times(1)).get(NICE_KEY) } @Test fun `retries if error cause is a timeout`() { whenever(bucket.get(NICE_KEY)) doThrow TIMEOUT_EXCEPTION assertThrows<FatalScraperException> { read() } verify(bucket, times(5)).get(NICE_KEY) } private fun read() = runBlocking { store.read(NICE_KEY) } } @Nested inner class List { @Test fun `lists directory contents if present`() { val blobAbc = mock<Blob> { on { name } doReturn "foo/abc/" } val blobDef = mock<Blob> { on { name } doReturn "foo/def/" } whenever(bucket.list(eq(prefix("foo/")), any()).iterateAll()) doReturn listOf(blobAbc, blobDef) assertEquals(listOf("abc", "def"), list()) } @Test fun `throws if file not present`() { whenever(bucket.list(anyVararg())) doThrow NOT_FOUND_EXCEPTION assertThrows<FileDoesntExistException> { list() } } @Test fun `throws without retries if unexpected error`() { whenever(bucket.list(anyVararg())) doThrow AUTH_EXCEPTION assertThrows<FatalScraperException> { list() } verify(bucket, times(1)).list(anyVararg()) } @Test fun `retries if error cause is a timeout`() { whenever(bucket.list(anyVararg())) doThrow TIMEOUT_EXCEPTION assertThrows<FatalScraperException> { list() } verify(bucket, times(5)).list(anyVararg()) } private fun list() = runBlocking { store.list(NICE_KEY) } } companion object { private const val NICE_BUCKET = "bucket" private const val NICE_KEY = "foo" private val NICE_DATA = byteArrayOf(1, 2, 3, 4) private val AUTH_EXCEPTION = StorageException(401, "Get out") private val NOT_FOUND_EXCEPTION = StorageException(404, "Uh oh") private val ALREADY_EXISTS_EXCEPTION = StorageException(412, "Uh oh") private val TIMEOUT_EXCEPTION = StorageException(SocketTimeoutException("No")) } }
#!/bin/sh # ImageAssets.sh # shellScriptStringGeneration # # Created by Arnav Gupta on 06/12/19. # Copyright © 2019 Arnav. All rights reserved. #configure input variables for script here projectDir="$SRCROOT" scriptDir="$PODS_ROOT/ImageDuplicate" # this ensure correct permissions are automatically added to any new shell script added to build-phase directory ls $scriptDir | while read line; do path="$projectDir/$line"; chmod u+x $path; done outputFile="$scriptDir/AVImageConstants.swift" cd $projectDir # remove any previously created temp files rm txcassets*.* 2>/dev/null # find all imageset names find . -name '*.imageset' > txcassets1.sh chmod 777 txcassets1.sh sed -i -e 's/^/"/;s/$/",/' txcassets1.sh cat txcassets1.sh > txcassets2.sh sed -i -e 's/^/basename /' txcassets2.sh sed -i -e 's/$/ .imageset/' txcassets2.sh sh txcassets2.sh > txcassets3.sh sed -i -e 's/^/ "/;s/$/"/' txcassets3.sh sed -i -e 's/.imageset,"/",/' txcassets3.sh touch txcassets5.sh echo "// This file is autogenerated, do not edit here" >> txcassets5.sh echo "" >> txcassets5.sh echo "public class AVImageConstants {" >> txcassets5.sh echo " static let imageNames: [String] = [" >> txcassets5.sh cat txcassets3.sh >> txcassets5.sh echo " ]" >> txcassets5.sh echo " static let imagePaths: [String] = [" >> txcassets5.sh cat txcassets1.sh >> txcassets5.sh echo " ]" >> txcassets5.sh echo "}" >> txcassets5.sh rm $outputFile mv txcassets5.sh $outputFile # remove any temp files created rm txcassets*.* 2>/dev/null
require "spec_helper" require "bitcoin_ticker.rb" module BitcoinTicker describe BitcoinTicker do let(:ticker) { BitcoinTicker.new } let(:slack_webhook_url) { "https://hooks.slack.com/services/123/123" } let(:slack_notifier) { instance_double("Slack Notifier") } let(:price_saver) { instance_double("Price Saver") } let(:price_checker) { instance_double("Price Checker") } before do allow(ENV).to receive(:[]).with("PERCENT_CHANGE_THRESHOLD").and_return("10") allow(ENV).to receive(:[]).with("SLACK_WEBHOOK_URL").and_return(slack_webhook_url) allow(ticker).to receive(:price_checker) { price_checker } allow(price_checker).to receive(:current_price) { current_price } allow(ticker).to receive(:price_saver) { price_saver } allow(price_saver).to receive(:read) { previous_price } allow(ticker).to receive(:slack_notifier).and_return(slack_notifier) end context "price rise" do let(:current_price) { 100 } let(:previous_price) { 50 } it "notifies slack when price and saves new price" do BitcoinTicker::TICKERS.each do |ticker| expect(slack_notifier).to receive(:notify).with(ticker, 100, true) expect(price_saver).to receive(:write).with(ticker, 100) end ticker.tick end context "less than threshold" do let(:current_price) { 49 } it "doesn't notify slack or save the new price" do expect(slack_notifier).not_to receive(:notify) expect(price_saver).not_to receive(:write) ticker.tick end end end context "price drop" do let(:current_price) { 50 } let(:previous_price) { 100 } it "notifies slack when price and saves new price" do BitcoinTicker::TICKERS.each do |ticker| expect(slack_notifier).to receive(:notify).with(ticker, 50, false) expect(price_saver).to receive(:write).with(ticker, 50) end ticker.tick end context "less than threshold" do let(:current_price) { 95 } it "doesn't notify slack or save the new price" do expect(slack_notifier).not_to receive(:notify) expect(price_saver).not_to receive(:write) ticker.tick end end end end describe PriceChecker do let(:price_checker) { described_class.new } let(:price) { 1000 } before do expect(Net::HTTP).to receive(:get_response) .with(URI(PriceChecker::PRICE_URIS[:btc])) .and_return(OpenStruct.new status: 200, body: "{ \"data\": { \"amount\": \"#{price}\" } }") expect(Net::HTTP).to receive(:get_response) .with(URI(PriceChecker::PRICE_URIS[:neo])) .and_return(OpenStruct.new status: 200, body: "[ { \"price_usd\": \"#{price}\" } ]") end it "returns the price" do expect(price_checker.current_price(:btc)).to eq price expect(price_checker.current_price(:neo)).to eq price end end describe PriceSaver do let(:price_saver) { described_class.new } before do Redis.new.del("btc-price") end it "starts empty" do expect(price_saver.read(:btc)).to eq(0.0) end it "saves the price" do price = 500.13 price_saver.write(:btc, price) expect(price_saver.read(:btc)).to eq(price) end end describe PriceComparer do let(:price_comparer) { described_class.new } it "returns true if increased more than threshold" do expect(price_comparer.compare_to_threshold(10, 20, 5)).to be true end it "returns false if lower than threshold" do expect(price_comparer.compare_to_threshold(10, 14, 50)).to be false end it "returns false if equal to threshold" do expect(price_comparer.compare_to_threshold(10, 11, 10)).to be false end it "returns true if descreased more than threshold" do expect(price_comparer.compare_to_threshold(20, 10, 5)).to be true end end describe SlackNotifier do let(:slack_notifier) { described_class.new } let(:current_price) { 123.45 } let(:webhook_url) { "https://slack.com/webhook_url/123" } before do allow(ENV).to receive(:[]).with("SLACK_WEBHOOK_URL").and_return webhook_url end it "has a full name and username for each supported ticker" do BitcoinTicker::TICKERS.each do |ticker| expect(SlackNotifier::FULLNAMES).to have_key(ticker) expect(SlackNotifier::USERNAMES).to have_key(ticker) end end it "posts current price to slack" do payload = '{"text":"Bitcoin is up to $123.45","username":"bitcoin-ticker"}' expect(Net::HTTP).to receive(:post_form).with(URI(webhook_url), payload: payload) slack_notifier.notify(:btc, current_price, true) end context "price drop" do it "posts current price to slack" do payload = '{"text":"Ethereum is down to $123.45","username":"ethereum-ticker"}' expect(Net::HTTP).to receive(:post_form).with(URI(webhook_url), payload: payload) slack_notifier.notify(:eth, current_price, false) end end end end
#!/usr/bin/env python # encoding: utf-8 # --------------------------------------------------------------------------------------------------------------------- # Name: scraper.py # Version: 0.1.3 # Summary: Zap Imóveis Scraper # A scraper that gathers data from Zap Imóveis website using BeautifulSoup. # # Author: Alexsander Lopes Camargos # Author-email: alcamargos@vivaldi.net # # License: MIT # --------------------------------------------------------------------------------------------------------------------- """ Zap Imóveis Scraper A scraper that gathers data from Zap Imóveis website using BeautifulSoup. """ import json import logging import time from enum import Enum from random import randint import pandas as pd import urllib3 from bs4 import BeautifulSoup from slugify import slugify TOWNS = ['Belo Horizonte'] STATES = ['mg'] # TOWNS = ['Belo Horizonte', 'Contagem', 'Betim', 'Governador Valadares', 'Montes Claros'] # URL templates to make searches. DOMAIN_NAME = 'www.zapimoveis.com.br' PATH = '/%(action)s/%(unit_type)s/%(state)s+%(city)s/?pagina=%(page)s' PORT = 443 CERT_REQS = 'CERT_NONE' QUANTITY_TO_FETCH = 5 RANDINT_STARTING = 60 RANDINT_FINAL = 120 class BusinessFilter(Enum): """Filters groups enumeration.""" Comprar = 'Venda' Alugar = 'Aluguel' Lancamentos = 'Lançamentos' class UnitType(Enum): """Unit type filter enumeration.""" Todos = 'Imoveis' Casas = 'Casas' Apartamentos = 'Apartamentos' Quitinetes = 'Quitinetes' class ListedItem: """A listed item on zapimoveis.com.br.""" Price = None Condominium_fee = None IPTU_fee = None Floor_size = None Number_bedrooms = None Number_bathrooms = None Parking_spaces = None Address = None Title = None Description = None Link = None Publisher = None Item_ID = None Unit_types = None class DataScraper: """Extracting selected data from the site zapimoveis.com.br and save for analysis.""" def __init__(self, *args): """Initiating an empty DataScraper.""" super(DataScraper, self).__init__(*args) @staticmethod def __fetch_data(action, unit_type, city, page): """Fetch data on the zapimoveis.com.br website using selection criteria.""" # Constructing the query using selection criteria. query_path = PATH % ({'action': slugify(action), 'unit_type': slugify(unit_type), 'state': STATES[0], 'city': slugify(city), 'page': page}) pool = urllib3.HTTPSConnectionPool(DOMAIN_NAME, PORT, CERT_REQS) # Make a request. page = pool.request('GET', query_path) logging.info(f'GET >> {pool.host}{query_path}\tSTATUS: {page.status}') soup = BeautifulSoup(page.data.decode('utf-8'), 'html.parser') page_data = soup.find(lambda tag: tag.name == "script" and isinstance(tag.string, str) and tag.string.startswith("window")) json_string = page_data.string.replace("window.__INITIAL_STATE__=", "").replace( ";(function(){var s;(s=document.currentScript||document.scripts[" "document.scripts.length-1]).parentNode.removeChild(s);}());", "") return json.loads(json_string)['results']['listings'] @staticmethod def __data_scraper(data): """Processing the data obtained from the zapimoveis.com.br website.""" item = ListedItem() item.Price = float(data['listing']['pricingInfos'][0].get('price', 0) if len( data['listing']['pricingInfos']) > 0 else 0) item.Condominium_fee = float(data['listing']['pricingInfos'][0].get('monthlyCondoFee', 0) if len( data['listing']['pricingInfos']) > 0 else 0) item.IPTU_fee = float(data['listing']['pricingInfos'][0].get('yearlyIptu', 0) if len( data['listing']['pricingInfos']) > 0 else 0) item.Floor_size = float(data['listing']['usableAreas'][0] if len(data['listing']['usableAreas']) > 0 else 0) item.Number_bedrooms = int(data['listing']['bedrooms'][0] if len(data['listing']['bedrooms']) > 0 else 0) item.Number_bathrooms = int(data['listing']['bathrooms'][0] if len(data['listing']['bathrooms']) > 0 else 0) item.Parking_spaces = int( data['listing']['parkingSpaces'][0] if len(data['listing']['parkingSpaces']) > 0 else 0) item.Address = (data['link']['data']['street'] + ", " + data['link']['data']['neighborhood'] + ", " + data['link']['data']['state']).strip(',').strip() item.Title = data['listing']['title'] item.Description = data['listing']['description'].replace('<br>', '\n').strip() item.Link = data['link']['href'] item.Publisher = data['account']['name'] item.Item_ID = data['listing']['id'] item.Unit_types = data['listing']['unitTypes'] return item @staticmethod def __data_to_csv(data): """Write data to a comma-separated values (csv) file.""" # Data frame constructor. data_frame = pd.DataFrame([(item.Price, item.Condominium_fee, item.Floor_size, item.Number_bedrooms, item.Number_bathrooms, item.Parking_spaces, item.IPTU_fee, item.Address, item.Title, # item.Description, item.Link, item.Publisher, item.Item_ID, item.Unit_types) for item in [item for item in data]], columns=['Price', 'Condominium', 'FloorSize', 'NumberOfBedrooms', 'NumberOfBathrooms', 'ParkingSpaces', 'IPTU', 'Address', 'Title', # TODO: Realizar a limpeza das informações antes de salvar no data frame. # 'Description', 'Link', 'Publisher', 'ItemID', 'UnitTypes']) # Write data frame to a comma-separated values (csv) file. data_frame.to_csv('data.csv', index=False) def __get_data(self): """Processing the pagination of results.""" listed_items = [] for query_town in TOWNS: for unit_type in UnitType: for page in range(1, QUANTITY_TO_FETCH): sleep_time = randint(RANDINT_STARTING, RANDINT_FINAL) results = self.__fetch_data(BusinessFilter.Alugar.value, unit_type.value, query_town, page) for result in results: listed_items.append(self.__data_scraper(result)) logging.info(f'Delay execution: {sleep_time}') time.sleep(sleep_time) return listed_items def execute(self): """Write data to a comma-separated values (csv) file.""" self.__data_to_csv(self.__get_data()) def main(): """Execute when the module is not initialized from an import statement.""" logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.INFO) logging.info('Zap Imóveis Scraper --- Started') data = DataScraper() data.execute() logging.info('Zap Imóveis Scraper --- Finished') if __name__ == "__main__": main()
#!/bin/bash SRCDIR=~/torvalds/linux cd $SRCDIR for ((i=12;i<=39;i++)) ; do LATEST=$(git tag | sed -n -e "s/v2\.6\.$i\.\([0-9]*\)$/\1/p" | sort -nr | head -1) echo -ne "v2.6.$i\t" git checkout -fq v2.6.$i.$LATEST find . -type f -name '*.[chS]' -exec wc -l {} \; | awk 'BEGIN{lines=0}{lines+=$1}END{print lines}' done for ((i=0;i<=19;i++)) ; do LATEST=$(git tag | sed -n -e "s/v3\.$i\.\([0-9]*\)$/\1/p" | sort -nr | head -1) echo -ne "v3.$i\t" git checkout -fq v3.$i.$LATEST find . -type f -name '*.[chS]' -exec wc -l {} \; | awk 'BEGIN{lines=0}{lines+=$1}END{print lines}' done for ((i=0;i<=20;i++)) ; do LATEST=$(git tag | sed -n -e "s/v4\.$i\.\([0-9]*\)$/\1/p" | sort -nr | head -1) echo -ne "v4.$i\t" git checkout -fq v4.$i.$LATEST find . -type f -name '*.[chS]' -exec wc -l {} \; | awk 'BEGIN{lines=0}{lines+=$1}END{print lines}' done for ((i=0;i<=2;i++)) ; do LATEST=$(git tag | sed -n -e "s/v5\.$i\.\([0-9]*\)$/\1/p" | sort -nr | head -1) echo -ne "v5.$i\t" git checkout -fq v5.$i.$LATEST find . -type f -name '*.[chS]' -exec wc -l {} \; | awk 'BEGIN{lines=0}{lines+=$1}END{print lines}' done
#!/usr/bin/env node import yargs from 'yargs'; import { generateAPIService } from './index'; const args = yargs .option('input', { alias: 'i', describe: 'apiDoc', type: 'string', required: true }) .option('headers', { describe: 'fetch headers', type: 'array' }) .option('operation-id-splitter', { describe: 'operationId 分隔符,默认', type: 'string' }) .option('template', { alias: 't', describe: '模板', type: 'string' }) .option('banner', { alias: 'b', describe: 'banner', type: 'string' }) .option('dump', { alias: 'd', describe: '导出', type: 'string' }).argv; generateAPIService({ input: args.input.match(/^(http|https)\:\/\//) ? { type: 'remote', url: args.input, headers: args.headers ? args.headers.reduce((re, cu) => { const [k, v] = (cu + '').split(':'); return { ...re, [k]: v }; }, {} as any) : undefined, } : { type: 'local', filename: args.input }, operationIdSplitter: args['operation-id-splitter'], template: args.template, banner: args.banner, dump: args.dump, }) .then(content => { if (!args.dump) console.log(content); }) .catch(err => { console.error(err); process.exit(1); });
package com.example.app import android.app.Activity class DemoActivity : Activity() { }
import CoverImage from './coverImage' import PostHeader from './postHeader' import PostBody from './postBody' import PostMeta from './postMeta' const Post = ({ post }) => { return ( <> {post?.featuredImage?.node && ( <CoverImage title={post?.title} coverImage={post?.featuredImage?.node} slug={post?.slug} uri={post?.uri} width='1920' /> )} <PostHeader title={post?.title} /> <PostMeta tags={post?.tags} categories={post?.categories} date={post?.date} author={post?.author?.node} /> <PostBody content={post?.content} /> </> ) } export default Post
package jobworker import "github.com/fatih/color" import "time" var stTime time.Time func ResultsDispatcher(resultQueue chan JobResult, signaler chan int) { stTime = time.Now() for { select { case jr := <-resultQueue: ProcessResult(&jr) case <-signaler: return } } } var cnt int = 0 var TotalDone int = 0 var Rate float64 var resultsToDispatch [](*JobResult) func ProcessResult(jresult *JobResult) { cnt += 1 TotalDone += 1 elapsed := time.Since(stTime) Rate = float64(cnt) / elapsed.Seconds() if elapsed.Seconds() > float64(15) { cnt = 1 stTime = time.Now() // color.Blue("\nResetting Counter") } // color.Cyan("#%d - Rate: %f jobs/seconds\n", TotalDone, Rate) if jresult.Status != 0 { color.Red("Error: %s", jresult.ErrorMsg) } resultsToDispatch = append(resultsToDispatch, jresult) if len(resultsToDispatch) > Config.DispatchBufferSize { DispatchMassResults() resultsToDispatch = [](*JobResult){} } } func DispatchMassResults() { // color.Red("\nDispatching Mass Results\n") for i := 0; i < len(resultsToDispatch); i++ { DispatchResult(resultsToDispatch[i]) } FlushCompletedJobs(Config.Fetch_Binkey) // color.Green("\nDispatching Done\n") }
package com.example.alexmelnikov.coinspace.ui.settings import android.content.Context import android.content.SharedPreferences import android.os.Bundle import android.support.v7.preference.PreferenceFragmentCompat import android.support.v7.preference.PreferenceManager import android.view.View import com.example.alexmelnikov.coinspace.BaseApp import com.example.alexmelnikov.coinspace.R import com.example.alexmelnikov.coinspace.model.interactors.IUserBalanceInteractor import javax.inject.Inject class SettingsFragment : PreferenceFragmentCompat() { @Inject lateinit var userBalanceInteractor: IUserBalanceInteractor private lateinit var currencyBeforeChange: String override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) { setPreferencesFromResource(R.xml.preferences, rootKey) } override fun onAttach(context: Context?) { super.onAttach(context) BaseApp.instance.component.inject(this) } }
'use strict' /** * Пространственные данные книги регистрации/хранения. */ module.exports = (sequelize, DataTypes) => { const spatialDataRd = sequelize.define('spatialDataRd', { // Описание пространственных данных description: { type: DataTypes.STRING, field: 'description' }, // Владелец ownerId: { type: DataTypes.UUID, field: 'owner_id' }, // Идентификатор масштаба scaleId: { type: DataTypes.UUID, field: 'scale_id' }, // Идентификатор системы координат coordinateProjectionId: { type: DataTypes.UUID, field: 'coordinate_projection_id' }, // Идентификатор тематического раздела thematicSectionId: { type: DataTypes.UUID, field: 'thematic_section_id' }, reason: { type: DataTypes.TEXT, field: 'reason' }, // Ограничения по доступу accessRestriction: { type: DataTypes.INTEGER, field: 'access_restriction' }, // Форма представления документов documentViewTypeId: { type: DataTypes.UUID, field: 'document_view_type_id' }, // Планировочный номер planningNumber: { type: DataTypes.TEXT, field: 'planning_number' }, documentTypeId: { type: DataTypes.UUID, field: 'document_type_id' }, // Кадастровый номер cadastralNumber: { type: DataTypes.TEXT, field: 'cadastral_number' }, isogdDocumentId: { type: DataTypes.UUID, field: 'isogd_document_id' }, // Номер спец части // В соотв. с ПП363 номер должен быть в формате МО_НР_НННН_ММ, // где МО_НР_ММММ - рег.номер документа. // ММ - номер карты в пределах документа. number: { type: DataTypes.INTEGER, field: 'number' }, // Во изменение. // приходится отслеживать изменения статусов частей, когда-либо указывавшихс в поле changin part в текущей сессии changingPartId: { type: DataTypes.STRING, field: 'changing_part_id' }, // Код карты СТП mapCodeId: { type: DataTypes.UUID, field: 'map_code_id' }, status: { type: DataTypes.INTEGER, field: 'status' }, // Ссылка на карточку ПД spatialDataPdId: { type: DataTypes.UUID, field: 'spatial_data_pd_id' } }, { tableName: 'spatial_data_rd', freezeTableName: true, timestamps: false, paranoid: false, schema: 'public' }) spatialDataRd.associate = models => { spatialDataRd.hasOne(models.spatialDataGd, { foreignKey: 'id' }) spatialDataRd.belongsTo(models.isogdDocument, { foreignKey: 'isogdDocumentId' }) spatialDataRd.belongsTo(models.documentType, { foreignKey: 'documentTypeId' }) spatialDataRd.belongsTo(models.documentViewType, { foreignKey: 'documentViewTypeId' }) spatialDataRd.belongsTo(models.spatialDataRd, { foreignKey: 'changing_part_id', as: 'changingPart' }) spatialDataRd.belongsTo(models.territoryPlanningDocument, { foreignKey: 'mapCodeId' }) spatialDataRd.belongsTo(models.thematicSection, { foreignKey: 'thematicSectionId' }) spatialDataRd.belongsTo(models.organization, { foreignKey: 'ownerId', as: 'owner' }) spatialDataRd.belongsTo(models.scale, { foreignKey: 'scaleId' }) spatialDataRd.belongsTo(models.coordinateProjection, { foreignKey: 'coordinateProjectionId' }) spatialDataRd.belongsTo(models.spatialDataPd, { foreignKey: 'spatialDataPdId' }) spatialDataRd.hasMany(models.spatialDataRdFile, { foreignKey: 'spatial_data_rd_id', as: 'files' }) spatialDataRd.hasMany(models.layersGroup, { foreignKey: 'spatial_data_id' }) // inheritModel(models.spatialDataGd, spatialDataRd) } return spatialDataRd }
## Login Login component. ``` <onka-login></onka-login> ```
# frozen_string_literal: true require 'rails_helper' RSpec.describe Fine do subject do described_class.new({ key: '1:1', fields: fields }.with_indifferent_access) end let(:fine) { subject } let(:fields) do { block: { key: 'DAMAGED' }, billDate: '2019-07-11', owed: { amount: '5000.00', currencyCode: 'USD' }, item: { fields: { barcode: 'xyz', bib: { key: '1184859', fields: { title: 'The Lego movie videogame [electronic resource]', author: 'Cool people made this' } }, call: { fields: { dispCallNumber: 'ZMS 4033', sortCallNumber: 'ZMS 004033' } } } } } end it 'has a key' do expect(fine.key).to eq '1:1' end it 'has a sequence' do expect(fine.sequence).to eq 1 end it 'has a status' do expect(fine.status).to eq 'DAMAGED' end it 'has a nice_status' do expect(fine.nice_status).to eq 'Damaged item' end it 'has a title' do expect(fine.title).to eq 'The Lego movie videogame [electronic resource]' end it 'has an author' do expect(fine.author).to eq 'Cool people made this' end it 'has a call number' do expect(fine.call_number).to eq 'ZMS 4033' end it 'has a shelf key' do expect(fine.shelf_key).to eq 'ZMS 004033' end it 'has a barcode' do expect(fine.barcode).to eq 'xyz' end it 'has a catkey' do expect(fine.catkey).to eq '1184859' end it 'has a bill date' do expect(fine.bill_date.strftime('%m/%d/%Y')).to eq '07/11/2019' end it 'has an amount owed' do expect(fine.owed).to eq 5000.00 end context 'without a related item' do let(:fields) do { block: { key: 'DAMAGED' }, billDate: '2019-07-11', owed: { amount: '5000.00', currencyCode: 'USD' } } end describe '#bib?' do it 'is false' do expect(fine.bib?).to eq false end end describe '#title' do it 'is nil' do expect(fine.title).to eq nil end end describe '#author' do it 'is nil' do expect(fine.author).to eq nil end end describe '#catkey' do it 'is nil' do expect(fine.catkey).to eq nil end end describe '#call_number' do it 'is nil' do expect(fine.call_number).to eq nil end end describe '#shelf_key' do it 'is nil' do expect(fine.shelf_key).to eq nil end end end end
#pragma once class AEApplication { public: AEApplication(); ~AEApplication(); AEApplication(AEApplication&) = delete; void operator=(AEApplication const&) = delete; bool Initialize(); void Run(); private: void BuildScene(const unsigned int = 0); void Update(); void AudioUpdate(); void Render(); private: bool sceneActive = false; std::vector<class IScene*> scenes; std::unique_ptr<class IScene> scenePtr; std::unique_ptr<class Timer> graphicsTimerPtr; std::unique_ptr<class Timer> audioTimerPtr; std::unique_ptr<class Window> windowPtr; std::unique_ptr<class EntityManager> entityManager; };
using Mitternacht.Database.Models; namespace Mitternacht.Database.Repositories { public interface ICustomReactionRepository : IRepository<CustomReaction> { } }
using UnityEngine; namespace BridgePattern.Case1.Base { /// <summary> /// * [The 'Implementation' interface] /// </summary> public interface ISize { void ProcessSize(GameObject gameObject); } }
# This file was automatically generated, any manual changes will be lost the # next time this file is generated. # # Platform: rbx 2.2.3.n18 RubyLint.registry.register('Date') do |defs| defs.define_constant('Date') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) klass.inherits(defs.constant_proxy('Comparable', RubyLint.registry)) klass.define_method('_httpdate') do |method| method.define_argument('str') end klass.define_method('_iso8601') do |method| method.define_argument('str') end klass.define_method('_jisx0301') do |method| method.define_argument('str') end klass.define_method('_parse') do |method| method.define_argument('str') method.define_optional_argument('comp') end klass.define_method('_rfc2822') do |method| method.define_argument('str') end klass.define_method('_rfc3339') do |method| method.define_argument('str') end klass.define_method('_rfc822') do |method| method.define_argument('str') end klass.define_method('_strptime') do |method| method.define_argument('str') method.define_optional_argument('fmt') end klass.define_method('_xmlschema') do |method| method.define_argument('str') end klass.define_method('civil') do |method| method.define_optional_argument('y') method.define_optional_argument('m') method.define_optional_argument('d') method.define_optional_argument('sg') end klass.define_method('commercial') do |method| method.define_optional_argument('y') method.define_optional_argument('w') method.define_optional_argument('d') method.define_optional_argument('sg') end klass.define_method('gregorian_leap?') do |method| method.define_argument('y') end klass.define_method('httpdate') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('iso8601') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('jd') do |method| method.define_optional_argument('jd') method.define_optional_argument('sg') end klass.define_method('jisx0301') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('julian_leap?') do |method| method.define_argument('y') end klass.define_method('leap?') do |method| method.define_argument('y') end klass.define_method('new') do |method| method.define_optional_argument('y') method.define_optional_argument('m') method.define_optional_argument('d') method.define_optional_argument('sg') method.returns { |object| object.instance } end klass.define_method('new!') do |method| method.define_rest_argument('args') end klass.define_method('ordinal') do |method| method.define_optional_argument('y') method.define_optional_argument('d') method.define_optional_argument('sg') end klass.define_method('parse') do |method| method.define_optional_argument('str') method.define_optional_argument('comp') method.define_optional_argument('sg') end klass.define_method('rfc2822') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('rfc3339') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('rfc822') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('strptime') do |method| method.define_optional_argument('str') method.define_optional_argument('fmt') method.define_optional_argument('sg') end klass.define_method('today') do |method| method.define_optional_argument('sg') end klass.define_method('valid_civil?') do |method| method.define_argument('y') method.define_argument('m') method.define_argument('d') method.define_optional_argument('sg') end klass.define_method('valid_commercial?') do |method| method.define_argument('y') method.define_argument('w') method.define_argument('d') method.define_optional_argument('sg') end klass.define_method('valid_date?') do |method| method.define_argument('y') method.define_argument('m') method.define_argument('d') method.define_optional_argument('sg') end klass.define_method('valid_jd?') do |method| method.define_argument('jd') method.define_optional_argument('sg') end klass.define_method('valid_ordinal?') do |method| method.define_argument('y') method.define_argument('d') method.define_optional_argument('sg') end klass.define_method('xmlschema') do |method| method.define_optional_argument('str') method.define_optional_argument('sg') end klass.define_method('yaml_tag_subclasses?') klass.define_instance_method('+') do |method| method.define_argument('n') end klass.define_instance_method('-') do |method| method.define_argument('x') end klass.define_instance_method('<<') do |method| method.define_argument('n') end klass.define_instance_method('<=>') do |method| method.define_argument('other') end klass.define_instance_method('===') do |method| method.define_argument('other') end klass.define_instance_method('>>') do |method| method.define_argument('n') end klass.define_instance_method('ajd') klass.define_instance_method('amjd') do |method| method.define_rest_argument('args') end klass.define_instance_method('asctime') klass.define_instance_method('ctime') klass.define_instance_method('cwday') klass.define_instance_method('cweek') klass.define_instance_method('cwyear') klass.define_instance_method('day') klass.define_instance_method('day_fraction') do |method| method.define_rest_argument('args') end klass.define_instance_method('downto') do |method| method.define_argument('min') method.define_block_argument('block') end klass.define_instance_method('england') klass.define_instance_method('eql?') do |method| method.define_argument('other') end klass.define_instance_method('friday?') klass.define_instance_method('gregorian') klass.define_instance_method('gregorian?') do |method| method.define_rest_argument('args') end klass.define_instance_method('hash') klass.define_instance_method('httpdate') klass.define_instance_method('initialize') do |method| method.define_optional_argument('ajd') method.define_optional_argument('of') method.define_optional_argument('sg') method.returns { |object| object.instance } end klass.define_instance_method('inspect') klass.define_instance_method('iso8601') klass.define_instance_method('italy') klass.define_instance_method('jd') do |method| method.define_rest_argument('args') end klass.define_instance_method('jisx0301') klass.define_instance_method('julian') klass.define_instance_method('julian?') do |method| method.define_rest_argument('args') end klass.define_instance_method('ld') do |method| method.define_rest_argument('args') end klass.define_instance_method('leap?') do |method| method.define_rest_argument('args') end klass.define_instance_method('marshal_dump') klass.define_instance_method('marshal_load') do |method| method.define_argument('a') end klass.define_instance_method('mday') klass.define_instance_method('mjd') do |method| method.define_rest_argument('args') end klass.define_instance_method('mon') klass.define_instance_method('monday?') klass.define_instance_method('month') klass.define_instance_method('new_start') do |method| method.define_optional_argument('sg') end klass.define_instance_method('next') klass.define_instance_method('next_day') do |method| method.define_optional_argument('n') end klass.define_instance_method('next_month') do |method| method.define_optional_argument('n') end klass.define_instance_method('next_year') do |method| method.define_optional_argument('n') end klass.define_instance_method('prev_day') do |method| method.define_optional_argument('n') end klass.define_instance_method('prev_month') do |method| method.define_optional_argument('n') end klass.define_instance_method('prev_year') do |method| method.define_optional_argument('n') end klass.define_instance_method('rfc2822') klass.define_instance_method('rfc3339') klass.define_instance_method('rfc822') klass.define_instance_method('saturday?') klass.define_instance_method('start') klass.define_instance_method('step') do |method| method.define_argument('limit') method.define_optional_argument('step') end klass.define_instance_method('strftime') do |method| method.define_optional_argument('fmt') end klass.define_instance_method('succ') klass.define_instance_method('sunday?') klass.define_instance_method('taguri') klass.define_instance_method('taguri=') klass.define_instance_method('thursday?') klass.define_instance_method('to_date') klass.define_instance_method('to_datetime') klass.define_instance_method('to_s') klass.define_instance_method('to_time') klass.define_instance_method('to_yaml') do |method| method.define_optional_argument('opts') end klass.define_instance_method('tuesday?') klass.define_instance_method('upto') do |method| method.define_argument('max') method.define_block_argument('block') end klass.define_instance_method('wday') do |method| method.define_rest_argument('args') end klass.define_instance_method('wednesday?') klass.define_instance_method('xmlschema') klass.define_instance_method('yday') klass.define_instance_method('year') end defs.define_constant('Date::ABBR_DAYNAMES') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::ABBR_MONTHNAMES') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::DAYNAMES') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::ENGLAND') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format::ABBR_DAYS') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format::ABBR_MONTHS') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format::Bag') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) klass.define_instance_method('[]') do |method| method.define_argument('key') end klass.define_instance_method('[]=') do |method| method.define_argument('key') method.define_argument('val') end klass.define_instance_method('_cent') klass.define_instance_method('_cent=') klass.define_instance_method('_comp') klass.define_instance_method('_comp=') klass.define_instance_method('_merid') klass.define_instance_method('_merid=') klass.define_instance_method('hour') klass.define_instance_method('hour=') klass.define_instance_method('initialize') klass.define_instance_method('mday') klass.define_instance_method('mday=') klass.define_instance_method('min') klass.define_instance_method('min=') klass.define_instance_method('mon') klass.define_instance_method('mon=') klass.define_instance_method('offset') klass.define_instance_method('offset=') klass.define_instance_method('sec') klass.define_instance_method('sec=') klass.define_instance_method('sec_fraction') klass.define_instance_method('sec_fraction=') klass.define_instance_method('to_hash') klass.define_instance_method('year') klass.define_instance_method('year=') klass.define_instance_method('zone') klass.define_instance_method('zone=') end defs.define_constant('Date::Format::Bag::Fast') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format::DAYS') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format::MONTHS') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Format::ZONES') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::GREGORIAN') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::HALF_DAYS_IN_DAY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::HOURS_IN_DAY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::ITALY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::Infinity') do |klass| klass.inherits(defs.constant_proxy('Numeric', RubyLint.registry)) klass.define_instance_method('+@') klass.define_instance_method('-@') klass.define_instance_method('<=>') do |method| method.define_argument('other') end klass.define_instance_method('abs') klass.define_instance_method('coerce') do |method| method.define_argument('other') end klass.define_instance_method('d') klass.define_instance_method('finite?') klass.define_instance_method('infinite?') klass.define_instance_method('initialize') do |method| method.define_optional_argument('d') method.returns { |object| object.instance } end klass.define_instance_method('nan?') klass.define_instance_method('zero?') end defs.define_constant('Date::JULIAN') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::LD_EPOCH_IN_CJD') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::MILLISECONDS_IN_DAY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::MILLISECONDS_IN_SECOND') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::MINUTES_IN_DAY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::MJD_EPOCH_IN_AJD') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::MJD_EPOCH_IN_CJD') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::MONTHNAMES') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::NANOSECONDS_IN_DAY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::NANOSECONDS_IN_SECOND') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::SECONDS_IN_DAY') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::UNIX_EPOCH_IN_AJD') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end defs.define_constant('Date::UNIX_EPOCH_IN_CJD') do |klass| klass.inherits(defs.constant_proxy('Object', RubyLint.registry)) end end
namespace Editor { public sealed class DivMathInverted : DivMath { public DivMathInverted(EquationContainer parent) : base(parent) { divMathSign.IsInverted = true; } protected override void AdjustVertical() { insideEquation.Top = Top + VerticalGap; divMathSign.Bottom = Bottom; } public override double RefY { get { return insideEquation.LastRow.MidY - Top; } } } }
package com.olshevchenko.currencyconverter.features.operations.domain.model /** * Exchange of [fromAmount] units of [fromCurrency] into [toAmount] units of [toCurrency] on a certain [dateTime] */ data class ExchangeOperation( val id: Int, val fromCurrency: String, val toCurrency: String, val fromAmount: Double, val toAmount: Double, val dateTime: String )
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.jboss.aerogear.memolist.service; import java.util.List; import javax.ejb.Stateless; import javax.inject.Inject; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import org.jboss.aerogear.memolist.security.RedHatUserBean; import org.jboss.aerogear.memolist.vo.Post; /** * * @author summers */ @Stateless @Named("feedService") public class FeedService { @PersistenceContext private EntityManager entityManager; public List<Post> getPosts() { return entityManager.createQuery("from Post order by posted desc", Post.class) .setMaxResults(10) .getResultList(); } public List<Post> getPosts(int page) { return entityManager.createQuery("from Post order by posted desc", Post.class) .setFirstResult(page * 10) .setMaxResults(10) .getResultList(); } }
//! Rope slices //! //! While we could just have the slicing methods on `Rope`s return `&str`s, //! this would have some serious drawbacks: to slice a rope as `&str`, we'd have //! to collect all the `Rope`'s characters into a `String` and then slice that //! `String`. Creating an intermediate `String` would be slow, would cause //! unnecessary allocations, and, in the case of `Rope::slice_mut()`, would //! return a mutable slice of a _new `String`_ –- mutating the slice would _not_ //! mutate the underlying `Rope`. // TODO: implement Borrow<RopeSlice> for Rope? use std::fmt; use std::cmp; use std::convert; #[cfg(feature = "unstable")] use collections::range::RangeArgument; #[cfg(not(feature = "unstable"))] use std::ops::Range; use super::Rope; use super::internals::Node; /// An immutable borrowed slice of a `Rope`. /// /// A `RopeSlice` represents an immutable borrowed slice of some or all the /// characters in a `Rope`. pub struct RopeSlice<'a> { node: &'a Node , offset: usize , len: usize } impl<'a> fmt::Display for RopeSlice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // TODO: don't create an intermediate string? write!(f, "{}", self.chars().collect::<String>()) } } impl<'a> fmt::Debug for RopeSlice<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { // TODO: don't create an intermediate string? write!( f, "RopeSlice {{ offset: {}, len {} }} [{:?}]" , self.offset, self.len, self.chars().collect::<String>()) } } // // /// An mutable borrowed slice of a `Rope`. // /// // /// A `RopeSliceMut` represents a mutable borrowed slice of some or all the // /// characters in a `Rope`. // #[derive(Debug)] // pub struct RopeSliceMut<'a> { node: &'a mut Node // , offset: usize // , len: usize // } // // impl<'a> RopeSliceMut<'a> { // // // TODO: share duplicate functionality with non-mutable RopeSlice in a less // // ugly way. Maybe an added generic? // // - eliza, 12/23/16 // // // TODO: add mutable iterators // // #[cfg(feature = "unstable")] // pub fn new<R>(node: &'a mut Node, range: R) -> Self // where R: RangeArgument<usize> { // let len = node.len(); // // // if the RangeArgument doesn't have a defined start index, // // the slice begins at the 0th index. // let start = *range.start().unwrap_or(&0); // // similarly, if there's no defined end, then the end index // // is the last index in the Rope. // let end = *range.end().unwrap_or(&len); // // let slice_len = end - start; // // // find the lowest node that contains both the slice start index and // // the end index // let (node, offset) = if start == 0 && end == len { // // if the slice contains the entire rope, then the spanning node // // is the root node // (node, 0) // } else { // node.spanning_mut(start, slice_len) // }; // // RopeSliceMut { node: node // , offset: offset // , len: slice_len } // } // #[cfg(not(feature = "unstable"))] // pub fn new(node: &'a mut Node, range: Range<usize>) -> Self { // let len = node.len(); // let slice_len = range.end - range.start; // // // find the lowest node that contains both the slice start index and // // the end index // let (node, offset) = if range.start == 0 && range.end == len { // // if the slice contains the entire rope, then the spanning node // // is the root node // (node, 0) // } else { // node.spanning_mut(range.start, slice_len) // }; // // RopeSliceMut { node: node // , offset: offset // , len: slice_len } // } // // #[cfg(feature = "unstable")] // #[inline] // fn slice_char_iter<I, T>(&'a self, i: I) -> impl Iterator<Item=T> + 'a // where I: Iterator<Item=T> // , I: 'a // , T: Copy { // i.skip(self.offset).take(self.len) // } // // #[cfg(feature = "unstable")] // fn slice_strings_iter<I>(&'a self, i: I) -> impl Iterator<Item=&'a str> +'a // where I: Iterator<Item=&'a str> // , I: 'a { // i.scan((self.offset, self.len), |curr, s| { // match *curr { // (0, 0) => None // , (0, ref mut remaining) if *remaining < s.len() => { // let r = *remaining; // *remaining = 0; // Some(&s[..r]) // } // , (0, ref mut remaining) => { // *remaining -= s.len(); // Some(s) // } // , (ref mut offset, _) if *offset > s.len() => { // *offset -= s.len(); // Some("") // } // , (ref mut offset, _) => { // let c = *offset; // *offset -= s.len(); // Some(&s[c..]) // } // } // }) // .skip_while(|&s| s == "") // } // #[cfg(not(feature = "unstable"))] // #[inline] // fn slice_char_iter<I, T>(&'a self, i: I) -> Box<Iterator<Item=T> + 'a> // where I: Iterator<Item=T> // , I: 'a // , T: Copy { // Box::new(i.skip(self.offset) // .take(self.len)) // } // // #[cfg(not(feature = "unstable"))] // fn slice_strings_iter<I>(&'a self, i: I) -> Box<Iterator<Item=&'a str> + 'a> // where I: Iterator<Item=&'a str> // , I: 'a { // Box::new(i.scan((self.offset, self.len), |curr, s| { // match *curr { // (0, 0) => None // , (0, ref mut remaining) if *remaining < s.len() => { // let r = *remaining; // *remaining = 0; // Some(&s[..r]) // } // , (0, ref mut remaining) => { // *remaining -= s.len(); // Some(s) // } // , (ref mut offset, _) if *offset > s.len() => { // *offset -= s.len(); // Some("") // } // , (ref mut offset, _) => { // let c = *offset; // *offset -= s.len(); // Some(&s[c..]) // } // } // }) // .skip_while(|&s| s == "")) // } // // unstable_iters! { // #[inline] // pub fn chars(&'a self) -> impl Iterator<Item=char> + 'a { // self.slice_char_iter(self.node.chars()) // } // #[inline] // pub fn char_indices(&'a self) -> impl Iterator<Item=(usize, char)> + 'a { // self.chars().enumerate() // } // #[inline] // pub fn bytes(&'a self) -> impl Iterator<Item=u8> + 'a { // self.slice_char_iter(self.node.bytes()) // } // #[inline] // pub fn split_whitespace(&'a self) -> impl Iterator<Item=&'a str> + 'a { // self.slice_strings_iter(self.node.split_whitespace()) // } // } // // /// Returns true if the bytes in `self` equal the bytes in `other` // #[inline] // fn bytes_eq<I>(&self, other: I) -> bool // where I: Iterator<Item=u8> { // self.bytes().zip(other).all(|(a, b)| a == b) // } // // /// Returns the length of `self.` // /// // /// This length is in bytes, not chars or graphemes. In other words, it may // /// not be what a human considers the length of the string. // #[inline] // pub fn len(&self) -> usize { self.len } // // /// Returns `true` if this `RopeSliceMut` is empty. // /// // /// # Examples // /// // /// A `RopeSliceMut` into an empty rope should be empty: // /// // /// ``` // /// use an_rope::Rope; // /// let mut an_empty_rope = Rope::new(); // /// assert!(an_empty_rope.slice_mut(0..0).is_empty()); // /// ``` // /// // /// // /// A `RopeSliceMut` that contains no characters should be empty, // /// even fi the sliced `Rope` is not empty: // /// // /// ``` // /// use an_rope::Rope; // /// let mut an_rope = Rope::from("a string that is not empty"); // /// assert!(an_rope.slice_mut(0..0).is_empty()); // /// ``` // /// // /// A `RopeSliceMut` with characters should not be empty: // /// // /// ``` // /// use an_rope::Rope; // /// let mut an_rope = Rope::from("a string"); // /// assert!(!an_rope.slice_mut(0..5).is_empty()); // /// ``` // #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } // // // // #[inline] // // fn take_node(&mut self) -> Node { // // use std::mem::replace; // // replace(self.node, Node::empty()) // // } // // /// Insert `rope` into `index` in this mutable `RopeSlice`. // /// // /// Note that the index to insert into is relative to the beginning of this // /// _slice_, not to the beginning of the sliced `Rope`. // /// // /// Consumes `rope`. // /// // /// # Panics // /// * If `index` is greater than the length of this `RopeSlice` // /// // /// # Time Complexity // /// O(log _n_) // /// // /// # Examples // /// If built with `--features unstable`: // /// ``` // /// #![feature(collections)] // /// #![feature(collections_range)] // /// ##[cfg(feature = "unstable")] // /// extern crate collections; // /// extern crate an_rope; // /// ##[cfg(feature = "unstable")] // /// # fn main() { // /// // /// use collections::range::RangeArgument; // /// use an_rope::Rope; // /// // /// let mut rope = Rope::from("this is a string"); // /// { // we have to create a new block here so that the mutable borrow // /// // on `Rope` will end // /// let mut slice = rope.slice_mut(8..); // /// slice.insert_rope(1, Rope::from("n example")); // /// } // /// assert_eq!(&rope, "this is an example string"); // /// # } // /// ``` // #[inline] // pub fn insert_rope<M>(&self, index: M, rope: Rope) -> Rope // where M: Metric // , Node: Measured<M> // , BranchNode: Measured<M> // , String: Measured<M> { // // assert!( index <= self.len() // // , "RopeSliceMut::insert_rope: index {} was > length {}" // // , index, self.len()); // if !rope.is_empty() { // // split the rope at the given index // let (left, right) = self.split(index + self.offset); // // // construct the new root node with `Rope` inserted // (left + rope.root + right).rebalance() // } else { // self.clone() // } // } // // /// Insert `ch` into `index` in this mutable `RopeSlice`. // /// // /// Note that the index to insert into is relative to the beginning of this // /// _slice_, not to the beginning of the sliced `Rope`. // /// // /// Consumes `ch`. // /// // /// # Panics // /// * If `index` is greater than the length of this `RopeSlice` // /// // /// # Time Complexity // /// O(log _n_) // /// // /// # Examples // /// If built with `--features unstable`: // /// ``` // /// #![feature(collections)] // /// #![feature(collections_range)] // /// ##[cfg(feature = "unstable")] // /// extern crate collections; // /// extern crate an_rope; // /// ##[cfg(feature = "unstable")] // /// # fn main() { // /// // /// use collections::range::RangeArgument; // /// use an_rope::Rope; // /// // /// let mut rope = Rope::from("this is a string"); // /// { // we have to create a new block here so that the mutable borrow // /// // on `Rope` will end // /// let mut slice = rope.slice_mut(8..); // /// slice.insert(1, 'n'); // /// } // /// assert_eq!(&rope, "this is an string"); // /// # } // /// ``` // pub fn insert(&mut self, index: usize, ch: char) { // assert!( index <= self.len() // , "RopeSliceMut::insert: index {} was > length {}" // , index, self.len()); // // TODO: this is gross... // let mut s = String::new(); // s.push(ch); // self.insert_rope(index, Rope::from(s)) // } // // // /// Insert `s` into `index` in this mutable `RopeSlice`. // /// // /// Note that the index to insert into is relative to the beginning of this // /// _slice_, not to the beginning of the sliced `Rope`. // /// // /// # Panics // /// * If `index` is greater than the length of this `RopeSlice` // /// // /// # Time Complexity // /// O(log _n_) // /// // /// # Examples // /// If built with `--features unstable`: // /// ``` // /// #![feature(collections)] // /// #![feature(collections_range)] // /// ##[cfg(feature = "unstable")] // /// extern crate collections; // /// extern crate an_rope; // /// ##[cfg(feature = "unstable")] // /// # fn main() { // /// // /// use collections::range::RangeArgument; // /// use an_rope::Rope; // /// // /// let mut rope = Rope::from("this is a string"); // /// { // we have to create a new block here so that the mutable borrow // /// // on `Rope` will end // /// let mut slice = rope.slice_mut(8..); // /// slice.insert_str(1, "n example"); // /// } // /// assert_eq!(&rope, "this is an example string"); // /// # } // /// ``` // pub fn insert_str(&mut self, index: usize, s: &str) { // assert!( index <= self.len() // , "RopeSliceMut::insert_str: index {} was > length {}" // , index, self.len()); // self.insert_rope(index, Rope::from(s)) // } // // } impl<'a> RopeSlice<'a> { unstable_iters! { #[inline] pub fn chars(&'a self) -> impl Iterator<Item=char> + 'a { self.slice_char_iter(self.node.chars()) } #[inline] pub fn char_indices(&'a self) -> impl Iterator<Item=(usize, char)> + 'a { self.chars().enumerate() } #[inline] pub fn bytes(&'a self) -> impl Iterator<Item=u8> + 'a { self.slice_char_iter(self.node.bytes()) } #[inline] pub fn split_whitespace(&'a self) -> impl Iterator<Item=&'a str> + 'a { self.slice_strings_iter(self.node.split_whitespace()) } } #[cfg(feature = "unstable")] pub fn new<R>(node: &'a Node, range: R) -> Self where R: RangeArgument<usize> { let len = node.len(); // if the RangeArgument doesn't have a defined start index, // the slice begins at the 0th index. let start = *range.start().unwrap_or(&0); // similarly, if there's no defined end, then the end index // is the last index in the Rope. let end = *range.end().unwrap_or(&node.len()); let slice_len = end.saturating_sub(start); // find the lowest node that contains both the slice start index and // the end index let (node, offset) = if start == 0 && end == len { // if the slice contains the entire rope, then the spanning node // is the root node (node, 0) } else { node.spanning(start, slice_len) }; RopeSlice { node: node , offset: offset , len: slice_len } } #[cfg(not(feature = "unstable"))] pub fn new(node: &'a Node, range: Range<usize>) -> Self { let len = node.len(); let slice_len = range.end.saturating_sub(range.start); // find the lowest node that contains both the slice start index and // the end index let (node, offset) = if range.start == 0 && range.end == len { // if the slice contains the entire rope, then the spanning node // is the root node (node, 0) } else { node.spanning(range.start, slice_len) }; RopeSlice { node: node , offset: offset , len: slice_len } } #[cfg(feature = "unstable")] #[inline] fn slice_char_iter<I, T>(&'a self, i: I) -> impl Iterator<Item=T> + 'a where I: Iterator<Item=T> , I: 'a , T: Copy { i.skip(self.offset).take(self.len) } #[cfg(feature = "unstable")] fn slice_strings_iter<I>(&'a self, i: I) -> impl Iterator<Item=&'a str> + 'a where I: Iterator<Item=&'a str> , I: 'a { i.scan((self.offset, self.len), |curr, s| { match *curr { (0, 0) => None , (0, ref mut remaining) if *remaining < s.len() => { let r = *remaining; *remaining = 0; Some(&s[..r]) } , (0, ref mut remaining) => { *remaining -= s.len(); Some(s) } , (ref mut offset, _) if *offset > s.len() => { *offset -= s.len(); Some("") } , (ref mut offset, _) => { let c = *offset; *offset -= s.len(); Some(&s[c..]) } } }) .skip_while(|&s| s == "") } #[cfg(not(feature = "unstable"))] #[inline] fn slice_char_iter<I, T>(&'a self, i: I) -> Box<Iterator<Item=T> + 'a> where I: Iterator<Item=T> , I: 'a , T: Copy { Box::new(i.skip(self.offset) .take(self.len)) } #[cfg(not(feature = "unstable"))] fn slice_strings_iter<I>(&'a self, i: I) -> Box<Iterator<Item=&'a str> + 'a> where I: Iterator<Item=&'a str> , I: 'a { Box::new(i.scan((self.offset, self.len), |curr, s| { match *curr { (0, 0) => None , (0, ref mut remaining) if *remaining < s.len() => { let r = *remaining; *remaining = 0; Some(&s[..r]) } , (0, ref mut remaining) => { *remaining -= s.len(); Some(s) } , (ref mut offset, _) if *offset > s.len() => { *offset -= s.len(); Some("") } , (ref mut offset, _) => { let c = *offset; *offset -= s.len(); Some(&s[c..]) } } }) .skip_while(|&s| s == "")) } /// Returns true if the bytes in `self` equal the bytes in `other` #[inline] fn bytes_eq<I>(&self, other: I) -> bool where I: Iterator<Item=u8> { self.bytes().zip(other).all(|(a, b)| a == b) } #[inline] pub fn len(&self) -> usize { self.len } /// Returns `true` if this `RopeSlice` is empty. /// /// # Examples /// /// A `RopeSlice` into an empty rope should be empty: /// /// ``` /// use an_rope::Rope; /// let an_empty_rope = Rope::new(); /// assert!(an_empty_rope.slice(0..0).is_empty()); /// ``` /// /// /// A `RopeSlice` that contains no characters should be empty, /// even fi the sliced `Rope` is not empty: /// /// ``` /// use an_rope::Rope; /// let an_rope = Rope::from("a string that is not empty"); /// assert!(an_rope.slice(0..0).is_empty()); /// ``` /// /// A `RopeSlice` with characters should not be empty: /// /// ``` /// use an_rope::Rope; /// let an_rope = Rope::from("a string"); /// assert!(!an_rope.slice(0..5).is_empty()); /// ``` #[inline] pub fn is_empty(&self) -> bool { self.len() == 0 } } //-- comparisons ---------------------------------------------------- impl<'a> cmp::Eq for RopeSlice<'a> {} impl<'a> cmp::PartialEq for RopeSlice<'a> { /// A rope equals another rope if all the bytes in both are equal. #[inline] fn eq(&self, other: &RopeSlice<'a>) -> bool { if self.len() == other.len() { self.bytes_eq(other.bytes()) } else { false } } } impl<'a> cmp::PartialEq<str> for RopeSlice<'a> { /// A rope equals another rope if all the bytes in both are equal. #[inline] fn eq(&self, other: &str) -> bool { if self.len() == other.len() { self.bytes_eq(other.bytes()) } else { false } } } impl<'a> cmp::PartialEq<&'a str> for RopeSlice<'a> { /// A rope equals another rope if all the bytes in both are equal. #[inline] fn eq(&self, other: &&'a str) -> bool { if self.len() == other.len() { self.bytes_eq((*other).bytes()) } else { false } } } // // impl<'a> cmp::Eq for RopeSliceMut<'a> {} // impl<'a> cmp::PartialEq for RopeSliceMut<'a> { // /// A rope equals another rope if all the bytes in both are equal. // #[inline] // fn eq(&self, other: &RopeSliceMut<'a>) -> bool { // if self.len() == other.len() { // self.bytes_eq(other.bytes()) // } else { // false // } // } // } // // impl<'a, 'b> cmp::PartialEq<RopeSlice<'b>> for RopeSliceMut<'a> { // /// A rope equals another rope if all the bytes in both are equal. // // #[inline] // fn eq(&self, other: &RopeSlice<'b>) -> bool { // if self.len() == other.len() { // self.bytes_eq(other.bytes()) // } else { // false // } // } // } // // impl<'a> cmp::PartialEq<str> for RopeSliceMut<'a> { // /// A rope equals another rope if all the bytes in both are equal. // // #[inline] // fn eq(&self, other: &str) -> bool { // if self.len() == other.len() { // self.bytes_eq(other.bytes()) // } else { // false // } // } // } impl<'a> convert::Into<Rope> for RopeSlice<'a> { /// Converts this `RopeSlice` into a new `Rope` fn into(self) -> Rope { Rope::from(self.chars().collect::<String>()) } } impl<'a> convert::Into<String> for RopeSlice<'a> { /// Converts this `RopeSlice` into a new `String` fn into(self) -> String { self.chars().collect::<String>() } } // // impl<'a> convert::Into<Rope> for RopeSliceMut<'a> { // /// Converts this `RopeSliceMut` into a new `Rope` // fn into(self) -> Rope { // Rope::from(self.chars().collect::<String>()) // } // } // // impl<'a> convert::Into<String> for RopeSliceMut<'a> { // /// Converts this `RopeSliceMut` into a new `String` // fn into(self) -> String { // self.chars().collect::<String>() // } // } #[cfg(test)] mod tests { use super::*; use ::Rope; #[test] fn char_indices() { let string = "aaaaabbbbbbccccccccccccdefgdefgaabababab"; let rope = Rope::from(string); let rope_slice = rope.slice(4..8); let string_slice = &string[4..8]; let indices = rope_slice.char_indices().zip(string_slice.char_indices()); for ((ridx, rch), (sidx, sch)) in indices { assert_eq!(rch, sch); assert_eq!(ridx, sidx); } } #[test] fn to() { let string = "aaaaabbbbbbccccccccccccdefgdefgaabababab"; let rope = Rope::from(string); let rope_slice = rope.slice(1..10); let string_slice = &string[1..10]; assert_eq!(&rope_slice, string_slice) } // #[test] // fn between() { // let string = "aaaaabbbbbbccccccccccccdefgdefgaabababab"; // let rope = Rope::from(string); // let rope_slice = rope.slice(1...10usize); // let string_slice = &string[1...10]; // assert_eq!(&rope_slice, string_slice) // } #[cfg(feature = "unstable")] #[test] fn until() { let string = "aaaaabbbbbbccccccccccdefgdefgaabababab"; let rope = Rope::from(string); let rope_slice = rope.slice(..10); let string_slice = &string[..10]; assert_eq!(&rope_slice, string_slice) } #[cfg(feature = "unstable")] #[test] fn from() { let mut string = "aaaaabbbbbbccccccccccccdefgdefgaabababab"; let mut rope = Rope::from(string); let rope_slice = rope.slice(5..); let string_slice = &string[5..]; assert_eq!(&rope_slice, string_slice) } #[cfg(feature = "unstable")] #[test] fn full() { let string = "aaaaabbbbbbccccccccccccdefgdefgaabababab"; let rope = Rope::from(string); let rope_slice = rope.slice(..); let string_slice = &string[..]; assert_eq!(&rope_slice, string_slice) } // #[test] // fn mut_char_indices() { // let mut string = // String::from("aaaaabbbbbbccccccccccccdefgdefgaabababab"); // let mut rope = Rope::from(string.clone()); // let rope_slice = rope.slice_mut(4..8); // let string_slice = &mut string[4..8]; // let indices = rope_slice.char_indices().zip(string_slice.char_indices()); // for ((ridx, rch), (sidx, sch)) in indices { // assert_eq!(rch, sch); // assert_eq!(ridx, sidx); // } // } // // #[test] // fn mut_to() { // let mut string = // String::from("aaaaabbbbbbccccccccccccdefgdefgaabababab"); // let mut rope = Rope::from(string.clone()); // let rope_slice = rope.slice_mut(1..10); // let string_slice = &mut string[1..10]; // assert_eq!(&rope_slice, string_slice) // } // #[cfg(feature = "unstable")] // #[test] // fn mut_until() { // let mut string = // String::from("aaaaabbbbbbccccccccccccdefgdefgaabababab"); // let mut rope = Rope::from(string.clone()); // let rope_slice = rope.slice_mut(..10); // let string_slice = &mut string[..10]; // assert_eq!(&rope_slice, string_slice) // } // #[cfg(feature = "unstable")] // #[test] // fn mut_from() { // let mut string = // String::from("aaaaabbbbbbccccccccccccdefgdefgaabababab"); // let mut rope = Rope::from(string.clone()); // let rope_slice = rope.slice_mut(5..); // let string_slice = &mut string[5..]; // assert_eq!(&rope_slice, string_slice) // } // // #[cfg(feature = "unstable")] // #[test] // fn mut_full() { // let mut string = // String::from("aaaaabbbbbbccccccccccccdefgdefgaabababab"); // let mut rope = Rope::from(string.clone()); // let rope_slice = rope.slice_mut(..); // let string_slice = &mut string[..]; // assert_eq!(&rope_slice, string_slice) // } // #[cfg(feature = "unstable")] // #[test] // fn mut_insert_rope() { // let mut rope = Rope::from("this is a string"); // { // let slice = rope.slice_mut(8..); // assert_eq!(&slice, "a string"); // } // { // let mut slice = rope.slice_mut(8..); // slice.insert_rope(1, Rope::from("n example")); // } // assert_eq!(&rope, "this is an example string"); // } // #[cfg(feature = "unstable")] // #[test] // fn mut_insert_str() { // let mut rope = Rope::from("this is a string"); // { // let slice = rope.slice_mut(8..); // assert_eq!(&slice, "a string"); // } // { // let mut slice = rope.slice_mut(8..); // slice.insert_str(1, "n example"); // } // assert_eq!(&rope, "this is an example string"); // } // #[cfg(feature = "unstable")] // #[test] // fn mut_insert_char() { // let mut rope = Rope::from("this is a string"); // { // let slice = rope.slice_mut(8..); // assert_eq!(&slice, "a string"); // } // { // let mut slice = rope.slice_mut(8..); // slice.insert(1, 'n'); // } // assert_eq!(&rope, "this is an string"); // } }
require 'controllers/application' module ActiveRecord module Acts #:nodoc: module Renderer #:nodoc: def self.included(base) base.extend(ClassMethods) end # Allows models to support render_to_file and render_to_string methods module ClassMethods def acts_as_renderer class_eval <<-EOV, __FILE__, __LINE__ include ActiveRecord::Acts::Renderer::InstanceMethods # Renders a template to a file with the included variable assignments def self.render_file(template, destination, assigns) if output = render_string(template, assigns) File.open(destination, 'w') do |file| file.write output end end end # Renders a template to a string with the included variable assignments def self.render_string(template, assigns) viewer = Class.new(ApplicationController) path = ActionController::Base.view_paths rescue ActionController::Base.view_root ActionView::Base.new(path, assigns, viewer).render(template) end EOV end end # For instance, if your model is HomePage, you could say: # home_page.render_to_file('page', "#{self.user.name}/page.html", :now => Time.now) # and the destination file would be rendered using the template 'page', with the instance # variables @now and @home_page populated with Time.now and the current instance, respectively # The functions render_to_file and render_to_string work the same way. module InstanceMethods # Renders a record instance to a file using the provided template and any additional variables. def render_to_file(template, destination, variables={}) assigns = variables.reverse_merge(self.class.class_name.underscore.to_sym => self) self.class.render_file(template, destination, assigns) end # Renders a record instance to a string using the provided template and additional variables. def render_to_string(template, variables={}) assigns = variables.reverse_merge(self.class.class_name.underscore.to_sym => self) self.class.render_string(template, assigns) end end end end end
MODULE TNOConstants use ISO_FORTRAN_ENV REAL (kind=4),PARAMETER :: Cnuk = 5.5 REAL (kind=4),PARAMETER :: kappa = 0.41 REAL (kind=4),PARAMETER :: Cmu = 0.09 REAL (kind=4),PARAMETER :: pi = 3.1415 INTEGER (4),PARAMETER :: limit = 5000 REAL (kind=4) :: omega ! NOTE: not a constant and used by function int1 and int2 END MODULE TNOConstants !=========================================================== MODULE Atmosphere use ISO_FORTRAN_ENV !atmosphere constants REAL (kind=4) nu REAL (kind=4) co REAL (kind=4) rho END MODULE Atmosphere !=========================================================== MODULE Wavenumber use ISO_FORTRAN_ENV REAL (kind=4) :: k REAL (kind=4) :: k1 REAL (kind=4) :: k3 END MODULE Wavenumber !=========================================================== MODULE BLParams use ISO_FORTRAN_ENV REAL (kind=4) :: d99(2) REAL (kind=4) :: Cf(2) REAL (kind=4) :: edgevel(2) END MODULE BLParams !=========================================================== MODULE AirfoilParams use ISO_FORTRAN_ENV REAL(kind=4) :: Mach LOGICAL :: ISSUCTION END MODULE AirfoilParams !===========================================================
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { ThemeModule } from '../../theme/theme.module'; import { ReactiveFormsModule } from '@angular/forms'; import { DocumentBackendRoutingModule, documentBackendRoutedComponents, } from './backend-routing.module'; import { DocumentService } from './document.service'; import { NgbDropdownModule } from '@ng-bootstrap/ng-bootstrap'; import { ZreEditorModule } from '../../editor/editor.module'; import { ContextMenuModule } from '../../context-menu/context-menu.module'; import { DialogModule } from '../../dialog'; import { ZreFormModule } from '../../form'; @NgModule({ imports: [ CommonModule, DocumentBackendRoutingModule, ThemeModule, NgbDropdownModule, ReactiveFormsModule, ZreEditorModule, ContextMenuModule, DialogModule, ZreFormModule, ], declarations: [...documentBackendRoutedComponents], providers: [ DocumentService, ] }) export class DocumentBackendModule {}
/* ::::: __________________________________________________________________ ::::: : ____\ .__ .__ _____ __. ____ ___ _______ .__ ______ .__ _____ .__ _. /____ : __\ .___! __|_/__ / _|__ / /_____ __| \ gRK __|_ \ __ |_ \ !___. /__ \ ! ___/ |/ /___/ | \__\ ._/ __\/ \ \___/ |/ \/ \_./ \___ ! / /__ (___ /\____\____|\ ____| / /___|\ ______. ____\|\ ___) __\ /____ \_/ ___________ \_/ __ |__/ _______ \_/ ____ |___/ _____ \_/ ____\ : /________________________________________________________________\ : ::::: + p H E N O M p R O D U C T I O N S + ::::: ============================================================================== bivrost! A socket server to shared socket descriptor bridge. Copyright (c) 2018, Bryan D. Ashby See LICENSE.TXT */ extern crate clap; extern crate codepage_437; extern crate docopt; #[macro_use] extern crate serde_derive; #[cfg(windows)] extern crate winapi; use clap::crate_version; use codepage_437::{FromCp437, IntoCp437, CP437_CONTROL}; use docopt::Docopt; use std::fs; use std::io::Error; use std::io::ErrorKind; use std::io::Write; use std::net::TcpStream; use std::path::Path; use std::process; use std::process::Command; use std::vec::Vec; const USAGE: &str = " bivrost! A socket server to shared socket descriptor bridge. Copyright (c) 2018, Bryan D. Ashby Usage: bivrost --port=<port> [--dropfile=<dropfile> --out=<out>] <target> bivrost --help | --version Options: -h, --help Show this message. --version Show the version of bivrost! --port=<port> Set server port in which to connect to. --dropfile=<dropfile> Set DOOR32.SYS dropfile path. --out=<out> Set output directory for new DOOR32.SYS. If not specified, original DOOR32.SYS will be overridden. Notes: If <target> contains arguments, it should be quoted. For example: \"DOOR.EXE /D -N 1\" Arguments within <target> may also contain {fd} which will be substituted with the shared socket descriptor (the same value to be found in the output DOOR32.SYS). If your door does not use DOOR32.SYS you can omit --dropfile and --out and still use {fd}."; const DOOR32_SYS_FILENAME: &str = "DOOR32.SYS"; #[derive(Debug, Deserialize)] struct Args { flag_port: i32, flag_dropfile: String, flag_out: String, arg_target: String, flag_version: bool, } // // DOOR32.SYS // https://github.com/NuSkooler/ansi-bbs/blob/master/docs/dropfile_formats/door32_sys.txt // fn read_door32sys_dropfile(dropfile_path: &str) -> Result<String, Error> { let pathname = Path::new(dropfile_path).file_name().ok_or(Error::new( ErrorKind::NotFound, format!("File {} does not name a file", dropfile_path), ))?; if !pathname .to_string_lossy() .eq_ignore_ascii_case(DOOR32_SYS_FILENAME) { return Err(Error::new( ErrorKind::InvalidInput, format!("File {} is not DOOR32.SYS", dropfile_path), )); } let contents = fs::read(pathname)?; Ok(String::from_cp437(contents, &CP437_CONTROL)) } #[cfg(windows)] fn dropfile_filename(filename: &str) -> String { filename.to_lowercase() } #[cfg(not(windows))] fn dropfile_filename(filename: &str) -> String { filename.to_string() } fn write_new_door32sys_dropfile( orig_contents: &str, out_path: &Path, socket_fd: u64, ) -> Result<String, Error> { if !out_path.is_dir() { return Err(Error::new( ErrorKind::NotFound, format!("{} is not a directory", out_path.to_string_lossy()), )); } // // First two lines are as follows: // 1 - Comm type (2=telnet) // 2 - Shared socket fd // ...the rest is just copied over from the original. // let dropfile_path = out_path.join(dropfile_filename(DOOR32_SYS_FILENAME)); let mut file = fs::File::create(&dropfile_path)?; file.write_all(b"2\r\n")?; file.write_all(socket_fd.to_string().as_bytes())?; file.write_all(b"\r\n")?; for line in orig_contents.lines().skip(2) { let cp437 = &line.to_string().into_cp437(&CP437_CONTROL).map_err(|e| { Error::new( ErrorKind::InvalidData, format!("Failed to convert to CP437: {}", e.into_string()), ) })?; file.write_all(cp437)?; file.write_all(b"\r\n")?; } let pathname = dropfile_path.to_string_lossy(); println!("Created new dropfile at {}", &pathname); Ok(pathname.to_string()) } #[cfg(windows)] fn get_socket_fd(stream: TcpStream) -> Result<u64, String> { use std::os::windows::io::AsRawSocket; use std::os::windows::raw::HANDLE; use winapi::shared::minwindef::TRUE; use winapi::um::handleapi::DuplicateHandle; use winapi::um::processthreadsapi::GetCurrentProcess; use winapi::um::winnt::DUPLICATE_SAME_ACCESS; let sock_handle = stream.as_raw_socket() as HANDLE; let mut dupe_handle: HANDLE = 0 as HANDLE; let dupe_handle_ptr: *mut HANDLE = &mut dupe_handle; let ret = unsafe { DuplicateHandle( GetCurrentProcess(), sock_handle, GetCurrentProcess(), dupe_handle_ptr, 0, TRUE, DUPLICATE_SAME_ACCESS, ) }; if ret == TRUE { Ok(dupe_handle as u64) } else { Err(format!( "Failed to duplicate handle: {}", Error::last_os_error().to_string() )) } } #[cfg(not(windows))] fn get_socket_fd(stream: TcpStream) -> Result<u64, String> { use std::os::unix::io::AsRawFd; Ok(stream.as_raw_fd() as u64) } fn connect_to_supplied_port(port: i32) -> Result<TcpStream, String> { let address = format!("localhost:{}", port); println!("Connecting to {}...", address); match TcpStream::connect(address) { Ok(stream) => Ok(stream), Err(e) => Err(e.to_string()), } } const EXIT_SUCCESS: i32 = 0; const EXIT_FAILURE: i32 = (-1); fn main() { let args: Args = Docopt::new(USAGE) .and_then(|d| d.deserialize()) .unwrap_or_else(|e| e.exit()); if args.flag_version { println!("{}", crate_version!()); process::exit(EXIT_SUCCESS); } let stream = connect_to_supplied_port(args.flag_port).unwrap_or_else(|e| { println!("Failed to connect: {}", e.to_string()); process::exit(EXIT_FAILURE); }); let shared_fd = get_socket_fd(stream).unwrap_or_else(|e| { println!("{}", e.to_string()); process::exit(EXIT_FAILURE); }); println!("Connected. Socket file descriptor is {}", shared_fd); if args.flag_dropfile.len() > 0 { let dropfile = read_door32sys_dropfile(&args.flag_dropfile).unwrap_or_else(|e| { println!( "Failed to read dropfile at {}: {}", args.flag_dropfile, e.to_string() ); process::exit(EXIT_FAILURE); }); let out_path = match args.flag_out.is_empty() { true => { let p = Path::new(&args.flag_dropfile); p.parent().unwrap() } false => Path::new(&args.flag_out), }; write_new_door32sys_dropfile(&dropfile, &out_path, shared_fd).unwrap_or_else(|e| { println!("{}", e.to_string()); process::exit(EXIT_FAILURE); }); } let split_args: Vec<String> = args.arg_target.split(' ').map(|a| a.to_string()).collect(); let mut target_args: Vec<String> = split_args .iter() .map(|arg| arg.replace("{fd}", &format!("{}", shared_fd))) .collect::<Vec<String>>(); let command = target_args.first().unwrap(); let target_exit_status = Command::new(command) .args(target_args.split_off(1)) .status() .unwrap_or_else(|e| { println!("Execute failed: {}", e.to_string()); process::exit(EXIT_FAILURE); }); match target_exit_status.code() { Some(code) => { println!("Process exited with code {}", code); process::exit(code); } None => { println!("Process terminated by signal"); process::exit(EXIT_FAILURE); } } }
module SmsBackupRenderer # Represents a single sender or recipient of an SMS or MMS message. class Participant # Returns the String address of the participant, such as '1 (234) 567-890'. attr_reader :address # Returns the String contact name for the participant, or nil if unknown. attr_reader :name # Returns true if this participant is the owner of the archive, otherwise false. attr_reader :owner # Returns true if this participant is a sender of the message, false if they are a recipient. attr_reader :sender def initialize(args) @address = args[:address] @name = args[:name] @owner = args[:owner] @sender = args[:sender] end def normalized_address @normalized_address ||= Participant.normalize_address(address) end # Normalizes a given address, for example '1 (234) 567-890' to '1234567890'. # # TODO: This is currently done in a very hacky, incomplete, embarrassingly-US-centric way. # # address - String address to normalize # # Returns the String normalized address. def self.normalize_address(address) address.gsub(/[\s\(\)\+\-]/, '') .gsub(/\A1(\d{10})\z/, '\\1') end end # Represents an SMS or MMS message. class Message # Returns a Time instance indicating when the message was sent or received. attr_reader :date_time # Returns true if the message was sent to address, false if received from address. attr_reader :outgoing # Returns an Array of Participant instances representing the senders and recipients of the message. # For MMS messages there may be multiple recipients. For SMS messages, the originator of the archive # is never represented, so there will only be a sender (for incoming messages) or a recipient # (for outgoing messages). attr_reader :participants # Returns an Array of MessagePart instances representing the contents of the message. attr_reader :parts # Returns the String subject/title of the message, likely nil. attr_reader :subject def initialize(args) @contact_name = args[:contact_name] @date_time = args[:date_time] @outgoing = args[:outgoing] @participants = args[:participants] @parts = args[:parts] || [] @subject = args[:subject] end # Returns the Participant instance for the message sender, or nil. def sender @sender ||= participants.detect(&:sender) end end # Represents a piece of content in a message, such as text or an image. See subclasses. class MessagePart end class UnsupportedPart < MessagePart # Returns a String containing the XML data of the message part. attr_reader :xml def initialize(xml) @xml = xml end end class TextPart < MessagePart # Returns the String content of the message part such as "Hey Jacob, don't you have something better to do?". attr_reader :text def initialize(text) @text = text end end class MediaPart < MessagePart # Returns the String content type for the message part such as 'image/jpeg'. attr_reader :content_type # Returns the String file path at which the content has been stored. attr_reader :path def initialize(content_type, path) @content_type = content_type @path = path end end class ImagePart < MediaPart; end class VideoPart < MediaPart; end end
create table act_id_membership ( USER_ID_ varchar(64) not null, GROUP_ID_ varchar(64) not null, primary key (USER_ID_, GROUP_ID_), constraint ACT_FK_MEMB_GROUP foreign key (GROUP_ID_) references act_id_group (ID_), constraint ACT_FK_MEMB_USER foreign key (USER_ID_) references act_id_user (ID_) ) collate = utf8_bin;
import React from 'react'; import Helmet from 'react-helmet'; import { connect } from 'react-redux'; // import * as Basic from '../../components/basic'; import EntityAuditTable from '../audit/EntityAuditTable'; import SearchParameters from '../../domain/SearchParameters'; import { RoleManager } from '../../redux/data'; const roleManager = new RoleManager(); /** * Role audit tab. * * @author Radek Tomiška * @since 12.0.0 */ class RoleAudit extends Basic.AbstractContent { getContentKey() { return 'content.audit'; } componentDidMount() { super.componentDidMount(); // const { entityId } = this.props.match.params; this.context.store.dispatch(roleManager.fetchEntityIfNeeded(entityId)); } getNavigationKey() { return 'role-audit-detail'; } render() { const { entity } = this.props; // ~ codeable support // if (!entity) { return ( <Basic.Loading isStatic show/> ); } // const forceSearchParameters = new SearchParameters() .setFilter('withVersion', true) .setFilter('relatedOwnerId', entity.id); // return ( <div> <Helmet title={ this.i18n('title') } /> <EntityAuditTable uiKey={ `role-audit-table-${ entity.id }` } forceSearchParameters={ forceSearchParameters }/> </div> ); } } function select(state, component) { const { entityId } = component.match.params; return { entity: roleManager.getEntity(state, entityId) }; } export default connect(select)(RoleAudit);
package daniel.zolnai.marathon.service import com.dumbster.smtp.SimpleSmtpServer import daniel.zolnai.marathon.TestSuite import daniel.zolnai.marathon.entity.{AppConfig, EmailConfig, Trigger} import scala.collection.JavaConverters._ /** * Tests the email client with a fake SMTP server. * Created by Daniel Zolnai on 2016-07-21. */ class EmailServiceTest extends TestSuite { private final val SENDER = "Test sender <test-sender@example.com>" private final val SUBJECT = "Test subject" private final val TEXT = "This is a test message." private final val SEND_TO = List("alice@example", "bob@example.com") test("sendEmail") { val fakeSmtpServer = SimpleSmtpServer.start(SimpleSmtpServer.AUTO_SMTP_PORT) val emailConfig = EmailConfig("localhost", fakeSmtpServer.getPort, SENDER, None, None, SUBJECT, SEND_TO.mkString(","), TEXT, isSSL = false) val configService = new ConfigService { override val appConfig: AppConfig = AppConfig(None, "", None, emailConfig, null) } val emailService = new EmailService(configService) // Test only the default values val trigger1 = new Trigger() emailService.sendEmail(trigger1, null) var emails = fakeSmtpServer.getReceivedEmails.asScala assert(emails.length == 1) var email = emails.head assert(email.getBody == TEXT) assert(email.getHeaderValue("Subject") == SUBJECT) assert(email.getHeaderValue("To") == SEND_TO.mkString(", ")) fakeSmtpServer.reset() // Test with overrides from a trigger val trigger2 = new Trigger() trigger2.emailSendTo = Some("charlie@example.com") trigger2.emailSubject = Some("Different subject") trigger2.emailText = Some("Different text") emailService.sendEmail(trigger2, null) emails = fakeSmtpServer.getReceivedEmails.asScala assert(emails.length == 1) email = emails.head assert(email.getBody == trigger2.emailText.get) assert(email.getHeaderValue("Subject") == trigger2.emailSubject.get) assert(email.getHeaderValue("To") == trigger2.emailSendTo.get) fakeSmtpServer.stop() } }
<?php namespace Clarkson\Filters\SiteHealth\Filters\Plugins\WooCommerce; use Clarkson\Filters\SiteHealth\Filters\Plugins\WooCommerce\Tab; class Tools extends Tab { public function __construct() { $this->title = __( 'Tools', 'woocommerce' ); $this->slug = 'tools'; } public function register_hooks() { add_filter( 'woocommerce_admin_status_tabs', array( $this, 'unset_tabs' ), 10, 1 ); } }
package com.nikolaykul.sebastian.di /** * Marker interface that informs *this* object can be injected * * @see AppInjector * @author NikolayKul */ interface Injectable
const db = require("./"); const Models = require("./Models"); async function createTables() { await db.authenticate(); await Models.ExampleModel.sync(); } module.exports = { createTables: createTables, wipeDBTables: async() => { await db.drop(); await createTables(); } };
package eg.edu.alexu.csd.oop.draw.cs62_67.model; import java.util.ArrayList; import eg.edu.alexu.csd.oop.draw.ICommand; import eg.edu.alexu.csd.oop.draw.Shape; public class UpdateShape implements ICommand{ private ArrayList<Shape> shapes; private Shape oldShape; private Shape newShape; public UpdateShape(ArrayList<Shape> shapes, Shape oldShape, Shape newShape){ this.shapes = shapes; this.oldShape = oldShape; this.newShape = newShape; } @Override public void execute() { int index = this.shapes.indexOf(oldShape); this.shapes.remove(oldShape); this.shapes.add(index, newShape); } @Override public void unexecute() { int index = this.shapes.indexOf(newShape); this.shapes.remove(newShape); this.shapes.add(index, oldShape); } @Override public Shape getNewShape() { // TODO Auto-generated method stub return newShape; } @Override public Shape getOldShape() { // TODO Auto-generated method stub return oldShape; } }
#include <word-search.h> /* Used instead of iterating over all pointers in trie because it takes extremely long when using full unicode set */ typedef struct { trie **node; int length; } node_index; static node_index trie_index; static trie *head; static int max_word_length = 0; // Builds trie when given file ptr bool load(FILE *list) { trie_index.node = calloc(DEFAULT_SIZE, sizeof(trie*)); if (!trie_index.node) { fprintf(stderr, "Failed to allocate memory\n"); return false; } trie_index.length = 0; head = calloc(1, sizeof(trie)); if (!head) { fprintf(stderr, "Failed to allocate memory\n"); return false; } index_node(head); wchar_t *word = NULL; while (feof(list) == 0) { word = get_word(list); if (!word) { return false; } insert(word); free(word); } return true; } // Does what it says on the tin indexes a node void index_node(trie *node) { static int size = DEFAULT_SIZE; if (size == trie_index.length) { size = size * 2; trie **tmp = realloc(trie_index.node, size * sizeof(trie*)); if (!tmp) { fprintf(stderr, "Failed to allocate memory\n"); } else if (tmp != trie_index.node) { trie_index.node = tmp; } } trie_index.node[trie_index.length] = node; trie_index.length++; } // Gets word from a file while ignoring seperating characters wchar_t *get_word(FILE *inptr) { int size = DEFAULT_SIZE; wchar_t *word = malloc(size * sizeof(wchar_t)); int count = 0; while (true) { if (size == count) { size = size * 2; wchar_t *tmp = realloc(word, size * sizeof(wchar_t)); if (!tmp) { free(word); return tmp; } else if (tmp != word) { word = tmp; } } wint_t wc = fgetwc(inptr); if (wc == '\n' || wc == ' ' || wc == WEOF) { break; } word[count] = towlower(wc); count++; } if (count > max_word_length) { max_word_length = count; } word = realloc(word, (count + 1) * sizeof(wchar_t)); word[count] = '\0'; return word; } // Frees trie using index void unload_trie(void) { for (int i = 0; i < trie_index.length; i++) { free(trie_index.node[i]); } free(trie_index.node); } // Inserts string into trie void insert(wchar_t *key) { trie *trav = head; for (int i = 0; i < wcslen(key); i++) { if (!trav->path[towlower(key[i])]) { trie *node = calloc(1, sizeof(trie)); if (!node) { fprintf(stderr, "Failed to allocate memory\n"); } index_node(node); trav->path[tolower(key[i])] = node; } trav = trav->path[towlower(key[i])]; } trav->valid = true; } // Traverses trie using string and returns the node if it exists trie *locate(pos *key, int n) { trie *node = head; for (int i = 0; i < n; i++) { node = node->path[towlower(key[i].ch)]; if (!node) { return NULL; } } return node; } int word_length(void) { return max_word_length; }
using Sims using NineML using Winston al = NineML.parse_ComponentClass("IaF.xml") uls = NineML.parse_Components("IaF_UL.xml") tf = 100.0 dt = 0.025 ul= uls[1] NineML.eval_Dynamics(al.dynamics, ul.name, ul.parameterValues, ul.initialValues, al.parameters, al.states, al.ports) model = ul.name iaf = eval(quote $model () end) iaf_s = create_sim(iaf) iaf_ptr = setup_sunsim(iaf_s) iaf_yout = sunsim(iaf_ptr, tf, int(tf/dt)) f = figure() pl = plot (iaf_yout.y[:,1], iaf_yout.y[:,2]) display(pl)
--- layout: slide title: "Welcome to our second slide!" --- My new fish tank has just opened for 7 residents! Date created: 8th Feb 2022 Use the left arrow to go back!
--- translation: automatic title: Anticorps anti-thyroglobuline description: Anticorps contre les protéines thyroïdiennes ---
<?php namespace loginBundle\Model; use Symfony\Component\Security\Core\User\UserProviderInterface; use Symfony\Component\Security\Core\User\UserInterface; use Symfony\Component\Security\Core\Exception\UsernameNotFoundException; use Symfony\Component\Security\Core\Exception\UnsupportedUserException; use Symfony\Component\DependencyInjection\ContainerInterface; use loginBundle\Model\UsuarioModel; class UserProvider implements UserProviderInterface { private $UsuarioModel; public function __construct(ContainerInterface $container = null) { $this->UsuarioModel = new UsuarioModel(); } public function loadUserByUsername($username = "none") { if ($username == "" || $username == "*") { $username = "_none_username"; throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); } $Args = Array('correo' => "'" . $username . "'"); $result_usuario = $this->UsuarioModel->findUser($Args); print_r($result_usuario); die(); if (!$result_usuario['status']) { throw new UsernameNotFoundException($result_usuario['data']); } if (count($result_usuario['data']) == 0) { throw new UsernameNotFoundException(sprintf('Username "%s" does not exist.', $username)); } $usuario = $result_usuario['data'][0]; $roles = array('ROLE_ADMIN'); $user = new Profile($usuario['correo'], $usuario['contraseña'], $roles); $user->setData($usuario); return $user; } public function refreshUser(UserInterface $user) { if (!$user instanceof Profile) { throw new UnsupportedUserException(sprintf('Instances of "%s" are not supported.', get_class($user))); } return $user; } public function supportsClass($class) { return $class === 'loginBundle\Model\Profile'; } }
import {expect} from 'chai'; import * as supertest from 'supertest'; import {CreatedNewUserData, signupNewUser} from "../utlis/auth"; import { withData } from 'leche'; const request = supertest('http://localhost:1308'); type TopicRequest = {name: string, isActive: boolean}; type StreamRequest = {track: string}; let newUserData: CreatedNewUserData; let topicRequestData: TopicRequest = {name: 'Tesla, Inc.', isActive: true}; before(async () => { newUserData = await signupNewUser() }); describe('Should streams CRUD works fine', function() { let createdTopicId: bigint before(async function () { const res = await request .post('/topics') .set('Authorization', newUserData.jwtToken) .send(topicRequestData) .expect(200); expect(res.body).has.property("id").greaterThan(0) createdTopicId = res.body.id await request .post('/topics/' + createdTopicId + '/streams') .set('Authorization', newUserData.jwtToken) .send({track: 'SomeUnknownWord'}) .expect(200); }); const streamsToCreate = { simpleStream: {track: 'Something'}, twoWordsStream: {track: 'Something else'}, } withData(streamsToCreate, async function(streamRequest: StreamRequest) { let createdStream: {id: bigint, track: string}; it('Should POST /topics/:id/streams 200 with valid stream request data', async function() { // @TODO Add check for topic Request instanceof. When TopicRequest will be moved to separate class. const res = await request .post('/topics/' + createdTopicId + '/streams') .set('Authorization', newUserData.jwtToken) .send(streamRequest) .expect(200); createdStream = res.body; validateStream(createdStream, streamRequest); }); it('Should PUT /topics/:id/streams 200 with valid stream request data', async function() { const streamUpdateRequest = {track: "Nothing"} const res = await request .put('/topics/' + createdTopicId + '/streams/' + createdStream.id) .set('Authorization', newUserData.jwtToken) .send(streamUpdateRequest) .expect(200); validateStream(res.body, streamUpdateRequest) }); it('Should DELETE /topics/:id/streams 200 with valid path', async function() { const res = await request .delete('/topics/' + createdTopicId + '/streams/' + createdStream.id) .set('Authorization', newUserData.jwtToken) .expect(200); }) it('Should DELETE /topics/:id/streams 404 with already deleted stream', async function() { const res = await request .delete('/topics/' + createdTopicId + '/streams/' + createdStream.id) .set('Authorization', newUserData.jwtToken) .expect(404); }) }); it('Should GET /topics/:id/streams 200 with existed streams data', async function() { const res = await request .get('/topics/' + createdTopicId + '/streams') .set('Authorization', newUserData.jwtToken) .expect(200); let streams = res.body expect(streams).length(1) // Count of data sets in streamsToCreate }); }); function validateStream(stream: {id: bigint, track: string}, expected: StreamRequest) { expect(stream).has.property("id").greaterThan(0); expect(stream).has.property("track").to.eql(expected.track); expect(stream).has.property("createdAt").not.empty; }
# Race class for potential player races (species, i.e. elf, dwarf, human) import random from api import get_data class Race : ''' A class representing a character's species ''' def __init__(self) : ''' Initialize member variables to default values ''' self.name = "" self.scores = {"STR" : 0, "DEX": 0,"INT" : 0,"CON" : 0,"WIS" : 0,"CHA" : 0 } self.speed = 0 self.languages = [] self.size = "" def generate(self,r_in="") : ''' Generate a species using the specified race, or randomly chosen if none is given''' endpoint = "api/races/" if r_in == "" : # Grab all races JSON data = get_data(endpoint)["results"] races = list() # Select a random race for elt in data : races.append(elt["index"]) print("Race: ", elt["index"]) self.name = races[random.randint(0,len(races) - 1)] print("Creating random race: ", self.name) else : # Select the input race self.name = r_in print("Creating race: ", self.name) # Grab this character's race JSON endpoint += (self.name + "/") data = get_data(endpoint) # Set data from JSON self.speed = data["speed"] self.size = data["size"] for elt in data["languages"] : self.languages.append(elt["name"]) for elt in data["ability_bonuses"] : self.scores[elt["name"]] = elt["bonus"] print("Bonus: ", elt["name"], " = ", elt["bonus"])
#!/bin/bash # My first script echo "VIRUS HAS BEEN ACTIVATED" echo "------------------------" SECONDS=0 python DDOS.py 10.0.0.3 echo "DDOS was executed for in $SECONDS seconds"
use rand::prelude::StdRng; use rand::SeedableRng; use crate::core::{Learner, Model, TrainingRow}; use crate::trees::splits::{Split, Splitter}; use super::{DecisionTreeParameters, LeafLearner, ModelNode, TrainingNode}; #[derive(Debug)] pub struct RegressionTreeLearner { splitter: Box<dyn Splitter<f64>>, learner: RegressionLeafLearner, params: DecisionTreeParameters, rng: StdRng, } impl RegressionTreeLearner { pub fn new( splitter: Box<dyn Splitter<f64>>, learner: LeafLearner, params: DecisionTreeParameters, seed_rng: Option<&mut StdRng>, ) -> Self { let rng = match seed_rng { Some(r) => SeedableRng::from_rng(r).expect("Seeding RNG failed."), None => SeedableRng::from_entropy(), }; Self { splitter, learner, params, rng } } fn split_internal( &mut self, data: Vec<TrainingRow<f64>>, split: Split, delta_impurity: f64, num_features: usize, remaining_depth: usize, ) -> TrainingNode<f64> { let (left_data, right_data): (Vec<_>, Vec<_>) = data.into_iter().partition(|row| split.turn_left(&row.features)); let left_child = self.build_child(left_data, num_features, remaining_depth); let right_child = self.build_child(right_data, num_features, remaining_depth); TrainingNode::internal( split, Box::new(left_child), Box::new(right_child), delta_impurity, self.params.max_depth - remaining_depth, ) } fn build_child( &mut self, data: Vec<TrainingRow<f64>>, num_features: usize, remaining_depth: usize, ) -> TrainingNode<f64> { let splitter = &mut self.splitter; let current_depth = self.params.max_depth - remaining_depth; let min_instances = self.params.min_leaf_instances; if data.len() >= 2 * min_instances && remaining_depth > 0 { let (split, delta) = splitter.find_best_split(&data, num_features, min_instances); if split != Split::None && delta > self.params.min_purity_increase { self.split_internal(data, split, delta, num_features, remaining_depth - 1) } else { TrainingNode::leaf(data, current_depth) } } else { TrainingNode::leaf(data, current_depth) } } } impl Learner<f64> for RegressionTreeLearner { fn fit(&mut self, data: &[TrainingRow<f64>]) -> Box<dyn Model<f64>> { let params = self.params; let my_data: Vec<TrainingRow<f64>> = data.to_vec(); let root_node = if params.max_depth == 0 { TrainingNode::leaf(my_data, 0) } else { let data_nf = data[0].features.num_features(); let actual_nf = data_nf.min(params.num_features); let min_count = params.min_leaf_instances; let max_depth = params.max_depth; let (split, delta) = self.splitter.find_best_split(&my_data, actual_nf, min_count); match split { Split::None => TrainingNode::leaf(my_data, 0), _split if delta < params.min_purity_increase => TrainingNode::leaf(my_data, 0), split => self.split_internal(my_data, split, delta, actual_nf, max_depth - 1), } }; todo!() } } pub struct RegressionTreeModel { training_node: TrainingNode<f64>, model_node: ModelNode<f64>, } #[cfg(test)] mod tests { use super::*; use crate::utils::linear_training_data; use crate::{trees::leaf::GuessTheMeanLearner, trees::splits::RegressionSplitter}; #[test] fn test_regression_tree() { let data = linear_training_data(100, &[0.0, 1.0, 2.0, 3.0], 5.0); let params: DecisionTreeParameters = Default::default(); let splitter = RegressionSplitter::new(true, None); let leaf_learner = LeafLearner::mean(GuessTheMeanLearner::new(None)); let mut tree = RegressionTreeLearner::new(Box::new(splitter), leaf_learner, params, None); let tic = std::time::SystemTime::now(); (0..10).for_each(|_| { let _ = tree.fit(&data); }); let toc = std::time::SystemTime::now(); let since = toc.duration_since(tic).expect(""); println!("{}", since.as_secs_f64() / 10.0); } }
import 'dart:io'; import 'package:dotenv/dotenv.dart' as dot; class Env { Map<String, String> env = {}; void load() { dot.load(); env = {} ..addAll(Platform.environment) ..addAll(dot.env); } } void main() { (Env()..load()).env.forEach((key, value) => print('$key=$value')); }
import React from 'react' import { shallow } from 'enzyme' import { Price, OldPrice, CurrentPrice } from './' describe('Price Component', () => { it('should have a default structure', () => { expect(shallow(<Price />)).toMatchSnapshot() }) it('should have a emphasize prop', () => { expect(shallow(<Price emphasize={false} />)).toMatchSnapshot() }) }) describe('OldPrice Component', () => { it('should have a default structure', () => { expect(shallow(<OldPrice>125 kr</OldPrice>)).toMatchSnapshot() }) }) describe('CurrentPrice Component', () => { it('should have a default structure', () => { expect(shallow(<CurrentPrice>125 kr</CurrentPrice>)).toMatchSnapshot() }) })
// Configurations export const dropboxConfig = { clientId: '<YOUR_CLIENT_ID>', redirectUri: '<YOUR_REDIRECTURI>/auth:now', responseType: 'token', trustUrl: 'https://www.dropbox.com' }; export const dropboxApi = { 'filesListFolderContinue': 'https://api.dropboxapi.com/2/files/list_folder/continue', 'filesListFolderGetLatestCursor': 'https://api.dropboxapi.com/2/files/list_folder/get_latest_cursor' }; export const firebaseConfig = { production: false, firebase: { apiKey: '<YOUR_API_KEY>', authDomain: '<YOUR_AUTH_DOMAIN>', databaseURL: '<YOUR_DATABASE_URL>', projectId: '<YOUR_PROJECT_ID>', storageBucket: '<YOUR_STORAGE_BUCKET>', messagingSenderId: '<YOUR_MESSAGING_SENDER_ID>' }, listPath: '/dbxwebhooks', orderBy: 'list_folder/accounts/0' }; // Constants export interface DbxAuth { accessToken?: string; tokenType?: string; uid?: string; accountId?: string; isAuth?: boolean; }
#!/usr/bin/env bash # # Bootstrap software installations with Ansible. # Exit immediately if a command exits or pipes a non-zero return code. # # Flags: # -e: Exit immediately when a command pipeline fails. # -o: Persist nonzero exit codes through a Bash pipe. # -u: Throw an error when an unset variable is encountered. set -eou pipefail ####################################### # Show CLI help information. # Cannot use function name help, since help is a pre-existing command. # Outputs: # Writes help information to stdout. ####################################### usage() { case "$1" in bootstrap) cat 1>&2 << EOF Bootware bootstrap Boostrap install computer software USAGE: bootware bootstrap [OPTIONS] OPTIONS: -c, --config <PATH> Path to bootware user configuation file --check Dry run and show possible changes --checkout <REF> Git reference to run against -d, --dev Run bootstrapping in development mode -h, --help Print help information -i, --inventory <IP-List> Ansible host IP addesses --no-passwd Do not ask for user password --no-setup Skip Bootware dependency installation -p, --playbook <FILE-NAME> Name of play to execute --password <PASSWORD> Remote host user password -s, --skip <TAG-LIST> Ansible playbook tags to skip --ssh-key <FILE-NAME> Path to SSH private key -t, --tags <TAG-LIST> Ansible playbook tags to select -u, --url <URL> URL of playbook repository --user <USER-NAME> Remote host user login name --windows Connect to a Windows host with SSH EOF ;; config) cat 1>&2 << EOF Bootware config Download default Bootware configuration file USAGE: bootware config [OPTIONS] OPTIONS: -d, --dest <PATH> Path to alternate download destination -e, --empty Write empty configuration file -h, --help Print help information -s, --source <URL> URL to configuration file EOF ;; main) cat 1>&2 << EOF $(version) Boostrapping software installer USAGE: bootware [OPTIONS] [SUBCOMMAND] OPTIONS: -h, --help Print help information -v, --version Print version information SUBCOMMANDS: bootstrap Boostrap install computer software config Generate Bootware configuration file setup Install dependencies for Bootware uninstall Remove Bootware files update Update Bootware to latest version See 'bootware <subcommand> --help' for more information on a specific command. EOF ;; setup) cat 1>&2 << EOF Bootware setup Install dependencies for Bootware USAGE: bootware setup [OPTIONS] OPTIONS: -h, --help Print help information EOF ;; uninstall) cat 1>&2 << EOF Bootware uninstall Remove Bootware files USAGE: bootware uninstall OPTIONS: -h, --help Print help information EOF ;; update) cat 1>&2 << EOF Bootware update Update Bootware to latest version USAGE: bootware update [OPTIONS] OPTIONS: -h, --help Print help information -v, --version <VERSION> Version override for update EOF ;; *) error "No such usage option '$1'" ;; esac } ####################################### # Assert that command can be found in system path. # Will exit script with an error code if command is not in system path. # Arguments: # Command to check availabilty. # Outputs: # Writes error message to stderr if command is not in system path. ####################################### assert_cmd() { # Flags: # -v: Only show file path of command. # -x: Check if file exists and execute permission is granted. if [[ ! -x "$(command -v "$1")" ]]; then error "Cannot find required $1 command on computer" fi } ####################################### # Subcommand to bootstrap software installations. # Globals: # BOOTWARE_CONFIG # BOOTWARE_NOPASSWD # BOOTWARE_NOSETUP # BOOTWARE_PLAYBOOK # BOOTWARE_SKIP # BOOTWARE_TAGS # BOOTWARE_URL # USER ####################################### bootstrap() { # /dev/null is never a normal file. local ask_passwd local check local checkout local cmd="pull" local config_path="${BOOTWARE_CONFIG:-"/dev/null"}" local connection="local" local inventory="127.0.0.1," local no_setup="${BOOTWARE_NOSETUP:-""}" local passwd local playbook="${BOOTWARE_PLAYBOOK:-"main.yaml"}" local skip="${BOOTWARE_SKIP:-""}" local ssh_key local tags="${BOOTWARE_TAGS:-""}" local url="${BOOTWARE_URL:-"https://github.com/wolfgangwazzlestrauss/bootware.git"}" local use_playbook local use_pull=1 local user_account="${USER:-root}" local windows # Check if Ansible should ask for user password. # # Flags: # -z: Check if string has zero length. if [[ -z "${BOOTWARE_NOPASSWD:-}" ]]; then ask_passwd=1 fi # Parse command line arguments. while [[ "$#" -gt 0 ]]; do case "$1" in -c | --config) config_path="$2" shift 2 ;; --check) check=1 shift 1 ;; --checkout) checkout="$2" shift 2 ;; -d | --dev) cmd="playbook" use_playbook=1 use_pull="" shift 1 ;; -h | --help) usage "bootstrap" exit 0 ;; -i | --inventory) inventory="$2" shift 2 ;; --no-passwd) ask_passwd="" shift 1 ;; --no-setup) no_setup=1 shift 1 ;; -p | --playbook) playbook="$2" shift 2 ;; --password) passwd="$2" shift 2 ;; -s | --skip) skip="$2" shift 2 ;; -t | --tags) tags="$2" shift 2 ;; --ssh-key) ssh_key="$2" shift 2 ;; -u | --url) url="$2" shift 2 ;; --user) user_account="$2" shift 2 ;; --windows) ask_passwd="" cmd="playbook" connection="ssh" use_playbook=1 use_pull="" windows=1 shift 1 ;; *) error_usage "No such option '$1'" "bootstrap" ;; esac done # Check if Ansible has data required if using a Windows connection. # # Flags: # -n: Check if the string has nonzero length. # -z: Check if string has zero length. if [[ -n "${windows:-}" && -z "${ssh_key:-}" ]]; then error "An SSH key must be provided for Windows connection" fi # Check if Bootware setup should be run. # # Flags: # -z: Check if string has zero length. if [[ -z "${no_setup:-}" ]]; then setup fi find_config_path "${config_path}" config_path="${RET_VAL}" log "Executing Ansible ${cmd:-pull}" log "Enter your user account password if prompted" "ansible-${cmd}" \ ${ask_passwd:+--ask-become-pass} \ ${check:+--check} \ ${checkout:+--checkout "${checkout}"} \ ${use_playbook:+--connection "${connection}"} \ ${passwd:+--extra-vars "ansible_password=${passwd}"} \ ${windows:+--extra-vars "ansible_pkg_mgr=scoop"} \ --extra-vars "ansible_python_interpreter=auto_silent" \ ${windows:+--extra-vars "ansible_shell_type=powershell"} \ ${windows:+--extra-vars "ansible_ssh_private_key_file=${ssh_key}"} \ ${windows:+--extra-vars "ansible_user=${user_account}"} \ --extra-vars "user_account=${user_account}" \ --extra-vars "@${config_path}" \ --inventory "${inventory}" \ ${use_pull:+--url "${url}"} \ ${tags:+--tags "${tags}"} \ ${skip:+--skip-tags "${skip}"} \ "${playbook}" } ####################################### # Subcommand to generate or download Bootware configuration file. # Globals: # HOME # Arguments: # Parent directory of Bootware script. # Outputs: # Writes status information to stdout. ####################################### config() { local src_url local dst_file="${HOME}/.bootware/config.yaml" local empty_cfg # Parse command line arguments. while [[ "$#" -gt 0 ]]; do case "$1" in -d | --dest) dst_file="$2" shift 2 ;; -e | --empty) empty_cfg="true" shift 1 ;; -h | --help) usage "config" exit 0 ;; -s | --source) src_url="$2" shift 2 ;; *) error_usage "No such option '$1'" "config" ;; esac done assert_cmd mkdir mkdir -p "$(dirname "${dst_file}")" # Check if empty configuration file should be generated. # # Flags: # -z: Check if string has zero length. if [[ "${empty_cfg:-}" == "true" || -z "${src_url:-}" ]]; then log "Writing empty configuration file to ${dst_file}" printf "passwordless_sudo: false" > "${dst_file}" else assert_cmd curl log "Downloading configuration file to ${dst_file}" # Download configuration file. # # FLAGS: # -L: Follow redirect request. # -S: Show errors. # -f: Use archive file. Must be third flag. # -o <path>: Write output to path instead of stdout. curl -LSfs "${src_url}" -o "${dst_file}" fi } ####################################### # Update dnf package lists. # # DNF's check-update command will give a 100 exit code if there are packages # available to update. Thus both 0 and 100 must be treated as successful exit # codes. # # Arguments: # Whether to use sudo command. ####################################### dnf_check_update() { ${1:+sudo} dnf check-update || { code="$?" [[ "${code}" -eq 100 ]] && return 0 return "${code}" } } ####################################### # Print error message and exit script with error code. # Outputs: # Writes error message to stderr. ####################################### error() { local bold_red="\033[1;31m" local default="\033[0m" printf "${bold_red}error${default}: %s\n" "$1" >&2 exit 1 } ####################################### # Print error message and exit script with usage error code. # Outputs: # Writes error message to stderr. ####################################### error_usage() { local bold_red="\033[1;31m" local default="\033[0m" printf "${bold_red}error${default}: %s\n" "$1" >&2 printf "Run \'bootware %s--help\' for usage.\n" "${2:+$2 }" >&2 exit 2 } ####################################### # Find path of Bootware configuation file. # Globals: # HOME # Arguments: # User supplied configuration path. # Outputs: # Writes error message to stderr if unable to find configuration file. # Retunrs: # Configuration file path. ####################################### find_config_path() { # Flags: # -f: Check if file exists and is a regular file. # -n: Check if the string has nonzero length. # -v: Only show file path of command. if [[ -f "${1:-}" ]]; then RET_VAL="$1" elif [[ -n "${BOOTWARE_CONFIG:-}" ]]; then RET_VAL="${BOOTWARE_CONFIG}" elif [[ -f "${HOME}/.bootware/config.yaml" ]]; then RET_VAL="${HOME}/.bootware/config.yaml" else log "Unable to find Bootware configuation file." config --empty RET_VAL="${HOME}/.bootware/config.yaml" fi log "Using ${RET_VAL} as configuration file" } ####################################### # Get full normalized path for file. # Alternative to realpath command, since it is not built into MacOS. ####################################### fullpath() { local working_dir # Flags: # -P: Resolve any symbolic links in the path. working_dir="$(cd "$(dirname "$1")" && pwd -P)" echo "${working_dir}/$(basename "$1")" } ####################################### # Print log message to stdout if logging is enabled. # Globals: # BOOTWARE_NOLOG # Outputs: # Log message to stdout. ####################################### log() { # Flags: # -z: Check if string has zero length. if [[ -z "${BOOTWARE_NOLOG:-}" ]]; then echo "$@" fi } ####################################### # Subcommand to configure boostrapping services and utilities. ####################################### setup() { local os_type local tmp_dir local use_sudo # Parse command line arguments. while [[ "$#" -gt 0 ]]; do case "$1" in -h | --help) usage "setup" exit 0 ;; *) error_usage "No such option '$1'" "setup" ;; esac done assert_cmd uname # Check if user is not root. if [[ "${EUID}" -ne 0 ]]; then use_sudo=1 fi # Get operating system. # # FLAGS: # -s: Print the kernel name. os_type="$(uname -s)" case "${os_type}" in Darwin) setup_macos ;; FreeBSD) setup_freebsd "${use_sudo}" ;; Linux) setup_linux "${use_sudo}" ;; *) error "Operating system ${os_type} is not supported" ;; esac ansible-galaxy collection install community.general > /dev/null ansible-galaxy collection install community.windows > /dev/null } ####################################### # Configure boostrapping services and utilities for Alpine distributions. ####################################### setup_alpine() { # Install dependencies for Bootware. # # Flags: # -v: Only show file path of command. # -x: Check if file exists and execute permission is granted. if [[ ! -x "$(command -v ansible)" ]]; then log "Installing Ansible" # Install Ansible with Python3 since most package managers provide an old # version of Ansible. ${1:+sudo} apk update ${1:+sudo} apk add python3 py3-pip ${1:+sudo} python3 -m pip install --upgrade pip setuptools wheel ${1:+sudo} python3 -m pip install ansible fi if [[ ! -x "$(command -v curl)" ]]; then log "Installing Curl" ${1:+sudo} apk update ${1:+sudo} apk add curl fi if [[ ! -x "$(command -v git)" ]]; then log "Installing Git" ${1:+sudo} apk update ${1:+sudo} apk add git fi } ####################################### # Configure boostrapping services and utilities for Arch distributions. ####################################### setup_arch() { # Install dependencies for Bootware. # # Flags: # -v: Only show file path of command. # -x: Check if file exists and execute permission is granted. if [[ ! -x "$(command -v ansible)" ]]; then log "Installing Ansible" # Installing Ansible via Python causes pacman conflicts with AWSCLI. ${1:+sudo} pacman -Suy --noconfirm ${1:+sudo} pacman -S --noconfirm ansible fi if [[ ! -x "$(command -v curl)" ]]; then log "Installing Curl" ${1:+sudo} pacman -Suy --noconfirm ${1:+sudo} pacman -S --noconfirm curl fi if [[ ! -x "$(command -v git)" ]]; then log "Installing Git" ${1:+sudo} pacman -Suy --noconfirm ${1:+sudo} pacman -S --noconfirm git fi if [[ ! -x "$(command -v yay)" ]]; then log "Installing Yay package manager" ${1:+sudo} pacman -Suy --noconfirm ${1:+sudo} pacman -S --noconfirm base-devel tmp_dir="$(mktemp -u)" git clone --depth 1 "https://aur.archlinux.org/yay.git" "${tmp_dir}" (cd "${tmp_dir}" && makepkg --noconfirm -is) yay --noconfirm -Suy fi } ####################################### # Configure boostrapping services and utilities for Debian distributions. ####################################### setup_debian() { # Avoid APT interactively requesting to configure tzdata. export DEBIAN_FRONTEND="noninteractive" # Install dependencies for Bootware. # # Flags: # -v: Only show file path of command. # -x: Check if file exists and execute permission is granted. if [[ ! -x "$(command -v ansible)" ]]; then # Install Ansible with Python3 since most package managers provide an old # version of Ansible. log "Installing Ansible" ${1:+sudo} apt-get -qq update ${1:+sudo} apt-get -qq install -y python3 python3-pip python3-apt ${1:+sudo} python3 -m pip install --upgrade pip setuptools wheel ${1:+sudo} python3 -m pip install ansible fi if [[ ! -x "$(command -v curl)" ]]; then log "Installing Curl" ${1:+sudo} apt-get -qq update ${1:+sudo} apt-get -qq install -y curl fi if [[ ! -x "$(command -v git)" ]]; then log "Installing Git" ${1:+sudo} apt-get -qq update ${1:+sudo} apt-get -qq install -y git fi } ####################################### # Configure boostrapping services and utilities for Fedora distributions. ####################################### setup_fedora() { # Install dependencies for Bootware. # # Flags: # -v: Only show file path of command. # -x: Check if file exists and execute permission is granted. if [[ ! -x "$(command -v ansible)" ]]; then log "Installing Ansible" # Installing Ansible via Python causes issues installing remote DNF packages # with Ansible. dnf_check_update "$1" ${1:+sudo} dnf install -y ansible fi if [[ ! -x "$(command -v curl)" ]]; then log "Installing Curl" dnf_check_update "$1" ${1:+sudo} dnf install -y curl fi if [[ ! -x "$(command -v git)" ]]; then log "Installing Git" dnf_check_update "$1" ${1:+sudo} dnf install -y git fi } ####################################### # Configure boostrapping services and utilities for FreeBSD. ####################################### setup_freebsd() { assert_cmd pkg # Install Ansible if not already installed. if [[ ! -x "$(command -v ansible)" ]]; then log "Installing Ansible" # Install Ansible with Python3 since most package managers provide an old # version of Ansible. ${1:+sudo} pkg update # Python's cryptography package requires a Rust compiler on FreeBSD. ${1:+sudo} pkg install -y python3 rust py_ver="$(python3 -c 'import sys; print("{}{}".format(*sys.version_info[:2]))')" ${1:+sudo} pkg install -y "py${py_ver}-pip" ${1:+sudo} python3 -m pip install --upgrade pip setuptools wheel ${1:+sudo} python3 -m pip install ansible fi # Install Curl if not already installed. if [[ ! -x "$(command -v curl)" ]]; then log "Installing Curl" ${1:+sudo} pkg update ${1:+sudo} pkg install -y curl fi # Install Git if not already installed. if [[ ! -x "$(command -v git)" ]]; then log "Installing Git" ${1:+sudo} pkg update ${1:+sudo} pkg install -y git fi } ####################################### # Configure boostrapping services and utilities for Linux. ####################################### setup_linux() { # Install dependencies for Bootware base on available package manager. # # Flags: # -v: Only show file path of command. # -x: Check if file exists and execute permission is granted. if [[ -x "$(command -v apk)" ]]; then setup_alpine "$1" elif [[ -x "$(command -v pacman)" ]]; then setup_arch "$1" elif [[ -x "$(command -v apt-get)" ]]; then setup_debian "$1" elif [[ -x "$(command -v dnf)" ]]; then setup_fedora "$1" else error "Unable to find supported package manager" fi } ####################################### # Configure boostrapping services and utilities for MacOS. ####################################### setup_macos() { assert_cmd curl # On Apple silicon, brew is not in the system path after installation. export PATH="/opt/homebrew/bin:${PATH}" # Install XCode command line tools if not already installed. # # Homebrew depends on the XCode command line tools. # Flags: # -p: Print path to active developer directory. if ! xcode-select -p &> /dev/null; then log "Installing command line tools for XCode" sudo xcode-select --install fi # Install Rosetta 2 for Apple Silicon if not already installed. # # TODO: Create better check to see if Rosetta 2 is already installed. # Flags: # -d: Check if path exists and is a directory. # -p: Print machine processor name. if [[ "$(uname -p)" == "arm" && ! -d "/opt/homebrew" ]]; then softwareupdate --agree-to-license --install-rosetta fi # Install Homebrew if not already installed. # # FLAGS: # -L: Follow redirect request. # -S: Show errors. # -f: Fail silently on server errors. # -s: Disable progress bars. # -x: Check if file exists and execute permission is granted. if [[ ! -x "$(command -v brew)" ]]; then log "Installing Homebrew" curl -LSfs "https://raw.githubusercontent.com/Homebrew/install/master/install.sh" | bash fi # Install Ansible if not already installed. if [[ ! -x "$(command -v ansible)" ]]; then log "Installing Ansible" brew install ansible fi # Install Git if not already installed. if [[ ! -x "$(command -v git)" ]]; then log "Installing Git" brew install git fi } ####################################### # Subcommand to remove Bootware files. # Outputs: # Writes status information about removed files. ####################################### uninstall() { local dst_file local use_sudo # Parse command line arguments. while [[ "$#" -gt 0 ]]; do case "$1" in -h | --help) usage "uninstall" exit 0 ;; *) error_usage "No such option '$1'" "update" ;; esac done assert_cmd chmod dst_file="$(fullpath "$0")" # Use sudo for system installation if user is not root. # # Flags: # -w: Check if file exists and it writable. if [[ ! -w "${dst_file}" && "${EUID}" -ne 0 ]]; then assert_cmd sudo use_sudo=1 fi # Do not quote the sudo parameter expansion. Bash will error due to be being # unable to find the "" command. ${use_sudo:+sudo} rm "${dst_file}" log "Uninstalled Bootware" } ####################################### # Subcommand to update Bootware script. # Arguments: # Parent directory of Bootware script. # Outputs: # Writes status information and updated Bootware version to stdout. ####################################### update() { local dst_file local src_url local use_sudo local version="master" # Parse command line arguments. while [[ "$#" -gt 0 ]]; do case "$1" in -h | --help) usage "update" exit 0 ;; -v | --version) version="$2" shift 2 ;; *) error_usage "No such option '$1'" "update" ;; esac done assert_cmd chmod assert_cmd curl dst_file="$(fullpath "$0")" src_url="https://raw.githubusercontent.com/wolfgangwazzlestrauss/bootware/${version}/bootware.sh" # Use sudo for system installation if user is not root. # # Flags: # -w: Check if file exists and it writable. if [[ ! -w "${dst_file}" && "${EUID}" -ne 0 ]]; then assert_cmd sudo use_sudo=1 fi log "Updating Bootware" # Do not quote the sudo parameter expansion. Bash will error due to be being # unable to find the "" command. ${use_sudo:+sudo} curl -LSfs "${src_url}" -o "${dst_file}" ${use_sudo:+sudo} chmod 755 "${dst_file}" log "Updated to version $(bootware --version)" } ####################################### # Print Bootware version string. # Outputs: # Bootware version string. ####################################### version() { echo "Bootware 0.3.4" } ####################################### # Script entrypoint. ####################################### main() { # Parse command line arguments. case "${1:-}" in bootstrap) shift 1 bootstrap "$@" ;; config) shift 1 config "$@" ;; setup) shift 1 setup "$@" ;; uninstall) shift 1 uninstall "$@" ;; update) shift 1 update "$@" ;; -h | --help) usage "main" ;; -v | --version) version ;; *) error_usage "No such subcommand '${1:-}'" ;; esac } # Only run main if invoked as script. Otherwise import functions as library. if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then main "$@" fi
<?php /** * 字符操作类 * * PHP version 5.4 * * @category Util * @package Util * @author zhaoyan <3032441712@qq.com> * @license https://github.com/3032441712/person/blob/master/LICENSE GNU License * @version GIT: $Id$ * @link http://www.168helps.com/blog */ namespace Util; /** * String 类 * * @category Util * @package Util * @author zhaoyan <1210965963@qq.com> * @license http://www.168helps.com/blog/license.txt 168helps License * @link http://www.168helps.com/blog */ class String { /** * 对字符串进行安全过滤 * 1.过滤特殊字符 * 2.去除两侧空格 * * @param mixed $data 输入数据 * * @return string 返回过滤后的字符 */ public static function safe($data) { if (is_array($data)) { foreach ($data as $k => $v) { $data[$k] = self::safe($v); } } elseif (is_string($data)) { return addslashes(trim($data)); } return $data; } /** * 将字符转换为bytes数组 * * @param string $str 字符数据 * @param string $encoding 字符编码 * * @return array */ public static function bytes($str, $encoding = 'utf-8') { $size = mb_strlen($str, $encoding); $data = new \SplFixedArray($size); for ($i = 0; $i < $size; $i++) { $data[$i] = mb_substr($str, $i, 1, $encoding); } return $data; } }
// Copyright (c) Jupyter Development Team. // Distributed under the terms of the Modified BSD License. import { ArrayExt, each } from '@phosphor/algorithm'; import { JSONValue } from '@phosphor/coreutils'; import { Message } from '@phosphor/messaging'; import { MimeData } from '@phosphor/coreutils'; import { AttachedProperty } from '@phosphor/properties'; import { ISignal, Signal } from '@phosphor/signaling'; import { Drag, IDragEvent } from '@phosphor/dragdrop'; import { PanelLayout, Widget } from '@phosphor/widgets'; import { h, VirtualDOM } from '@phosphor/virtualdom'; import { ICellModel, Cell, IMarkdownCellModel, CodeCell, MarkdownCell, ICodeCellModel, RawCell, IRawCellModel } from '@jupyterlab/cells'; import { IEditorMimeTypeService, CodeEditor } from '@jupyterlab/codeeditor'; import { IChangedArgs, nbformat } from '@jupyterlab/coreutils'; import { IObservableMap, IObservableList } from '@jupyterlab/observables'; import { IRenderMimeRegistry } from '@jupyterlab/rendermime'; import { INotebookModel } from './model'; /** * The data attribute added to a widget that has an active kernel. */ const KERNEL_USER = 'jpKernelUser'; /** * The data attribute added to a widget that can run code. */ const CODE_RUNNER = 'jpCodeRunner'; /** * The data attribute added to a widget that can undo. */ const UNDOER = 'jpUndoer'; /** * The class name added to notebook widgets. */ const NB_CLASS = 'jp-Notebook'; /** * The class name added to notebook widget cells. */ const NB_CELL_CLASS = 'jp-Notebook-cell'; /** * The class name added to a notebook in edit mode. */ const EDIT_CLASS = 'jp-mod-editMode'; /** * The class name added to a notebook in command mode. */ const COMMAND_CLASS = 'jp-mod-commandMode'; /** * The class name added to the active cell. */ const ACTIVE_CLASS = 'jp-mod-active'; /** * The class name added to selected cells. */ const SELECTED_CLASS = 'jp-mod-selected'; /** * The class name added to an active cell when there are other selected cells. */ const OTHER_SELECTED_CLASS = 'jp-mod-multiSelected'; /** * The class name added to unconfined images. */ const UNCONFINED_CLASS = 'jp-mod-unconfined'; /** * The class name added to a drop target. */ const DROP_TARGET_CLASS = 'jp-mod-dropTarget'; /** * The class name added to a drop source. */ const DROP_SOURCE_CLASS = 'jp-mod-dropSource'; /** * The class name added to drag images. */ const DRAG_IMAGE_CLASS = 'jp-dragImage'; /** * The class name added to singular drag images */ const SINGLE_DRAG_IMAGE_CLASS = 'jp-dragImage-singlePrompt'; /** * The class name added to the drag image cell content. */ const CELL_DRAG_CONTENT_CLASS = 'jp-dragImage-content'; /** * The class name added to the drag image cell content. */ const CELL_DRAG_PROMPT_CLASS = 'jp-dragImage-prompt'; /** * The class name added to the drag image cell content. */ const CELL_DRAG_MULTIPLE_BACK = 'jp-dragImage-multipleBack'; /** * The mimetype used for Jupyter cell data. */ const JUPYTER_CELL_MIME = 'application/vnd.jupyter.cells'; /** * The threshold in pixels to start a drag event. */ const DRAG_THRESHOLD = 5; /** * The interactivity modes for the notebook. */ export type NotebookMode = 'command' | 'edit'; /** * A widget which renders static non-interactive notebooks. * * #### Notes * The widget model must be set separately and can be changed * at any time. Consumers of the widget must account for a * `null` model, and may want to listen to the `modelChanged` * signal. */ export class StaticNotebook extends Widget { /** * Construct a notebook widget. */ constructor(options: StaticNotebook.IOptions) { super(); this.addClass(NB_CLASS); this.node.dataset[KERNEL_USER] = 'true'; this.node.dataset[UNDOER] = 'true'; this.rendermime = options.rendermime; this.layout = new Private.NotebookPanelLayout(); this.contentFactory = options.contentFactory || StaticNotebook.defaultContentFactory; this.editorConfig = options.editorConfig || StaticNotebook.defaultEditorConfig; this.notebookConfig = options.notebookConfig || StaticNotebook.defaultNotebookConfig; this._mimetypeService = options.mimeTypeService; } /** * A signal emitted when the model of the notebook changes. */ get modelChanged(): ISignal<this, void> { return this._modelChanged; } /** * A signal emitted when the model content changes. * * #### Notes * This is a convenience signal that follows the current model. */ get modelContentChanged(): ISignal<this, void> { return this._modelContentChanged; } /** * The cell factory used by the widget. */ readonly contentFactory: StaticNotebook.IContentFactory; /** * The Rendermime instance used by the widget. */ readonly rendermime: IRenderMimeRegistry; /** * The model for the widget. */ get model(): INotebookModel { return this._model; } set model(newValue: INotebookModel) { newValue = newValue || null; if (this._model === newValue) { return; } let oldValue = this._model; this._model = newValue; if (oldValue && oldValue.modelDB.isCollaborative) { void oldValue.modelDB.connected.then(() => { oldValue.modelDB.collaborators.changed.disconnect( this._onCollaboratorsChanged, this ); }); } if (newValue && newValue.modelDB.isCollaborative) { void newValue.modelDB.connected.then(() => { newValue.modelDB.collaborators.changed.connect( this._onCollaboratorsChanged, this ); }); } // Trigger private, protected, and public changes. this._onModelChanged(oldValue, newValue); this.onModelChanged(oldValue, newValue); this._modelChanged.emit(void 0); } /** * Get the mimetype for code cells. */ get codeMimetype(): string { return this._mimetype; } /** * A read-only sequence of the widgets in the notebook. */ get widgets(): ReadonlyArray<Cell> { return (this.layout as PanelLayout).widgets as ReadonlyArray<Cell>; } /** * A configuration object for cell editor settings. */ get editorConfig(): StaticNotebook.IEditorConfig { return this._editorConfig; } set editorConfig(value: StaticNotebook.IEditorConfig) { this._editorConfig = value; this._updateEditorConfig(); } /** * A configuration object for notebook settings. */ get notebookConfig(): StaticNotebook.INotebookConfig { return this._notebookConfig; } set notebookConfig(value: StaticNotebook.INotebookConfig) { this._notebookConfig = value; this._updateNotebookConfig(); } /** * Dispose of the resources held by the widget. */ dispose() { // Do nothing if already disposed. if (this.isDisposed) { return; } this._model = null; super.dispose(); } /** * Handle a new model. * * #### Notes * This method is called after the model change has been handled * internally and before the `modelChanged` signal is emitted. * The default implementation is a no-op. */ protected onModelChanged( oldValue: INotebookModel, newValue: INotebookModel ): void { // No-op. } /** * Handle changes to the notebook model content. * * #### Notes * The default implementation emits the `modelContentChanged` signal. */ protected onModelContentChanged(model: INotebookModel, args: void): void { this._modelContentChanged.emit(void 0); } /** * Handle changes to the notebook model metadata. * * #### Notes * The default implementation updates the mimetypes of the code cells * when the `language_info` metadata changes. */ protected onMetadataChanged( sender: IObservableMap<JSONValue>, args: IObservableMap.IChangedArgs<JSONValue> ): void { switch (args.key) { case 'language_info': this._updateMimetype(); break; default: break; } } /** * Handle a cell being inserted. * * The default implementation is a no-op */ protected onCellInserted(index: number, cell: Cell): void { // This is a no-op. } /** * Handle a cell being moved. * * The default implementation is a no-op */ protected onCellMoved(fromIndex: number, toIndex: number): void { // This is a no-op. } /** * Handle a cell being removed. * * The default implementation is a no-op */ protected onCellRemoved(index: number, cell: Cell): void { // This is a no-op. } /** * Handle a new model on the widget. */ private _onModelChanged( oldValue: INotebookModel, newValue: INotebookModel ): void { let layout = this.layout as PanelLayout; if (oldValue) { oldValue.cells.changed.disconnect(this._onCellsChanged, this); oldValue.metadata.changed.disconnect(this.onMetadataChanged, this); oldValue.contentChanged.disconnect(this.onModelContentChanged, this); // TODO: reuse existing cell widgets if possible. Remember to initially // clear the history of each cell if we do this. while (layout.widgets.length) { this._removeCell(0); } } if (!newValue) { this._mimetype = 'text/plain'; return; } this._updateMimetype(); let cells = newValue.cells; if (!cells.length) { cells.push( newValue.contentFactory.createCell(this.notebookConfig.defaultCell, {}) ); } each(cells, (cell: ICellModel, i: number) => { this._insertCell(i, cell); }); cells.changed.connect(this._onCellsChanged, this); newValue.contentChanged.connect(this.onModelContentChanged, this); newValue.metadata.changed.connect(this.onMetadataChanged, this); } /** * Handle a change cells event. */ private _onCellsChanged( sender: IObservableList<ICellModel>, args: IObservableList.IChangedArgs<ICellModel> ) { let index = 0; switch (args.type) { case 'add': index = args.newIndex; each(args.newValues, value => { this._insertCell(index++, value); }); break; case 'move': this._moveCell(args.oldIndex, args.newIndex); break; case 'remove': each(args.oldValues, value => { this._removeCell(args.oldIndex); }); // Add default cell if there are no cells remaining. if (!sender.length) { const model = this.model; // Add the cell in a new context to avoid triggering another // cell changed event during the handling of this signal. requestAnimationFrame(() => { if (!model.isDisposed && !model.cells.length) { model.cells.push( model.contentFactory.createCell( this.notebookConfig.defaultCell, {} ) ); } }); } break; case 'set': // TODO: reuse existing widgets if possible. index = args.newIndex; each(args.newValues, value => { // Note: this ordering (insert then remove) // is important for getting the active cell // index for the editable notebook correct. this._insertCell(index, value); this._removeCell(index + 1); index++; }); break; default: return; } } /** * Create a cell widget and insert into the notebook. */ private _insertCell(index: number, cell: ICellModel): void { let widget: Cell; switch (cell.type) { case 'code': widget = this._createCodeCell(cell as ICodeCellModel); widget.model.mimeType = this._mimetype; break; case 'markdown': widget = this._createMarkdownCell(cell as IMarkdownCellModel); if (cell.value.text === '') { (widget as MarkdownCell).rendered = false; } break; default: widget = this._createRawCell(cell as IRawCellModel); } widget.addClass(NB_CELL_CLASS); let layout = this.layout as PanelLayout; layout.insertWidget(index, widget); this.onCellInserted(index, widget); } /** * Create a code cell widget from a code cell model. */ private _createCodeCell(model: ICodeCellModel): CodeCell { let rendermime = this.rendermime; let contentFactory = this.contentFactory; const editorConfig = this.editorConfig.code; let options = { editorConfig, model, rendermime, contentFactory, updateEditorOnShow: false }; const cell = this.contentFactory.createCodeCell(options, this); cell.syncCollapse = true; cell.syncEditable = true; cell.syncScrolled = true; return cell; } /** * Create a markdown cell widget from a markdown cell model. */ private _createMarkdownCell(model: IMarkdownCellModel): MarkdownCell { let rendermime = this.rendermime; let contentFactory = this.contentFactory; const editorConfig = this.editorConfig.markdown; let options = { editorConfig, model, rendermime, contentFactory, updateEditorOnShow: false }; const cell = this.contentFactory.createMarkdownCell(options, this); cell.syncCollapse = true; cell.syncEditable = true; return cell; } /** * Create a raw cell widget from a raw cell model. */ private _createRawCell(model: IRawCellModel): RawCell { let contentFactory = this.contentFactory; const editorConfig = this.editorConfig.raw; let options = { editorConfig, model, contentFactory, updateEditorOnShow: false }; const cell = this.contentFactory.createRawCell(options, this); cell.syncCollapse = true; cell.syncEditable = true; return cell; } /** * Move a cell widget. */ private _moveCell(fromIndex: number, toIndex: number): void { let layout = this.layout as PanelLayout; layout.insertWidget(toIndex, layout.widgets[fromIndex]); this.onCellMoved(fromIndex, toIndex); } /** * Remove a cell widget. */ private _removeCell(index: number): void { let layout = this.layout as PanelLayout; let widget = layout.widgets[index] as Cell; widget.parent = null; this.onCellRemoved(index, widget); widget.dispose(); } /** * Update the mimetype of the notebook. */ private _updateMimetype(): void { let info = this._model.metadata.get( 'language_info' ) as nbformat.ILanguageInfoMetadata; if (!info) { return; } this._mimetype = this._mimetypeService.getMimeTypeByLanguage(info); each(this.widgets, widget => { if (widget.model.type === 'code') { widget.model.mimeType = this._mimetype; } }); } /** * Handle an update to the collaborators. */ private _onCollaboratorsChanged(): void { // If there are selections corresponding to non-collaborators, // they are stale and should be removed. for (let i = 0; i < this.widgets.length; i++) { let cell = this.widgets[i]; for (let key of cell.model.selections.keys()) { if (!this._model.modelDB.collaborators.has(key)) { cell.model.selections.delete(key); } } } } /** * Update editor settings for notebook cells. */ private _updateEditorConfig() { for (let i = 0; i < this.widgets.length; i++) { const cell = this.widgets[i]; let config: Partial<CodeEditor.IConfig>; switch (cell.model.type) { case 'code': config = this._editorConfig.code; break; case 'markdown': config = this._editorConfig.markdown; break; default: config = this._editorConfig.raw; break; } Object.keys(config).forEach((key: keyof CodeEditor.IConfig) => { cell.editor.setOption(key, config[key]); }); cell.editor.refresh(); } } /** * Apply updated notebook settings. */ private _updateNotebookConfig() { // Apply scrollPastEnd setting. this.toggleClass( 'jp-mod-scrollPastEnd', this._notebookConfig.scrollPastEnd ); } private _editorConfig = StaticNotebook.defaultEditorConfig; private _notebookConfig = StaticNotebook.defaultNotebookConfig; private _mimetype = 'text/plain'; private _model: INotebookModel = null; private _mimetypeService: IEditorMimeTypeService; private _modelChanged = new Signal<this, void>(this); private _modelContentChanged = new Signal<this, void>(this); } /** * The namespace for the `StaticNotebook` class statics. */ export namespace StaticNotebook { /** * An options object for initializing a static notebook. */ export interface IOptions { /** * The rendermime instance used by the widget. */ rendermime: IRenderMimeRegistry; /** * The language preference for the model. */ languagePreference?: string; /** * A factory for creating content. */ contentFactory?: IContentFactory; /** * A configuration object for the cell editor settings. */ editorConfig?: IEditorConfig; /** * A configuration object for notebook settings. */ notebookConfig?: INotebookConfig; /** * The service used to look up mime types. */ mimeTypeService: IEditorMimeTypeService; } /** * A factory for creating notebook content. * * #### Notes * This extends the content factory of the cell itself, which extends the content * factory of the output area and input area. The result is that there is a single * factory for creating all child content of a notebook. */ export interface IContentFactory extends Cell.IContentFactory { /** * Create a new code cell widget. */ createCodeCell( options: CodeCell.IOptions, parent: StaticNotebook ): CodeCell; /** * Create a new markdown cell widget. */ createMarkdownCell( options: MarkdownCell.IOptions, parent: StaticNotebook ): MarkdownCell; /** * Create a new raw cell widget. */ createRawCell(options: RawCell.IOptions, parent: StaticNotebook): RawCell; } /** * A config object for the cell editors. */ export interface IEditorConfig { /** * Config options for code cells. */ readonly code: Partial<CodeEditor.IConfig>; /** * Config options for markdown cells. */ readonly markdown: Partial<CodeEditor.IConfig>; /** * Config options for raw cells. */ readonly raw: Partial<CodeEditor.IConfig>; } /** * Default configuration options for cell editors. */ export const defaultEditorConfig: IEditorConfig = { code: { ...CodeEditor.defaultConfig, lineWrap: 'off', matchBrackets: true, autoClosingBrackets: true }, markdown: { ...CodeEditor.defaultConfig, lineWrap: 'on', matchBrackets: false, autoClosingBrackets: false }, raw: { ...CodeEditor.defaultConfig, lineWrap: 'on', matchBrackets: false, autoClosingBrackets: false } }; /** * A config object for the notebook widget */ export interface INotebookConfig { /** * Enable scrolling past the last cell */ scrollPastEnd: boolean; /** * The default type for new notebook cells. */ defaultCell: nbformat.CellType; } /** * Default configuration options for notebooks. */ export const defaultNotebookConfig: INotebookConfig = { scrollPastEnd: true, defaultCell: 'code' }; /** * The default implementation of an `IContentFactory`. */ export class ContentFactory extends Cell.ContentFactory implements IContentFactory { /** * Create a new code cell widget. * * #### Notes * If no cell content factory is passed in with the options, the one on the * notebook content factory is used. */ createCodeCell( options: CodeCell.IOptions, parent: StaticNotebook ): CodeCell { if (!options.contentFactory) { options.contentFactory = this; } return new CodeCell(options).initializeState(); } /** * Create a new markdown cell widget. * * #### Notes * If no cell content factory is passed in with the options, the one on the * notebook content factory is used. */ createMarkdownCell( options: MarkdownCell.IOptions, parent: StaticNotebook ): MarkdownCell { if (!options.contentFactory) { options.contentFactory = this; } return new MarkdownCell(options).initializeState(); } /** * Create a new raw cell widget. * * #### Notes * If no cell content factory is passed in with the options, the one on the * notebook content factory is used. */ createRawCell(options: RawCell.IOptions, parent: StaticNotebook): RawCell { if (!options.contentFactory) { options.contentFactory = this; } return new RawCell(options).initializeState(); } } /** * A namespace for the staic notebook content factory. */ export namespace ContentFactory { /** * Options for the content factory. */ export interface IOptions extends Cell.ContentFactory.IOptions {} } /** * Default content factory for the static notebook widget. */ export const defaultContentFactory: IContentFactory = new ContentFactory(); } /** * A notebook widget that supports interactivity. */ export class Notebook extends StaticNotebook { /** * Construct a notebook widget. */ constructor(options: Notebook.IOptions) { super(Private.processNotebookOptions(options)); this.node.tabIndex = -1; // Allow the widget to take focus. // Allow the node to scroll while dragging items. this.node.setAttribute('data-p-dragscroll', 'true'); } /** * A signal emitted when the active cell changes. * * #### Notes * This can be due to the active index changing or the * cell at the active index changing. */ get activeCellChanged(): ISignal<this, Cell> { return this._activeCellChanged; } /** * A signal emitted when the state of the notebook changes. */ get stateChanged(): ISignal<this, IChangedArgs<any>> { return this._stateChanged; } /** * A signal emitted when the selection state of the notebook changes. */ get selectionChanged(): ISignal<this, void> { return this._selectionChanged; } /** * The interactivity mode of the notebook. */ get mode(): NotebookMode { return this._mode; } set mode(newValue: NotebookMode) { let activeCell = this.activeCell; if (!activeCell) { newValue = 'command'; } if (newValue === this._mode) { this._ensureFocus(); return; } // Post an update request. this.update(); let oldValue = this._mode; this._mode = newValue; if (newValue === 'edit') { // Edit mode deselects all cells. each(this.widgets, widget => { this.deselect(widget); }); // Edit mode unrenders an active markdown widget. if (activeCell instanceof MarkdownCell) { activeCell.rendered = false; } activeCell.inputHidden = false; } else { // Focus on the notebook document, which blurs the active cell. this.node.focus(); } this._stateChanged.emit({ name: 'mode', oldValue, newValue }); this._ensureFocus(); } /** * The active cell index of the notebook. * * #### Notes * The index will be clamped to the bounds of the notebook cells. */ get activeCellIndex(): number { if (!this.model) { return -1; } return this.model.cells.length ? this._activeCellIndex : -1; } set activeCellIndex(newValue: number) { let oldValue = this._activeCellIndex; if (!this.model || !this.model.cells.length) { newValue = -1; } else { newValue = Math.max(newValue, 0); newValue = Math.min(newValue, this.model.cells.length - 1); } this._activeCellIndex = newValue; let cell = this.widgets[newValue]; if (cell !== this._activeCell) { // Post an update request. this.update(); this._activeCell = cell; this._activeCellChanged.emit(cell); } if (this.mode === 'edit' && cell instanceof MarkdownCell) { cell.rendered = false; } this._ensureFocus(); if (newValue === oldValue) { return; } this._trimSelections(); this._stateChanged.emit({ name: 'activeCellIndex', oldValue, newValue }); } /** * Get the active cell widget. * * #### Notes * This is a cell or `null` if there is no active cell. */ get activeCell(): Cell | null { return this._activeCell; } /** * Dispose of the resources held by the widget. */ dispose(): void { if (this.isDisposed) { return; } this._activeCell = null; super.dispose(); } /** * Select a cell widget. * * #### Notes * It is a no-op if the value does not change. * It will emit the `selectionChanged` signal. */ select(widget: Cell): void { if (Private.selectedProperty.get(widget)) { return; } Private.selectedProperty.set(widget, true); this._selectionChanged.emit(void 0); this.update(); } /** * Deselect a cell widget. * * #### Notes * It is a no-op if the value does not change. * It will emit the `selectionChanged` signal. */ deselect(widget: Cell): void { if (!Private.selectedProperty.get(widget)) { return; } Private.selectedProperty.set(widget, false); this._selectionChanged.emit(void 0); this.update(); } /** * Whether a cell is selected. */ isSelected(widget: Cell): boolean { return Private.selectedProperty.get(widget); } /** * Whether a cell is selected or is the active cell. */ isSelectedOrActive(widget: Cell): boolean { if (widget === this._activeCell) { return true; } return Private.selectedProperty.get(widget); } /** * Deselect all of the cells. */ deselectAll(): void { let changed = false; each(this.widgets, widget => { if (Private.selectedProperty.get(widget)) { changed = true; } Private.selectedProperty.set(widget, false); }); if (changed) { this._selectionChanged.emit(void 0); } // Make sure we have a valid active cell. this.activeCellIndex = this.activeCellIndex; this.update(); } /** * Move the head of an existing contiguous selection to extend the selection. * * @param index - The new head of the existing selection. * * #### Notes * If there is no existing selection, the active cell is considered an * existing one-cell selection. * * If the new selection is a single cell, that cell becomes the active cell * and all cells are deselected. * * There is no change if there are no cells (i.e., activeCellIndex is -1). */ extendContiguousSelectionTo(index: number): void { let { head, anchor } = this.getContiguousSelection(); let i: number; // Handle the case of no current selection. if (anchor === null) { if (index === this.activeCellIndex) { // Already collapsed selection, nothing more to do. return; } // We will start a new selection below. head = this.activeCellIndex; anchor = this.activeCellIndex; } // Move the active cell. We do this before the collapsing shortcut below. this.activeCellIndex = index; // Make sure the index is valid, according to the rules for setting and clipping the // active cell index. This may change the index. index = this.activeCellIndex; // Collapse the selection if it is only the active cell. if (index === anchor) { this.deselectAll(); return; } let selectionChanged = false; if (head < index) { if (head < anchor) { Private.selectedProperty.set(this.widgets[head], false); selectionChanged = true; } // Toggle everything strictly between head and index except anchor. for (i = head + 1; i < index; i++) { if (i !== anchor) { Private.selectedProperty.set( this.widgets[i], !Private.selectedProperty.get(this.widgets[i]) ); selectionChanged = true; } } } else if (index < head) { if (anchor < head) { Private.selectedProperty.set(this.widgets[head], false); selectionChanged = true; } // Toggle everything strictly between index and head except anchor. for (i = index + 1; i < head; i++) { if (i !== anchor) { Private.selectedProperty.set( this.widgets[i], !Private.selectedProperty.get(this.widgets[i]) ); selectionChanged = true; } } } // Anchor and index should *always* be selected. if (!Private.selectedProperty.get(this.widgets[anchor])) { selectionChanged = true; } Private.selectedProperty.set(this.widgets[anchor], true); if (!Private.selectedProperty.get(this.widgets[index])) { selectionChanged = true; } Private.selectedProperty.set(this.widgets[index], true); if (selectionChanged) { this._selectionChanged.emit(void 0); } } /** * Get the head and anchor of a contiguous cell selection. * * The head of a contiguous selection is always the active cell. * * If there are no cells selected, `{head: null, anchor: null}` is returned. * * Throws an error if the currently selected cells do not form a contiguous * selection. */ getContiguousSelection(): { head: number | null; anchor: number | null } { let cells = this.widgets; let first = ArrayExt.findFirstIndex(cells, c => this.isSelected(c)); // Return early if no cells are selected. if (first === -1) { return { head: null, anchor: null }; } let last = ArrayExt.findLastIndex( cells, c => this.isSelected(c), -1, first ); // Check that the selection is contiguous. for (let i = first; i <= last; i++) { if (!this.isSelected(cells[i])) { throw new Error('Selection not contiguous'); } } // Check that the active cell is one of the endpoints of the selection. let activeIndex = this.activeCellIndex; if (first !== activeIndex && last !== activeIndex) { throw new Error('Active cell not at endpoint of selection'); } // Determine the head and anchor of the selection. if (first === activeIndex) { return { head: first, anchor: last }; } else { return { head: last, anchor: first }; } } /** * Scroll so that the given position is centered. * * @param position - The vertical position in the notebook widget. * * @param threshold - An optional threshold for the scroll (0-50, defaults to * 25). * * #### Notes * If the position is within the threshold percentage of the widget height, * measured from the center of the widget, the scroll position will not be * changed. A threshold of 0 means we will always scroll so the position is * centered, and a threshold of 50 means scrolling only happens if position is * outside the current window. */ scrollToPosition(position: number, threshold = 25): void { let node = this.node; let ar = node.getBoundingClientRect(); let delta = position - ar.top - ar.height / 2; if (Math.abs(delta) > (ar.height * threshold) / 100) { node.scrollTop += delta; } } /** * Set URI fragment identifier. */ setFragment(fragment: string): void { // Wait all cells are rendered then set fragment and update. void Promise.all(this.widgets.map(widget => widget.ready)).then(() => { this._fragment = fragment; this.update(); }); } /** * Handle the DOM events for the widget. * * @param event - The DOM event sent to the widget. * * #### Notes * This method implements the DOM `EventListener` interface and is * called in response to events on the notebook panel's node. It should * not be called directly by user code. */ handleEvent(event: Event): void { if (!this.model) { return; } switch (event.type) { case 'contextmenu': if (event.eventPhase === Event.CAPTURING_PHASE) { this._evtContextMenuCapture(event as PointerEvent); } break; case 'mousedown': if (event.eventPhase === Event.CAPTURING_PHASE) { this._evtMouseDownCapture(event as MouseEvent); } else { this._evtMouseDown(event as MouseEvent); } break; case 'mouseup': if (event.currentTarget === document) { this._evtDocumentMouseup(event as MouseEvent); } break; case 'mousemove': if (event.currentTarget === document) { this._evtDocumentMousemove(event as MouseEvent); } break; case 'keydown': this._ensureFocus(true); break; case 'dblclick': this._evtDblClick(event as MouseEvent); break; case 'focusin': this._evtFocusIn(event as MouseEvent); break; case 'focusout': this._evtFocusOut(event as MouseEvent); break; case 'p-dragenter': this._evtDragEnter(event as IDragEvent); break; case 'p-dragleave': this._evtDragLeave(event as IDragEvent); break; case 'p-dragover': this._evtDragOver(event as IDragEvent); break; case 'p-drop': this._evtDrop(event as IDragEvent); break; default: break; } } /** * Handle `after-attach` messages for the widget. */ protected onAfterAttach(msg: Message): void { super.onAfterAttach(msg); let node = this.node; node.addEventListener('contextmenu', this, true); node.addEventListener('mousedown', this, true); node.addEventListener('mousedown', this); node.addEventListener('keydown', this); node.addEventListener('dblclick', this); node.addEventListener('focusin', this); node.addEventListener('focusout', this); // Capture drag events for the notebook widget // in order to preempt the drag/drop handlers in the // code editor widgets, which can take text data. node.addEventListener('p-dragenter', this, true); node.addEventListener('p-dragleave', this, true); node.addEventListener('p-dragover', this, true); node.addEventListener('p-drop', this, true); } /** * Handle `before-detach` messages for the widget. */ protected onBeforeDetach(msg: Message): void { let node = this.node; node.removeEventListener('contextmenu', this, true); node.removeEventListener('mousedown', this, true); node.removeEventListener('mousedown', this); node.removeEventListener('keydown', this); node.removeEventListener('dblclick', this); node.removeEventListener('focusin', this); node.removeEventListener('focusout', this); node.removeEventListener('p-dragenter', this, true); node.removeEventListener('p-dragleave', this, true); node.removeEventListener('p-dragover', this, true); node.removeEventListener('p-drop', this, true); document.removeEventListener('mousemove', this, true); document.removeEventListener('mouseup', this, true); } /** * A message handler invoked on an `'after-show'` message. */ protected onAfterShow(msg: Message): void { this._checkCacheOnNextResize = true; } /** * A message handler invoked on a `'resize'` message. */ protected onResize(msg: Widget.ResizeMessage): void { if (!this._checkCacheOnNextResize) { return super.onResize(msg); } this._checkCacheOnNextResize = false; const cache = this._cellLayoutStateCache; const width = parseInt(this.node.style.width, 10); if (cache) { if (width === cache.width) { // Cache identical, do nothing return; } } // Update cache this._cellLayoutStateCache = { width }; // Fallback: for (let w of this.widgets) { if (w instanceof Cell) { w.editorWidget.update(); } } } /** * A message handler invoked on an `'before-hide'` message. */ protected onBeforeHide(msg: Message): void { // Update cache const width = parseInt(this.node.style.width, 10); this._cellLayoutStateCache = { width }; } /** * Handle `'activate-request'` messages. */ protected onActivateRequest(msg: Message): void { this._ensureFocus(true); } /** * Handle `update-request` messages sent to the widget. */ protected onUpdateRequest(msg: Message): void { let activeCell = this.activeCell; // Set the appropriate classes on the cells. if (this.mode === 'edit') { this.addClass(EDIT_CLASS); this.removeClass(COMMAND_CLASS); } else { this.addClass(COMMAND_CLASS); this.removeClass(EDIT_CLASS); } if (activeCell) { activeCell.addClass(ACTIVE_CLASS); } let count = 0; each(this.widgets, widget => { if (widget !== activeCell) { widget.removeClass(ACTIVE_CLASS); } widget.removeClass(OTHER_SELECTED_CLASS); if (this.isSelectedOrActive(widget)) { widget.addClass(SELECTED_CLASS); count++; } else { widget.removeClass(SELECTED_CLASS); } }); if (count > 1) { activeCell.addClass(OTHER_SELECTED_CLASS); } if (this._fragment) { let el; try { el = this.node.querySelector(this._fragment); } catch (error) { console.warn('Unable to set URI fragment identifier', error); } if (el) { el.scrollIntoView(); } this._fragment = ''; } } /** * Handle a cell being inserted. */ protected onCellInserted(index: number, cell: Cell): void { if (this.model && this.model.modelDB.isCollaborative) { let modelDB = this.model.modelDB; void modelDB.connected.then(() => { if (!cell.isDisposed) { // Setup the selection style for collaborators. let localCollaborator = modelDB.collaborators.localCollaborator; cell.editor.uuid = localCollaborator.sessionId; cell.editor.selectionStyle = { ...CodeEditor.defaultSelectionStyle, color: localCollaborator.color }; } }); } cell.editor.edgeRequested.connect(this._onEdgeRequest, this); // If the insertion happened above, increment the active cell // index, otherwise it stays the same. this.activeCellIndex = index <= this.activeCellIndex ? this.activeCellIndex + 1 : this.activeCellIndex; } /** * Handle a cell being moved. */ protected onCellMoved(fromIndex: number, toIndex: number): void { let i = this.activeCellIndex; if (fromIndex === i) { this.activeCellIndex = toIndex; } else if (fromIndex < i && i <= toIndex) { this.activeCellIndex--; } else if (toIndex <= i && i < fromIndex) { this.activeCellIndex++; } } /** * Handle a cell being removed. */ protected onCellRemoved(index: number, cell: Cell): void { // If the removal happened above, decrement the active // cell index, otherwise it stays the same. this.activeCellIndex = index <= this.activeCellIndex ? this.activeCellIndex - 1 : this.activeCellIndex; if (this.isSelected(cell)) { this._selectionChanged.emit(void 0); } } /** * Handle a new model. */ protected onModelChanged( oldValue: INotebookModel, newValue: INotebookModel ): void { super.onModelChanged(oldValue, newValue); // Try to set the active cell index to 0. // It will be set to `-1` if there is no new model or the model is empty. this.activeCellIndex = 0; } /** * Handle edge request signals from cells. */ private _onEdgeRequest( editor: CodeEditor.IEditor, location: CodeEditor.EdgeLocation ): void { let prev = this.activeCellIndex; if (location === 'top') { this.activeCellIndex--; // Move the cursor to the first position on the last line. if (this.activeCellIndex < prev) { let editor = this.activeCell.editor; let lastLine = editor.lineCount - 1; editor.setCursorPosition({ line: lastLine, column: 0 }); } } else { this.activeCellIndex++; // Move the cursor to the first character. if (this.activeCellIndex > prev) { let editor = this.activeCell.editor; editor.setCursorPosition({ line: 0, column: 0 }); } } this.mode = 'edit'; } /** * Ensure that the notebook has proper focus. */ private _ensureFocus(force = false): void { let activeCell = this.activeCell; if (this.mode === 'edit' && activeCell) { if (!activeCell.editor.hasFocus()) { activeCell.editor.focus(); } } if (force && !this.node.contains(document.activeElement)) { this.node.focus(); } } /** * Find the cell index containing the target html element. * * #### Notes * Returns -1 if the cell is not found. */ private _findCell(node: HTMLElement): number { // Trace up the DOM hierarchy to find the root cell node. // Then find the corresponding child and select it. while (node && node !== this.node) { if (node.classList.contains(NB_CELL_CLASS)) { let i = ArrayExt.findFirstIndex( this.widgets, widget => widget.node === node ); if (i !== -1) { return i; } break; } node = node.parentElement; } return -1; } /** * Handle `contextmenu` event. */ private _evtContextMenuCapture(event: PointerEvent): void { // Allow the event to propagate un-modified if the user // is holding the shift-key (and probably requesting // the native context menu). if (event.shiftKey) { return; } // `event.target` sometimes gives an orphaned node in Firefox 57, which // can have `null` anywhere in its parent tree. If we fail to find a // cell using `event.target`, try again using a target reconstructed from // the position of the click event. let target = event.target as HTMLElement; let index = this._findCell(target); if (index === -1) { target = document.elementFromPoint( event.clientX, event.clientY ) as HTMLElement; index = this._findCell(target); } let widget = this.widgets[index]; if (widget && widget.editorWidget.node.contains(target)) { // Prevent CodeMirror from focusing the editor. // TODO: find an editor-agnostic solution. event.preventDefault(); } } /** * Handle `mousedown` event in the capture phase for the widget. */ private _evtMouseDownCapture(event: MouseEvent): void { const { button, shiftKey } = event; // `event.target` sometimes gives an orphaned node in Firefox 57, which // can have `null` anywhere in its parent tree. If we fail to find a // cell using `event.target`, try again using a target reconstructed from // the position of the click event. let target = event.target as HTMLElement; let index = this._findCell(target); if (index === -1) { target = document.elementFromPoint( event.clientX, event.clientY ) as HTMLElement; index = this._findCell(target); } let widget = this.widgets[index]; // On OS X, the context menu may be triggered with ctrl-left-click. In // Firefox, ctrl-left-click gives an event with button 2, but in Chrome, // ctrl-left-click gives an event with button 0 with the ctrl modifier. if ( button === 2 && !shiftKey && widget && widget.editorWidget.node.contains(target) ) { this.mode = 'command'; // Prevent CodeMirror from focusing the editor. // TODO: find an editor-agnostic solution. event.preventDefault(); } } /** * Handle `mousedown` events for the widget. */ private _evtMouseDown(event: MouseEvent): void { const { button, shiftKey } = event; // We only handle main or secondary button actions. if (!(button === 0 || button === 2)) { return; } // Shift right-click gives the browser default behavior. if (shiftKey && button === 2) { return; } // Find the target cell. let target = event.target as HTMLElement; let index = this._findCell(target); if (index === -1) { // `event.target` sometimes gives an orphaned node in // Firefox 57, which can have `null` anywhere in its parent line. If we fail // to find a cell using `event.target`, try again using a target // reconstructed from the position of the click event. target = document.elementFromPoint( event.clientX, event.clientY ) as HTMLElement; index = this._findCell(target); } let widget = this.widgets[index]; let targetArea: 'input' | 'prompt' | 'cell' | 'notebook'; if (widget) { if (widget.editorWidget.node.contains(target)) { targetArea = 'input'; } else if (widget.promptNode.contains(target)) { targetArea = 'prompt'; } else { targetArea = 'cell'; } } else { targetArea = 'notebook'; } // Make sure we go to command mode if the click isn't in the cell editor If // we do click in the cell editor, the editor handles the focus event to // switch to edit mode. if (targetArea !== 'input') { this.mode = 'command'; } if (targetArea === 'notebook') { this.deselectAll(); } else if (targetArea === 'prompt' || targetArea === 'cell') { // We don't want to prevent the default selection behavior // if there is currently text selected in an output. const hasSelection = window.getSelection().toString() !== ''; if (button === 0 && shiftKey && !hasSelection) { // Prevent browser selecting text in prompt or output event.preventDefault(); // Shift-click - extend selection try { this.extendContiguousSelectionTo(index); } catch (e) { console.error(e); this.deselectAll(); return; } // Enter selecting mode this._mouseMode = 'select'; document.addEventListener('mouseup', this, true); document.addEventListener('mousemove', this, true); } else if (button === 0 && !shiftKey) { // Prepare to start a drag if we are on the drag region. TODO: If there is no drag, we'll deselect on mouseup. if (targetArea === 'prompt' && this.isSelectedOrActive(widget)) { // Prepare for a drag start this._dragData = { pressX: event.clientX, pressY: event.clientY, index: index }; // Enter possible drag mode this._mouseMode = 'couldDrag'; document.addEventListener('mouseup', this, true); document.addEventListener('mousemove', this, true); event.preventDefault(); } else { this.deselectAll(); this.activeCellIndex = index; } } else if (button === 2) { if (!this.isSelectedOrActive(widget)) { this.deselectAll(); this.activeCellIndex = index; } event.preventDefault(); } } else if (targetArea === 'input') { if (button === 2 && !this.isSelectedOrActive(widget)) { this.deselectAll(); this.activeCellIndex = index; } } // If we didn't set focus above, make sure we get focus now. this._ensureFocus(true); } /** * Handle the `'mouseup'` event on the document. */ private _evtDocumentMouseup(event: MouseEvent): void { // Remove the event listeners we put on the document document.removeEventListener('mousemove', this, true); document.removeEventListener('mouseup', this, true); if (this._mouseMode === 'couldDrag') { // We didn't end up dragging if we are here, so treat it as a click event. // Find the target cell. let target = event.target as HTMLElement; let index = this._findCell(target); if (index === -1) { // `event.target` sometimes gives an orphaned node in // Firefox 57, which can have `null` anywhere in its parent line. If we fail // to find a cell using `event.target`, try again using a target // reconstructed from the position of the click event. target = document.elementFromPoint( event.clientX, event.clientY ) as HTMLElement; index = this._findCell(target); } this.deselectAll(); this.activeCellIndex = index; } this._mouseMode = null; event.preventDefault(); event.stopPropagation(); } /** * Handle the `'mousemove'` event for the widget. */ private _evtDocumentMousemove(event: MouseEvent): void { event.preventDefault(); event.stopPropagation(); // If in select mode, update the selection switch (this._mouseMode) { case 'select': let target = event.target as HTMLElement; let index = this._findCell(target); if (index !== -1) { this.extendContiguousSelectionTo(index); } break; case 'couldDrag': // Check for a drag initialization. let data = this._dragData; let dx = Math.abs(event.clientX - data.pressX); let dy = Math.abs(event.clientY - data.pressY); if (dx >= DRAG_THRESHOLD || dy >= DRAG_THRESHOLD) { this._mouseMode = null; this._startDrag(data.index, event.clientX, event.clientY); } break; default: break; } } /** * Handle the `'p-dragenter'` event for the widget. */ private _evtDragEnter(event: IDragEvent): void { if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) { return; } event.preventDefault(); event.stopPropagation(); let target = event.target as HTMLElement; let index = this._findCell(target); if (index === -1) { return; } let widget = (this.layout as PanelLayout).widgets[index]; widget.node.classList.add(DROP_TARGET_CLASS); } /** * Handle the `'p-dragleave'` event for the widget. */ private _evtDragLeave(event: IDragEvent): void { if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) { return; } event.preventDefault(); event.stopPropagation(); let elements = this.node.getElementsByClassName(DROP_TARGET_CLASS); if (elements.length) { (elements[0] as HTMLElement).classList.remove(DROP_TARGET_CLASS); } } /** * Handle the `'p-dragover'` event for the widget. */ private _evtDragOver(event: IDragEvent): void { if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) { return; } event.preventDefault(); event.stopPropagation(); event.dropAction = event.proposedAction; let elements = this.node.getElementsByClassName(DROP_TARGET_CLASS); if (elements.length) { (elements[0] as HTMLElement).classList.remove(DROP_TARGET_CLASS); } let target = event.target as HTMLElement; let index = this._findCell(target); if (index === -1) { return; } let widget = (this.layout as PanelLayout).widgets[index]; widget.node.classList.add(DROP_TARGET_CLASS); } /** * Handle the `'p-drop'` event for the widget. */ private _evtDrop(event: IDragEvent): void { if (!event.mimeData.hasData(JUPYTER_CELL_MIME)) { return; } event.preventDefault(); event.stopPropagation(); if (event.proposedAction === 'none') { event.dropAction = 'none'; return; } let target = event.target as HTMLElement; while (target && target.parentElement) { if (target.classList.contains(DROP_TARGET_CLASS)) { target.classList.remove(DROP_TARGET_CLASS); break; } target = target.parentElement; } let source: Notebook = event.source; if (source === this) { // Handle the case where we are moving cells within // the same notebook. event.dropAction = 'move'; let toMove: Cell[] = event.mimeData.getData('internal:cells'); // Compute the to/from indices for the move. let fromIndex = ArrayExt.firstIndexOf(this.widgets, toMove[0]); let toIndex = this._findCell(target); // This check is needed for consistency with the view. if (toIndex !== -1 && toIndex > fromIndex) { toIndex -= 1; } else if (toIndex === -1) { // If the drop is within the notebook but not on any cell, // most often this means it is past the cell areas, so // set it to move the cells to the end of the notebook. toIndex = this.widgets.length - 1; } // Don't move if we are within the block of selected cells. if (toIndex >= fromIndex && toIndex < fromIndex + toMove.length) { return; } // Move the cells one by one this.model.cells.beginCompoundOperation(); if (fromIndex < toIndex) { each(toMove, cellWidget => { this.model.cells.move(fromIndex, toIndex); }); } else if (fromIndex > toIndex) { each(toMove, cellWidget => { this.model.cells.move(fromIndex++, toIndex++); }); } this.model.cells.endCompoundOperation(); } else { // Handle the case where we are copying cells between // notebooks. event.dropAction = 'copy'; // Find the target cell and insert the copied cells. let index = this._findCell(target); if (index === -1) { index = this.widgets.length; } let start = index; let model = this.model; let values = event.mimeData.getData(JUPYTER_CELL_MIME); let factory = model.contentFactory; // Insert the copies of the original cells. model.cells.beginCompoundOperation(); each(values, (cell: nbformat.ICell) => { let value: ICellModel; switch (cell.cell_type) { case 'code': value = factory.createCodeCell({ cell }); break; case 'markdown': value = factory.createMarkdownCell({ cell }); break; default: value = factory.createRawCell({ cell }); break; } model.cells.insert(index++, value); }); model.cells.endCompoundOperation(); // Select the inserted cells. this.deselectAll(); this.activeCellIndex = start; this.extendContiguousSelectionTo(index - 1); } } /** * Start a drag event. */ private _startDrag(index: number, clientX: number, clientY: number): void { let cells = this.model.cells; let selected: nbformat.ICell[] = []; let toMove: Cell[] = []; each(this.widgets, (widget, i) => { let cell = cells.get(i); if (this.isSelectedOrActive(widget)) { widget.addClass(DROP_SOURCE_CLASS); selected.push(cell.toJSON()); toMove.push(widget); } }); let activeCell = this.activeCell; let dragImage: HTMLElement = null; let countString: string; if (activeCell.model.type === 'code') { let executionCount = (activeCell.model as ICodeCellModel).executionCount; countString = ' '; if (executionCount) { countString = executionCount.toString(); } } else { countString = ''; } // Create the drag image. dragImage = Private.createDragImage( selected.length, countString, activeCell.model.value.text.split('\n')[0].slice(0, 26) ); // Set up the drag event. this._drag = new Drag({ mimeData: new MimeData(), dragImage, supportedActions: 'copy-move', proposedAction: 'copy', source: this }); this._drag.mimeData.setData(JUPYTER_CELL_MIME, selected); // Add mimeData for the fully reified cell widgets, for the // case where the target is in the same notebook and we // can just move the cells. this._drag.mimeData.setData('internal:cells', toMove); // Add mimeData for the text content of the selected cells, // allowing for drag/drop into plain text fields. const textContent = toMove.map(cell => cell.model.value.text).join('\n'); this._drag.mimeData.setData('text/plain', textContent); // Remove mousemove and mouseup listeners and start the drag. document.removeEventListener('mousemove', this, true); document.removeEventListener('mouseup', this, true); this._mouseMode = null; void this._drag.start(clientX, clientY).then(action => { if (this.isDisposed) { return; } this._drag = null; each(toMove, widget => { widget.removeClass(DROP_SOURCE_CLASS); }); }); } /** * Handle `focus` events for the widget. */ private _evtFocusIn(event: MouseEvent): void { let target = event.target as HTMLElement; let i = this._findCell(target); if (i !== -1) { let widget = this.widgets[i]; // If the editor itself does not have focus, ensure command mode. if (!widget.editorWidget.node.contains(target)) { this.mode = 'command'; } this.activeCellIndex = i; // If the editor has focus, ensure edit mode. let node = widget.editorWidget.node; if (node.contains(target)) { this.mode = 'edit'; } } else { // No cell has focus, ensure command mode. this.mode = 'command'; } if (this.mode === 'command' && target !== this.node) { delete this.node.dataset[CODE_RUNNER]; } else { this.node.dataset[CODE_RUNNER] = 'true'; } } /** * Handle `focusout` events for the notebook. */ private _evtFocusOut(event: MouseEvent): void { let relatedTarget = event.relatedTarget as HTMLElement; // Bail if the window is losing focus, to preserve edit mode. This test // assumes that we explicitly focus things rather than calling blur() if (!relatedTarget) { return; } // Bail if the item gaining focus is another cell, // and we should not be entering command mode. const i = this._findCell(relatedTarget); if (i !== -1) { const widget = this.widgets[i]; if (widget.editorWidget.node.contains(relatedTarget)) { return; } } // Otherwise enter command mode if not already. if (this.mode !== 'command') { this.mode = 'command'; // Switching to command mode currently focuses the notebook element, so // refocus the relatedTarget so the focus actually switches as intended. if (relatedTarget) { relatedTarget.focus(); } } } /** * Handle `dblclick` events for the widget. */ private _evtDblClick(event: MouseEvent): void { let model = this.model; if (!model) { return; } this.deselectAll(); // `event.target` sometimes gives an orphaned node in Firefox 57, which // can have `null` anywhere in its parent tree. If we fail to find a // cell using `event.target`, try again using a target reconstructed from // the position of the click event. let target = event.target as HTMLElement; let i = this._findCell(target); if (i === -1) { target = document.elementFromPoint( event.clientX, event.clientY ) as HTMLElement; i = this._findCell(target); } if (i === -1) { return; } this.activeCellIndex = i; if (model.cells.get(i).type === 'markdown') { let widget = this.widgets[i] as MarkdownCell; widget.rendered = false; } else if (target.localName === 'img') { target.classList.toggle(UNCONFINED_CLASS); } } /** * Remove selections from inactive cells to avoid * spurious cursors. */ private _trimSelections(): void { for (let i = 0; i < this.widgets.length; i++) { if (i !== this._activeCellIndex) { let cell = this.widgets[i]; cell.model.selections.delete(cell.editor.uuid); } } } private _activeCellIndex = -1; private _activeCell: Cell | null = null; private _mode: NotebookMode = 'command'; private _drag: Drag = null; private _fragment = ''; private _dragData: { pressX: number; pressY: number; index: number } = null; private _mouseMode: 'select' | 'couldDrag' | null = null; private _activeCellChanged = new Signal<this, Cell>(this); private _stateChanged = new Signal<this, IChangedArgs<any>>(this); private _selectionChanged = new Signal<this, void>(this); // Attributes for optimized cell refresh: private _cellLayoutStateCache?: { width: number }; private _checkCacheOnNextResize = false; } /** * The namespace for the `Notebook` class statics. */ export namespace Notebook { /** * An options object for initializing a notebook widget. */ export interface IOptions extends StaticNotebook.IOptions {} /** * The content factory for the notebook widget. */ export interface IContentFactory extends StaticNotebook.IContentFactory {} /** * The default implementation of a notebook content factory.. * * #### Notes * Override methods on this class to customize the default notebook factory * methods that create notebook content. */ export class ContentFactory extends StaticNotebook.ContentFactory {} /** * A namespace for the notebook content factory. */ export namespace ContentFactory { /** * An options object for initializing a notebook content factory. */ export interface IOptions extends StaticNotebook.ContentFactory.IOptions {} } export const defaultContentFactory: IContentFactory = new ContentFactory(); } /** * A namespace for private data. */ namespace Private { /** * An attached property for the selected state of a cell. */ export const selectedProperty = new AttachedProperty<Cell, boolean>({ name: 'selected', create: () => false }); /** * A custom panel layout for the notebook. */ export class NotebookPanelLayout extends PanelLayout { /** * A message handler invoked on an `'update-request'` message. * * #### Notes * This is a reimplementation of the base class method, * and is a no-op. */ protected onUpdateRequest(msg: Message): void { // This is a no-op. } } /** * Create a cell drag image. */ export function createDragImage( count: number, promptNumber: string, cellContent: string ): HTMLElement { if (count > 1) { if (promptNumber !== '') { return VirtualDOM.realize( h.div( h.div( { className: DRAG_IMAGE_CLASS }, h.span( { className: CELL_DRAG_PROMPT_CLASS }, '[' + promptNumber + ']:' ), h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent) ), h.div({ className: CELL_DRAG_MULTIPLE_BACK }, '') ) ); } else { return VirtualDOM.realize( h.div( h.div( { className: DRAG_IMAGE_CLASS }, h.span({ className: CELL_DRAG_PROMPT_CLASS }), h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent) ), h.div({ className: CELL_DRAG_MULTIPLE_BACK }, '') ) ); } } else { if (promptNumber !== '') { return VirtualDOM.realize( h.div( h.div( { className: `${DRAG_IMAGE_CLASS} ${SINGLE_DRAG_IMAGE_CLASS}` }, h.span( { className: CELL_DRAG_PROMPT_CLASS }, '[' + promptNumber + ']:' ), h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent) ) ) ); } else { return VirtualDOM.realize( h.div( h.div( { className: `${DRAG_IMAGE_CLASS} ${SINGLE_DRAG_IMAGE_CLASS}` }, h.span({ className: CELL_DRAG_PROMPT_CLASS }), h.span({ className: CELL_DRAG_CONTENT_CLASS }, cellContent) ) ) ); } } } /** * Process the `IOptions` passed to the notebook widget. * * #### Notes * This defaults the content factory to that in the `Notebook` namespace. */ export function processNotebookOptions(options: Notebook.IOptions) { if (options.contentFactory) { return options; } else { return { rendermime: options.rendermime, languagePreference: options.languagePreference, contentFactory: Notebook.defaultContentFactory, mimeTypeService: options.mimeTypeService }; } } }
/** @jsxImportSource @emotion/react */ import { css, useTheme } from '@emotion/react'; import clsx from 'clsx'; import React, { useCallback, useEffect, useRef, useState } from 'react'; import { clamp } from '../../utils'; type SwipeItem = { index: number; content: React.ReactNode; }; type SwiperProps = { items: SwipeItem[]; onSwipe?: (current: number, distance: number) => any; onSwipeStart?: (current: number) => any; onSwipeEnd?: (current: number) => any; onClick?: (index: number) => any; autoPlay?: boolean; loop?: boolean; delay?: number; vertical?: boolean; indicator?: (total: number, current: number) => React.ReactNode; className?: string; }; const Swiper = ({ items, autoPlay = false, vertical = false, loop = false, delay = 3000, onSwipeStart, onSwipeEnd, onSwipe, onClick, className, }: SwiperProps) => { const computeCurrentItems = useCallback(() => { return items.length > 1 ? items.slice(-1).concat(items, items.slice(0, 1)) : items; }, [items]); const ref = useRef(null); const [touchResult, setTouchResult] = useState({ clientX: 0, clientY: 0 }); const [isTouching, setIsTouching] = useState(false); const [currentIndex, setCurrentIndex] = useState(0); const [boundingInfos, setBoundingInfos] = useState<{ width: number; height: number }>({ width: 0, height: 0 }); const [translateY, setTranslateY] = useState<string | number>(0); const [translateX, setTranslateX] = useState<string | number>(0); const theme = useTheme(); const styles = css({ overflow: 'hidden', whiteSpace: 'nowrap', '& > ul': { transform: `${ typeof translateX != 'string' ? `translate3d(${translateX}px,${translateY}px,0)` : `translate3d(${translateX},${translateY},0)` }`, '& > li': { display: 'inline-flex', width: '100%', }, }, }); useEffect(() => { if (autoPlay) { const iv = setInterval(() => {}, delay); return clearInterval(iv); } }, []); useEffect(() => { setBoundingInfos((ref.current as any)?.getBoundingClientRect()); }, [ref]); const handleTouchStart = (e: React.TouchEvent<HTMLLIElement>) => { setIsTouching(true); setTouchResult(e.touches[e.touches.length - 1]); onSwipeStart?.(currentIndex); }; const handleTouchMove = (e: React.TouchEvent<HTMLLIElement>) => { const currentTouchResult = e.touches[e.touches.length - 1]; const diff = currentTouchResult[vertical ? 'clientY' : 'clientX'] - touchResult[vertical ? 'clientY' : 'clientX']; const isFirstItem = currentIndex == items[0].index && !loop; const isLastItem = currentIndex == items[items.length - 1].index && !loop; const currentNeededLength = boundingInfos[vertical ? 'height' : 'width']; const currentTranslate = currentIndex * currentNeededLength; console.log('currentTranslate', currentTranslate); const setTranslateXByDiff = (diffClamped: number) => { if (diff < 0) { setTranslateX(-currentTranslate + diffClamped); } else { setTranslateX(currentTranslate + diffClamped); } }; if (isFirstItem) { const diffClamped = clamp(diff, -currentNeededLength, 0); setTranslateXByDiff(diffClamped); } else if (isLastItem) { const diffClamped = clamp(diff, 0, currentNeededLength); setTranslateXByDiff(diffClamped); } else setTranslateXByDiff(diff); onSwipe?.(currentIndex, diff); }; const handleTouchEnd = (e: React.TouchEvent<HTMLLIElement>) => { setIsTouching(false); const currentTouchResult = e.changedTouches[e.changedTouches.length - 1]; const diff = currentTouchResult[vertical ? 'clientY' : 'clientX'] - touchResult[vertical ? 'clientY' : 'clientX']; const isRightDirection = diff < 0; const toggle = Math.abs(diff) >= boundingInfos[vertical ? 'height' : 'width'] / 2; const newCurrentIndex = currentIndex + (toggle ? (isRightDirection ? 1 : -1) : 0); setCurrentIndex(newCurrentIndex); if (vertical) { setTranslateY(`${newCurrentIndex * (isRightDirection ? -1 : 1) * 100}%`); } else { setTranslateX(`${newCurrentIndex * (isRightDirection ? -1 : 1) * 100}%`); } setTouchResult(currentTouchResult); onSwipeEnd?.(currentIndex); }; return ( <div css={styles} ref={ref} className={clsx(className)}> <ul> {items.map(v => { return ( <li key={v.index + 'swipeitem'} onTouchStart={e => handleTouchStart(e)} onTouchMove={e => handleTouchMove(e)} onTouchEnd={e => handleTouchEnd(e)} onClick={e => onClick?.(v.index)}> {v.content} </li> ); })} </ul> </div> ); }; export default Swiper;
package example.framework; import javax.servlet.http.HttpServletRequest; public class PathHelper { public String getLookupPathForRequest(HttpServletRequest request) { // First, see if it is an included request String includeServletPath = (String) request.getAttribute("javax.servlet.include.servlet_path"); if (includeServletPath != null) { // Try path info; only if that's null (servlet is mapped to an // URL extension instead of to prefix) use servlet path. String includePathInfo = (String) request.getAttribute("javax.servlet.include.path_info"); return (includePathInfo == null) ? includeServletPath : includePathInfo; } // Seems that the servlet was not called as the result of a // RequestDispatcher.include(...). Try pathInfo then servletPath again, // only now directly on the request object: String path = request.getPathInfo(); if (path != null) { return path; } path = request.getServletPath(); if (path != null) { return path; } // Seems that it is a servlet mapped with prefix, and there was no extra path info. return ""; } }
export type { AngularV9Main } from './angular-v9.main.runtime'; export { AngularV9Env } from './angular-v9.env'; export { AngularV9Aspect, AngularV9Aspect as default } from './angular-v9.aspect';
const ROOT = Symbol('root') const UPDATE = Symbol('update') const CANCEL = Symbol('cancel') const INTERRUPT = Symbol('interrupt') /** Pool of used children per parent */ const pool = new WeakMap() /** Use with {@link Layer#subscribe} to listen for any store changes */ export const ANY = Symbol('any') /** Current stack of layers being resolved */ export const stack = [] /** * Read from store. Returns value * @param {any} [key] Store key name, omitting key yields store object * @param {any} [initial] Initial value if not found in store * @returns {Array} A touple of current value and an update function */ export function store (key, initial) { console.assert(stack.length, 'store used outside render cycle') var layer = stack[0] if (!key) return [layer.store, (next) => layer.update(next)] if (typeof key === 'string' && key[0] === '$') { const _key = key.substring(1) let value if (hasOwnProperty(layer.store[_key])) { value = layer.store[_key] } else if (typeof initial !== 'undefined') { value = layer.store[_key] = initial layer.changes.add(_key) } return [value, (next) => layer.update(key, next)] } var value = layer.store[key] if (typeof value === 'undefined' && typeof initial !== 'undefined') { value = layer.store[key] = initial layer.changes.add(key) } return [value, (next) => layer.update(key, next)] } /** * Watch store for changes * @param {any} key store key to watch or function to call on any change * @param {Function} [fn] Function ot call when value of key change * @returns {void} */ export function watch (key, fn) { console.assert(stack.length, 'watch used outside render cycle') if (Array.isArray(key)) { return key.forEach((_key) => watch(_key, function () { var layer = stack[0] return fn(key.map((__key) => layer.store[__key])) })) } else if (typeof key === 'function') { fn = key key = ANY } if (key === ANY) { stack.forEach((layer) => layer.subscribe(key, fn)) } else { const layer = stack.find((layer) => hasOwnProperty(layer.store, key)) if (layer) { layer.subscribe(key, fn) if (layer.fresh) layer.changes.add(key) } } } /** * Creates a layer for a component * @param {Function} fn Component render Function * @param {Object} store Store to use for component * @param {...any} args Arguments to forward to component * @returns {Layer} */ export function use (fn, store, ...args) { var layer = stack[0] if (store == null) store = {} if (!layer) return new Layer(ROOT, fn, store, args) if (!layer.children.has(fn)) layer.children.set(fn, new Set()) if (!pool.get(layer).has(fn)) pool.get(layer).set(fn, new Set()) var child var children = layer.children.get(fn) var candidates = pool.get(layer).get(fn) var key = typeof store.key === 'undefined' ? children.size + 1 : store.key for (const candidate of candidates) { if (candidate.key === key) { child = candidate child.assign(store, args) break } } if (!child) { store = Object.assign(Object.create(layer.store), store) child = new Layer(key, fn, store, args) } children.add(child) return child } export class Layer { /** * Create a layer * @param {any} key Unique identifier for component * @param {Function} fn Component render Function * @param {Object} store Store to use for Component * @param {Array} args Arguments to forward to component */ constructor (key, fn, store, args) { this.key = key this.args = args this.store = store this.render = render this.fresh = true this.stack = [...stack] this.changes = new Set() this.children = new Map() this.listeners = new Map() pool.set(this, new WeakMap()) var queued = false var running = false /** * Call component render function, recursively rerunning on every update * @returns {any} */ function render () { if (running) { queued = true } else { try { queued = false running = true var res = unwind(fn(...this.args)) } catch (err) { if (err === INTERRUPT) { queued = true } else if (err === CANCEL) { var cancel = true } else { throw err } } finally { running = false } if (cancel) return if (queued) res = this.render() return res } } } /** * Make updates to layer internals on reuse * @param {Object} store Properties with which to extend store * @param {Array} args Arguments to forward to component * @returns {void} */ assign (store, args) { this.args = args Object.assign(this.store, store) } /** * Resolve component * @param {Function} callback Function to call on async updates * @returns {any} */ resolve (callback) { if (!stack.includes(this)) { stack.unshift(this) } if (typeof callback === 'function') { this.subscribe(UPDATE, function onupdate (res) { callback(res) return onupdate }) } try { for (const key of this.changes) { this.emit(key, this.store[key]) } const res = this.render() for (const key of this.changes) { this.emit(key, this.store[key]) } return res } finally { const pooled = pool.get(this) for (const [fn, children] of this.children) { pooled.set(fn, new Set(children)) } this.fresh = false this.children.clear() this.changes.clear() stack.shift() } } /** * Update store, issuing an async render * @param {any} key Key of the value to update or a new store to assign * @param {any} [value] New value to assign for key * @returns {void} */ update (key, value) { if (typeof value === 'undefined') { Object.assign(this.store, key) key = ANY } else if (typeof key === 'string' && key[0] === '$') { key = key.substring(1) this.store[key] = value } else { if (hasOwnProperty(this.store, key)) { this.store[key] = value } else { const parent = this.stack.find(function (parent) { return hasOwnProperty(parent.store, key) }) if (!parent) { this.store[key] = value } else { parent.changes.add(key) parent.emit(UPDATE, parent.resolve(), { any: false }) if (stack.includes(this)) throw CANCEL return } } } this.changes.add(key) if (stack.includes(this)) throw INTERRUPT this.emit(UPDATE, this.resolve(), { any: false }) } /** * Subscribe to changes made to store. The listener function may return * a callback function which will be called on next change, before render. * @param {any} key Key to subscribe to * @param {Function} fn Function to call on change * @returns {void} */ subscribe (key, fn) { if (!this.listeners.has(fn)) { this.listeners.set(fn, new Set()) } this.listeners.get(fn).add(key) } /** * Emit change * @param {any} key Emit an event to subscribed listeners * @param {any} value New value for subscribed key * @param {Object} [opts] Configure behavior * @param {boolean} [opts.any=true] Trigger listerns for {@link ANY} */ emit (key, value, opts = {}) { var { any = true } = opts var listeners = [] for (const [fn, keys] of this.listeners.entries()) { if (!keys.has(key) && (!any || !keys.has(ANY))) continue const cleanup = keys.has(key) && key !== ANY ? fn(value) : fn() this.listeners.delete(fn) if (typeof cleanup === 'function') listeners.push(cleanup) } for (const listener of listeners) { this.subscribe(key, listener) } } } /** * Resolve nested generator and promises * @param {any} obj * @param {any} [value] * @returns {any} */ function unwind (obj, value) { if (isGenerator(obj)) { const res = obj.next(value) if (res.done) return res.value if (isPromise(res.value)) { return res.value.then(unwind).then((val) => unwind(obj, val)) } return unwind(obj, res.value) } else if (isPromise(obj)) { return obj.then(unwind) } return obj } /** * Determin if object is promise * @param {any} obj * @returns {boolean} */ function isPromise (obj) { return !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function' } /** * Determine if object is generator * @param {any} obj * @return {boolean} */ function isGenerator (obj) { return obj && typeof obj.next === 'function' && typeof obj.throw === 'function' } /** * Check if object has key set on self * @param {Object} obj The object to check * @param {any} key The key to look for */ function hasOwnProperty (obj, key) { return Object.prototype.hasOwnProperty.call(obj, key) }