text
stringlengths
184
4.48M
/*************************************************************************************************/ /*! \file login_command.cpp \attention (c) Electronic Arts. All Rights Reserved. */ /*************************************************************************************************/ /*************************************************************************************************/ /*! \class LoginCommand Sends Nucleus an email and password for authentication. */ /*************************************************************************************************/ /*** Include Files *******************************************************************************/ #include "framework/blaze.h" #include "framework/connection/outboundhttpservice.h" #include "framework/protocol/restprotocolutil.h" #include "framework/util/locales.h" #include "framework/util/shared/blazestring.h" #include "framework/usersessions/usersession.h" #include "framework/usersessions/usersessionmanager.h" #include "framework/tdf/userevents_server.h" #include "framework/tdf/userdefines.h" #include "framework/oauth/oauthslaveimpl.h" #include "framework/oauth/accesstokenutil.h" #include "authentication/authenticationimpl.h" #include "authentication/rpc/authenticationslave/login_stub.h" #include "authentication/tdf/authentication.h" #include "authentication/util/authenticationutil.h" #include "authentication/util/checkentitlementutil.h" #include "authentication/util/consolerenameutil.h" #include "proxycomponent/nucleusidentity/rpc/nucleusidentityslave.h" #include "proxycomponent/nucleusidentity/tdf/nucleusidentity.h" #include "nucleusconnect/tdf/nucleusconnect.h" #include "nucleusconnect/rpc/nucleusconnectslave.h" namespace Blaze { namespace Authentication { /*** Defines/Macros/Constants/Typedefs ***********************************************************/ /*** Public Methods ******************************************************************************/ class LoginCommand : public LoginCommandStub { public: LoginCommand(Message* message, LoginRequest* request, AuthenticationSlaveImpl* componentImpl); /* Private methods *******************************************************************************/ private: LoginCommandStub::Errors execute() override; BlazeRpcError doLogin(ClientPlatformType clientPlatform, ClientType clientType, const char8_t* productName, AccountId& accountId, PersonaId& personaId, eastl::string& personaName, ExternalId& externalId, eastl::string& externalString); private: AuthenticationSlaveImpl* mComponent; bool mIsUnderage; eastl::string mDeviceId; DeviceLocality mDeviceLocality; }; DEFINE_LOGIN_CREATE() LoginCommand::LoginCommand(Message* message, LoginRequest* request, AuthenticationSlaveImpl* componentImpl) : LoginCommandStub(message, request), mComponent(componentImpl), mIsUnderage(false) { } LoginCommandStub::Errors LoginCommand::execute() { // Backwards compatibility convert the LoginRequest into the expected format: convertToPlatformInfo(mRequest.getPlatformInfo(), mRequest.getExternalId(), nullptr, INVALID_ACCOUNT_ID, INVALID); const char8_t* serviceName = getPeerInfo()->getServiceName(); const char8_t* productName = mRequest.getProductName(); if (productName[0] == '\0') // productName is optional. If not specified, use the default of the service. productName = gController->getServiceProductName(serviceName); if (!mComponent->isValidProductName(productName)) { ERR_LOG("[LoginCommand].execute: Invalid product name " << productName << " specified in request."); return AUTH_ERR_INVALID_FIELD; } ClientPlatformType servicePlatform = gController->getServicePlatform(serviceName); if (servicePlatform == common) { // If connected to the 'common' default service name (i.e. via gRPC on the EADP Service Mesh), // then the product name can be used to specify the service platform ClientPlatformType productPlatform = mComponent->getProductPlatform(productName); if (productPlatform != INVALID) servicePlatform = productPlatform; } // For login call, use the platform info from the service that user is trying to connect to. // This way, we can verify whether the credentials provided by the user are appropriate for the service's // platform. if (servicePlatform == common) { ERR_LOG("[LoginCommand].execute: Login command can only be used with a real platform. The service(" << serviceName << ") does not belong to a real platform."); return AUTH_ERR_INVALID_PLATFORM; } ClientType clientType = mRequest.getClientType(); if (clientType == CLIENT_TYPE_INVALID) clientType = getPeerInfo()->getClientType(); const char8_t* clientVersion = ""; const char8_t* sdkVersion = ""; if (getPeerInfo()->getClientInfo() != nullptr) { const ClientPlatformType clientInfoPlatform = getPeerInfo()->getClientInfo()->getPlatform(); TRACE_LOG("[LoginCommand].execute : Client's platform (" << ClientPlatformTypeToString(clientInfoPlatform) << "), service's platform(" << ClientPlatformTypeToString(servicePlatform) << ")."); if (clientInfoPlatform != servicePlatform) { WARN_LOG("[LoginCommand].execute : Client's platform (" << ClientPlatformTypeToString(clientInfoPlatform) << ") via preAuth " << "does not match service's platform("<< ClientPlatformTypeToString(servicePlatform) << "). Override with service's platform."); getPeerInfo()->getClientInfo()->setPlatform(servicePlatform); } clientVersion = getPeerInfo()->getClientInfo()->getClientVersion(); sdkVersion = getPeerInfo()->getClientInfo()->getBlazeSDKVersion(); } AccountId accountId = INVALID_ACCOUNT_ID; PersonaId personaId = INVALID_BLAZE_ID; ExternalId externalId = INVALID_EXTERNAL_ID; eastl::string externalString; eastl::string personaName; if (!mComponent->isBelowPsuLimitForClientType(clientType)) { INFO_LOG("[LoginCommand].execute : PSU limit of " << mComponent->getPsuLimitForClientType(clientType) << " for client type " << ClientTypeToString(clientType) << " has been reached."); char8_t addrStr[Login::MAX_IPADDRESS_LEN] = { 0 }; getPeerInfo()->getRealPeerAddress().toString(addrStr, sizeof(addrStr)); PlatformInfo platformInfo; convertToPlatformInfo(platformInfo, externalId, externalString.c_str(), accountId, servicePlatform); gUserSessionMaster->sendLoginPINError(AUTH_ERR_EXCEEDS_PSU_LIMIT, getUserSessionId(), platformInfo, personaId, getPeerInfo()->getLocale(), getPeerInfo()->getCountry(), sdkVersion, clientType, addrStr, serviceName, productName, clientVersion, mIsUnderage); return AUTH_ERR_EXCEEDS_PSU_LIMIT; } BlazeRpcError err = doLogin(servicePlatform, clientType, productName, accountId, personaId, personaName, externalId, externalString); if (err == Blaze::ERR_OK) { mComponent->getMetricsInfoObj()->mLogins.increment(1, productName, clientType); char8_t lastAuth[Blaze::Authentication::MAX_DATETIME_LENGTH]; Blaze::TimeValue curTime = Blaze::TimeValue::getTimeOfDay(); curTime.toAccountString(lastAuth, sizeof(lastAuth)); mComponent->getMetricsInfoObj()->setLastAuthenticated(lastAuth); } else { mComponent->getMetricsInfoObj()->mLoginFailures.increment(1, productName, clientType); char8_t addrStr[Login::MAX_IPADDRESS_LEN] = {0}; getPeerInfo()->getRealPeerAddress().toString(addrStr, sizeof(addrStr)); GeoLocationData geoIpData; gUserSessionManager->getGeoIpData(getPeerInfo()->getRealPeerAddress(), geoIpData); bool sendPINErrorEvent = (err == AUTH_ERR_INVALID_TOKEN) || (err == AUTH_ERR_EXCEEDS_PSU_LIMIT) || (err == AUTH_ERR_BANNED) || (err == ERR_COULDNT_CONNECT); PlatformInfo platformInfo; convertToPlatformInfo(platformInfo, externalId, externalString.c_str(), accountId, servicePlatform); gUserSessionMaster->generateLoginEvent(err, getUserSessionId(), USER_SESSION_NORMAL, platformInfo, mDeviceId.c_str(), mDeviceLocality, personaId, personaName.c_str(), getPeerInfo()->getLocale(), getPeerInfo()->getCountry(), sdkVersion, clientType, addrStr, serviceName, productName, geoIpData, mComponent->getProjectId(productName), LOCALE_BLANK, 0, clientVersion, sendPINErrorEvent, mIsUnderage); } return commandErrorFromBlazeError(err); } BlazeRpcError LoginCommand::doLogin(ClientPlatformType clientPlatform, ClientType clientType, const char8_t* productName, AccountId& accountId, PersonaId& personaId, eastl::string& personaName, ExternalId& externalId, eastl::string& externalString) { BlazeRpcError err = Blaze::ERR_SYSTEM; if (!mComponent->shouldBypassRateLimiter(clientType)) { err = mComponent->tickAndCheckLoginRateLimit(); if (err != Blaze::ERR_OK) { // an error occurred while the fiber was asleep, so we must exit with the error. WARN_LOG("[LoginCommand].doLogin(): tickAndCheckLoginRateLimit failed with error[" << ErrorHelp::getErrorName(err) << "]. Login attempts are being rate limited. (See totalLoginsPerMinute in authentication.cfg)" ); return err; } } OAuth::OAuthSlaveImpl* oAuthSlave = mComponent->oAuthSlaveImpl(); if (oAuthSlave == nullptr) { ERR_LOG("[LoginCommand].doLogin: oAuthSlave is nullptr"); return Blaze::ERR_SYSTEM; } bool isLoginByAccessToken = (mRequest.getAccessToken() != nullptr && mRequest.getAccessToken()[0] != '\0'); // Step 1: Get the access token from Nucleus NucleusConnect::GetAccessTokenResponse tokenResponse; InetAddress inetAddr = AuthenticationUtil::getRealEndUserAddr(this); const char8_t* clientId = mComponent->getBlazeServerNucleusClientId(); err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getAccessTokenResponse(mRequest.getAccessToken(), mRequest.getAuthCode(), productName, inetAddr, tokenResponse)); if (err != Blaze::ERR_OK) { if (isLoginByAccessToken) { ERR_LOG("[LoginCommand].doLogin: getAccessTokenResponse failed with error(" << ErrorHelp::getErrorName(err) << "). Access Token: " << mRequest.getAccessToken()); } else { ERR_LOG("[LoginCommand].doLogin: getAccessTokenResponse failed with error(" << ErrorHelp::getErrorName(err) << "). Auth Code: " << mRequest.getAuthCode()); } return err; } const char8_t *userAccessToken = tokenResponse.getAccessToken(); OAuth::AccessTokenUtil tokenUtil; err = tokenUtil.retrieveServerAccessToken(OAuth::TOKEN_TYPE_BEARER); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: Failed to retrieve server access token with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } const char8_t* serverAccessToken = tokenUtil.getAccessToken(); // Step 2: Get the token info NucleusConnect::GetTokenInfoRequest tokenInfoRequest; tokenInfoRequest.setAccessToken(userAccessToken); tokenInfoRequest.setIpAddress(inetAddr.getIpAsString()); tokenInfoRequest.setClientId(clientId); NucleusConnect::JwtPayloadInfo jwtPayloadInfo; NucleusConnect::GetTokenInfoResponse tokenInfoResponse; err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getTokenInfo(tokenInfoRequest, tokenInfoResponse, jwtPayloadInfo, clientPlatform)); if (err != Blaze::ERR_OK) { WARN_LOG("[LoginCommand].doLogin: getTokenInfo failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } // Validate the deviceId mDeviceId = tokenInfoResponse.getDeviceId(); mDeviceLocality = DEVICELOCALITY_UNKNOWN; int8_t deviceLocalityInt = 0; blaze_str2int(tokenInfoResponse.getConnectionType(), &deviceLocalityInt); mDeviceLocality = static_cast<DeviceLocality>(deviceLocalityInt); if (mDeviceLocality == DEVICELOCALITY_UNKNOWN) { WARN_LOG("[LoginCommand].doLogin: Device Locality is UNKNOWN."); } ProductMap::const_iterator itr = mComponent->getConfig().getProducts().find(productName); if (itr != mComponent->getConfig().getProducts().end()) { if ((itr->second->getDeviceIdLogLevel() == LOG_ALWAYS) || ((itr->second->getDeviceIdLogLevel() == LOG_WHEN_EMPTY) && mDeviceId.empty())) { INFO_LOG("[LoginCommand].doLogin: DeviceId(" << mDeviceId << ") for account(" << tokenInfoResponse.getAccountId() << "), console environment(" << tokenInfoResponse.getConsoleEnv() << "), token clientId(" << tokenInfoResponse.getClientId() << "), is underage(" << tokenInfoResponse.getIsUnderage() << "), stop process(" << tokenInfoResponse.getStopProcess() << "), clientType(" << ClientTypeToString(getPeerInfo()->getClientType()) << "), IP(" << getPeerInfo()->getRealPeerAddress() << "), platform(" << ClientPlatformTypeToString(clientPlatform) << "), deviceType(" << mDeviceLocality << ")."); } if (mDeviceId.empty() && itr->second->getRequireDeviceId()) { INFO_LOG("[LoginCommand].doLogin: Login failed; DeviceId is empty."); return AUTH_ERR_INVALID_TOKEN; } const char8_t* authSource = itr->second->getAuthenticationSource(); if (authSource == nullptr || authSource[0] == '\0') { ERR_LOG("[LoginCommand].doLogin: authSource not found in tokenInfo. Failing login." << tokenInfoResponse); if (isLoginByAccessToken) return AUTH_ERR_INVALID_TOKEN; else return AUTH_ERR_INVALID_AUTHCODE; } if (mComponent->getConfig().getVerifyAuthSource()) // kill switch for the auth source verification functionality { // Due to a variety of reasons, we have ended up in a lame situation. Configuration of authSource on the client wasn't a requirement until recently (Circa March 2019). If the auth source // was not provisioned, Nucleus returns the clientId as the auth source. Coincidentally, this is bad for the shared cluster where the clientId is same for all the platforms. // check top level bool authSourceMismatch = (blaze_stricmp(tokenInfoResponse.getAuthSource(), authSource) != 0); if (authSourceMismatch) { // check nested configuration for this platform/product const AccessList& accessList = itr->second->getAccess(); for (const auto& access : accessList) { if (blaze_stricmp(tokenInfoResponse.getAuthSource(), access->getProjectId()) == 0) { authSourceMismatch = false; break; } } } if (authSourceMismatch) { // In a shared cluster, the specification of a authenticationSource on client is a MUST (except PC Dev). // In single platform scenario, the we accept clientId as an authentication source. if (gController->isSharedCluster()) { // pc dev often does not have origin launcher support so skip it. bool mismatchAllowed = (clientPlatform == pc || clientPlatform == steam) && (blaze_stricmp(gController->getServiceEnvironment(), "dev") == 0); if (!mismatchAllowed) { ERR_LOG("[LoginCommand].doLogin: The authSource (" << tokenInfoResponse.getAuthSource() << ") returned by Nucleus for blaze product (" << productName << ") user is trying to log into did not match " << " the configured authSource/projectId(" << authSource << "). authSource must match with the projectId for the shared cluster." << "Failing login."); if (isLoginByAccessToken) return AUTH_ERR_INVALID_TOKEN; else return AUTH_ERR_INVALID_AUTHCODE; } } else { // Nucleus returns the nucleus client Id as authSource of an auth_code if the client did not specify a authSource. So we check that to support old flow. if (blaze_stricmp(tokenInfoResponse.getAuthSource(), gController->getBlazeServerNucleusClientId()) != 0) { ERR_LOG("[LoginCommand].doLogin: In fallback path, the authSource (" << tokenInfoResponse.getAuthSource() << ") returned by Nucleus for the blaze product (" << productName << ") user is trying to log" << " into did not match with the configured authSource/projectId(" << authSource << ") or " << "clientId (" << gController->getBlazeServerNucleusClientId() << "). Failing login."); if (isLoginByAccessToken) return AUTH_ERR_INVALID_TOKEN; else return AUTH_ERR_INVALID_AUTHCODE; } } } } } else { // This should have already failed in the execute() but adding here as a safety net. ERR_LOG("[LoginCommand].doLogin: Invalid product name " << productName << " specified in request."); return AUTH_ERR_INVALID_FIELD; } const ClientTypeFlags& flags = gUserSessionManager->getClientTypeDescription(clientType); if (flags.getValidateSandboxId()) { // Verify that the console environment used is valid: err = mComponent->verifyConsoleEnv(clientPlatform, productName, tokenInfoResponse.getConsoleEnv()); if (err != Blaze::ERR_OK) { // Error logging performed in verifyConsoleEnv TRACE_LOG("[LoginCommand].doLogin: An error occurred while verifying console environment (" << tokenInfoResponse.getConsoleEnv() << ")."); return err; } } // Get the value of the 'StopProcess' flag on the users account. See https://developer.ea.com/display/CI/GOPFR-4171%09%5BGDPR%5D+Subject+Access+Requests+-+Pull+and+delete+per-user+records+design+spec const bool stopProcess = (blaze_stricmp(tokenInfoResponse.getStopProcess(), "on") == 0); AccountId pidId = INVALID_BLAZE_ID; blaze_str2int(tokenInfoResponse.getPidId(), &pidId); blaze_str2int(tokenInfoResponse.getAccountId(), &accountId); // Step 3: Check online access entitlements if (clientPlatform == steam) { OAuth::AccessTokenUtil fullScopeServerTokenUtil; { //retrieve full scope server access token in a block to avoid changing function context permission UserSession::SuperUserPermissionAutoPtr autoPtr(true); err = fullScopeServerTokenUtil.retrieveServerAccessToken(OAuth::TOKEN_TYPE_BEARER); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: Failed to retrieve full scope server access token with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } } TRACE_LOG("[LoginCommand].doLogin: calling getRefreshExternalEntitlements for accountId(" << accountId << ") and personaId (" << tokenInfoResponse.getPersonaId() << ")."); NucleusIdentity::GetRefreshExternalEntitlementsRequest req; NucleusIdentity::GetRefreshExternalEntitlementsResponse resp; req.getAuthCredentials().setAccessToken(fullScopeServerTokenUtil.getAccessToken()); req.getAuthCredentials().setUserAccessToken(userAccessToken); req.setPidId(pidId); // GOSOPS-198001: // This call times out at 7s on C&I's end when talking to Steam. After 7s, C&I may end up sending us 200 response without actually refreshing the entitlements in steam (the // current entitlements will be returned). This means we can run into a very transient error if this is the first time the user is logging in and the call to Steam takes over // 7s. err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getRefreshExternalEntitlements(req, resp)); if (err != Blaze::ERR_OK) { //Nucleus Identity Resilience: Soft dependency on getRefreshExternalEntitlements. If rpc failed because of unavailable Nucleus service, blaze should ignore the error. if (oAuthSlave->isNucleusServiceUnavailable(err)) { WARN_LOG("[LoginCommand].doLogin: getRefreshExternalEntitlements failed with error(" << ErrorHelp::getErrorName(err) << "). Ignoring the error due to Nucleus service is unavailable."); err = Blaze::ERR_OK; } else { ERR_LOG("[LoginCommand].doLogin: getRefreshExternalEntitlements failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } } } CheckEntitlementUtil checkEntUtil(*mComponent, clientType); err = mComponent->commonEntitlementCheck(accountId, checkEntUtil, clientType, productName, this, userAccessToken, clientId); if (err != Blaze::ERR_OK) { //Nucleus Identity Resilience: Soft dependency on entitlement check. If rpc failed because of unavailable Nucleus service, blaze should ignore the error. if (oAuthSlave->isNucleusServiceUnavailable(err)) { WARN_LOG("[LoginCommand].doLogin: commonEntitlementCheck failed with error (" << ErrorHelp::getErrorName(err) << ") for accountId(" << accountId << ") on platform(" << Blaze::ClientPlatformTypeToString(clientPlatform) << "). Ignoring the error due to Nucleus service is unavailable."); err = Blaze::ERR_OK; } else { ERR_LOG("[LoginCommand].doLogin: commonEntitlementCheck failed with error (" << ErrorHelp::getErrorName(err) << ") for accountId(" << accountId << ") on platform(" << Blaze::ClientPlatformTypeToString(clientPlatform) << "). Soft check(" << checkEntUtil.getSoftCheck() << ")."); if (!checkEntUtil.getSoftCheck()) return err; } } const char8_t* addrStr = inetAddr.getIpAsString(); eastl::string userTokenBearer(eastl::string::CtorSprintf(), "%s %s", tokenResponse.getTokenType(), userAccessToken); // Step 4: get the full account info NucleusIdentity::GetAccountRequest accountRequest; NucleusIdentity::GetAccountResponse accountResponse; //for better compatibility with old version Nucleus API, do not use dual token on getAccount call accountRequest.getAuthCredentials().setAccessToken(userTokenBearer.c_str()); accountRequest.getAuthCredentials().setClientId(clientId); accountRequest.getAuthCredentials().setIpAddress(addrStr); err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getAccount(accountRequest, accountResponse, &jwtPayloadInfo, clientPlatform)); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: getAccount failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } if (clientPlatform == nx) externalString = accountResponse.getPid().getExternalRefValue(); else externalId = EA::StdC::AtoU64(accountResponse.getPid().getExternalRefValue()); // Step 5: Find the Origin namespace persona for this account (used in the loginUserSession below) NucleusIdentity::GetPersonaListRequest personaListRequest; NucleusIdentity::GetPersonaListResponse personaListResponse; personaListRequest.getAuthCredentials().setAccessToken(serverAccessToken); personaListRequest.getAuthCredentials().setUserAccessToken(userAccessToken); personaListRequest.getAuthCredentials().setClientId(clientId); personaListRequest.getAuthCredentials().setIpAddress(addrStr); personaListRequest.setPid(pidId); personaListRequest.setExpandResults("true"); personaListRequest.getFilter().setNamespaceName(NAMESPACE_ORIGIN); personaListRequest.getFilter().setStatus("ACTIVE"); err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getPersonaList(personaListRequest, personaListResponse, &jwtPayloadInfo)); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: getPersonaList failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } OriginPersonaId originPersonaId = INVALID_BLAZE_ID; const char8_t* originPersonaName = nullptr; personaId = tokenInfoResponse.getPersonaId(); if (!personaListResponse.getPersonas().getPersona().empty()) { originPersonaId = personaListResponse.getPersonas().getPersona()[0]->getPersonaId(); originPersonaName = personaListResponse.getPersonas().getPersona()[0]->getDisplayName(); } // Step 5.5: Get personaId for PC platform (steam/epic) as persona_id returned in getTokenInfo is null; Get external refernce id as well since pc platform games doesn't return it in the GetAccount api call. if (personaId == INVALID_BLAZE_ID && clientPlatform == steam) { //reusing personaListRequest but setting namespace from client platform personaListRequest.getFilter().setNamespaceName(gController->getNamespaceFromPlatform(clientPlatform)); NucleusIdentity::GetPersonaListResponse filteredPersonaListResponse; err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getPersonaList(personaListRequest, filteredPersonaListResponse, &jwtPayloadInfo)); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: getPersonaList failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } if (!filteredPersonaListResponse.getPersonas().getPersona().empty()) { personaId = filteredPersonaListResponse.getPersonas().getPersona()[0]->getPersonaId(); } OAuth::AccessTokenUtil fullScopeServerTokenUtil; { //retrieve full scope server access token in a block to avoid changing function context permission UserSession::SuperUserPermissionAutoPtr autoPtr(true); err = fullScopeServerTokenUtil.retrieveServerAccessToken(OAuth::TOKEN_TYPE_BEARER); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: Failed to retrieve full scope server access token with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } } NucleusIdentity::GetExternalRefRequest externalRefRequest; NucleusIdentity::GetExternalRefResponse externalRefResponse; externalRefRequest.getAuthCredentials().setAccessToken(fullScopeServerTokenUtil.getAccessToken()); externalRefRequest.getAuthCredentials().setUserAccessToken(userAccessToken); externalRefRequest.getAuthCredentials().setClientId(clientId); externalRefRequest.getAuthCredentials().setIpAddress(addrStr); externalRefRequest.setExpandResults("true"); externalRefRequest.setPersonaId(personaId); err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getExternalRef(externalRefRequest, externalRefResponse, &jwtPayloadInfo)); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: getExternalRef failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } if (externalRefResponse.getPersonaReference().empty()) { ERR_LOG("[LoginCommand].doLogin: getExternalRef failed to get external reference id"); return ERR_SYSTEM; } externalId = EA::StdC::AtoU64(externalRefResponse.getPersonaReference().front()->getReferenceValue()); } // Step 6: Get the info for the persona associated with the access token and set response info NucleusIdentity::GetPersonaInfoRequest personaInfoRequest; NucleusIdentity::GetPersonaInfoResponse personaInfoResponse; const char8_t* personaNamespace = nullptr; if (personaId != INVALID_BLAZE_ID && clientPlatform != nx) // Switch persona names are not unique, so we use the Origin persona name on the nx platform { personaInfoRequest.getAuthCredentials().setAccessToken(serverAccessToken); personaInfoRequest.getAuthCredentials().setUserAccessToken(userAccessToken); personaInfoRequest.getAuthCredentials().setClientId(clientId); personaInfoRequest.getAuthCredentials().setIpAddress(addrStr); personaInfoRequest.setPid(pidId); personaInfoRequest.setPersonaId(personaId); err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getPersonaInfo(personaInfoRequest, personaInfoResponse, &jwtPayloadInfo)); if (err != Blaze::ERR_OK) { ERR_LOG("[LoginCommand].doLogin: getPersonaInfo failed with error(" << ErrorHelp::getErrorName(err) << ")"); return err; } personaName = personaInfoResponse.getPersona().getDisplayName(); personaNamespace = personaInfoResponse.getPersona().getNamespaceName(); // check that the persona tied to the token is in the same namespace as this server // is configured for to ensure there's no namespace mismatch const char8_t* serviceNamespace = (clientPlatform != INVALID) ? gController->getNamespaceFromPlatform(clientPlatform) : ""; if (clientPlatform == INVALID || blaze_stricmp(serviceNamespace, personaNamespace) != 0) { WARN_LOG("[LoginCommand].doLogin: Persona namespace(" << personaNamespace << ") does not match clientPlatform (" << ClientPlatformTypeToString(clientPlatform) << ")'s expected namespace ("<< serviceNamespace <<")."); return AUTH_ERR_INVALID_TOKEN; } } else { // check that this is an origin login enabled server, otherwise, token is invalid if // it doesn't contain personaId if (personaId == INVALID_BLAZE_ID && blaze_stricmp(gController->getNamespaceFromPlatform(clientPlatform), NAMESPACE_ORIGIN) != 0) { WARN_LOG("[LoginCommand].doLogin: Server is not configured for Origin namespace, but personaId was not specified in token."); return AUTH_ERR_INVALID_TOKEN; } if (originPersonaId == static_cast<OriginPersonaId>(INVALID_BLAZE_ID)) { WARN_LOG("[LoginCommand].doLogin: Rejecting " << (clientPlatform == nx ? "Switch login; Origin account is required but" : "Origin login; token does not contain a valid persona and" ) << " no active origin personas exist for accountId:" << accountId); return AUTH_ERR_INVALID_TOKEN; } personaNamespace = NAMESPACE_ORIGIN; if (personaId == INVALID_BLAZE_ID) personaId = originPersonaId; personaName = originPersonaName; } LogContextOverride contextOverride(personaId, mDeviceId.c_str(), personaName.c_str(), getPeerInfo()->getRealPeerAddress(), accountId, clientPlatform); mIsUnderage = accountResponse.getPid().getUnderagePid(); mResponse.setIsUnderage(accountResponse.getPid().getUnderagePid()); mResponse.setIsOfLegalContactAge(!accountResponse.getPid().getUnderagePid()); mResponse.setIsAnonymous(accountResponse.getPid().getAnonymousPid()); // Step 7: Fill in all the required information to login the user, and log them in. // Adding warning logging for users that are possibly hackers so that game teams can further investigate. // Essentially we want to validate, and warn otherwise: // 1) XOne: the externalId passed up in the request TDF matches the value returned from Nucleus for this account // (except on ps4, where we fetch externalId from Nucleus only and don't send it from the client). // 2) ExternalId returned from Nucleus is valid (all platforms). bool checkClientExternalIdMatchesNucleus = ((clientPlatform == ClientPlatformType::xone) || (clientPlatform == ClientPlatformType::xbsx)) && flags.getCheckExternalId() && !oAuthSlave->isMock(); // Only checking Xbl here, since that's all that's available: if ((checkClientExternalIdMatchesNucleus && mRequest.getPlatformInfo().getExternalIds().getXblAccountId() != externalId) || externalId == INVALID_EXTERNAL_ID) { WARN_LOG("[LoginCommand].doLogin: Possible hacker/fraudulent account! XblId(" << externalId << ") returned by Nucleus vs tdf request XblId(" << mRequest.getPlatformInfo().getExternalIds().getXblAccountId() << ") for accountId[" << accountId << "], persona[" << personaName << "], IP address[" << addrStr << "]"); } // Copy the returned external value into the PlatformInfo, before copying that into the UserInfoData: convertToPlatformInfo(mRequest.getPlatformInfo(), externalId, externalString.c_str(), accountId, originPersonaId, originPersonaName, clientPlatform); // fetch settings from Player Settings Service NucleusIdentity::GetPlayerSettingsRequest playerSettingsRequest; NucleusIdentity::GetPlayerSettingsResponse playerSettingsResponse; playerSettingsRequest.getAuthCredentials().setAccessToken(serverAccessToken); playerSettingsRequest.getAuthCredentials().setUserAccessToken(userAccessToken); playerSettingsRequest.setName(mComponent->getConfig().getPssSchemaName()); playerSettingsRequest.setAccountId(accountId); err = AuthenticationUtil::authFromOAuthError(oAuthSlave->getPlayerSettings(playerSettingsRequest, playerSettingsResponse)); if (err != Blaze::ERR_OK) { WARN_LOG("[LoginCommand].doLogin: getPlayerSettings failed with error(" << ErrorHelp::getErrorName(err) << ") -- using defaults"); } // Step 8: Fill in all the required information to login the user, and log them in. UserInfoData userData; mRequest.getPlatformInfo().copyInto(userData.getPlatformInfo()); userData.setId(personaId); userData.setPidId(pidId); userData.setPersonaName(personaName.c_str()); userData.setAccountLocale(LocaleTokenCreateFromDelimitedString(accountResponse.getPid().getLocale())); userData.setAccountCountry(LocaleTokenGetShortFromString(accountResponse.getPid().getCountry())); // account country is not locale-related, but re-using locale macro for convenience userData.setOriginPersonaId(originPersonaId); userData.setLastLoginDateTime(TimeValue::getTimeOfDay().getSec()); userData.setLastLocaleUsed(getPeerInfo()->getLocale()); userData.setLastCountryUsed(getPeerInfo()->getCountry()); userData.setLastAuthErrorCode(Blaze::ERR_OK); userData.setIsChildAccount(accountResponse.getPid().getUnderagePid()); userData.setStopProcess(stopProcess); userData.setVoipDisabled(playerSettingsResponse.getVoipDisabled()); userData.setPersonaNamespace(personaNamespace); bool updateCrossPlatformOpt = mRequest.getCrossPlatformOpt() != DEFAULT; if (updateCrossPlatformOpt) userData.setCrossPlatformOptIn(mRequest.getCrossPlatformOpt() == OPTIN); const char8_t* ipAsString = AuthenticationUtil::getRealEndUserAddr(this).getIpAsString(); //Make the call to register the session bool geoIpSucceeded = true; UserInfoDbCalls::UpsertUserInfoResults upsertUserInfoResults(userData.getAccountCountry()); err = gUserSessionMaster->createNormalUserSession(userData, *getPeerInfo(), clientType, getConnectionUserIndex(), productName, false, tokenInfoResponse.getIpGeoLocation(), geoIpSucceeded, upsertUserInfoResults, false, updateCrossPlatformOpt, tokenInfoResponse.getDeviceId(), mDeviceLocality, &tokenResponse, ipAsString); if (err == USER_ERR_EXISTS) { //we hit a conflict in user info table which means that existing entries are outdated -- update them Blaze::Authentication::ConsoleRenameUtil consoleRenameUtil(getPeerInfo()); err = consoleRenameUtil.doRename(userData, upsertUserInfoResults, updateCrossPlatformOpt, true); if (err == ERR_OK) { err = gUserSessionMaster->createNormalUserSession(userData, *getPeerInfo(), clientType, getConnectionUserIndex(), productName, false, tokenInfoResponse.getIpGeoLocation(), geoIpSucceeded, upsertUserInfoResults, true, updateCrossPlatformOpt, tokenInfoResponse.getDeviceId(), mDeviceLocality, &tokenResponse, ipAsString); } } if (err == Blaze::ERR_OK) { UserLoginInfo& userLoginInfo = mResponse.getUserLoginInfo(); const UserInfo& userInfo = gCurrentLocalUserSession->getUserInfo(); userLoginInfo.setBlazeId(gCurrentLocalUserSession->getBlazeId()); userLoginInfo.setIsFirstLogin(gCurrentLocalUserSession->getSessionFlags().getFirstLogin()); userLoginInfo.setIsFirstConsoleLogin(gCurrentLocalUserSession->getSessionFlags().getFirstConsoleLogin()); userLoginInfo.setLastLoginDateTime(userInfo.getPreviousLoginDateTime()); char8_t sessionKey[MAX_SESSION_KEY_LENGTH]; gCurrentLocalUserSession->getKey(sessionKey); userLoginInfo.setSessionKey(sessionKey); userInfo.getPlatformInfo().copyInto(userLoginInfo.getPlatformInfo()); userLoginInfo.setAccountId(userInfo.getPlatformInfo().getEaIds().getNucleusAccountId()); userLoginInfo.getPersonaDetails().setDisplayName(userInfo.getPersonaName()); userLoginInfo.getPersonaDetails().setExtId(getExternalIdFromPlatformInfo(userData.getPlatformInfo())); userLoginInfo.getPersonaDetails().setPersonaId(gCurrentLocalUserSession->getBlazeId()); userLoginInfo.setGeoIpSucceeded(geoIpSucceeded); } else { if (err == ERR_DUPLICATE_LOGIN) { err = AUTH_ERR_DUPLICATE_LOGIN; } else if (err == ERR_NOT_PRIMARY_PERSONA) { err = AUTH_ERR_NOT_PRIMARY_PERSONA; } ERR_LOG("[LoginCommand].doLogin: loginUserSession() failed with error[" << ErrorHelp::getErrorName(err) << "]"); } return err; } } // Authentication } // Blaze
import configparser import requests import streamlit as st from langchain import OpenAI from langchain.callbacks import get_openai_callback import os LANGUAGE_INSTRUCTIONS_DICT = { # "Chinese": "- 请使用中文输出\n", "English": "- Please output English.\n", } # New: Dictionary for academic paper section prompts PAPER_SECTION_PROMPTS = { "General": "Review for any grammatical or syntactical errors. Ensure the sentences in the paragraph flow logically. Replace any vague or ambiguous words with clearer terms. Avoid jargon unless it's standard in the field and necessary for understanding. Ensure variety in sentence structures. Break up long sentences if they are hard to understand. Ensure the tone is consistent and appropriate for an academic paper.", "Title": "Ensure the title captures the essence of the research succinctly.", "Abstract": "Ensure it provides a concise summary of the research.", "Introduction": "Establish context and background of the study.", "Methodology": "Streamline the methods description, ensuring clarity for replication.", "Results": "Emphasize significant findings using clear language.", "Discussion": "Interpret results and link them back to existing literature.", "Conclusion": "Summarize main research points.", } def get_user_ip(): try: ip = requests.get("https://api64.ipify.org?format=json").json()["ip"] except Exception as e: ip = "unknown" return ip def get_text(user_inputs): # Read the whitelist from the config file # config = configparser.ConfigParser() # config.read("config.ini") # whitelist = set(config["whitelist"]["ip_addresses"].split(", ")) # Get the user's IP address # user_ip = get_user_ip() # if user_ip in whitelist: # If the user is in the whitelist, don't limit their inputs input_text = st.text_area( label="", placeholder="Input your text here...", key="text_input" ) # Add the input to the session_state if it doesn't already exist if "user_input_list" not in st.session_state: st.session_state.user_input_list = [] # Append the input to the user_input_list if input_text: st.session_state.user_input_list.append(input_text) # else: # # If the user is not in the whitelist, limit their inputs to 10 # if user_ip not in user_inputs: # user_inputs[user_ip] = 1 # else: # user_inputs[user_ip] += 1 # if user_inputs[user_ip] <= 10: # input_text = st.text_area( # label="", placeholder="Input your text here...", key="text_input" # ) # # Add the input to the session_state if it doesn't already exist # if "user_input_list" not in st.session_state: # st.session_state.user_input_list = [] # # Append the input to the user_input_list # if input_text: # st.session_state.user_input_list.append(input_text) # else: # input_text = "" # st.warning("You have exceeded the maximum number of inputs (10).") return input_text def get_language_instructions(language): return LANGUAGE_INSTRUCTIONS_DICT.get(language, "") @st.cache_data() def load_LLM(): llm = OpenAI( # model_name="gpt-4", temperature=0.1, max_tokens=2048, ) return llm def display_interface(): col1, col2 = st.columns(2) with col1: st.markdown( "LinguaShine is the ultimate tool for anyone looking to polish their language. Try it out today and see the difference for yourself!" ) st.markdown( "[Please Give Me a 🌟Star🌟 on Github](https://github.com/chenhuiyu/LinguaShine)" ) with col2: st.image(image="DALL·E 2023-04-21 11.03.08.png", width=250) st.markdown("## Enter Your Text") col1, col2 = st.columns(2) with col1: option_language = st.selectbox( "Please select the language you want to input.", ("English", "English") ) with col2: # New column for selecting the section of the academic paper option_paper_section = st.selectbox( "Select the section of the academic paper you want to optimize.", list(PAPER_SECTION_PROMPTS.keys()), ) return option_language, option_paper_section def handle_conversion(llm, input_text, language, section): # Create the PromptTemplate object with the input variables and the template template = """**Task**: You have been presented with a section from an English academic paper in the field of Civil Engineering. Your role is to refine this section, ensuring its clarity and accessibility without compromising its technical integrity. Afterward, detail the improvements you made and their significance. **Objective**: A well-optimized paper isn't just technically accurate; it's also accessible and easy to follow. Your refinements should make the content resonate more effectively with its primary audience—Civil Engineering professionals—while also being comprehensible to a wider academic readership. **Areas of Focus**: 1. **Content Clarity**: - **Issue**: A cluttered text often hides the main point, causing confusion. - **Optimize**: Distill the content to spotlight the primary idea. Excise any redundant or tangential sentences. - **Benefit**: Enhanced focus and reduced reader effort. 2. **Logical Flow**: - **Issue**: Disjointed sentences can disrupt the narrative flow. - **Optimize**: Sequence sentences for a coherent progression of ideas. - **Benefit**: A smoother reading experience. 3. **Word Choice**: - **Issue**: Ambiguous or complex words can alienate readers. - **Optimize**: Use clear and precise terminology. Retain field-specific jargon only when indispensable. - **Benefit**: Improved comprehension. 4. **Grammar & Syntax**: - **Issue**: Grammatical errors undermine credibility. - **Optimize**: Ensure linguistic correctness, from verb tenses to sentence structures. - **Benefit**: A polished and professional presentation. 5. **Sentence Structure**: - **Issue**: Overly lengthy or abrupt sentences can be off-putting. - **Optimize**: Aim for a mix of sentence lengths, prioritizing clarity. - **Benefit**: Enhanced readability. 6. **Tone & Formality**: - **Issue**: Inconsistent or casual tone can diminish the paper's gravitas. - **Optimize**: Maintain a consistent, scholarly tone. Steer clear of colloquial expressions. - **Benefit**: Ensures the work is taken seriously. **Presented Section**: - {section} --- **Input Text**: Here's a section from a Civil Engineering academic paper: - {text} --- **Expected Output**: Your submission should comprise two segments: the refined text and a specific analysis of your refinements. - Refined Text:(In English) - Analysis:(In Chinese) """ # Combine the template, the input variables, and the instructions prompt_with_query = template.format( language=language, section=PAPER_SECTION_PROMPTS[section], text=input_text ) # prompt_with_query += PAPER_SECTION_PROMPTS[section] # Display the modified query if input_text: with get_openai_callback() as cb: output = llm(prompt_with_query) st.markdown("### Your Converted Text") st.success(output) st.write(cb) def main(user_inputs): st.set_page_config(page_title="LinguaShine", page_icon=":robot:") st.header("LinguaShine") ( option_language, option_paper_section, ) = display_interface() # Updated function return language = get_language_instructions(option_language) input_text = get_text(user_inputs) llm = load_LLM() # st.button("Convert!") if input_text and st.button("Convert!"): handle_conversion(llm, input_text, language, option_paper_section) if __name__ == "__main__": if "user_inputs" not in st.session_state: st.session_state.user_inputs = {} main(st.session_state.user_inputs)
import { createAsyncThunk } from "@reduxjs/toolkit"; import { getBlogAPI, getBlogsAPI } from 'apis/axios/blog/get' import { REDUX_SLICE_NAMES, BLOG_DETAILS_DATA_FIELDS, BRIEF_BLOG_DATA_FIELDS } from 'utilities/constants' import { briefBlogsSeletor } from './BlogsSlice' import { RequestBriefBlogsInfoProps, RequestBlogDetailsInfoProps, BriefBlogsReduxStateProps, BlogDataProps, BlogDetailsDataProps } from 'types/index.d.ts' export const fetchBriefBlogsByTypeAsyncThunk = createAsyncThunk( `${REDUX_SLICE_NAMES.BLOGS}/fetchBriefBlogsByType`, /** * @param {RequestBriefBlogsInfoProps} requestBriefBlogsInfo */ async (requestBriefBlogsInfo, thunkAPI) => { try { const state = thunkAPI.getState(); const { type, fields } = requestBriefBlogsInfo; const briefBlogsByType = briefBlogsSeletor(state, type); const limit = briefBlogsByType ? briefBlogsByType.limit : 5; const skip = briefBlogsByType ? briefBlogsByType.skip : 0; const query = { limit: limit, skip: skip, filter: `quality:${type}`, fields: fields, userId: state.user.currentUser._id }; const response = await getBlogsAPI(query); return [type, response.data]; } catch (error) { console.error(error.message); } } ); export const fetchBlogDetailsByIdAsyncThunk = createAsyncThunk( `${REDUX_SLICE_NAMES.BLOGS}/fetchBlogDetailsById`, /** * @param {RequestBlogDetailsInfoProps} requestBlogDetailsInfo */ async (requestBlogDetailsInfo, thunkAPI) => { try { const { blogId, options } = requestBlogDetailsInfo; const query = { blogId: blogId, fields: options.canGetFull ? "" : BLOG_DETAILS_DATA_FIELDS }; const response = await getBlogAPI(query); return [blogId, response.data]; } catch (error) { console.error(error.message); } } ); export const refetchBriefBlogsByTypeAsyncThunk = createAsyncThunk( `${REDUX_SLICE_NAMES.BLOGS}/refetchBriefBlogsByType`, /** * @param {RequestBriefBlogsInfoProps} requestBriefBlogsInfo */ async (requestBriefBlogsInfo, thunkAPI) => { try { const { type, fields } = requestBriefBlogsInfo; const state = thunkAPI.getState(); const limit = 5; const skip = 0; const query = { limit: limit, skip: skip, filter: `quality:${type}`, fields: fields, userId: state.user.currentUser._id }; const response = await getBlogsAPI(query); return [type, response.data]; } catch (error) { console.error(error.message); } } );
import { Component } from '@angular/core'; import {AbstractControl, FormControl, FormGroup, ValidationErrors, ValidatorFn, Validators} from "@angular/forms"; import {AuthServiceService} from "../services/auth-service.service"; import {Router} from "@angular/router"; @Component({ selector: 'app-registration', templateUrl: './registration.component.html', styleUrls: ['./registration.component.scss'] }) export class RegistrationComponent { registerForm!: FormGroup; constructor(private authService: AuthServiceService, private router: Router) { this.registerForm = new FormGroup({ 'email': new FormControl(null, [Validators.required, Validators.email]), 'username': new FormControl(null, Validators.required), 'confirm-password': new FormControl(null, Validators.required), 'password': new FormControl(null, Validators.required) }, { validators: this.passwordMatchValidator}); } async onSubmit() { try { console.log(this.registerForm.valid) let result = await this.authService.register(this.registerForm.value.email, this.registerForm.value.password, this.registerForm.value.username); if (result) { this.router.navigate(['/']); } } catch (e) { console.log(e); } } passwordMatchValidator(control: AbstractControl): ValidationErrors | null { const form = control as FormGroup; return form.get('password')?.value === form.get('confirm-password')?.value ? null : {'mismatch': true}; } passwordsMatch() { return this.registerForm.get('password')?.value === this.registerForm.get('confirm-password')?.value } }
import { BottomSheetModal, BottomSheetModalProvider, } from "@gorhom/bottom-sheet"; import React, { ReactNode, useCallback, useEffect, useMemo, useRef, } from "react"; import { StyleSheet, View } from "react-native"; import OutsidePressHandler from "react-native-outside-press"; import IconButton from "../Buttons/IconButton"; interface Props { children: ReactNode; isOpen: boolean; // for observer, state is manage within this component itself setIsOpen: React.Dispatch<React.SetStateAction<boolean>>; } const BottomModalOnly = ({ isOpen, setIsOpen, children }: Props) => { // ref const bottomSheetModalRef = useRef<BottomSheetModal>(null); // variables const snapPoints = useMemo(() => ["1%", "50%"], []); // callbacks const handlePresentModalPress = useCallback(() => { setIsOpen(true); bottomSheetModalRef.current?.present(); }, []); // when pressed outside const handleDismissModalPress = useCallback(() => { setIsOpen(false); bottomSheetModalRef.current?.dismiss(); }, []); const handleSheetChanges = useCallback((index: number) => { if (index === 1) return setIsOpen(true); if (index === -1) return setIsOpen(false); }, []); useEffect(() => { if (isOpen) { bottomSheetModalRef.current?.present(); } else { bottomSheetModalRef.current?.dismiss(); } }, [isOpen]); // renders return ( <BottomSheetModalProvider> <OutsidePressHandler disabled={false} onOutsidePress={() => { handleDismissModalPress(); }} > <View style={styles.container}> <BottomSheetModal ref={bottomSheetModalRef} index={1} snapPoints={snapPoints} onChange={handleSheetChanges} enablePanDownToClose enableOverDrag detached topInset={-200} bottomInset={0} > <View style={styles.contentContainer}>{children}</View> </BottomSheetModal> </View> </OutsidePressHandler> </BottomSheetModalProvider> ); }; const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", zIndex: 100, position: "absolute", }, contentContainer: { flex: 1, alignItems: "center", }, }); export default BottomModalOnly;
import { useState } from "react" import Searching from "../../general/Searching" import { Card, CardActions, CardContent, CardHeader, IconButton, Typography } from "@mui/material" import { Link } from "react-router-dom" import { GridDeleteIcon } from "@mui/x-data-grid" import EditIcon from '@mui/icons-material/Edit'; import FloatingActionButtonSize from "../../general/ButtonFloat" function ProductCard(props) { const {products} = props const {deleteProduct} = props const[search,setSearch] = useState("") const enviarSearch = (msg) =>{ setSearch(msg.target.value) } let result = [] if(!search){ result = products } else{ result = products.filter((dato)=> dato.name.toLowerCase().includes(search.toLocaleLowerCase()) ) } return ( <> <Searching enviarSearch={enviarSearch}/> {result.map( (product) => ( <div key={product.id} style={{ display: 'inline-block', marginLeft: '20px',marginTop:'20px' }}> <Card sx={{ maxWidth: 345,minWidth:345 }}> <CardHeader className='text-center' title={product.name} /> <CardContent> <Typography variant="body2" color="text.secondary"> {product.category_id.name} </Typography> </CardContent> <CardActions disableSpacing> <Link> <IconButton onClick={()=>deleteProduct(product.id)}> <GridDeleteIcon /> </IconButton> </Link> <Link Link to={`/edit_product/${product.id}`}> <IconButton aria-label="share"> <EditIcon /> </IconButton> </Link> </CardActions> </Card> </div> ))} <Link to='/create_product'> <FloatingActionButtonSize back='/view_card_category'/> </Link> </> ) } export default ProductCard
import pytest from flask import url_for from app.models import User def test_get_register(test_client, test_app): """Test registration page access.""" with test_app.test_request_context(): response = test_client.get(url_for('main.register'), follow_redirects=True) assert response.status_code == 200 assert b"Username" in response.data assert b"Email" in response.data assert b"Password" in response.data assert b"Sign Up" in response.data assert b"Already have an account?" in response.data def test_get_login(test_client, test_app): """Test login page access.""" with test_app.test_request_context(): response = test_client.get(url_for('main.login'), follow_redirects=True) assert response.status_code == 200 assert b"Login" in response.data assert b"Email" in response.data assert b"Password" in response.data assert b"Login" in response.data assert b"Don't have an account?" in response.data def test_register(test_client, test_app): """Test the registration process.""" with test_app.test_request_context(): response = test_client.post(url_for('main.register'), data={ 'username': 'newuser', 'email': '[email protected]', 'password': 'password', 'submit': True }, follow_redirects=True) print(response.data) assert response.status_code == 200 assert b'Your account has been created!' in response.data def test_login(test_client, init_database): """Test the login process.""" with test_client: response = test_client.post(url_for('main.login'), data={ 'email': '[email protected]', 'password': 'password', 'submit': True }, follow_redirects=True) assert response.status_code == 200 assert b'You are logged in' in response.data
import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { UserComponent } from './main/user/user.component'; import { AddUserComponent } from './main/user/add-user/add-user.component'; import { SideBarComponent } from './main/user/side-bar/side-bar.component'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { HttpClientModule } from '@angular/common/http'; import { ToastrModule } from 'ngx-toastr'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { NgDragDropModule } from 'ng-drag-drop'; @NgModule({ declarations: [ AppComponent, UserComponent, AddUserComponent, SideBarComponent ], imports: [ BrowserModule, AppRoutingModule, ReactiveFormsModule, FormsModule, HttpClientModule, ToastrModule.forRoot(), BrowserAnimationsModule, NgDragDropModule.forRoot() ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
//Interface interface CamisetaBase{ setColor(color); getColor(); } //Decorador function estampar(logo: string){ return function(target: Function){ target.prototype.estampacion = function():void{ console.log("Camiseta estampada con el logo de: "+logo); } } } //Clase (molde del objeto) @estampar('Gucci Gang') class Camiseta implements CamisetaBase{ //Propiedades (caracteristicas del objeto) private color: string; private modelo: string; private marca: string; private talla: string; private precio: number; //Metodos (funciones o acciones del objeto) constructor(color, modelo, marca, talla, precio){ this.color = color; this.modelo = modelo; this.marca = marca; this.talla = talla; this.precio = precio; } public setColor(color){ this.color = color; } public getColor(){ return this.color; } } /*var camiseta = new Camiseta("rojo", "manga larga", "Nike", "L", 14); camiseta.setColor("verde"); console.log(camiseta);*/ //Clase hija class Sudadera extends Camiseta{ public capucha: boolean; setCapucha(capucha:boolean){ this.capucha = capucha; } getCapucha():boolean{ return this.capucha; } } var camiseta = new Camiseta("rojo", "manga larga", "Nike", "L", 14); console.log(camiseta); camiseta.estampacion(); var sudadera_nike = new Sudadera("verde", "manga larga", "Puma", "XL", 24); sudadera_nike.setCapucha(true); sudadera_nike.setColor("Plomo"); console.log(sudadera_nike);
function xq = lanczos(t, x, tq, a) % xq = LANCZOS(t, x, tq, a) % % Interpolate a signal using Lanczos kernel. % % INPUT: % t time of the original signal, must be equally spaced % x original signal % tq requested time for interpolated signal % a scale factor for Lanczos kernel % If a = 0, then the Whittaker-Shannon interpolation is used % instead. % % OUTPUT: % xq interpolated signal % % EXAMPLE: % % run a demo % lanczos('demo'); % % Last modified by sirawich-at-princeton.edu, 10/19/2021 defval('a', 0) % demo if ischar(t) % original signal t = (-10:0.227:10)'; A = [6 5 4]'; f = [1 0.75 0.3]'; p = [0.1 2/pi 0.4]'; x = sin(2 * pi * (t * f' + p')) * A; % requested signal tq = (-15:0.01:15)'; xq = lanczos(t, x, tq, 3); xq_expected = sin(2 * pi * (tq * f' + p')) * A; % plot the result figure subplot(3,1,1) plot(t, x, 'k-o') hold on grid on plot(tq, xq, 'r') legend('original', 'reconstruct') ylabel('x') title(sprintf(['lanzcos demo: dt-original = %.3f s, ' ... 'dt-interpolated = %.3f s, a = %.2f'], t(2)-t(1), tq(2)-tq(1), 3)); subplot(3,1,2) plot(tq, xq_expected, 'k'); hold on grid on plot(tq, xq, 'r') legend('expected', 'reconstruct') ylabel('x') subplot(3,1,3) plot(tq, xq - xq_expected) grid on ylabel('difference') xlabel('t') return end if size(t, 2) > 1 t = t'; end if size(x, 2) > 1 x = x'; end if size(tq, 2) > 1 tq = tq'; end % sampling period dt = t(2) - t(1); if a == 0 % Whittaker-Shannon interpolation formula xq = sinc((repmat(tq, 1, length(t)) - repmat(t', length(tq), 1)) / dt) * x; else % apply Lanczos window xq = lanczoswindow((repmat(tq, 1, length(t)) - repmat(t', length(tq), 1)) / dt, a) * x; end end function y = lanczoswindow(x, a) y = sinc(x) .* sinc(x/a); y(abs(x) > a) = 0; end
>>>> ```yaml 标题: 4.变量、作用域、内存 variable、scope、memory 摘要: - 变量与原始值、引用值 - 执行上下文 - 垃圾回收 ``` <<<< 1.原始值 & 引用值 primitive value & reference value ES的变量可包含2种值类型: 原始值、引用值。 "原始值 primitive value"是最简原子化数据单位。 "引用值 reference value"是由多个值一起构成的对象。 存储原始值的变量,在访问该变量时,直接访问该原始值。称"按值访问(by value)"。 存储引用值的变量,在访问该变量时,访问该变量的引用。称"按引用访问(by reference)"。 注意,在大多数语言中,字串是作为对象存储的。 1.动态属性 dynamic properties 对一个引用型变量(引用型的值必然是对象),可以动态修改其属性。 1.例子 ```js let psycho = new Object() psycho.name = 'Joe' ``` 2.复制值 copying values 原始值是简单值,存放在栈中;引用值是复杂值,存放在堆中。 栈的查找速度更快;堆的存储空间更大。 原始值不可更改,相当稳定;引用值可以自由扩展,需求空间。 1.赋值的底层机制 给变量复制一个 1、原始值 向目标变量复制进的是`值` 1.例子 ```js let a = 66 let b = a ``` 名 值 ·--------------------· ·--------------------· | a | 66 | | a | 66 | ·--------------------· ·--------------------· | | | => | b | 66 | ·--------------------· ·--------------------· | | | | | | ·--------------------· ·--------------------· 2、引用值 向目标变量复制进的是`引用` 1.例子 ```js let a = new Object() let b = a ``` 名 值 ·--------------------· ·--------------------· | a | ref_Object | | a | ref_Object | ·--------------------· ·--------------------· | | | => | b | ref_Object | ·--------------------· ·--------------------· | | | | | | ·--------------------· ·--------------------· 3.函数传参 argument passing [-参考: 《JS传参: 传值还是传引用?》 https://zhuanlan.zhihu.com/p/234992146 -] 1.原理 在向函数传参时,函数内部会建立相应的参数名变量,然后复制一份入参的值给参数名变量。参数名变量在下面简称为“名变量”。 也即: 当入参的值是基本值,名变量直接赋为该基本值。(如 1、123、'abc' 等) 当入参的值是引用值,名变量直接赋为该引用值。(如 0x00001001、0x00001002 等) 在表现上,非常类似于传入引用,但其实不是。是在本地创建了对入参值复制的名变量。 [-补充: 这一过程其实就如同普通的变量复制值 1.例子 ```js let a = { aa: 'aaa' } let b = a b = { bb: 'bbb' } ``` 在最后一行,如果将 b 覆写,将会消除 b 与 a 的联系。 -] 1.例子 ```js /* 01 */ function setName(obj) /* 02 */ { /* 03 */ obj.name = 'Nicholas' /* 04 */ obj = new Object() /* 05 */ obj.name = 'Greg' /* 06 */ } /* 07 */ /* 08 */ let person = new Object() /* 09 */ setName(person) /* 10 */ /* 11 */ console.log(person.name) // "Nicholas" ``` 1.解析 在 01 行,传入的变量 obj 其实是对 person 的值的复制(一个函数域的名变量)。 在 04 行,被覆写的是这个名变量 obj,所以并不影响外部的 person。 4.判定类型 determining type 1.判定变量的原始类型 判定变量的原始类型,使用`typeof`操作符。 typeof 操作符用来判定原始值时很好用,它会如实返回 string、number、boolean、undefined 的结果。 但是,对于是 null 或 object 类型的值,它都会返回 object。 1.typeof 1.语法 ```js typeof some_value ``` 语句返回被判定值的类型字串(有 'string'、'number'、'boolean'、'undefined'、'symbol'、'object'、、) [-补充: 1.完整的 typeof 判定表 类型: 判定结果: `Undefined` "undefined" `Null` "object" // 原因参见下方主题 `Boolean` "boolean" `Number` "number" `BigInt` "bigint" `String` "string" `Symbol` "symbol" `Function` "function" `Class` "function" // 类(Class)等价于 function `任何其它对象` "object" 2.typeof null 的历史源流 typeof null 会判定为 object。这是 JS 语言本身的设计失误。 在 JS 的最初实现中,JS 中的值是由一个类型标记标签和实际数据值联合表示的。 对象的类型标签是`0`,而 null 在语义上表示「空指针」(空指针在绝大多数平台下的值被设为 0x00)。因为这个缘故,null 的类型标签也被记为 0,与 Object 的类型标签相同。 ES 标准委员会曾有过判定 null 为 null 的提案,但是被否了[笑哭]。 -] 2.判定变量的引用类型 实际上,大多数时候我们并不关心一个值是不是对象类型,而是想知道它是什么类型的对象。 为此,使用`instanceof`操作符。 1.instanceof 1.语法 ```js some_instance instanceof SomeClass ``` 语句返回布尔值,是否左侧实例是右侧指定的引用类型。为真则表明实例变量属于该类。 用 instanceof 检测 Object 构造函数,将恒返回 true。因为所有引用类型都是 Object 的实例。 用 instanceof 检测 原始值,将恒返回 false。因为原始值不是对象。 2.执行上下文 & 作用域 execution context & scope "执行上下文 (execution context)"简称"上下文 (context)"。变量/函数的上下文决定了它们可访问的数据,以及它们的行为。 每个上下文都有一个关联的"变量对象 (variable object)",所有在该上下文中定义的变量/函数都存在于这个对象上。变量对象无法通过代码访问(因为是实现在语言规范/引擎上的),但是后台在处理数据时会用到它。 +1.全局上下文 global execution context 执行上下文有两种,函数上下文(即一般上下文)和全局上下文。 全局上下文是最外层的上下文,根据ES的宿主环境不同而不同。 在浏览器环境中,全局上下文是`window` 在 Node.js 环境中,全局上下文是`global` 1.全局上下文中的 var、let、const 声明 在全局上下文中,声明的 var、let、const 都会存在于上下文中,但只有 var 声明的变量会被添加到全局对象上。 上下文在其所有代码都执行完后,会被销毁。 +2.ES代码执行流 每个"函数调用 (function call)"都有自己的上下文。当"代码执行 (code execution)"流入函数时,函数的上下文会被推入一个"上下文栈 (context stack)"。在函数执行完之后,上下文栈会弹出该函数上下文,将控制权返还给之前的执行上下文。 上下文在执行其中代码时,(引擎)会创建一个由上下文变量对象们构成的"作用域链 (scope chain)"。作用域链提供了,对,执行上下文进入的所有变量与函数的顺序访问。 [-补充|资料: 参考资料 <[link] url="https://softwareengineering.stackexchange.com/questions/189967/what-is-an-activation-object-in-javascript"> 参考资料 <[link] url="https://stackoverflow.com/questions/6337344/activation-and-variable-object-in-javascript/21324672#21324672"> 1.执行上下文 execution context "执行上下文 (execution context)"是一个由 1、"变量对象 (variable object)" 若当前执行在函数,则这个变量对象在性质上是"活动对象 (activation object)" 2、"作用域链 (scope chain)" 外部逐层的上下文变量对象构成的顺序链。 3、"this"值 一起构成的对象。 2.变量对象 variable object "变量对象 (variable object)"是一个抽象概念。 1、在当前执行上下文是"全局 (global)"时,变量对象就是「全局」。 取决于环境,「全局」可以是`window`、`document`、`global`等。 2、在当前执行上下文是"函数 (function)"时,变量对象就是"活动对象 (activation object)"。 应当注意到,ECMAScript 规定了,函数是定义作用域的源。 3.活动对象 activation object "活动对象 (activation object)"是一个由 1、当前函数的合法的入参们。 2、当前函数的入参集合`arguments`对象。 3、当前函数的内部的任何变量与(具名)函数。 一起构成的对象。 -] 作用域链的最前端,总是,当前执行上下文的变量对象。 若当前执行上下文是函数,而非根环境,则其变量对象被特别称为"活动对象 (activation object)"。活动对象仅在函数执行时被创建。 作用域链的下一节,是包含上下文的变量对象。 作用域链的下下一节,是包包含上下文的变量对象。 作用域链的下下下一节,是包包包含上下文的变量对象。 . . . 直至全局上下文(根环境)。 1.例子 ```js function compare(value1,value2) { if(value1 < value2) { return -1 } else if(value1 > value2) { return 1 } else { return 0 } } var result = compare(5, 10) ``` 1.解析 在全局执行上下文中,执行到"调用 compare() 函数"时,JS 引擎创建了一个活动对象: 活动对象 = { arguments: [5, 10], value1: 5, value2: 10, } +3.标识符解析 在代码执行时,"标识符 (identifier)"的解析是沿着作用域逐级搜索标识符名完成的。从作用域链最前端逐级向后搜索。如果在一次搜索中没有找到标识符,则报错。 1.例子 - 向上查找一级 ```js var color = 'blue' function changeColor() { if(color === 'blue') { color = 'red' } else { color = 'blue' } } changeColor() ``` 对于这个例子,函数 changeColor() 的作用域链包含两个对象: 1、它自己的变量对象 2、全局上下文的变量对象 changeColor() 能够访问到变量 color,是因为在这个函数的作用域链向上(向外)查找,可以找到标识名为 color 的值。 2.例子 - 向上查找多级 ```js var color = 'blue' function changeColor() { let anotherColor = 'red' function swapColors() { let tempColor = anotherColor anotherColor = color color = tempColor // 这里可以访问color、anotherColor 和tempColor } // 这里可以访问color 和anotherColor,但访问不到tempColor swapColors(); } // 这里只能访问color changeColor(); ``` 注意,函数参数也是当前上下文的变量(这在函数参数按值传递时讲过),和上下文中其他变量遵循一样的访问行为。 1.作用域链增强 scope chain augmentation 执行上下文主要是「全局上下文」、「函数上下文」两种,另外在 eval() 调用的内部会存在第三种「eval上下文」。 某些语句可以在作用域链前端临时添加一个上下文,这个上下文在代码执行完后会被删除。这在如下两种情况时会发生: 1、try/catch 语句的 catch 2、with 语句 1.catch catch 语句会创建一个新的变量对象,这个变量对象包含对抛出的错误对象的声明。 2.with 在作用域链前端添加一个指定的对象(该对象是代码中的显式的对象,而不是上下文变量对象,那个是访问不到的)。 [-资料: 《JavaScript中 with 的用法》 https://zhuanlan.zhihu.com/p/97850060 -] 1.语法 with(some_object) { // executions } [-注释:以下主题是扩展内容-] 2.例子 ```js var a_quite_long_name_object = { a: 1, b: 2, c: 3, } // 要更新其中的项,正常写法是 // a_quite_long_name_object.a = 2 a_quite_long_name_object.b = 3 a_quite_long_name_object.c = 4 // 要更新其中的项,with写法是 // with(a_quite_long_name_object) { a = 3 b = 4 c = 5 } // 奇技淫巧了属于是 ~ ``` 3.缺陷 1、数据泄露 2、性能下降 4.最佳实践 不要使用 with 2.变量声明 variable declaration 未作声明而直接初始化的变量,会被添加到全局上下文。 [-补充: 在严格模式下,未作声明而直接初始化变量的语句,会直接报错。 -] 1.var `var`声明的变量,会被自动添加到最近的上下文。 1.声明提升 hoisting JS引擎会检查函数中所有的 var 声明,将它们通通提到函数顶部,位于所有其他代码前。 [-补充|注释: 这一提升行为在正式顺序执行代码前被执行一遍。 如此设计的考虑是,不用考虑作用域中是否已经定义了同名变量,允许随意新建声明。 -] 2.let let 跟正常编程语言一样,必须先声明再使用,且不能重复声明。 1.块作用域 let 声明的变量,只作用于所在代码块中。 [-扩展: 1.块级作用域 由最近的一对花括号`{}`框定包含的词法范围是一个块作用域。 也即,if 块、while 块、function 块、或甚至单独手写的一个花括号范围,都是块作用域。 -] 2.暂时性死区 let 必须先声明后使用。 。。。略教科书解释。 [-补充: 1.暂时性死区 Temporal Dead Zone "暂时性死区 (Temporal Dead Zone)"是一种状态,表示变量"不可达 (unreachable)"。 严格来讲,在实际的 JS 运行时中,let 和 const 也会在第一遍的代码扫描中被提升到顶部,引擎是知道代码中存在这些标识名的 let 和 const 声明的。 但是,在直到真正执行到其声明前,的一片执行区域中,这些变量都是不可达的(而 var 声明的标识名会作 undefined)。 总结而言,「暂时性死区」就是,变量尽管被提升了,但在其正式声明前都不可用,的一片区域(一种状态)。 -] 3.const const 的用法与 let 基本一致。额外的,const 必须显式初始化。 1.必须显式初始化 const 声明必须显式初始化,否则编译器报错。 1.例子 ```js const a // SyntaxError: Missing initializer in const declaration ``` 2.声明的顶级原语不可变 immutable toplevel const 声明的引用不可变,也即,其声明的基本值或对象不可改。 不过声明的对象的内容可改,因为那就不是 const 的顶级原语了。 如果要令声明的整个对象不可改,使用 Object.freeze()。 2.最佳实践 在可能的情况下,尽量多的使用 const。有两点原因: 1、const 声明暗示变量的类型不变,可被 JS 引擎优化。 2、const 声明明示变量的值不变,避免了意外的重新赋值导致的bug。 4.标识符查找 identifier lookup 。。。 参见章节 <[link] url="#2"> 3.垃圾回收(GC) garbage collection JavaScript 是一门使用了垃圾回收的语言,意为,执行环境负责在代码执行时管理内存。 相对比的,在 C、C++ 中,需要开发者自己手动跟踪管理内存使用,这带来巨大的开发负担,同时也易造成诸多问题。 垃圾回收程序会周期型的自动运行。 浏览器垃圾回收主要有标记清理、引用计数这两种策略。 1.标记清理 mark-and-sweep 标记清理是JS中最常用的GC策略。 1.机制 当变量进入执行上下文,如在函数中声明一个变量,该变量被标记为“存在于执行上下文中”;当变量离开执行上下文,该变量被标记为“脱离于执行上下文外”。 在GC周期时,只保留标记在上下文中的变量,清除其他的,释放内存。 2.引用计数 引用计数是JS中较少用的GC策略。 1.机制 声明一个变量,然后赋给它一个引用值时,这个值的引用数为1。 当该值也被分配给另一个变量,该值引用数+1。 当某个变量断开了对该值的引用,该值引用数-1。 在下一个GC周期,释放引用数为0的值的内存。 1.缺陷 1.循环引用 circular reference 当两个对象互相含有指向对方的指针,它们永远不会被释放。 3.性能 GC的周期调度策略,各浏览器厂家的引擎不尽相同。 4.内存管理 操作系统分配给浏览器的内存通常比桌面软件要少很多,主要是出于安全考虑,避免脚本吃太多内存。所以内存管理就很重要。 +1.解除引用 dereferencing 如果一个数据不再需要,将它设置为null,从而释放引用。 此方法尤其适合于全局变量/全局属性,因为全局环境不会被标记清扫。 1.通过 const、let 提升性能 const、let 以块(而非函数)作为作用域,比函数作用域的标记判定细粒度更小,能更早地令GC介入。 2.隐藏类和删除操作 hidden class & delete 【】 3.内存泄漏 memory leaks 在开发者代码中,绝大部分的内存泄漏都是不合理的引用导致的。通常在这些情况下发生: 1.意外创建的全局变量 1.例子 ```js function setName() { name = 'Psycho' } ``` 变量 name 会被添加到 window 上并常驻存在。 不过一个正常的开发者应该不会有这么不规范的写法。 2.闭包引用 关于闭包的内容详见 <[link] url="file://./10.函数.awn?to=#14.2"> 1.例子 - 函数闭包 ```js let outer = function() { let name = 'Psycho' return function() { return name } } ``` 调用 outer() 会导致 name 的内存被泄露。只要 outer() 返回的函数存在,就会一直持有对 name 的引用。 2.例子 - 定时器闭包 ```js let name = 'Psycho' setInterval(() => { console.log(name) }, 100) ``` 只要定时器一直在运行,回调函数中引用的 name 就会一直占用内存。 4.静态分配与对象池 static allocation & object pools 这个属于极端优化,在大多数时候是过早优化,不用考虑。 。。。 // DOCEND
/* * Copyright (C) 2016 - present Instructure, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.instructure.student.fragment import android.content.res.ColorStateList import android.content.res.Configuration import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.appcompat.app.AlertDialog import androidx.appcompat.widget.AppCompatCheckedTextView import com.instructure.canvasapi2.models.CanvasContext import com.instructure.canvasapi2.models.ToDo import com.instructure.canvasapi2.utils.pageview.PageView import com.instructure.interactions.router.Route import com.instructure.pandautils.analytics.SCREEN_VIEW_TO_DO_LIST import com.instructure.pandautils.analytics.ScreenView import com.instructure.pandautils.binding.viewBinding import com.instructure.pandautils.features.discussion.router.DiscussionRouterFragment import com.instructure.pandautils.utils.* import com.instructure.student.R import com.instructure.student.adapter.TodoListRecyclerAdapter import com.instructure.student.databinding.FragmentListTodoBinding import com.instructure.student.databinding.PandaRecyclerRefreshLayoutBinding import com.instructure.student.features.assignments.details.AssignmentDetailsFragment import com.instructure.student.interfaces.NotificationAdapterToFragmentCallback import com.instructure.student.router.RouteMatcher @ScreenView(SCREEN_VIEW_TO_DO_LIST) @PageView class ToDoListFragment : ParentFragment() { private val binding by viewBinding(FragmentListTodoBinding::bind) private lateinit var recyclerViewBinding: PandaRecyclerRefreshLayoutBinding private var canvasContext by ParcelableArg<CanvasContext>(key = Const.CANVAS_CONTEXT) private var recyclerAdapter: TodoListRecyclerAdapter? = null private var adapterToFragmentCallback: NotificationAdapterToFragmentCallback<ToDo> = object : NotificationAdapterToFragmentCallback<ToDo> { override fun onRowClicked(todo: ToDo, position: Int, isOpenDetail: Boolean) { recyclerAdapter?.setSelectedPosition(position) onRowClick(todo) } override fun onRefreshFinished() { if (!isAdded) return setRefreshing(false) binding.editOptions.setGone() if (recyclerAdapter?.size() == 0) { setEmptyView(recyclerViewBinding.emptyView, R.drawable.ic_panda_sleeping, R.string.noTodos, R.string.noTodosSubtext) } } override fun onShowEditView(isVisible: Boolean) { binding.editOptions.setVisible(isVisible) } override fun onShowErrorCrouton(message: Int) = Unit } override fun title(): String = getString(R.string.Todo) override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? { return layoutInflater.inflate(R.layout.fragment_list_todo, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { recyclerViewBinding = PandaRecyclerRefreshLayoutBinding.bind(binding.root) with (binding.toolbar) { inflateMenu(R.menu.fragment_list_todo) menu.findItem(R.id.todoListFilter).setOnMenuItemClickListener { showCourseFilterDialog() true } } recyclerAdapter = TodoListRecyclerAdapter(requireContext(), canvasContext, adapterToFragmentCallback) recyclerAdapter?.let { configureRecyclerView( view, requireContext(), it, R.id.swipeRefreshLayout, R.id.emptyView, R.id.listView ) } recyclerViewBinding.listView.isSelectionEnabled = false binding.confirmButton.text = getString(R.string.markAsDone) binding.confirmButton.setOnClickListener { recyclerAdapter?.confirmButtonClicked() } binding.cancelButton.setText(R.string.cancel) binding.cancelButton.setOnClickListener { recyclerAdapter?.cancelButtonClicked() } updateFilterTitle(recyclerAdapter?.getFilterMode() ?: NoFilter) binding.clearFilterTextView.setOnClickListener { recyclerAdapter?.loadDataWithFilter(NoFilter) updateFilterTitle(recyclerAdapter?.getFilterMode() ?: NoFilter) } } private fun updateFilterTitle(filterMode: FilterMode) { binding.clearFilterTextView.setVisible(filterMode != NoFilter) binding.todoFilterTitle.setText(filterMode.titleId) } override fun onActivityCreated(savedInstanceState: Bundle?) { super.onActivityCreated(savedInstanceState) binding.toolbar.title = title() navigation?.attachNavigationDrawer(this, binding.toolbar) } override fun applyTheme() { setupToolbarMenu(binding.toolbar) ViewStyler.themeToolbarColored(requireActivity(), binding.toolbar, ThemePrefs.primaryColor, ThemePrefs.primaryTextColor) } override fun onConfigurationChanged(newConfig: Configuration) { super.onConfigurationChanged(newConfig) recyclerAdapter?.let { configureRecyclerView( requireView(), requireContext(), it, R.id.swipeRefreshLayout, R.id.emptyView, R.id.listView, R.string.noTodos ) } if (recyclerAdapter?.size() == 0) { recyclerViewBinding.emptyView.changeTextSize() if (resources.configuration.orientation == Configuration.ORIENTATION_PORTRAIT) { if (isTablet) { recyclerViewBinding.emptyView.setGuidelines(.24f, .53f, .62f, .12f, .88f) } else { recyclerViewBinding.emptyView.setGuidelines(.28f, .6f, .73f, .12f, .88f) } } else { if (isTablet) { //change nothing, at least for now } else { recyclerViewBinding.emptyView.setGuidelines(.2f, .7f, .74f, .15f, .85f) } } } } private fun onRowClick(toDo: ToDo?) { when { toDo?.assignment != null -> { // Launch assignment details fragment. if (toDo.assignment!!.discussionTopicHeader != null) { val groupTopic = toDo.assignment!!.discussionTopicHeader!!.groupTopicChildren.firstOrNull() if (groupTopic == null) { // Launch discussion details fragment RouteMatcher.route(requireActivity(), DiscussionRouterFragment.makeRoute(toDo.canvasContext!!, toDo.assignment!!.discussionTopicHeader!!)) } else { // Launch discussion details fragment with the group RouteMatcher.route(requireActivity(), DiscussionRouterFragment.makeRoute(CanvasContext.emptyGroupContext(groupTopic.groupId), groupTopic.id)) } } else { // Launch assignment details fragment. RouteMatcher.route(requireActivity(), AssignmentDetailsFragment.makeRoute(toDo.canvasContext!!, toDo.assignment!!.id)) } } toDo?.scheduleItem != null -> // It's a Calendar event from the Upcoming API. RouteMatcher.route(requireActivity(), CalendarEventFragment.makeRoute(toDo.canvasContext!!, toDo.scheduleItem!!)) toDo?.quiz != null -> // It's a Quiz let's launch the quiz details fragment RouteMatcher.route(requireActivity(), BasicQuizViewFragment.makeRoute(toDo.canvasContext!!, toDo.quiz!!, toDo.quiz!!.url!!)) } } private fun showCourseFilterDialog() { val choices = arrayOf(getString(R.string.favoritedCoursesLabel)) var checkedItem = choices.indexOf(getString(recyclerAdapter?.getFilterMode()?.titleId ?: NoFilter.titleId)) val dialog = AlertDialog.Builder(requireContext()) .setTitle(R.string.filterByEllipsis) .setSingleChoiceItems(choices, checkedItem) { _, index -> checkedItem = index }.setPositiveButton(android.R.string.ok) { _, _ -> if (checkedItem >= 0) recyclerAdapter?.loadDataWithFilter(convertFilterChoiceToMode(choices[checkedItem])) updateFilterTitle(recyclerAdapter?.getFilterMode() ?: NoFilter) }.setNegativeButton(android.R.string.cancel, null) .create() dialog.setOnShowListener { dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ThemePrefs.textButtonColor) dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ThemePrefs.textButtonColor) dialog.listView.children<AppCompatCheckedTextView>().forEach { checkbox -> checkbox.compoundDrawableTintList = ColorStateList.valueOf(ThemePrefs.brandColor) } } dialog.show() } private fun convertFilterChoiceToMode(filter: String) : FilterMode { return when (filter) { getString(FavoritedCourses.titleId) -> FavoritedCourses else -> NoFilter } } override fun onDestroyView() { super.onDestroyView() recyclerAdapter?.cancel() } companion object { fun makeRoute(canvasContext: CanvasContext): Route = Route(ToDoListFragment::class.java, canvasContext, Bundle()) private fun validateRoute(route: Route) = route.canvasContext != null fun newInstance(route: Route): ToDoListFragment? { if (!validateRoute(route)) return null return ToDoListFragment().withArgs(route.canvasContext!!.makeBundle()) } } } sealed class FilterMode(val titleId: Int) object FavoritedCourses : FilterMode(R.string.favoritedCoursesLabel) object NoFilter : FilterMode(R.string.allCourses)
// // Document.swift // Blocks // // Created by 沈畅 on 5/8/19. // Copyright © 2019 Chang Shen. All rights reserved. // import UIKit class Document: UIDocument { struct BlocksBundle: Codable { let blocks: [Block] let deletedUUIDs: Set<UUID> } static let blocksChangedNotification: Notification.Name = Notification.Name("DocumentBlocksChangedNotification") // Observe this notificationCenter for document changes let notificationCenter = NotificationCenter() private var blocks = [Block]() private var deletedUUIDs = Set<UUID>() private var blockChanges = [BlockChange]() // Called by View Controller func startObservingDocumentStateNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(self.documentStateChanged), name: UIDocument.stateChangedNotification, object: nil) } @objc private func documentStateChanged(notification: Notification) { print() print(" 🔀documentStateChanged: \(documentStateString()) [\(hasUnsavedChanges ? "hasUnsavedChanges💾" : "nothingToSave🤷‍♂️")]") if documentState.contains(.inConflict) { resolveConflict() } } // MARK: UIDocument Override override func contents(forType typeName: String) throws -> Any { // Encode your document with an instance of NSData or NSFileWrapper let jsonEncoder = JSONEncoder() jsonEncoder.outputFormatting = .prettyPrinted let data = try! jsonEncoder.encode(BlocksBundle(blocks: blocks, deletedUUIDs: deletedUUIDs)) as NSData let compressedData = try data.compressed(using: .zlib) print() print("✍️contents(forType:) Time: \(Date()) DEBUG: \(blocksDebugString(blocks: blocks)) DELETED: \(deletedBlocksDebugString(deletedUUIDs: deletedUUIDs))") return compressedData } override func load(fromContents contents: Any, ofType typeName: String?) throws { // Load your document from contents let data = contents as! NSData let decompressedData = try data.decompressed(using: .zlib) as Data let jsonDecoder = JSONDecoder() let decodedBundle = try jsonDecoder.decode(BlocksBundle.self, from: decompressedData) let decodedBlocks = decodedBundle.blocks let decodedDeletedUUIDs = decodedBundle.deletedUUIDs deletedUUIDs = deletedUUIDs.union(decodedDeletedUUIDs) print() print("\(self.documentState.contains(.closed) ? " " : "")📖load(fromContents:) Time: \(Date()) ") // May 15 5:29 PM if !documentState.contains(.closed) { // Document is open // May 15 5:29 PM. Attempting to merge within load(fromContents:) //blockChanges = findChange(old: blocks, new: decodedBlocks) let merged = merge(first: blocks, second: decodedBlocks, deleted: deletedUUIDs) //print("📖Merged: \(blocksDebugString(blocks: merged))") blockChanges = findChange(old: blocks, new: merged) // End May 15 5:29 PM print(" BLOCK CHANGES: " + blockChanges.debugDescription) if !blockChanges.isEmpty { //print(" OLD BLOCKS: \(blocksDebugString(blocks: blocks))") blocks = merged // Send notification notificationCenter.post(name: Document.blocksChangedNotification, object: nil) } } else { blocks = decodedBlocks print(" document is closed. No notification sent") } } override func handleError(_ error: Error, userInteractionPermitted: Bool) { super.handleError(error, userInteractionPermitted: userInteractionPermitted) print(error) } } // Methods for Controller (API) extension Document { func addBlock(_ block: Block, atIndex index: Int? = nil) { blockChanges = [BlockChange.insert(block: block, index: index ?? blocks.count)] blocks.insert(block, at: index ?? blocks.count) notificationCenter.post(name: Document.blocksChangedNotification, object: nil) } func deleteBlock(at index: Int, addToDeletedUUIDs: Bool = true) { guard index >= 0 && index < blocks.count else { fatalError() } let blockToDelete = blocks[index] if addToDeletedUUIDs { deletedUUIDs.insert(blockToDelete.uuid) } blocks.remove(at: index) blockChanges = [BlockChange.delete(index: index)] notificationCenter.post(name: Document.blocksChangedNotification, object: nil) } func setBlockUsesRoundedCorners(at index: Int, _ usesRoundedCorners: Bool) { guard index >= 0 && index < blocks.count else { fatalError() } blocks[index].usesRoundedCorners = usesRoundedCorners blocks[index].modificationDate = Date() blockChanges = [BlockChange.modify(block: blocks[index], index: index)] notificationCenter.post(name: Document.blocksChangedNotification, object: nil) } func removeDeletedUUID(uuid: UUID) { deletedUUIDs.remove(uuid) } func blocksIterator() -> IndexingIterator<[Block]> { return blocks.makeIterator() } func getBlockChanges() -> [BlockChange] { return blockChanges } func getNumberOfBlocks() -> Int { return blocks.count } func getBlock(at index: Int) -> Block? { return (0 <= index && index < blocks.count) ? blocks[index] : nil } } extension Document { private func findChange(old: [Block], new: [Block]) -> [BlockChange] { //let patches = patch(from: old, to: new) let patches = new.difference(from: old) var blockChanges = [BlockChange]() for patch in patches { switch patch { case .insert(let offset, let element, _): blockChanges.append(BlockChange.insert(block: element, index: offset)) case .remove(let offset, _, _): blockChanges.append(BlockChange.delete(index: offset)) } } // Find modifications var newDictionary = [UUID:(Int,Block)]() for (index, newBlock) in new.enumerated() { newDictionary[newBlock.uuid] = (index,newBlock) } for oldBlock in old { guard let (index,newBlock) = newDictionary[oldBlock.uuid] else { continue } // If new does not contain oldBlock identifier, skip if !newBlock.fullyEquals(other: oldBlock) { blockChanges.append(BlockChange.modify(block: newBlock, index: index)) } } // print("==findChange==") // print("Old: \(blocksDebugString(blocks: old))") // print("New: \(blocksDebugString(blocks: new))") // print("Changes: \(blockChanges)") return blockChanges } func resolveConflict() { print() print("===⚠️resolveConflict()⚠️===") var bundleVersions = [BlocksBundle]() print(" Current blocks: \(blocksDebugString(blocks: blocks))") let conflictVersions = NSFileVersion.unresolvedConflictVersionsOfItem(at: self.fileURL)! print(" unresolvedConflictVersions Count: \(conflictVersions.count)") for conflictVersion in conflictVersions { let conflictDocument = Document(fileURL: conflictVersion.url) print(" ===BEGIN OPENING CONFLICT DOCUMENT===") let fileCoordinator = NSFileCoordinator(filePresenter: nil) var readingError: NSError? = nil fileCoordinator.coordinate(readingItemAt: conflictVersion.url, options: [], error: &readingError) { (url) in do { try conflictDocument.read(from: conflictVersion.url) bundleVersions.append(BlocksBundle(blocks: conflictDocument.blocks, deletedUUIDs: conflictDocument.deletedUUIDs)) //print(" Conflict document blocks: \(blocksDebugString(blocks: conflictDocument.blocks))") print(" ===END OPENING CONFLICT DOCUMENT===") } catch { fatalError("Failed to read from conflictDocument. Error \(error)") } } } let result = BlocksBundle(blocks: self.blocks, deletedUUIDs: self.deletedUUIDs) let merged = bundleVersions.reduce(into: result) { (result, bundle) in let mergedDeletedUUIDs = result.deletedUUIDs.union(bundle.deletedUUIDs) let mergedBlocks = merge(first: result.blocks, second: bundle.blocks, deleted: mergedDeletedUUIDs) result = BlocksBundle(blocks: mergedBlocks, deletedUUIDs: mergedDeletedUUIDs) } blockChanges = findChange(old: self.blocks, new: merged.blocks) print(" BLOCK CHANGES: \(blockChanges)") print(" Reminder: Current blocks: \(blocksDebugString(blocks: blocks))") if !blockChanges.isEmpty { // Send notification notificationCenter.post(name: Document.blocksChangedNotification, object: nil) blocks = merged.blocks // Only update blocks if there are changes } if (deletedUUIDs != merged.deletedUUIDs) { deletedUUIDs = merged.deletedUUIDs } do { print(" Begin to removeOtherVersions") print(" Current: \(NSFileVersion.currentVersionOfItem(at: self.fileURL)!.modificationDate!)") let conflictVersions = NSFileVersion.unresolvedConflictVersionsOfItem(at: self.fileURL)! for conflictVersion in conflictVersions { print(" RemovedConflict: \(conflictVersion.modificationDate!)") conflictVersion.isResolved = true } try NSFileVersion.removeOtherVersionsOfItem(at: self.fileURL) } catch { fatalError() } print("===END resolveConflict()===") } // https://stackoverflow.com/questions/51404787/how-to-merge-two-sorted-arrays-in-swift func merge(first: [Block], second: [Block], deleted: Set<UUID>) -> [Block] { let all = first + second.reversed() let merged = all.reduce(into: (all, [Block]()), { (result, block) in guard let firstBlock = result.0.first else { return } guard let lastBlock = result.0.last else { return } if firstBlock.creationDate < lastBlock.creationDate { result.0.removeFirst() if !deleted.contains(firstBlock.uuid) { result.1.append(firstBlock) } } else if firstBlock.creationDate > lastBlock.creationDate { result.0.removeLast() if !deleted.contains(lastBlock.uuid) { result.1.append(lastBlock) } } else { result.0.removeFirst() if result.0.count >= 1 && firstBlock == lastBlock { // Last one only need to be removed once. result.0.removeLast() } if !deleted.contains(firstBlock.uuid) { // Append the version with the latest modification date. let useFirstBlock = firstBlock.modificationDate > lastBlock.modificationDate result.1.append(useFirstBlock ? firstBlock : lastBlock) } } }).1 print() print(" ===🥣MERGE🥣===") print(" First: \(blocksDebugString(blocks: first))") print(" Second: \(blocksDebugString(blocks: second))") print(" Deleted: \(deletedBlocksDebugString(deletedUUIDs: deleted))") print(" Merged: \(blocksDebugString(blocks: merged))") print(" ===END MERGE===") print() return merged } } // Debug string for blocks extension Document { func blocksDebugString() -> String { return "BLOCKS: " + blocksDebugString(blocks: self.blocks) + " DELETED: " + deletedBlocksDebugString(deletedUUIDs: self.deletedUUIDs) } private func blocksDebugString(blocks: [Block]) -> String { return blocks.map{$0.uuid.uuidString}.reduce("Count: \(blocks.count), UUIDs: {", {$0 + $1 + ", "}) + "}" } private func deletedBlocksDebugString(deletedUUIDs: Set<UUID>) -> String { return deletedUUIDs.map{$0.uuidString}.reduce("Count: \(deletedUUIDs.count), UUIDs: {", {$0 + $1 + ", "}) + "}" } func documentStateString() -> String { return documentState.debugDescription } } extension UIDocument.State: CustomDebugStringConvertible { public var debugDescription: String { var str = "" if self.contains(.normal) { str += "Normal, " } if self.contains(.closed) { str += "Closed, " } if self.contains(.inConflict) { str += "In conflict, " } if self.contains(.savingError) { str += "Saving error, " } if self.contains(.editingDisabled) { str += "Editing disabled, " } if self.contains(.progressAvailable) { str += "Progress available, " } str.removeLast(2) return str } }
import io import datetime import zipfile import functools import numpy as np import pandas as pd import requests import slr import slr.wind def missing2nan(value, missing=-99999): """convert the value to nan if the float of value equals the missing value""" value = float(value) if value == missing: return np.nan return value def year2date(year_fraction, dtype="datetime64[s]"): """convert a fraction of a year + fraction of a year to a date, for example 1993.083 -~> 1993-02-01. The dtype should be a valid numpy datetime unit, such as datetime64[s]""" startpoints = np.linspace(0, 1, num=12, endpoint=False) remainder = np.mod(year_fraction, 1) year = np.floor_divide(year_fraction, 1).astype("int") month = np.searchsorted(startpoints, remainder) if (month == 0).all(): # if month is set to 0 (for annual data), set to january month = np.ones_like(month) dates = [ datetime.datetime(year_i, month_i, 1) for year_i, month_i in zip(year, month) ] datetime64s = np.asarray(dates, dtype=dtype) return datetime64s def get_data(zf, station, dataset_name): """get data for the station (pandas record) from the dataset (url)""" info = dict(dataset_name=dataset_name, id=station.name) bytes = zf.read("{dataset_name}/data/{id}.rlrdata".format(**info)) df = pd.read_csv( io.BytesIO(bytes), sep=";", names=("year", "height", "interpolated", "flags"), converters={ "year": lambda x: float(x), "height": lambda x: missing2nan(x), "interpolated": str.strip, }, ) df["station"] = station.name # store time as t df["t"] = year2date(df.year) # use time as an index df = df.set_index("t") return df def get_data_with_wind( station, dataset_name, zipfiles, monthly_wind_df=None, annual_wind_df=None ): """get data for the station (pandas record) from the dataset (url)""" if "monthly" in dataset_name: assert ( monthly_wind_df is not None ), "for monthly dataset, please pass the monthly_wind_df argument" if "annual" in dataset_name: assert ( annual_wind_df is not None ), "for annual dataset, please pass the annual_wind_df argument" info = dict(dataset_name=dataset_name, id=station.name) url_names = get_url_names() bytes = zipfiles[dataset_name].read(url_names[dataset_name].format(**info)) df = pd.read_csv( io.BytesIO(bytes), sep=";", names=("year", "height", "interpolated", "flags"), converters={ "height": lambda x: missing2nan(x) - station["nap-rlr"], "interpolated": str.strip, }, ) df["station"] = station.name # store time as t df["t"] = year2date(df.year, dtype="<M8[ns]") df["alpha"] = station["alpha"] df = df.set_index("t") # merge the wind and water levels if "monthly" in dataset_name: merged = pd.merge( df, monthly_wind_df, how="left", left_index=True, right_index=True, ) else: merged = pd.merge( df, annual_wind_df, how="left", left_index=True, right_index=True, ) # fill in missing wind merged["u"] = merged["u"].fillna(merged["u"].mean()) merged["v"] = merged["v"].fillna(merged["v"].mean()) merged["u2"] = merged["u2"].fillna(merged["u2"].mean()) merged["v2"] = merged["v2"].fillna(merged["v2"].mean()) # recompute speed and direction merged["speed"] = np.sqrt(merged["u"] ** 2 + merged["v"] ** 2) merged["direction"] = np.mod(np.angle(merged["u"] + merged["v"] * 1j), 2 * np.pi) return merged def get_psmsl_urls(local): src_dir = slr.get_src_dir() psmsl_urls_remote = { "met_monthly": "http://www.psmsl.org/data/obtaining/met.monthly.data/met_monthly.zip", "rlr_monthly": "http://www.psmsl.org/data/obtaining/rlr.monthly.data/rlr_monthly.zip", "rlr_annual": "http://www.psmsl.org/data/obtaining/rlr.annual.data/rlr_annual.zip", } psmsl_data_dir = src_dir / "data" / "psmsl" psmsl_urls_local = { "met_monthly": psmsl_data_dir / "met_monthly.zip", "rlr_monthly": psmsl_data_dir / "rlr_monthly.zip", "rlr_annual": psmsl_data_dir / "rlr_annual.zip", } if local: psmsl_urls = psmsl_urls_local else: psmsl_urls = psmsl_urls_remote return psmsl_urls def get_url_names(): url_names = { "datum": "{dataset_name}/RLR_info/{id}.txt", "diagram": "{dataset_name}/RLR_info/{id}.png", "url": "http://www.psmsl.org/data/obtaining/rlr.diagrams/{id}.php", "rlr_monthly": "{dataset_name}/data/{id}.rlrdata", "rlr_annual": "{dataset_name}/data/{id}.rlrdata", "met_monthly": "{dataset_name}/data/{id}.metdata", "doc": "{dataset_name}/docu/{id}.txt", "contact": "{dataset_name}/docu/{id}_auth.txt", } return url_names def get_zipfiles(local=True): zipfiles = {} psmsl_urls = get_psmsl_urls(local=local) for dataset_name, psmsl_url in psmsl_urls.items(): if local: zf = zipfile.ZipFile(psmsl_url) else: resp = requests.get(psmsl_url) # we can read the zipfile stream = io.BytesIO(resp.content) zf = zipfile.ZipFile(stream) zipfiles[dataset_name] = zf return zipfiles def get_station_list(zf, dataset_name="rlr_annual", local=True): # this list contains a table of # station ID, latitude, longitude, station name, coastline code, station code, and quality flag csvtext = zf.read("{}/filelist.txt".format(dataset_name)) stations = pd.read_csv( io.BytesIO(csvtext), sep=";", names=("id", "lat", "lon", "name", "coastline_code", "station_code", "quality"), converters={"name": str.strip, "quality": str.strip}, ) stations = stations.set_index("id") # each station has a number of files that you can look at. # here we define a template for each filename # stations that we are using for our computation # define the name formats for the relevant files url_names = get_url_names() # add url's def get_url(station, dataset_name): """return the url of the station information (diagram and datum)""" info = dict(dataset_name=dataset_name, id=station.name) url = url_names["url"].format(**info) return url psmsl_urls = get_psmsl_urls(local) for dataset_name in psmsl_urls: # fill in the dataset parameter using the global dataset_name f = functools.partial(get_url, dataset_name=dataset_name) # compute the url for each station stations[dataset_name + "_url"] = stations.apply(f, axis=1) return stations def get_main_stations(): src_dir = slr.get_src_dir() main_stations_path = src_dir / "data" / "deltares" / "main_stations.json" main_stations = pd.read_json(main_stations_path) main_stations = main_stations.set_index("id") return main_stations def add_series_to_stations( selected_stations, local=True, wind_product="NCEP1", reference_point_wind=None, gtsm_version="2022", ): zipfiles = get_zipfiles(local=local) monthly_wind_products, annual_wind_products = slr.wind.get_wind_products( reference_point_wind=reference_point_wind ) annual_wind_df = annual_wind_products[wind_product] monthly_wind_df = monthly_wind_products[wind_product] monthly_gtsm_df, annual_gtsm_df = slr.wind.get_gtsm_dfs(version=gtsm_version) # get data for all stations for dataset_name in get_psmsl_urls(local=local): f = functools.partial( # this function fills in missing wind with nan slr.psmsl.get_data_with_wind, dataset_name=dataset_name, # don't include year otherwise we get year_x and year_y monthly_wind_df=monthly_wind_df.drop(columns=["year"]), annual_wind_df=annual_wind_df.drop(columns=["year"]), zipfiles=zipfiles, ) # look up the data for each station selected_stations[dataset_name] = [ f(station) for _, station in selected_stations.iterrows() ] # add surge to stations annual data rlr_annual_dfs = [] rlr_monthly_dfs = [] met_monthly_dfs = [] for idx, station in selected_stations.iterrows(): annual_df = station["rlr_annual"] assert ( station.ddl_id in annual_gtsm_df["ddl_id"].values ), f"ddl_id ({station.ddl_id}) of station: {station.name} not in gtsm" # add gtsm annual_df = pd.merge( annual_df, annual_gtsm_df[annual_gtsm_df.ddl_id == station["ddl_id"]].set_index( "year" )[["surge_mm"]], left_on="year", right_index=True, how="left", ) annual_df["surge_mm"] = annual_df["surge_mm"].fillna( annual_df["surge_mm"].mean() ) annual_df["height - surge"] = annual_df["height"] - annual_df["surge_mm"] annual_df["height - surge anomaly"] = annual_df["height"] - ( annual_df["surge_mm"] - annual_df["surge_mm"].mean() ) rlr_annual_dfs.append(annual_df) # Add gtsm to monthly data rlr_monthly_df = station["rlr_monthly"] monthly_gtsm_df_i = monthly_gtsm_df[ monthly_gtsm_df["ddl_id"] == station["ddl_id"] ] rlr_monthly_df = pd.merge( rlr_monthly_df, monthly_gtsm_df_i[["t", "surge_mm"]], left_index=True, right_on="t", how="left", ) rlr_monthly_df = rlr_monthly_df.set_index("t") rlr_monthly_df["surge_mm"] = rlr_monthly_df["surge_mm"].fillna( rlr_monthly_df["surge_mm"].mean() ) rlr_monthly_df["height - surge"] = ( rlr_monthly_df["height"] - rlr_monthly_df["surge_mm"] ) rlr_monthly_df["height - surge anomaly"] = rlr_monthly_df["height"] - ( rlr_monthly_df["surge_mm"] - rlr_monthly_df["surge_mm"].mean() ) rlr_monthly_dfs.append(rlr_monthly_df) # also for the metric data met_monthly_df = station["met_monthly"] monthly_gtsm_df_i = monthly_gtsm_df[ monthly_gtsm_df["ddl_id"] == station["ddl_id"] ] met_monthly_df = pd.merge( met_monthly_df, monthly_gtsm_df_i[["t", "surge_mm"]], left_index=True, right_on="t", how="left", ) met_monthly_df = met_monthly_df.set_index("t") met_monthly_df["surge_mm"] = met_monthly_df["surge_mm"].fillna( met_monthly_df["surge_mm"].mean() ) met_monthly_df["height - surge"] = ( met_monthly_df["height"] - met_monthly_df["surge_mm"] ) met_monthly_df["height - surge anomaly"] = met_monthly_df["height"] - ( met_monthly_df["surge_mm"] - met_monthly_df["surge_mm"].mean() ) met_monthly_dfs.append(met_monthly_df) selected_stations["rlr_annual"] = rlr_annual_dfs selected_stations["rlr_monthly"] = rlr_monthly_dfs selected_stations["met_monthly"] = met_monthly_dfs return selected_stations def add_aggregated_stations(selected_stations): """add the aggregated stations to the list, note that the psmsl_ids are hard coded.""" aggregated_stations = [ { "ddl_id": "NL", "name": "Netherlands", "psmsl_id": 10000, "idx": [20, 22, 23, 24, 25, 32], }, { "ddl_id": "NL-DELFZL", "name": "Netherlands (without Delfzijl)", "psmsl_id": 10001, "idx": [20, 22, 23, 25, 32], }, ] frames = [selected_stations] for aggregated_station in aggregated_stations: sub_selection = selected_stations.loc[aggregated_station["idx"]] row = { "name_rws": aggregated_station["name"], "name": aggregated_station["name"], "ddl_id": aggregated_station["ddl_id"], "location": aggregated_station["name"], "psmsl_id": aggregated_station["psmsl_id"], "id": aggregated_station["psmsl_id"], } for dataset_name in ["rlr_annual", "rlr_monthly", "met_monthly"]: data_per_station = pd.concat(sub_selection[dataset_name].tolist()) grouped = data_per_station[ ["year", "height", "u2", "v2", "surge_mm"] ].groupby("t") mean_df = grouped.mean().reset_index() # # filter out non-trusted part (before NAP, also with some missing stations) mean_df = mean_df[mean_df["year"] >= 1890].copy() surge = mean_df["surge_mm"] mean_df["station"] = aggregated_station["psmsl_id"] # recompute the surge and anomalies surge = surge.fillna(surge.mean()) mean_df["height - surge"] = mean_df["height"] - surge mean_df["height - surge anomaly"] = mean_df["height"] - ( surge - surge.mean() ) mean_df = mean_df.set_index("t") row[dataset_name] = mean_df frames.append(pd.DataFrame([pd.Series(row, name=row["id"])])) selected_stations = pd.concat(frames) return selected_stations
import { Button, HStack, Heading, Image, List, ListItem, Spinner, Text, } from "@chakra-ui/react"; import useGenres, { Genre } from "../hooks/useGeners"; import getCroppedImageUrl from "../services/image-url"; import GenreSkeleton from "./GenreSkeleton"; interface Props { onSelectGenre: (genre: Genre) => void; selectedGenre: Genre | null; } const GenreList = ({ onSelectGenre, selectedGenre }: Props) => { const { data, isLoading, error } = useGenres(); if (error) return null; const skeleton = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; return ( <> <Heading fontSize="2xl" marginBottom={3}> Genres </Heading> <List> {isLoading && skeleton.map((skel) => ( <ListItem key={skel}> <GenreSkeleton /> </ListItem> ))} {data.map((genre) => ( <ListItem key={genre.id} paddingY={"5px"}> <HStack> <Image objectFit={"cover"} boxSize={"32px"} borderRadius={10} src={getCroppedImageUrl(genre.image_background)} /> <Button whiteSpace={"normal"} textAlign={"left"} fontWeight={genre.id === selectedGenre?.id ? "bold" : "normal"} onClick={() => onSelectGenre(genre)} variant={"link"} fontSize={"lg"} > {genre.name} </Button> </HStack> </ListItem> ))} </List> </> ); }; export default GenreList;
<template> <v-col cols="12" md="4"> <div class="flip-card my-16"> <div class="flip-card-inner border rounded-xl bg-white"> <div class="flip-card-front"> <canvas id="graphe" class="px-4 py-1"> </canvas> </div> </div> </div> </v-col> <v-col cols="12" md="8"> <v-container fluid> <v-responsive class="align-center text-center"> <v-row class="align-center mb-2 mb-md-0"> <v-col cols="12" md="6"> <v-text-field single-line hide-details clearable flat rounded="pill" v-model="search" variant="solo" bg-color="white" label="Rechercher" prepend-inner-icon="mdi-magnify" class="border rounded-pill"></v-text-field> </v-col> <v-col cols="12" md="3" offset-md="3" class="d-flex justify-end"> <v-btn prepend-icon="mdi-plus" color="primary" @click="displayAddDialog()">Ajouter</v-btn> </v-col> </v-row> <v-data-table hover items-per-page-text="Nombre d'éléments par page" fixed-header id="tableau" :headers="tableHeaders" :items="tableItems" :search="search" height="500" class="border rounded-lg"> <template v-slot:headers> <tr> <template v-for="header in tableHeaders" :key="header.value"> <th class="text-button">{{ header.title }}</th> </template> </tr> </template> <template v-slot:item="{ item }"> <tr> <td class="text-left">{{ item.nom }}</td> <td class="text-left">{{ item.nbHeure }}</td> <td class="text-left">{{ item.tauxHoraire }}</td> <td class="text-left">{{ item.nbHeure * item.tauxHoraire }}</td> <td class="text-center"> <v-menu> <template v-slot:activator="{ props }"> <v-btn flat variant="plain" icon="mdi-dots-vertical" size="small" v-bind="props"></v-btn> </template> <v-list class="rounded-lg"> <v-list-item link prepend-icon="mdi-pencil" @click="displayEditDialog(item.numEns)">Editer</v-list-item> <v-divider></v-divider> <v-list-item link prepend-icon="mdi-delete" class="text-red-accent-4" @click="displayDeleteDialog(item.numEns)">Supprimer</v-list-item> </v-list> </v-menu> </td> </tr> </template> <template v-slot:no-data> <tr> <td>Rien n'a été trouvé</td> </tr> </template> </v-data-table> <v-row class="pt-4"> <v-col cols="12"> <div class="d-flex justify-space-evenly border rounded-lg py-5" v-for="max in maxies" :key="max"> <p class="text-button">Salaire minimum : <span class="text-red">{{ max.minSalaire }}</span></p> <p class="text-button">Salaire maximum : <span class="text-green">{{ max.maxSalaire }}</span></p> <p class="text-button">Salaire total : <span class="text-blue">{{ max.totalSalaire }}</span></p> </div> </v-col> </v-row> <v-dialog v-model="dialogEditer" scrollable persistent max-width="650px" transition="dialog-bottom-transition"> <v-card class="px-2 py-4" rounded="lg"> <v-card-title primary-title>Editer</v-card-title> <v-card-item> <v-row class="pt-2"> <v-col cols="12"> <v-text-field rounded="lg" variant="outlined" label="Nom" v-model="nomEnseignant"></v-text-field> </v-col> <v-col cols="12" md="5"> <v-text-field rounded="lg" variant="outlined" label="Nombre d'heures" v-model="nbHeureEnseignant"></v-text-field> </v-col> <v-col cols="12" md="6" offset="0" offset-md="1"> <v-text-field rounded="lg" variant="outlined" label="Taux horaire" v-model="tauxHoraireEnseignant"></v-text-field> </v-col> </v-row> </v-card-item> <v-card-actions class="justify-end"> <v-btn flat color="secondary" @click="dialogEditer = false">Annuler</v-btn> <v-btn flat color="primary" @click="editerEnseignant(choosen.numEns)">Confirmer</v-btn> </v-card-actions> </v-card> </v-dialog> <v-dialog v-model="dialogSupprimer" scrollable persistent max-width="650px" transition="dialog-bottom-transition"> <v-card class="px-2 py-4" rounded="lg"> <v-card-title primary-title>Supprimer</v-card-title> <v-card-item> <p>Voulez-vous supprimer cette ligne ?</p> <v-row class="pt-2"> <v-col cols="12"> <v-table class="border-t border-b py-2"> <tr> <td>{{ choosen.nom }}</td> <td>{{ choosen.nbHeure }}</td> <td>{{ choosen.tauxHoraire }}</td> <td>{{ choosen.nbHeure * choosen.tauxHoraire }}</td> </tr> </v-table> </v-col> </v-row> </v-card-item> <v-card-actions class="justify-end"> <v-btn flat color="secondary" @click="dialogSupprimer = false">Annuler</v-btn> <v-btn flat color="error" @click="supprimerEnseignant(choosen.numEns)">Confirmer</v-btn> </v-card-actions> </v-card> </v-dialog> <v-dialog v-model="dialogAjouter" scrollable persistent max-width="850px" transition="dialog-bottom-transition"> <v-card class="px-2 py-4" rounded="lg"> <v-card-title primary-title>Ajouter</v-card-title> <v-card-item> <v-row class="pt-2"> <v-col cols="12"> <v-text-field rounded="lg" variant="outlined" label="Nom" v-model="nomNew"></v-text-field> </v-col> <v-col cols="12" md="5"> <v-text-field rounded="lg" variant="outlined" label="Nombre d'heures" v-model="nbHeureNew"></v-text-field> </v-col> <v-col cols="12" md="6" offset="0" offset-md="1"> <v-text-field rounded="lg" variant="outlined" label="Taux horaire" v-model="tauxHoraireNew"></v-text-field> </v-col> </v-row> </v-card-item> <v-card-actions class="justify-end"> <v-btn flat color="secondary" @click="dialogAjouter = false">Annuler</v-btn> <v-btn flat color="primary" @click="ajouterEnseignant()">Confirmer</v-btn> </v-card-actions> </v-card> </v-dialog> <v-snackbar variant="tonal" :timeout="snack.timeout" v-model="snack.snackValue" :color="snack.color"> <div class="d-flex align-center justify-space-between"> <p class="px-4">{{ message.message }}</p> <v-btn flat variant="text" @click="snack.snackValue = false">Fermer</v-btn> </div> </v-snackbar> </v-responsive> </v-container> </v-col> </template> <script setup> import { ref, onMounted } from 'vue'; import { $get, $post, $delete } from "../../plugins/axios" let theGraph = null; const dest = ref(null); const items = ref([]); const tableHeaders = [ { title: "Nom", value: "nom", sortable: true, width: "30%" }, { title: "Nombre d'heures", value: "nbHeure", sortable: true, width: "20%" }, { title: "Taux horaire", value: "tauxHoraire", sortable: true, width: "20%" }, { title: "Salaire", value: "salaire", width: "20%" }, { title: "Action", value: "salaire", width: "10%" } ]; const tableItems = ref([]); const maxies = ref([]); const search = ref(null); let message = null; const dialogEditer = ref(false); const dialogSupprimer = ref(false); const dialogAjouter = ref(false); const snack = ref({ snackValue: false, color: "green", timeout: 3000 }); const choosen = ref([]); const nomEnseignant = ref(null); const nbHeureEnseignant = ref(null); const tauxHoraireEnseignant = ref(null); const nomNew = ref(null); const nbHeureNew = ref(null); const tauxHoraireNew = ref(null); const retrieve = async () => { tableItems.value = await $get("enseignants"); items.value = await $get("maxies"); items.value = items.value.shift(); maxies.value = await $get("maxies"); } onMounted(async () => { dest.value = document.getElementById("graphe"); await retrieve(); theGraph = new Chart(dest.value, { type: "doughnut", data: { labels: ["SALAIRE MINIMUM", "SALAIRE MAXIMUM", "SALAIRE TOTAL"], datasets: [{ data: [items.value.minSalaire, items.value.maxSalaire, items.value.totalSalaire], backgroundColor: [ "#FFECB3", "#B2DFDB", "#F0F4C3" ], borderColor: [ "rgba(0, 0, 0, 0.1)" ], borderWidth: 3 }] }, options: { scales: { y: { beginAtZero: true } }, aspectRation: 1, plugins: { legend: { position: "bottom" } } } }); console.log(theGraph); }); const updateChart = () => { theGraph.data.datasets[0].data = [ items.value.minSalaire, items.value.maxSalaire, items.value.totalSalaire ]; theGraph.update(); } const prepareData = (idEnseignant) => { choosen.value = tableItems.value.filter(item => { return item.numEns == idEnseignant; }) choosen.value = choosen.value.shift(); } const displayEditDialog = (idEnseignant) => { prepareData(idEnseignant); nomEnseignant.value = choosen.value.nom; nbHeureEnseignant.value = choosen.value.nbHeure; tauxHoraireEnseignant.value = choosen.value.tauxHoraire; dialogEditer.value = true; }; const displayDeleteDialog = (idEnseignant) => { prepareData(idEnseignant); dialogSupprimer.value = true; } const displayAddDialog = () => { nomNew.value = null; nbHeureNew.value = null; tauxHoraireNew.value = null; dialogAjouter.value = true; } const editerEnseignant = async (idEnseignant) => { message = await $post("edit-enseignant", { numEns: idEnseignant, nom: nomEnseignant.value, nbHeure: nbHeureEnseignant.value, tauxHoraire: tauxHoraireEnseignant.value }); dialogEditer.value = false; snack.value.color = "success"; snack.value.timeout = 3000; snack.value.snackValue = true; await retrieve(); updateChart(); }; const supprimerEnseignant = async (idEnseignant) => { message = await $delete("remove-enseignant/" + idEnseignant); dialogSupprimer.value = false; snack.value.color = "error"; snack.value.timeout = 6000; snack.value.snackValue = true; await retrieve(); updateChart(); }; const ajouterEnseignant = async () => { message = await $post("add-enseignant", { nom: nomNew.value, nbHeure: nbHeureNew.value, tauxHoraire: tauxHoraireNew.value }); dialogAjouter.value = false; snack.value.color = "success"; snack.value.timeout = 3000; snack.value.snackValue = true; await retrieve(); updateChart(); } </script> <style scoped> .flip-card { background-color: transparent; perspective: 1500px; } .flip-card-inner { text-align: center; transition: transform 0.6s; transform-style: preserve-3d; } .flip-card:hover .flip-card-inner { transform: rotateY(20deg); } .flip-card-front { -webkit-backface-visibility: hidden; backface-visibility: hidden; } </style>
import { Router } from "express"; import Category from '../model/Category.js'; import { sanitizeInput } from "../utils/index.js"; const router = new Router(); /** * @swagger * /categories: * get: * summary: Get all categories * tags: [Categories] * responses: * "200": * description: The array of all available category and its subcategories * contents: * application/json: * schema: * $ref: '#/components/schemas/Categories' * "500": * description: Server Error * contents: * application/json */ router.get("/", async (req, res, next) => { try { const categories = await Category.FindAll(); res.status(200).json(categories) } catch (error) { next(error) } }); /** * * @swagger * /categories/{id}: * get: * summary: Get Category info by ID * tags: [Categories] * parameters: * - in: path * name: id * schema: * type: string * required: true * description: ID of category * responses: * "200": * description: Successfully got the categories information * contents: * application/json: * schema: * $ref: '#/components/schemas/Categories' * "500": * $ref: '#/components/responses/500' */ router.get("/:id", async (req, res, next) => { try { const { id } = req.params; const category = await Category.FindCategoryById(sanitizeInput(id)); if(category === undefined || category == null) return new Erro("Undefined") res.status(200).json(category); } catch (error) { next(error); } }); /** * @swagger * /categories: * post: * summary: Create new category * tags: [Categories] * requestBody: * required: true * content: * application/json: * schema: * $ref: '#/components/schemas/Categories' * responses: * "500": * $ref: '#/components/responses/500' * "401": * $ref: '#/components/responses/401' * "201": * description: Category created successfully. * contents: * application/json: * schema: * $ref: '#/components/schemas/Categories' * */ router.post("/", async(req, res, next) => { console.log("Here") try { console.log("Body", req.body) const newCategories = new Category({...req.body}); const categoryId = newCategories.save(); res.status(201).json({categoryId: categoryId}) } catch (error) { console.log(error) next(error); } }) export default router;
import { Box,CssBaseline, Stack, useTheme } from '@mui/material' import React from 'react' import Header from '../components/Header'; import Title from '../components/Title'; import SmallTitle from '../components/SmallTitle'; import GroupButton from '../components/GroupButton'; import UseTitle from '../components/UseTitle'; import GridCard from '../components/GridCard'; import BenefitTitle from '../components/BenefitTitle'; import RoundedCard from '../components/RoundedCard'; import BaseCard from '../components/BaseCard'; import FooterSection from '../components/Footer'; import BgImage from '../components/BgImage'; import RoadMap from '../components/RoadMap'; import ArrowUpwardIcon from '@mui/icons-material/ArrowUpward'; import { motion } from 'framer-motion'; function Page() { const [closeNav, setcloseNav] = React.useState(false); const ref = React.useRef(null); const theme = useTheme() const handleTo =()=>{ window.scrollTo({ behavior:'smooth', top:0 }) } return ( <Box ref={ref} component={motion.div} sx={{ backgroundColor:theme.main.bgBlack, width:'100%', minHeight:'100vh', paddingX:{ xs:3.5, md:6 }, paddingTop:{ xs:2, md:4 } }}> <ArrowUpwardIcon onClick={handleTo} sx={{ color:'#fff', fontSize:'2.5rem', position:'fixed', bottom:0, right:10, cursor:'pointer', zIndex:1000 }} /> <CssBaseline/> <Header closeNav={closeNav} setcloseNav={setcloseNav} /> <Title closeNav={closeNav} /> <SmallTitle/> <Stack sx={{ width:'100%', display:'flex', flexDirection:'column', justifyContent:'center', alignItems:'center', marginTop:4 }}> <GroupButton/> <BgImage/> <UseTitle/> <GridCard/> <BenefitTitle/> <RoundedCard/> <BaseCard/> <RoadMap/> <FooterSection/> </Stack> </Box> ) } export default Page
package ex02_loop; public class Ex03_break { public static void main(String[] args) { // break문 // switch문을 종료할 때 사용한다. // 반복문(for, while)을 종료할 때 사용한다. // 모금 목표 : 100000원 // 한 번에 30원씩 모금 // 1회 모금액 30원 현재 30원 // 2회 모금액 30원 현재 60원 // ... int total = 0; int money = 30; int serial = 0; int goal = 100000; while(true) { // 무한 루프 if(total >= goal) { // == 를 사용하면 goal과 일치하는 값이 나오지 않는 경우 계속 루프한다. break; } total += money; serial++; System.out.println(serial + "회 모금액 " + money + "\t현재 " + total + "원"); } } }
/** * @file Endianness.ts @verbatim 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. @endverbatim */ /** https://en.wikipedia.org/wiki/Endianness * x86-64 instruction set architectures use the little-endian format * RISC-V and ARM support both * JavaScript DataView use big-endian by default (why?) */ export enum EnumEndianness { LITTLE_ENDIAN = 0, BIG_ENDIAN = 1, } export class Endianness { protected endianness: EnumEndianness; public constructor(initialEnumEndianness:EnumEndianness = EnumEndianness.LITTLE_ENDIAN) { this.endianness = initialEnumEndianness; /*Attention!!! In JavaScript DataView by default is Big Endian!!!*/ } public isBigEndian(): boolean { return this.endianness === EnumEndianness.BIG_ENDIAN; } public isLittleEndian(): boolean { return this.endianness === EnumEndianness.LITTLE_ENDIAN; } public _setBigEndian(): void { this.endianness = EnumEndianness.BIG_ENDIAN; } public setBigEndian(): boolean { return this.set(EnumEndianness.BIG_ENDIAN); } public _setLittleEndian(): void { this.endianness = EnumEndianness.LITTLE_ENDIAN; } public setLittleEndian(): boolean { return this.set(EnumEndianness.LITTLE_ENDIAN); } public get(): EnumEndianness { return this.endianness; } public _set(newEnumEndianness: EnumEndianness): void { this.endianness = newEnumEndianness; } public set(newEnumEndianness: EnumEndianness): boolean { let changed = this.endianness !== newEnumEndianness; this.endianness = newEnumEndianness; return changed; } public toString(): string { return EnumEndianness[this.endianness]; } public setRandom() { if(Math.random() > 0.5) this.setLittleEndian(); else this.setBigEndian(); } }
package org.jsp.adminBus.service; import java.util.Optional; import org.jsp.adminBus.dao.AdminDao; import org.jsp.adminBus.dto.Admin; import org.jsp.adminBus.dto.ResponseStructure; import org.jsp.adminBus.exception.LoginInvalidException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Service; @Service public class AdminService { @Autowired private AdminDao adminDao; ResponseStructure<Admin> structure=new ResponseStructure<>(); public ResponseEntity<ResponseStructure<Admin>> saveAdmin(Admin admin){ structure.setData(adminDao.saveAdmin(admin)); structure.setMessage("Admin saved"); structure.setStatusCode(HttpStatus.CREATED.value()); return new ResponseEntity<ResponseStructure<Admin>>(structure,HttpStatus.CREATED); } public ResponseEntity<ResponseStructure<Admin>> updateAdmin(Admin admin){ Optional<Admin> dbOptional=adminDao.findById(admin.getId()); if(dbOptional.isPresent()) { Admin dbAdmin=dbOptional.get(); dbAdmin.setName(admin.getName()); dbAdmin.setEmail(admin.getEmail()); dbAdmin.setGst(admin.getGst()); dbAdmin.setPhone(admin.getPhone()); dbAdmin.setPassword(admin.getPassword()); dbAdmin.setBus(admin.getBus()); dbAdmin.setTravels_name(admin.getTravels_name()); structure.setData(adminDao.saveAdmin(admin)); structure.setMessage("Admin updated successfully"); structure.setStatusCode(HttpStatus.ACCEPTED.value()); return new ResponseEntity<ResponseStructure<Admin>>(structure,HttpStatus.ACCEPTED); } throw new LoginInvalidException("Id Not Present"); } public ResponseEntity<ResponseStructure<Admin>> loginByPhoneAndPassword(long phone,String password){ Optional<Admin> dbOptional=adminDao.loginByPhoneAndPassword(phone, password); if(dbOptional.isPresent()) { structure.setMessage("Login Successful"); structure.setData(dbOptional.get()); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<ResponseStructure<Admin>>(structure,HttpStatus.OK); } throw new LoginInvalidException("Wrong Phone and Password"); } public ResponseEntity<ResponseStructure<Admin>> loginByEmailAndPassword(String email,String password){ Optional<Admin> dbOptional=adminDao.loginByEmailAndPassword(email, password); if(dbOptional.isPresent()) { structure.setMessage("Login Successful"); structure.setData(dbOptional.get()); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<ResponseStructure<Admin>>(structure,HttpStatus.OK); } throw new LoginInvalidException("Wrong Email and Password"); } public ResponseEntity<ResponseStructure<Admin>> findAdminById(int id){ Optional<Admin> dbOptional=adminDao.findById(id); if(dbOptional.isPresent()) { structure.setData(dbOptional.get()); structure.setMessage("Finding successful"); structure.setStatusCode(HttpStatus.OK.value()); return new ResponseEntity<ResponseStructure<Admin>>(structure,HttpStatus.OK); } throw new LoginInvalidException("Invalid Id"); } }
import { syntaxTree } from '@codemirror/language' import type { EditorState, Extension, Range } from '@codemirror/state' import { RangeSet, StateField } from '@codemirror/state' import type { DecorationSet } from '@codemirror/view' import { Decoration, EditorView, WidgetType } from '@codemirror/view' interface ImageWidgetParams { url: string, } class ImageWidget extends WidgetType { readonly url constructor({ url }: ImageWidgetParams) { super() this.url = url } eq(imageWidget: ImageWidget) { return imageWidget.url === this.url } toDOM() { const container = document.createElement('div') const backdrop = container.appendChild(document.createElement('div')) const figure = backdrop.appendChild(document.createElement('figure')) const image = figure.appendChild(document.createElement('img')) container.setAttribute('aria-hidden', 'true') container.className = 'cm-image-container' backdrop.className = 'cm-image-backdrop' figure.className = 'cm-image-figure' image.className = 'cm-image-img' image.src = this.url container.style.paddingBottom = '0.5rem' container.style.paddingTop = '0.5rem' backdrop.classList.add('cm-image-backdrop') backdrop.style.borderRadius = 'var(--ink-internal-border-radius)' backdrop.style.display = 'flex' backdrop.style.alignItems = 'center' backdrop.style.justifyContent = 'center' backdrop.style.overflow = 'hidden' backdrop.style.maxWidth = '100%' figure.style.margin = '0' image.style.display = 'block' image.style.maxHeight = 'var(--ink-internal-block-max-height)' image.style.maxWidth = '100%' image.style.width = '100%' return container } } export const images = (): Extension => { const imageRegex = /!\[.*?\]\((?<url>.*?)\)/ const imageDecoration = (imageWidgetParams: ImageWidgetParams) => Decoration.widget({ widget: new ImageWidget(imageWidgetParams), side: -1, block: true, }) const decorate = (state: EditorState) => { const widgets: Range<Decoration>[] = [] syntaxTree(state).iterate({ enter: ({ type, from, to }) => { if (type.name === 'Image') { const result = imageRegex.exec(state.doc.sliceString(from, to)) if (result && result.groups && result.groups.url) widgets.push(imageDecoration({ url: result.groups.url }).range(state.doc.lineAt(from).from)) } }, }) return widgets.length > 0 ? RangeSet.of(widgets) : Decoration.none } const imagesField = StateField.define<DecorationSet>({ create(state) { return decorate(state) }, update(images, transaction) { if (transaction.docChanged) return decorate(transaction.state) return images.map(transaction.changes) }, provide(field) { return EditorView.decorations.from(field) }, }) return [ imagesField, ] }
import React, { useState, useEffect } from 'react'; import apiClient from '../../spotify'; import './favorites.css'; export default function Favorites() { const [favorites, setFavorites] = useState([]); useEffect(() => { const fetchFavorites = async () => { try { const response = await apiClient.get('/me/tracks'); setFavorites(response.data.items); } catch (error) { console.error("There was an error fetching the favorites data!", error); } }; fetchFavorites(); }, []); return ( <div className="favorites-container screen-container flex"> <h2>Your Favorite Tracks</h2> <div className="favorites-items"> {favorites.map(item => ( <div key={item.track.id} className="favorites-item"> {item.track.album.images[0] && ( <img src={item.track.album.images[0].url} alt={`${item.track.name} cover`} className="favorites-item-cover" /> )} <div className="favorites-item-info"> <h3>{item.track.name}</h3> <p>{item.track.artists.map(artist => artist.name).join(', ')}</p> <audio controls> <source src={item.track.preview_url} type="audio/mpeg" /> Your browser does not support the audio element. </audio> </div> </div> ))} </div> </div> ); }
#' Independence Metropolis-Hastings #' #' @param x The current state (scalar or numeric vector). #' @param log_target A function taking a scalar or numeric vector that evaluates the log-target #' density, returning a numeric scalar. #' @param pseudo List specifying the pseudo-target (proposal distribution). If the list length is #' equal to the number of dimensions in \code{x}, each element is itself a list that specifies #' the pseudo-target for the corresponding dimension with functions \code{ld} #' that evaluates the log density for that dimension, #' and \code{q} that evaluates the quantile (inverse-CDF) function for that dimension. #' If the dimension of \code{x} is one, then supply only the inner list #' specifying the single pseudo-target. #' #' If \code{x} is a vector but a single pseudo-target is supplied, the list must #' contain a log-density function \code{ld} that accepts a vector, and a \code{r} #' function that takes no arguments and generates a single multivariate draw from the #' proposal distribution. #' @return A list containing the new state, \code{x}, and whether the proposed value was accepted, logical \code{accpt}. #' @importFrom stats runif #' @export #' @examples #' lf <- function(x) dbeta(x[1], 3, 4, log = TRUE) + dbeta(x[2], 5, 3, log = TRUE) #' n_iter <- 100 # set to 1e3 for more complete illustration #' draws <- matrix(0.2, nrow = n_iter, ncol = 2) #' nAccpt <- 0L #' pseudo <- list( list(ld = function(x) dbeta(x, 2, 2, log = TRUE), #' q = function(u) qbeta(u, 2, 2)), #' list(ld = function(x) dbeta(x, 2, 2, log = TRUE), #' q = function(u) qbeta(u, 2, 2)) #' ) #' for (i in seq.int(2, n_iter)) { #' out <- imh_pseudo(draws[i - 1, ], log_target = lf, pseudo = pseudo) #' draws[i,] <- out$x #' nAccpt <- nAccpt + out$accpt #' cat(i, '\r') #' } #' nAccpt / (nrow(draws) - 1) #' plot(draws[,1], draws[,2], xlim = c(0, 1)) #' hist(draws[,1], freq = FALSE); curve(dbeta(x, 3, 4), col = "blue", add = TRUE) #' hist(draws[,2], freq = FALSE); curve(dbeta(x, 5, 3), col = "blue", add = TRUE) imh_pseudo <- function(x, log_target, pseudo) { K <- length(x) if (K == 1) { out <- imh_pseudo_univ(x = x, log_target = log_target, pseudo = pseudo, K = K) } else { out <- imh_pseudo_mv(x = x, log_target = log_target, pseudo = pseudo, K = K) } out } imh_pseudo_univ <- function(x, log_target, pseudo, K = K) { lfx0 <- log_target(x) - pseudo$ld(x) u1 <- runif(K) x1 <- pseudo$q(u1) lfx1 <- log_target(x1) - pseudo$ld(x1) lprob_accpt <- lfx1 - lfx0 lu_accpt <- log(runif(1)) if (isTRUE(lu_accpt < lprob_accpt)) { out <- list(x = x1, accpt = TRUE) } else { out <- list(x = x, accpt = FALSE) } out } imh_pseudo_mv <- function(x, log_target, pseudo, K = K) { Kpseu <- length(pseudo) if (Kpseu == K) { lfx0 <- log_target(x) - sum(sapply(1:K, function(k) pseudo[[k]]$ld(x[k]))) u1 <- runif(K) x1 <- sapply(1:K, function(k) pseudo[[k]]$q(u1[k])) lfx1 <- log_target(x1) - sum(sapply(1:K, function(k) pseudo[[k]]$ld(x1[k]))) } else if (Kpseu == 1) { lfx0 <- log_target(x) - pseudo$ld(x) x1 <- pseudo$r() lfx1 <- log_target(x1) - pseudo$ld(x1) } else { stop("imh_pseudo_mv() requires the pseudo (proposal) list to be of length 1 or length matching that of input vector x.") } lprob_accpt <- lfx1 - lfx0 lu_accpt <- log(runif(1)) if (isTRUE(lu_accpt < lprob_accpt)) { out <- list(x = x1, accpt = TRUE) } else { out <- list(x = x, accpt = FALSE) } out }
import React, { useMemo, Dispatch, createContext } from "react"; export interface IFirebaseData { id: string; amount: number; category: string; date: string; transactionType: string; description: string; } export type FirebaseDataContextType = { firebaseData: IFirebaseData[]; setFirebaseData: Dispatch<IFirebaseData[]>; transactionsArray: IFirebaseData[]; setTransactionsArray: Dispatch<IFirebaseData[]>; }; export const FirebaseDataContext = createContext<FirebaseDataContextType>({ firebaseData: [], setFirebaseData: () => {}, transactionsArray: [], setTransactionsArray: () => {}, }); type FirebaseDataProps = { children: React.ReactNode; }; export const FirebaseDataProvider: React.FC<FirebaseDataProps> = ({ children, }) => { const [firebaseData, setFirebaseData] = React.useState<IFirebaseData[]>([]); const [transactionsArray, setTransactionsArray] = React.useState< IFirebaseData[] >([]); const contextValue = useMemo(() => { return { firebaseData, setFirebaseData, transactionsArray, setTransactionsArray, }; }, [firebaseData, setFirebaseData, transactionsArray, setTransactionsArray]); return ( <FirebaseDataContext.Provider value={contextValue}> {children} </FirebaseDataContext.Provider> ); };
// The boilerplate includes a definition of repeat. repeat will take a Function operation, and a Number num, and invoke operation num times: // // var count = 0 // repeat(function() { // count++ // }, 100) // // console.log('executed %d times.', count) // // => executed 100 times. // // BUT note that executing repeat with a large num causes a stack overflow: // // var count = 0 // repeat(function() { // count++ // }, 100000) // // console.log('executed %d times', count) // // => RangeError: Maximum call stack size exceeded // // # Task // // Modify the boilerplate below such that it uses a trampoline to continuously call itself synchronously. // // You can assume that the operation passed to repeat does not take arguments (or they are already bound to the function) and the return value is not important. // // ## Conditions // // * Do not change the implementation of repeat to include any loops(you may change it in other ways though). // // ## Hints // // * Modify `repeat` so it returns the 'next step', if there is one. // * A trampoline continues to synchronously execute steps, getting new steps, until there are no more steps. You can use a loop here! // * If your program takes a long time to run, something is probably wrong. Use Control - C to kill the node process. function repeat(operation, num) { if (!num) return; return function() { operation(); return repeat(operation, --num); }; } function trampoline(fn) { while (fn()); } module.exports = function(operation, num) { return trampoline(repeat(operation, num)); }; /* Official Solution function repeat(operation, num) { return function() { if (num <= 0) return operation() return repeat(operation, --num) } } function trampoline(fn) { while(fn && typeof fn === 'function') { fn = fn() } } module.exports = function(operation, num) { trampoline(function() { return repeat(operation, num) }) } */
# Documentation This section is related to your work on clean code and documentation in week 5. I originaly failed to make my part of the app that was due for week 3,, but I am now commenting it as I finished it during this week's practical. ## Clean Code Rules ### Rule 1: Meaningful Variable Names **Summary**: In clean code, variable names should be descriptive and indicative of their purpose, promoting code readability. - ![Screenshot a](images/screenshota.png) **Example**: In the code provided, the variable `System_varTypes` represents a collection of system variables, making its purpose clear. **Implementation**: The choice of variable name `System_varTypes` effectively communicates its role in the code. ### Rule 2: Avoid Magic Numbers **Summary**: Avoid using hard-coded, unexplained numerical values (magic numbers) in the code. Instead, use named constants or variables with descriptive names. **Example**: In the code, there are no instances of magic numbers. All numbers and values are self-explanatory or stored in variables/constants. **Implementation**: The absence of magic numbers enhances code readability and maintainability. ### Rule 3: DRY Principle (Don't Repeat Yourself) **Summary**: Avoid duplicating code segments. Reuse code whenever possible to reduce redundancy and simplify maintenance. **Example**: In the code provided, the same validation logic for user inputs is repeated in multiple event handlers. **Implementation**: To adhere to the DRY principle, the validation logic can be encapsulated in a separate method and called from each event handler, reducing code duplication and improving maintainability. ### Rule 4: Proper Indentation and Formatting **Summary**: Maintain consistent and clear code formatting with proper indentation, line breaks, and spacing. - ![Screenshot c](images/screenshotc.png) **Example**: The code is well-formatted with consistent indentation and spacing, enhancing readability. **Implementation**: Consistent formatting improves code readability and maintainability. ### Rule 5: Single Responsibility Principle (SRP) **Summary**: Each function or class should have one clear responsibility. Avoid functions or classes that do too many things. - ![Screenshot d](images/screenshotd.png) - ![Screenshot e](images/screenshote.png) **Example**: In the code, each method ( `OnAddSystem_varTypeClicked`, `OnSystem_varTypeTapped`, for exemple here) has a clear and distinct responsibility related to system variable management. **Implementation**: The code adheres to the SRP by assigning specific tasks to individual methods. ### Rule 6: Clear and Concise Comments **Summary**: Use comments sparingly and focus on explaining the 'why' and not the 'how.' Clear, concise comments provide valuable insights into code intent. **Example**: The code provides comments explaining the purpose of each method and event handler, making it clear why each piece of code exists. **Implementation**: Comments in the code provide insights into code intent and are concise, aiding understanding without duplicating code explanations. ## Integration of Doxygen Comments Doxygen comments have been integrated into the codebase to facilitate code documentation. However, Doxygen failed to provide any changes to the code comments, issueing in not adding anything. I think a bug occured and doing it multiple times did not change the result of the maneuver. - ![Screenshot f](images/screenshotf.png) - ![Screenshot g](images/screenshotg.png) ## Highlighting Clean Code Practices Three examples will be provided to showcase how clean code practices have eliminated the need for comments: 1. **Descriptive Function Names**: Function names like `OnAddSystem_varTypeClicked` and `OnSystem_varTypeTapped` clearly indicate their purpose, eliminating the need for additional comments. 2. **Proper Indentation and Formatting**: The code is indented accordingly to the C# coding practices. As it is not necessary for the code to run unlike python for exemple, it is helpful to make the code self explainatory and remove the need for comments. 3. **Avoidance of Magic Numbers**: No magic numbers are present in the code; variables and constants are used instead, making the code self-documenting. ## Conclusion This documentation highlights the adherence to clean code principles, the integration of Doxygen comments which unfortunatly didn't work out, and the reduction of comments through clean code practices. The provided examples and explanations aim to enhance code quality and maintainability, thus offering a better experience for futur people working on the code.
+++ title = "How to use, with Codex" author = ["Shane Mulligan"] date = 2021-10-11T00:00:00+13:00 keywords = ["codex", "pen", "openai", "emacs"] draft = false +++ ## Summary {#summary} This is a prompt for obtaining examples of how to use something, such as a function or an import. ## Bindings {#bindings} {{< highlight emacs-lisp "linenos=table, linenostart=1" >}} (define-key pen-map (kbd "H-p e") 'pf-get-an-example-of-the-usage-of-a-function/2) {{< /highlight >}} | kb | f | | |---------|--------------------------------------------------|-----------| | `H-p e` | `pf-get-an-example-of-the-usage-of-a-function/2` | `pen-map` | ## Prompt {#prompt} `pf-get-an-example-of-the-usage-of-a-function/2` {{< highlight yaml "linenos=table, linenostart=1" >}} task: "Get an example of the usage of a function" doc: "Given a function name, provide an example of its usage" prompt-version: 2 prompt: |+ Examples of function usage: <delim> Language: "Haskell" Function: "map" Usage:<delim> map (*2) [1..10] <delim> Language: <q:language> Function: <q:function> Usage:<delim> engine: OpenAI Codex force-engine: OpenAI Codex temperature: 0.5 max-generated-tokens: 80 n-completions: 8 top-p: 1 stop-sequences: - "<delim>" vars: - function - language examples: - map completion: true # This is just to make it a bit easier when you select multiple lines to define preprocessors: - pen-str onelineify # Also trim off excess, when unonelineify doesn't quite do it postprocessor: pen-str unonelineify | sed -z "s/Language:.*//" # fz-pretty: on var-defaults: - "(pen-thing-at-point-ask \"symbol\" t)" - "(pen-detect-language-ask)" # validator: "grep -q <function>" {{< /highlight >}} ## Question {#question} How to use use this? {{< highlight text "linenos=table, linenostart=1" >}} import Control.Monad ( forM_ ) {{< /highlight >}} ### Prompting result {#prompting-result} {{< highlight text "linenos=table, linenostart=1" >}} import Control.Monad ( forM_ ) forM_ [1..10] $ \x -> do print x print x {{< /highlight >}} ### Transformation with `pf-transform-code/3` {#transformation-with-pf-transform-code-3} {{< highlight text "linenos=table, linenostart=1" >}} remove the do and put on one line {{< /highlight >}} ### Solution {#solution} {{< highlight text "linenos=table, linenostart=1" >}} *Main Control.Monad> forM_ [1..10] $ \x -> print x 1 2 3 4 5 6 7 8 9 10 {{< /highlight >}} ## Demo {#demo} <!-- Play on asciinema.com --> <!-- <a title="asciinema recording" href="https://asciinema.org/a/qqil5ZUjIDHRxQyaLDnigIq4k" target="_blank"><img alt="asciinema recording" src="https://asciinema.org/a/qqil5ZUjIDHRxQyaLDnigIq4k.svg" /></a> --> <!-- Play on the blog --> <script src="https://asciinema.org/a/qqil5ZUjIDHRxQyaLDnigIq4k.js" id="asciicast-qqil5ZUjIDHRxQyaLDnigIq4k" async></script>
package com.nopcommerce.common; import org.testng.annotations.Test; import commons.BasePage; import commons.BaseTest; import commons.PageGeneratorManager; import pageObjects.nopCommerce.portal.UserAddressPageObject; import pageObjects.nopCommerce.portal.UserCustomerInfoPageObject; import pageObjects.nopCommerce.portal.UserHomePageObject; import pageObjects.nopCommerce.portal.UserLoginPageObject; import pageObjects.nopCommerce.portal.UserMyProductReviewPageObject; import pageObjects.nopCommerce.portal.UserRegisterPageObject; import pageObjects.nopCommerce.portal.UserRewardPointPageObject; import org.testng.annotations.BeforeClass; import org.testng.annotations.BeforeTest; import org.testng.annotations.Parameters; import java.util.Random; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.testng.Assert; import org.testng.annotations.AfterClass; import org.testng.annotations.AfterTest; public class Common_01_Register_End_User extends BaseTest { private WebDriver driver; //declare (khai bao) private String lastName, firstName; public static String emailAddress, password; private UserHomePageObject homePage; private UserRegisterPageObject registerPage; @Parameters("browser") @BeforeTest public void User_01_Register(String browserName) { driver = getBrowserDriver(browserName); homePage = PageGeneratorManager.getUserHomePage(driver); firstName ="Automation"; lastName = "FC"; password ="123456"; emailAddress = "afc" + generateFakeNumber() + "@mail.vn"; log.info("Register - Step 01: Navigate to 'Register' page"); registerPage = homePage.clickToRegisterLink(); log.info("Register - Step 02: enter to FirsName with value is '" + firstName + "'"); registerPage.inputToFirstNameTextbox(firstName); log.info("Register - Step 03: enter to LastName with value is '" + lastName + "'"); registerPage.inputToLastNameTextbox(lastName); log.info("Register - Step 04: enter to Email with value is '" + emailAddress + "'"); registerPage.inputToEmailTextbox(emailAddress); log.info("Register - Step 05: enter to Password with value is '" + password + "'"); registerPage.inputToPasswordTextbox(password); log.info("Register - Step 06: enter to Confirm Pass with value is '" + password + "'"); registerPage.inputToConfirmPasswordTextbox(password); log.info("Register - Step 07: click on 'Register' Button"); registerPage.clickToRegisterButton(); log.info("Register - Step 08: verify message register success"); Assert.assertEquals(registerPage.getSuccessRegisterMessage(), "Your registration completed"); driver.quit(); } }
<!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" /> <!-- Navbar --> <title>iCoder</title> </head> <body style="background-color:rgb(241, 222, 181)"> <nav class="navbar navbar-expand-lg navbar-dark" style="background-color: rgb(30, 1, 29)"> <a class="navbar-brand" href="#">iCoder</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item"> <a class="nav-link" href="/index.html">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item "> <a class="nav-link" href="/about.html">About</a> </li> <li class="nav-item active"> <a class="nav-link" href="/contact.html">Contact Us</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Topics</a> <div class="dropdown-menu" aria-labelledby="navbarDropdown" style="background-color: rgb(225, 255, 1);"> <a class="dropdown-item" href="https://www.javatpoint.com" title="It will take you to another website, click to continue." target="_blank">C++</a> <a class="dropdown-item" href="https://www.javatpoint.com" title="It will take you to another website, click to continue." target="_blank">Java</a> <a class="dropdown-item" href="https://www.javatpoint.com" title="It will take you to another website, click to continue." target="_blank">JavaScript</a> <a class="dropdown-item" href="https://www.javatpoint.com" title="It will take you to another website, click to continue." target="_blank">Web Development</a> <a class="dropdown-item" href="https://www.javatpoint.com" title="It will take you to another website, click to continue." target="_blank">Python</a> <div class="dropdown-divider"></div> <a class="dropdown-item" href="#">Support</a> <a class="dropdown-item" href="/contact.html">Write for us</a> </div> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" /> <button class="btn btn-outline-danger my-2 my-sm-0" type="submit"> Search </button> </form> <br> <div class="mx-1"> <button class="btn btn-outline-light" data-toggle="modal" data-target="#LoginModal">Login</button> <button class="btn btn-outline-success" data-toggle="modal" data-target="#SineUpModal">Sine Up</button> </div> </div> </nav> <br /> <!-- Login Modal --> <div class="modal fade" id="LoginModal" tabindex="-1" role="dialog" aria-labelledby="LoginModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="LoginModalLabel">Login to iCoder</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1"> </div> <div class="form-group form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Check me out</label> </div> <a href="/login.html" button type="submit" class="btn btn-primary">Submit</a> <!-- <button type="submit" class="btn btn-primary" >Submit</button> --> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> <!--Sine Up Modal --> <div class="modal fade" id="SineUpModal" tabindex="-1" role="dialog" aria-labelledby="SineUpModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="SineUpModalLabel">Get an iCoder account</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <form> <div class="form-group"> <label for="exampleInputEmail1">Email address</label> <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"> <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small> </div> <div class="form-group"> <label for="exampleInputPassword1">Password</label> <input type="password" class="form-control" id="exampleInputPassword1"> </div> <div class="form-group"> <label for="exampleInputPassword1">Confirm Password</label> <input type="password" class="form-control" id="exampleInputPassword1"> </div> <div class="form-group form-check"> <input type="checkbox" class="form-check-input" id="exampleCheck1"> <label class="form-check-label" for="exampleCheck1">Check me out</label> </div> <a href="/sineup.html" button type="submit" class="btn btn-primary">Submit</a> <!-- <button type="submit" class="btn btn-primary">Submit</button> --> </form> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> <br /> <div class="container my-4"> <h2>Contact Us</h2> <form> <div class="form-group"> <label for="exampleFormControlInput1">Email address</label> <input type="email" class="form-control" id="exampleFormControlInput1" placeholder="[email protected]"> </div> <div class="form-group"> <label for="exampleFormControlSelect1">Select your query</label> <select class="form-control" id="exampleFormControlSelect1"> <option>Web Development</option> <option>Technology</option> <option>Languages </option> <option>Frameworks</option> <option>Others</option> </select> </div> <div class="form-group row"> <div class="col-sm-2">Are you a member?</div> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="gridCheck1"> <label class="form-check-label" for="gridCheck1"> Yes </label> </div> </div> </div> <div class="form-group row"> <div class="col-sm-2">Are you a professor?</div> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="gridCheck2"> <label class="form-check-label" for="gridCheck2"> Yes </label> </div> </div> </div> <div class="form-group row"> <div class="col-sm-2">Are you a codder?</div> <div class="col-sm-10"> <div class="form-check"> <input class="form-check-input" type="checkbox" id="gridCheck3"> <label class="form-check-label" for="gridCheck3"> Yes </label> </div> </div> </div><br> <div class="form-group"> <label for="exampleFormControlTextarea1">Tell us about yourself</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea><br> </div> <div class="form-group"> <label for="exampleFormControlTextarea1">Elaborate your concern</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea><br> <div> <a href="/thanks.html" button type="submit" class="btn btn-primary">Submit</a> </div> </div> </form> </div> <footer class="container"> <p class="float-right"><a href="#">Back to top</a></p> <p>© 2022-2024 iCoder , Inc. · <a href="#">Privacy</a> · <a href="#">Terms</a></p> </footer> <!-- Optional JavaScript --> <!-- jQuery first, then Popper.js, then Bootstrap JS --> <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo" crossorigin="anonymous"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.min.js" integrity="sha384-wfSDF2E50Y2D1uUdj0O3uMBJnjuUD4Ih7YwaYd1iqfktj0Uod8GCExl3Og8ifwB6" crossorigin="anonymous"></script> </body> </html>
<?xml version="1.0" encoding="utf-8"?><!-- Copyright (C) 2016 The Android Open Source 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. --><!-- COMPLETED (2) Remove the old layout --><!-- COMPLETED (3) Use ConstraintLayout to create the new list item layout --> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical"> <!-- This TextView holds the weather data for one particular day in the forecast --> <ImageView android:id="@+id/weather_icon" android:layout_width="50dp" android:layout_height="50dp" android:layout_marginStart="5dp" android:contentDescription="@string/a11y_forecast_icon" app:layout_constraintLeft_toLeftOf="parent" tools:background="@drawable/art_clouds" /> <TextView android:id="@+id/date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="15dp" android:layout_marginTop="8dp" app:layout_constraintLeft_toRightOf="@id/weather_icon" app:layout_constraintTop_toTopOf="parent" tools:text="@tools:sample/date/mmddyy" /> <TextView android:id="@+id/condition" android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintLeft_toLeftOf="@id/date" app:layout_constraintTop_toBottomOf="@id/date" tools:text="@string/condition_953" /> <TextView android:id="@+id/low_temperature" android:layout_width="60dp" android:layout_height="match_parent" android:gravity="center" android:maxLines="1" android:textAppearance="@style/TextAppearance.AppCompat.Large" app:layout_constraintRight_toRightOf="parent" tools:text="13C" /> <TextView android:id="@id/high_temperature" android:layout_width="60dp" android:layout_height="match_parent" android:gravity="center" android:textAppearance="@style/TextAppearance.AppCompat.Large" app:layout_constraintRight_toLeftOf="@id/low_temperature" tools:text="15C" /> <!-- This View serves as a visual divider between list items --> <android.support.constraint.Guideline android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent="0.5" /> </android.support.constraint.ConstraintLayout>
import 'package:flutter/material.dart'; import 'package:labsql/homepage.dart'; import 'package:labsql/createprofilepage.dart'; import 'package:labsql/myprofilepage.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({super.key}); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { // This widget is the root of your application. int screenIndex = 0; final pageScreen = [ const HomePage(), MyProfilePage() ]; @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( appBar: AppBar( title: const Text('Post Data App'), backgroundColor: Colors.cyan, ), body: pageScreen[screenIndex], bottomNavigationBar: BottomNavigationBar( items: const [ BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'), BottomNavigationBarItem(icon: Icon(Icons.person), label: 'My Profile'), ], onTap: (value) { setState(() { screenIndex = value; }); }, currentIndex: screenIndex, ), ), ); } }
import { Component } from '@angular/core'; import { FormArray, FormGroup } from '@angular/forms'; import { Router } from '@angular/router'; import { Observable } from 'rxjs'; import { DialogService } from '@tylertech/forge-angular'; import { Utils } from 'src/utils'; import { IProfile } from 'src/app/shared/interfaces/person.interface'; import { AppDataService } from 'src/app/app-data.service'; import { AppToastService } from 'src/app/app-toast.service'; import { IAddressFormGroup, IPersonalFormGroup, ProfileCacheService } from './profile-cache.service'; import { ConfirmDialogComponent } from '../shared/components/confirm-dialog/confirm-dialog.component'; @Component({ selector: 'app-profile', templateUrl: './profile.component.html', styleUrls: ['./profile.component.scss'] }) export class ProfileComponent { private noImageUrl = 'mock-data/no-image.png'; public get personalFormGroup() { return this.cache.formGroup.get('personalFormGroup') as FormGroup<IPersonalFormGroup>; } public get addressFormGroup() { return this.cache.formGroup.get('addressFormGroup') as FormGroup<IAddressFormGroup>; } public activeTab = 0; public imageUrl?: string; constructor( private router: Router, private appDataService: AppDataService, private dialogService: DialogService, private appToastService: AppToastService, public cache: ProfileCacheService ) { if (this.cache.profile) { this.loadForm(this.cache.profile); } } public canDeactivate(): boolean | Observable<boolean> { if (!this.cache.formGroup.dirty) { return true; } return new Observable<boolean>(s => { const dialogRef = this.dialogService.show( ConfirmDialogComponent, { backdropClose: false, escapeClose: false }, { data: { title: 'Unsaved changes', message: 'You have unsaved changes which will be lost, do you want to continue?' } } ); const dialogSub = dialogRef.afterClosed.subscribe((result) => { dialogSub.unsubscribe(); if (result) { this.cache.formGroup.reset(); } s.next(result); }); }); } public onLoadProfile() { this.appDataService.getProfile().subscribe((result: IProfile) => { this.cache.formGroup.reset(); this.cache.profile = result; this.loadForm(this.cache.profile); }); } public onTabSelected(route: string) { switch (this.activeTab) { case 0: this.personalFormGroup.markAsTouched(); break; case 1: this.addressFormGroup.markAsTouched(); break; } switch (route) { case 'personal': this.activeTab = 0; break; case 'address': this.activeTab = 1; break; } this.router.navigate([`profile/${route}`]); } public onSave() { if (this.cache.formGroup.invalid) { return; } this.cache.profile = this.parseForm(this.cache.profile?.id); this.cache.formGroup.markAsPristine(); this.appToastService.show('Profile saved.'); } public onCancel() { this.cache.formGroup.reset(); this.cache.formGroup.markAsPristine(); this.imageUrl = undefined; this.cache.profile = undefined; } public onImageError(event: Event) { const targetElement = event.target as HTMLImageElement; if (!targetElement.src.includes(this.noImageUrl)) { targetElement.src = this.noImageUrl; targetElement.onerror = null; } } public isInvalid(values: boolean[]) { return values.every(v => v === true); } private loadForm(profile: IProfile) { this.imageUrl = `mock-data/${Utils.formatNumber(this.cache.profile?.id as number, '2.0-0')}-small.png`; (this.personalFormGroup.get('friends') as FormArray)?.clear(); this.personalFormGroup.patchValue(profile); this.addressFormGroup.patchValue(profile.address as any); } private parseForm(id?: number): IProfile { return { id: id || -1, firstName: this.personalFormGroup.value.firstName as string, lastName: this.personalFormGroup.value.lastName as string, gender: this.personalFormGroup.value.gender as any, email: this.personalFormGroup.value.email as string, phone: this.personalFormGroup.value.phone as string, dateOfBirth: this.personalFormGroup.value.dateOfBirth as Date, address: this.addressFormGroup.value as any }; } }
/* Q. Level wise linkedlist Given a binary tree, write code to create a separate linked list for each level. You need to return the array which contains head of each level linked list. Input format : The first line of input contains data of the nodes of the tree in level order form. The data of the nodes of the tree is separated by space. If any node does not have left or right child, take -1 in its place. Since -1 is used as an indication whether the left or right nodes exist, therefore, it will not be a part of the data of any node. Output format : Each level linked list is printed in new line (elements are separated by space). Sample Input 1: 5 6 10 2 3 -1 -1 -1 -1 -1 9 -1 -1 Sample Output 1: 5 6 10 2 3 9 */ #include <iostream> #include <queue> #include <vector> template <typename T> class Node { public: T data; Node<T> *next; Node(T data) { this->data = data; this->next = NULL; } }; template <typename T> class BinaryTreeNode { public: T data; BinaryTreeNode<T> *left; BinaryTreeNode<T> *right; BinaryTreeNode(T data) { this->data = data; left = NULL; right = NULL; } }; using namespace std; vector<Node<int>*> constructLinkedListForEachLevel(BinaryTreeNode<int> *root) { // Write your code here vector<Node<int>*> v; if(root == NULL){ return v; } queue<BinaryTreeNode<int>*> q; q.push(root); q.push(NULL); Node<int>* head = NULL, *tail = NULL; while(!q.empty()){ BinaryTreeNode<int>* front = q.front(); q.pop(); if(front == NULL){ v.push_back(head); if(q.empty()){ break; } head = NULL; tail = NULL; q.push(NULL); continue; } Node<int>* newNode = new Node<int>(front -> data); if(head == NULL){ head = newNode; tail = newNode; }else{ tail -> next = newNode; tail = newNode; } if(front -> left != NULL){ q.push(front -> left); } if(front -> right != NULL){ q.push(front -> right); } } return v; } /* vector<Node<int>*> constructLinkedListForEachLevel(BinaryTreeNode<int> *root) { // Write your code here vector<Node<int>*> v; if(!root){ return v; } queue<BinaryTreeNode<int>*> pendingNodes; pendingNodes.push(root); pendingNodes.push(NULL); Node<int> *head = NULL, *tail = NULL; while(!pendingNodes.empty()){ BinaryTreeNode<int> *front = pendingNodes.front(); pendingNodes.pop(); Node<int> *newNode = new Node<int>(front -> data); if(!head){ head = newNode; tail = newNode; }else{ tail -> next = newNode; tail = newNode; } if(front -> left){ pendingNodes.push(front -> left); } if(front -> right){ pendingNodes.push(front -> right); } if(!pendingNodes.front()){ pendingNodes.pop(); v.push_back(head); head = NULL; tail = NULL; if(!pendingNodes.empty()){ pendingNodes.push(NULL); } } } return v; } */ BinaryTreeNode<int> *takeInput() { int rootData; cin >> rootData; if (rootData == -1) { return NULL; } BinaryTreeNode<int> *root = new BinaryTreeNode<int>(rootData); queue<BinaryTreeNode<int> *> q; q.push(root); while (!q.empty()) { BinaryTreeNode<int> *currentNode = q.front(); q.pop(); int leftChild, rightChild; cin >> leftChild; if (leftChild != -1) { BinaryTreeNode<int> *leftNode = new BinaryTreeNode<int>(leftChild); currentNode->left = leftNode; q.push(leftNode); } cin >> rightChild; if (rightChild != -1) { BinaryTreeNode<int> *rightNode = new BinaryTreeNode<int>(rightChild); currentNode->right = rightNode; q.push(rightNode); } } return root; } void print(Node<int> *head) { Node<int> *temp = head; while (temp != NULL) { cout << temp->data << " "; temp = temp->next; } cout << endl; } int main() { BinaryTreeNode<int> *root = takeInput(); vector<Node<int> *> ans = constructLinkedListForEachLevel(root); for (int i = 0; i < ans.size(); i++) { print(ans[i]); } }
import { TestBed } from '@angular/core/testing'; import { ContactsService } from './contacts.service'; import { HttpClient, HttpErrorResponse } from '@angular/common/http'; import { of, defer } from 'rxjs'; import { contact } from '../shared/contact.model'; describe('ContactsService', () => { function asyncData<T>(data: T) { return defer(() => Promise.resolve(data)); } function asyncError<T>(errorObject: any) { return defer(() => Promise.reject(errorObject)); } let httpClientSpy: { get: jasmine.Spy }; httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']); beforeEach(() => TestBed.configureTestingModule({ providers: [ { provide: HttpClient, useValue: httpClientSpy } ] })); it('should be created', () => { const service: ContactsService = TestBed.get(ContactsService); expect(service).toBeTruthy(); }); it('should return expected contacts', (done: DoneFn) => { const expectedContacts: contact[] = [ { _id: 'id', firstName: 'contactFn1', lastName: 'contactLn1', index: '0', company: 'quicken Loans', email: '[email protected]', phone: '1-800-QUICKENLOANS', address: 'quicken loans street' }, { _id: 'id1', firstName: 'contactFn2', lastName: 'contactLn2', index: '1', company: 'quicken Loans', email: '[email protected]', phone: '1-800-QUICKENLOANS', address: 'quicken loans street' }]; const contactsService: ContactsService = TestBed.get(ContactsService); httpClientSpy.get.and.returnValue(asyncData(expectedContacts)); contactsService.getContacts().subscribe((contacts) => { expect(contacts).toEqual(expectedContacts); done(); } ); }); it('should return an error when the contacts server returns a 404', (done: DoneFn) => { const contactsService: ContactsService = TestBed.get(ContactsService); const errorResponse = new HttpErrorResponse({ error: 'test 404 error', status: 404, statusText: 'Not Found' }); httpClientSpy.get.and.returnValue(asyncError(errorResponse)) contactsService.getContacts().subscribe( contacts => fail('expected an error, not heroes'), error => expect(error.message).toContain('Http failure response for (unknown url): 404 Not Found') ); done(); }); });
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using BusinessObject.BusinessObject; using Service.Interface; using AutoMapper; using BusinessObject.DTO.Response; using GroupProject.Mapper; using BusinessObject.DTO.Request; using DAO; using System.Xml.Linq; namespace GroupProject.Controllers.AuctionController { [Route("api/[controller]")] [ApiController] public class AuctionsController : ControllerBase { private readonly IAuctionService _auction; private readonly IMapper _mapper; public AuctionsController(IAuctionService auction, IMapper mapper) { _auction = auction; _mapper = mapper; } // GET: api/Auctions [HttpGet] public ActionResult<IEnumerable<AuctionResponseDTO>> GetAuctions() { if (_auction.GetAuction() == null) { return NotFound(); } var config = new MapperConfiguration( cfg => cfg.AddProfile(new AuctionProfile()) ); // create mapper var mapper = config.CreateMapper(); var data = _auction.GetAuction().ToList().Select(auction => mapper.Map<Auction, AuctionResponseDTO>(auction)); return Ok(data); ; } // GET: api/Auctions/5 [HttpGet("{id}")] public ActionResult<Auction> GetAuction(int id) { if (_auction.GetAuction() == null) { return NotFound(); } var auction = _auction.GetAuctionById(id); if (auction == null) { return NotFound(); } return auction; } // PUT: api/Auctions/5 // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPut] public async Task<IActionResult> PutAuction(int id, AuctionUpdateDTO autionUpdateDTO) { try { if (autionUpdateDTO.AuctionID != id) { return NotFound(); } var action = _mapper.Map<Auction>(autionUpdateDTO); _auction.UpdateAuction(action); return Ok("Update Successfully"); } catch (Exception ex) { return BadRequest(ex.Message); } } // POST: api/Auctions // To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754 [HttpPost] public ActionResult<Auction> PostAuction(AuctionCreateDTO auctioncreateDTO) { var config = new MapperConfiguration( cfg => cfg.AddProfile(new AuctionProfile()) ); var mapper = config.CreateMapper(); var auction = mapper.Map<Auction>(auctioncreateDTO); _auction.AddNewAuction(auction); return Ok(auction); } // DELETE: api/Auctions/5 [HttpDelete("{id}")] public async Task<IActionResult> DeleteAuction(int id) { if (_auction.GetAuction() == null) { return NotFound(); } var auction = _auction.GetAuctionById(id); if (auction == null) { return NotFound(); } _auction.DeleteAuction(auction); return NoContent(); } } }
import { Component, Input, OnInit } from '@angular/core'; import { Comment } from '../../interfaces/comment.model'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { PostService } from '../../services/post.service'; import { getAuth } from 'firebase/auth'; import { app } from '../../../app.module'; import { Router } from '@angular/router'; import { AuthService } from '../../services/auth.service'; @Component({ selector: 'app-comment', templateUrl: './comment.component.html', styleUrls: ['./comment.component.scss'] }) export class CommentComponent implements OnInit { @Input() postId!: string; comments: Comment[] = []; commentForm: FormGroup; commentUsers: { [uid: string]: string } = {}; isLoggedIn = false; constructor(private postService: PostService, private fb: FormBuilder, private router: Router, private authService: AuthService) { this.commentForm = this.fb.group({ content: ['', Validators.required] }); } ngOnInit(): void { this.postService.getComments(this.postId).then(comments => { this.comments = comments; comments.forEach(comment => { this.getUserNameById(comment.authorId).then(name => { this.commentUsers[comment.authorId] = name; }); }); }); const auth = getAuth(app); auth.onAuthStateChanged(user => { this.isLoggedIn = !!user; }); } async addComment() { const user = getAuth(app).currentUser; if (user) { if (!this.commentForm.valid) { return; } const comment: Comment = this.commentForm.value; await this.postService.createComment(this.postId, comment); this.commentForm.reset(); this.ngOnInit(); // Reload comments } else { // Handle the case where the user is not authenticated this.router.navigate(['/login']); } } // Methods to edit or delete comments for authenticated users or superusers async getUserNameById(authorId: string) { // returns the First and Last name of the user const user = await this.authService.getUserById(authorId); return `${user.firstName} ${user.lastName}`; } }
package com.github.hemoptysisheart.parking.client.google import com.github.hemoptysisheart.parking.client.google.data.AutocompleteParams import com.github.hemoptysisheart.parking.client.google.data.DirectionsParams import com.github.hemoptysisheart.parking.client.google.data.DirectionsRoute import com.github.hemoptysisheart.parking.client.google.data.FindPlaceParams import com.github.hemoptysisheart.parking.client.google.data.NearbySearchParams import com.github.hemoptysisheart.parking.client.google.data.Place import com.github.hemoptysisheart.parking.client.google.data.PlaceAutocompletePrediction import com.github.hemoptysisheart.parking.client.google.data.PlaceParams /** * [Places API](https://console.cloud.google.com/apis/library/places-backend.googleapis.com) */ interface MapsClient { /** * [Place Details](https://developers.google.com/maps/documentation/places/web-service/details) */ suspend fun place(params: PlaceParams): Place? /** * [Place Autocomplete](https://developers.google.com/maps/documentation/places/web-service/autocomplete) */ suspend fun autocomplete(params: AutocompleteParams): List<PlaceAutocompletePrediction> /** * [주변 지역 검색](https://developers.google.com/maps/documentation/places/web-service/search-nearby) */ suspend fun nearBy(params: NearbySearchParams): List<Place> /** * [Find Place](https://developers.google.com/maps/documentation/places/web-service/search-find-place)용 인자. */ suspend fun findPlace(params: FindPlaceParams): List<Place> /** * [Directions API를 통해 경로 찾기](https://developers.google.com/maps/documentation/directions/get-directions) */ suspend fun directions(params: DirectionsParams): List<DirectionsRoute> }
/* O objetivo desse VPL é praticar os comandos de entrada e saída específicos de C++ (cin, cout) e também a utilização do tipo string. Não utilize outros comando de entrada como o getline. Escreva um programa que lê apenas uma única palavra da entrada. Em seguida, seu programa deve contar o número de vogais presente na palavra. Ao final, deve-se imprimir a quantidade de vezes que uma determinada vogal apareceu. Se uma vogal não apareceu nenhuma vez ela não deve ser impressa. Para facilitar, você pode assumir que as palavras sempre terão todas as letras minúsculas. Exemplos de entrada e saída: input = estudantes output = a 1 e 2 u 1 input = abacaxi output = a 3 i 1 */ #include <iostream> int main() { std::string palavra; std::cin >> palavra; int vogais[5] = {0, 0, 0, 0, 0}; for (int i = 0; i < palavra.size(); i++) { if (palavra[i] == 'a') { vogais[0]++; } else if (palavra[i] == 'e') { vogais[1]++; } else if (palavra[i] == 'i') { vogais[2]++; } else if (palavra[i] == 'o') { vogais[3]++; } else if (palavra[i] == 'u') { vogais[4]++; } } if (vogais[0] > 0) { std::cout << "a " << vogais[0] << std::endl; } if (vogais[1] > 0) { std::cout << "e " << vogais[1] << std::endl; } if (vogais[2] > 0) { std::cout << "i " << vogais[2] << std::endl; } if (vogais[3] > 0) { std::cout << "o " << vogais[3] << std::endl; } if (vogais[4] > 0) { std::cout << "u " << vogais[4] << std::endl; } return 0; }
import React, { useState } from "react"; import { AiOutlineArrowRight as SendArrow } from "react-icons/ai"; interface IMessagesInput { handleSendMessage: (value: string) => void; } export const MessagesInput = ({ handleSendMessage }: IMessagesInput) => { const [messageValue, setMessageValue] = useState<string>(""); const isButtonVisable = messageValue.length; const handleClickButton = () => { handleSendMessage(messageValue); setMessageValue(""); }; return ( <div className="flex gap-[4px] px-[24px] pb-[17px]"> <input type="text" value={messageValue} onChange={(e) => setMessageValue(e.target.value)} placeholder="Your message..." className="w-full rounded-2xl border pb-[28px] pl-[16px] pr-[12px] pt-[8px] text-xs outline-none focus:border-black" /> {isButtonVisable ? ( <button className="flex h-full items-center justify-center rounded-2xl bg-yellow-400 p-[16px]" onClick={handleClickButton} > <SendArrow /> </button> ) : ( "" )} </div> ); };
import { useState } from 'react'; import BoxShadow from '../../../../components/BoxShadow/BoxShadow'; import './Board.scss'; import { CellData, Mark, TurnsData } from '../../../../utils/types/interfaces'; import { renderIcon } from '../../../../utils/helpers/helpers'; interface BoardProps { onSelectCell: (rowIndex: number, colIndex: number) => void; markToDissappear: TurnsData | undefined; activePlayer: Mark; gameBoard: Mark[][]; } export default function Board(props: BoardProps) { const [hoveredCell, setHoveredCell] = useState<CellData | null>(null); function handleMouseEnter(rowIndex: number, colIndex: number) { setHoveredCell({ row: rowIndex, col: colIndex }); } function handleMouseLeave() { setHoveredCell(null); } function isMarkToDissappear(rowIndex: number, colIndex: number) { if (props.markToDissappear) { return ( rowIndex === props.markToDissappear.cell.row && colIndex === props.markToDissappear.cell.col ); } } return ( <> <ol className="board"> {props.gameBoard.map((row, rowIndex) => ( <li key={rowIndex}> <ol className="column"> {row.map((playerMark, colIndex) => ( <BoxShadow key={colIndex}> <div onClick={() => { handleMouseLeave(); props.onSelectCell(rowIndex, colIndex); }} onMouseEnter={() => handleMouseEnter(rowIndex, colIndex)} onMouseLeave={handleMouseLeave} className={`board-cell navy-theme ${playerMark !== Mark.NONE ? 'disabled' : ''}`} > {isMarkToDissappear(rowIndex, colIndex) ? renderIcon(playerMark, false, true) : renderIcon(playerMark)} {playerMark === Mark.NONE && hoveredCell?.row === rowIndex && hoveredCell?.col === colIndex && renderIcon(props.activePlayer, true)} </div> </BoxShadow> ))} </ol> </li> ))} </ol> </> ); }
# 수들의 합 ----- ### 🌞 문제 서로 다른 N개의 자연수의 합이 S라고 한다. S를 알 때, 자연수 N의 최댓값은 얼마일까? ### 📝 입력 첫째 줄에 자연수 S(1 ≤ S ≤ 4,294,967,295)가 주어진다. ### 👋 출력 첫째 줄에 자연수 N의 최댓값을 출력한다. ### 🚩 입출력 예제 - 입력 200 - 출력 19 ### 👩‍💻 풀이 ```python s = int(input()) answer = 0 start = 1 end = s while start <= end: mid = (start + end) // 2 if (mid * (mid + 1)) // 2 <= s: answer = mid start = mid + 1 else: end = mid - 1 print(answer) ``` ### 🔑 구현 아이디어 - 이분 탐색 또는 그리디로 푸는 문제인데 이분 탐색을 연습하려고 이분 탐색으로 풀었다. - (mid * (mid + 1) // 2)를 통해 1부터 mid까지의 값을 구했다. - 구한 값이 s보다 작거나 같으면 answer에 mid를 넣고 start를 mid + 1로 바꾼다. ### 🙋‍♀‍ 문제에 대한 나의 생각 - end를 문제 조건에 있는 값으로 해서 sum 함수가 잘 반응을 하지 못 했다. 그래서 다른 분의 코드를 참고했는데, 어렸을 때 배웠던 공식을 이용하면 간단했던 것이었다. - 이분 탐색 문제를 오랜만에 풀어보니 쉬운 문제임에도 헷갈렸다. 복습은 필수! ------------- #### 📚 출처 - [백준 1789](https://www.acmicpc.net/problem/1789) - [참고](https://data-bank.tistory.com/36) #### 📅 공부 날짜 및 소요 시간 - ❌ 2022.02.08 (생각 및 구현 : 30분 -> 답 보고 이해 5분) #### 🌳 문제 난이도 : 실버 5 #### ⭐ 개인적인 난이도 : 0.5 / 5
<?php namespace App\NotificationPublisher\Infrastructure\Persistence\Repository; use App\NotificationPublisher\Domain\Entity\Notification; use App\NotificationPublisher\Domain\Repository\NotificationRepository; use App\NotificationPublisher\Infrastructure\Persistence\Entity\DoctrineNotification; use DateTime; use Doctrine\ORM\EntityManagerInterface; class DoctrineNotificationRepository implements NotificationRepository { private EntityManagerInterface $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } public function findAll(int $page, int $limit): array { $doctrineNotifications = $this->entityManager->createQueryBuilder() ->select(array('n')) ->from(DoctrineNotification::class, 'n') ->orderBy('n.id', 'DESC') ->setFirstResult($page === 1 ? $page - 1 : $page * $limit) ->setMaxResults($limit) ->getQuery() ->getResult(); $notifications = []; foreach ($doctrineNotifications as $doctrineNotification){ $notificationDto = $doctrineNotification->toDto(); $notification = new Notification(); $notification->setId($notificationDto->getId()); $notification->setContent($notificationDto->getContent()); $notification->setSubject($notificationDto->getSubject()); $notification->setUserId($notificationDto->getUserId()); $notification->setEmail($notificationDto->getEmail()); $notification->setPhone($notificationDto->getPhone()); $notification->setSendingDate($notificationDto->getSendingDate()); $notification->setAttempts($notificationDto->getAttempts()); $notification->setStatus($notificationDto->getStatus()); $notifications[] = $notification; } return $notifications; } public function findAllByStatus(string $status): array { $doctrineNotifications = $this->entityManager->createQueryBuilder() ->select(array('n')) ->from(DoctrineNotification::class, 'n') ->where('n.status = \''.$status.'\'') ->orderBy('n.id', 'DESC') ->getQuery() ->getResult(); $notifications = []; foreach ($doctrineNotifications as $doctrineNotification){ $notificationDto = $doctrineNotification->toDto(); $notification = new Notification(); $notification->setId($notificationDto->getId()); $notification->setContent($notificationDto->getContent()); $notification->setSubject($notificationDto->getSubject()); $notification->setUserId($notificationDto->getUserId()); $notification->setEmail($notificationDto->getEmail()); $notification->setPhone($notificationDto->getPhone()); $notification->setSendingDate($notificationDto->getSendingDate()); $notification->setAttempts($notificationDto->getAttempts()); $notification->setStatus($notificationDto->getStatus()); $notifications[] = $notification; } return $notifications; } public function create(Notification $notification): void { $notificationDto = $notification->toDto(); $doctrineNotification = new DoctrineNotification(); $doctrineNotification->setContent($notificationDto->getContent()); $doctrineNotification->setSubject($notificationDto->getSubject()); $doctrineNotification->setUserId($notificationDto->getUserId()); $doctrineNotification->setEmail($notificationDto->getEmail()); $doctrineNotification->setPhone($notificationDto->getPhone()); $doctrineNotification->setSendingDate((new DateTime('now'))); $doctrineNotification->setAttempts(1); $doctrineNotification->setStatus($notificationDto->getStatus()); $this->entityManager->persist($doctrineNotification); $this->entityManager->flush(); } public function update(Notification $notification): void { $notificationDto = $notification->toDto(); $doctrineNotification = $this->entityManager->createQueryBuilder() ->select(array('n')) ->from(DoctrineNotification::class, 'n') ->where('n.id = '.$notificationDto->getId()) ->getQuery() ->getResult()[0]; $doctrineNotification->setSendingDate((new DateTime('now'))); $doctrineNotification->setAttempts($notificationDto->getAttempts()); $doctrineNotification->setStatus($notificationDto->getStatus()); $this->entityManager->persist($doctrineNotification); $this->entityManager->flush(); } }
package software.wings.service.impl.yaml.handler.infraprovisioner; import static io.harness.data.structure.EmptyPredicate.isEmpty; import static io.harness.data.structure.EmptyPredicate.isNotEmpty; import static io.harness.exception.WingsException.USER; import static io.harness.validation.Validator.notNullCheck; import static software.wings.beans.Application.GLOBAL_APP_ID; import static java.util.stream.Collectors.toList; import io.harness.beans.SecretManagerConfig; import io.harness.exception.InvalidRequestException; import software.wings.beans.Application; import software.wings.beans.InfrastructureProvisionerType; import software.wings.beans.NameValuePair; import software.wings.beans.SettingAttribute; import software.wings.beans.TerraformInfrastructureProvisioner; import software.wings.beans.TerraformInfrastructureProvisioner.Yaml; import software.wings.beans.yaml.ChangeContext; import software.wings.service.impl.yaml.handler.NameValuePairYamlHandler; import software.wings.service.intfc.AppService; import software.wings.service.intfc.SettingsService; import software.wings.service.intfc.security.SecretManager; import software.wings.utils.Utils; import com.google.inject.Inject; import java.util.List; public class TerraformInfrastructureProvisionerYamlHandler extends InfrastructureProvisionerYamlHandler<Yaml, TerraformInfrastructureProvisioner> { @Inject SettingsService settingsService; @Inject AppService appService; @Inject SecretManager secretManager; protected String getSourceRepoSettingId(String appId, String sourceRepoSettingName) { Application application = appService.get(appId); SettingAttribute settingAttribute = settingsService.getSettingAttributeByName(application.getAccountId(), sourceRepoSettingName); notNullCheck("Invalid Source Repo Setting:" + sourceRepoSettingName, settingAttribute, USER); return settingAttribute.getUuid(); } protected String getSourceRepoSettingName(String appId, String sourceRepoSettingId) { SettingAttribute settingAttribute = settingsService.get(GLOBAL_APP_ID, sourceRepoSettingId); notNullCheck("Invalid Source Repo Setting:" + sourceRepoSettingId, settingAttribute, USER); return settingAttribute.getName(); } @Override public Yaml toYaml(TerraformInfrastructureProvisioner bean, String appId) { Yaml yaml = Yaml.builder().build(); super.toYaml(yaml, bean); yaml.setType(InfrastructureProvisionerType.TERRAFORM.name()); yaml.setPath(bean.getPath()); yaml.setSourceRepoSettingName(getSourceRepoSettingName(appId, bean.getSourceRepoSettingId())); yaml.setSourceRepoBranch(bean.getSourceRepoBranch()); yaml.setCommitId(bean.getCommitId()); yaml.setRepoName(bean.getRepoName()); if (isNotEmpty(bean.getBackendConfigs())) { yaml.setBackendConfigs(getSortedNameValuePairYamlList(bean.getBackendConfigs(), bean.getAppId())); } if (isNotEmpty(bean.getEnvironmentVariables())) { yaml.setEnvironmentVariables(getSortedNameValuePairYamlList(bean.getEnvironmentVariables(), bean.getAppId())); } if (isNotEmpty(bean.getKmsId())) { SecretManagerConfig secretManagerConfig = secretManager.getSecretManager(bean.getAccountId(), bean.getKmsId()); yaml.setSecretMangerName(secretManagerConfig.getName()); } yaml.setSkipRefreshBeforeApplyingPlan(bean.isSkipRefreshBeforeApplyingPlan()); return yaml; } private List<software.wings.beans.NameValuePair.Yaml> getSortedNameValuePairYamlList( List<NameValuePair> nameValuePairList, String appId) { NameValuePairYamlHandler nameValuePairYamlHandler = getNameValuePairYamlHandler(); List<NameValuePair.Yaml> nvpYamlList = nameValuePairList.stream() .map(nameValuePair -> nameValuePairYamlHandler.toYaml(nameValuePair, appId)) .collect(toList()); return Utils.getSortedNameValuePairYamlList(nvpYamlList); } @Override public TerraformInfrastructureProvisioner upsertFromYaml( ChangeContext<Yaml> changeContext, List<ChangeContext> changeSetContext) { String yamlFilePath = changeContext.getChange().getFilePath(); String accountId = changeContext.getChange().getAccountId(); String appId = yamlHelper.getAppId(accountId, yamlFilePath); notNullCheck("Couldn't retrieve app from yaml:" + yamlFilePath, appId, USER); TerraformInfrastructureProvisioner current = TerraformInfrastructureProvisioner.builder().build(); toBean(current, changeContext, appId); String name = yamlHelper.getNameFromYamlFilePath(changeContext.getChange().getFilePath()); TerraformInfrastructureProvisioner previous = (TerraformInfrastructureProvisioner) infrastructureProvisionerService.getByName(appId, name); if (previous != null) { current.setUuid(previous.getUuid()); current.setSyncFromGit(changeContext.getChange().isSyncFromGit()); current = (TerraformInfrastructureProvisioner) infrastructureProvisionerService.update(current); } else { current = (TerraformInfrastructureProvisioner) infrastructureProvisionerService.save(current); } changeContext.setEntity(current); return current; } private void toBean(TerraformInfrastructureProvisioner bean, ChangeContext<TerraformInfrastructureProvisioner.Yaml> changeContext, String appId) { TerraformInfrastructureProvisioner.Yaml yaml = changeContext.getYaml(); String yamlFilePath = changeContext.getChange().getFilePath(); super.toBean(changeContext, bean, appId, yamlFilePath); bean.setPath(yaml.getPath()); bean.setSourceRepoSettingId(getSourceRepoSettingId(appId, yaml.getSourceRepoSettingName())); validateBranchCommitId(yaml.getSourceRepoBranch(), yaml.getCommitId()); bean.setSourceRepoBranch(yaml.getSourceRepoBranch()); bean.setCommitId(yaml.getCommitId()); bean.setRepoName(yaml.getRepoName()); bean.setSkipRefreshBeforeApplyingPlan(yaml.isSkipRefreshBeforeApplyingPlan()); if (isNotEmpty(yaml.getBackendConfigs())) { bean.setBackendConfigs(getNameValuePairList(yaml.getBackendConfigs())); } if (isNotEmpty(yaml.getEnvironmentVariables())) { bean.setEnvironmentVariables(getNameValuePairList(yaml.getEnvironmentVariables())); } if (isNotEmpty(yaml.getSecretMangerName())) { SecretManagerConfig secretManagerConfig = secretManager.getSecretManagerByName(bean.getAccountId(), yaml.getSecretMangerName()); bean.setKmsId(secretManagerConfig.getUuid()); } } private List<NameValuePair> getNameValuePairList(List<NameValuePair.Yaml> nameValuePairList) { return nameValuePairList.stream() .map(nvpYaml -> NameValuePair.builder() .name(nvpYaml.getName()) .value(nvpYaml.getValue()) .valueType(nvpYaml.getValueType()) .build()) .collect(toList()); } private void validateBranchCommitId(String sourceRepoBranch, String commitId) { if (isEmpty(sourceRepoBranch) && isEmpty(commitId)) { throw new InvalidRequestException("Either sourceRepoBranch or commitId should be specified", USER); } if (isNotEmpty(sourceRepoBranch) && isNotEmpty(commitId)) { throw new InvalidRequestException("Cannot specify both sourceRepoBranch and commitId", USER); } } @Override public Class getYamlClass() { return Yaml.class; } @Override public TerraformInfrastructureProvisioner get(String accountId, String yamlFilePath) { return (TerraformInfrastructureProvisioner) yamlHelper.getInfrastructureProvisioner(accountId, yamlFilePath); } }
<?php namespace Devinci\Bladekit; use Illuminate\Support\Facades\Blade; use Illuminate\Support\Facades\Log; class DirectiveRegistry { /** * Register all Bladekit directives. * * @return void */ public static function registerAllDirectives() { self::registerBladekitStylesDirective(); self::registerBladekitScriptsDirective(); self::registerBladekitAssetDirective(); } /** * Register the directive for including JS files. * * @return string The generated script tag. */ protected static function registerBladekitScriptsDirective() { Blade::directive('bladekitScripts', function () { return '<script src="' . asset(static::getJsPath()) . '"></script>' . PHP_EOL; }); } /** * Get the path for Bladekit JavaScript file. * * @return string The JavaScript file path. */ protected static function getJsPath() { $publishedJsPath = public_path('js/vendor/devinci-it/bladekit/bladekit.js'); return $publishedJsPath; // return file_exists($publishedJsPath) ? asset('js/vendor/devinci-it/bladekit/bladekit.js') : asset('js/vendor/devinci-it/bladekit/bladekit.js'); } /** * Register the directive for including CSS files. * * @return string The generated link tags for CSS files. */ protected static function registerBladekitStylesDirective() { Blade::directive('bladekitStyles', function () { $cssFiles = static::getCssFiles(); return implode(PHP_EOL, array_map(function ($file) { return '<link rel="stylesheet" href="' . asset($file) . '">'; }, $cssFiles)); }); } /** * Get Bladekit CSS files. * * @return array CSS files paths. */ protected static function getCssFiles() { $publishedCssPath = public_path('vendor/devinci-it/bladekit/css/'); if (file_exists($publishedCssPath)) { $cssFiles = glob($publishedCssPath . '*.css'); return array_map('asset', $cssFiles); } $cssFiles = glob(__DIR__ . '/../resources/css/*.css'); return array_map('asset', $cssFiles); } protected static function registerBladekitAssetDirective() { Blade::directive('bladekitAsset', function ($expression) { try { // Extract parameters from the expression preg_match('/(\'|")([^\'"]+)(\'|")/', $expression, $matches); $assetName = trim($matches[2]); // Assuming the expression only contains the asset name // Construct the full asset path within the published directory $publishedPath = "js/vendor/devinci-it/bladekit/js/$assetName"; // Check if the published asset exists if (file_exists(public_path($publishedPath))) { return asset($publishedPath); // Return the asset URL using the asset() helper function } // If the published asset does not exist, log a warning Log::warning("Published asset '$publishedPath' not found."); // Optionally, you can handle the missing asset further or return a fallback value return ''; } catch (\Exception $e) { // Log the exception Log::error($e->getMessage()); // Optionally, you can handle the exception further or return a fallback value return ''; } }); } }
package proj; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpSession; import jakarta.ws.rs.*; import jakarta.ws.rs.core.Context; import jakarta.ws.rs.core.MediaType; import jakarta.ws.rs.core.Response; @Path("/bid") public class AuctionController { @Context private HttpServletRequest servletRequest; private ItemDAO itemDAO = new ItemDAO(); @GET @Path("/forward") @Produces(MediaType.APPLICATION_JSON) public Response getForwardPage( @QueryParam("itemID") int id) { Item item = itemDAO.read(id); return Response.status(Response.Status.OK).entity(item).build(); } @POST @Path("/placeForwardBid") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response placeBid(BidRequest bidRequest) { // Ensure the user is logged in HttpSession session = servletRequest.getSession(); User loggedInUser = (User) session.getAttribute("loggedInUser"); if (loggedInUser == null) { return Response.status(Response.Status.UNAUTHORIZED).entity("User not logged in").build(); } // Retrieve the item for which the bid is being placed int itemId = bidRequest.getItemId(); Item item = itemDAO.read(itemId); if (item == null) { return Response.status(Response.Status.NOT_FOUND).entity("Item not found").build(); } // Validate the bid amount ( can add more validation) double bidAmount = bidRequest.getBidAmount(); if (bidAmount <= item.getHighestBid()) { return Response.status(Response.Status.BAD_REQUEST).entity("Bid must be higher than the current highest bid").build(); } // Update the item's highest bid and bidder in the DB bidRequest.setUserName(loggedInUser.getUsername()); itemDAO.updateBid(itemId, bidAmount, loggedInUser.getUsername()); // Notify connected WebSocket clients about the new bid // BiddingWebSocket.broadcastBidUpdate(bidRequest); return Response.status(Response.Status.OK).entity(bidRequest).build(); } @GET @Path("/dutch") @Produces(MediaType.APPLICATION_JSON) public Response getDutchPage( @QueryParam("itemID") int id) { Item item = itemDAO.read(id); return Response.status(Response.Status.OK).entity(item).build(); } @POST @Path("/placeDutchBid") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response placeDutchBid(BidRequest bidRequest) { // Ensure the user is logged in HttpSession session = servletRequest.getSession(); User loggedInUser = (User) session.getAttribute("loggedInUser"); if (loggedInUser == null) { return Response.status(Response.Status.UNAUTHORIZED).entity("User not logged in").build(); } // Retrieve the item for which the bid is being placed int itemId = bidRequest.getItemId(); Item item = itemDAO.read(itemId); if (item == null) { return Response.status(Response.Status.NOT_FOUND).entity("Item not found").build(); } bidRequest.setUserName(loggedInUser.getUsername()); // itemDAO.delete(itemId); ForwardBidWebSocket.broadcastBidUpdate(bidRequest); return Response.status(Response.Status.OK).entity(bidRequest).build(); } @GET @Path("/getLatestBid") @Produces(MediaType.APPLICATION_JSON) public Response getLatestBid(@QueryParam("itemID") int id) { Item item = itemDAO.read(id); if (item != null) { BidRequest bid = new BidRequest(); bid.setBidAmount(Math.max(item.getHighestBid(), item.getPrice())); bid.setUserName(item.getHighestBidder()); return Response.status(Response.Status.OK).entity(bid).build(); } else { return Response.status(Response.Status.NOT_FOUND).entity("Item not found").build(); } } @GET @Path("/auctionEnded/{itemID}") @Produces(MediaType.APPLICATION_JSON) public Response paymentEnded(@PathParam("itemID") int itemID) { Item item = itemDAO.read(itemID); HttpSession session = servletRequest.getSession(); User loggedInUser = (User) session.getAttribute("loggedInUser"); if (loggedInUser == null) { return Response.status(Response.Status.UNAUTHORIZED).entity("User not logged in").build(); } if (item == null) { return Response.status(Response.Status.NOT_FOUND).entity("Item not found").build(); } if (!loggedInUser.getUsername().equals(item.getHighestBidder())){ return Response.status(Response.Status.UNAUTHORIZED).entity("User is not the winning bidder").build(); } if (item != null) { //itemDAO.delete(itemID); return Response.status(Response.Status.OK).entity(item).build(); }else return Response.status(Response.Status.NOT_FOUND).entity("Item not found").build(); } }
<script setup> import { reactive, inject, watch, ref, onMounted} from 'vue'; import axios from 'axios'; import debounce from 'lodash.debounce'; import CardList from '../components/CardList.vue' const { cart, addToCart, removeFromCart } = inject('cart'); const items = ref([]); const filters = reactive ({ searchQuery: '', sortBy: 'title' }); const onClickAddPlus = (item) => { if (!item.isAdded) { addToCart(item); } else { removeFromCart(item); } console.log(cart); } const onChangeSelect = event => { filters.sortBy = event.target.value } const onChangeSearchInput = debounce((event) => { filters.searchQuery = event.target.value }, 500) const addToFavorite = async (item) => { try { if (!item.isFavorite) { const obj = { item_id: item.id } item.isFavorite = true const {data} = await axios.post(`https://1dba12d59af42e98.mokky.dev/favorites`, obj); item.favoriteId = data.id; } else { item.isFavorite = false await axios.delete(`https://1dba12d59af42e98.mokky.dev/favorites/${item.favoriteId}`); item.favoriteId = null; } } catch (error) { console.log(error); } } const fetchFavorite = async () => { try { const {data: favorites} = await axios.get(`https://1dba12d59af42e98.mokky.dev/favorites`) items.value = items.value.map(item => { const favorite = favorites.some(favorite => favorite.item_id === item.id); if (!favorite) { return item; } return { ...item, isFavorite: true, favoriteId: favorite.id, } }); console.log(items); } catch (error) { console.log(error); } } const fetchItems = async () => { try { const params = { sortBy: filters.sortBy, // searchQuery: filters.searchQuery } if (filters.searchQuery) { params.title = `*${filters.searchQuery}*` } const {data} = await axios.get(`https://1dba12d59af42e98.mokky.dev/items`, { params }) items.value = data.map((obj) => ({ ...obj, isFavorite: false, favoriteId: null, isAdded: false })) ; } catch (error) { console.log(error); } } onMounted (async () => { const localCart = localStorage.getItem('cart'); cart.value = localCart ? JSON.parse(localCart) : []; await fetchItems(); await fetchFavorite(); items.value = items.value.map((item) => ({ ...item, isAdded: cart.value.some((cartItem) => cartItem.id === item.id) })) }) watch(cart, () => { items.value = items.value.map((item) => ({ ...item, isAdded: false })) }) watch(filters,fetchItems) </script> <template> <div class="flex justify-between items-center"> <h2 class="text-3xl font-bold mb-10">Все кроссовки</h2> <div class="flex gap-4"> <select @change="onChangeSelect" class="py-2 px-2 border border-md outline-none" name="" id=""> <option value="name">По названию</option> <option value="price">По цене (дешевые)</option> <option value="-price">По цене (дорогие)</option> </select> <div class="relative"> <img class="absolute left-4 top-3" src="/search.svg" > <input @input="onChangeSearchInput" class="border rounded-md py-2 pl-11 pr-4 outline-none focus:border-gray-400" type="search" name="" id="" placeholder="Поиск..."> </div> </div> </div> <div class="mt-10"> <CardList :items="items" @add-to-favorite="addToFavorite" @add-to-cart="onClickAddPlus"/> </div> </template>
<?php namespace App\Events; use Illuminate\Broadcasting\Channel; use Illuminate\Broadcasting\InteractsWithSockets; use Illuminate\Broadcasting\PresenceChannel; use Illuminate\Broadcasting\PrivateChannel; use Illuminate\Contracts\Broadcasting\ShouldBroadcast; use Illuminate\Foundation\Events\Dispatchable; use Illuminate\Notifications\DatabaseNotification; use Illuminate\Queue\SerializesModels; class NotificationToggledEvent implements ShouldBroadcast { use Dispatchable, InteractsWithSockets, SerializesModels; /** * Create a new event instance. * * @return void */ public function __construct(public DatabaseNotification $notification) { // } /** * Get the channels the event should broadcast on. * * @return \Illuminate\Broadcasting\Channel|array */ public function broadcastOn() { return new PrivateChannel('notification-toggled'); } public function broadcastWith():array { return [ 'notification' => $this->notification, 'added' => is_null($this->notification->read_at) ]; } }
/* |-------------------------------------------------------------------------- | Routes |-------------------------------------------------------------------------- | | This file is dedicated for defining HTTP routes. A single file is enough | for majority of projects, however you can define routes in different | files and just make sure to import them inside this file. For example | | Define routes in following two files | ├── start/routes/cart.ts | ├── start/routes/customer.ts | | and then import them inside `start/routes.ts` as follows | | import './routes/cart' | import './routes/customer'' | */ import Route from '@ioc:Adonis/Core/Route' Route.group(() => { Route.get('/', async ({ view }) => { return view.render('welcome') }) Route.get('/login', 'AuthController.getLogin') Route.get('/register', 'AuthController.getRegister') Route.post('/register', 'AuthController.register') Route.post('/login', 'AuthController.login') }).middleware('guest') Route.group(() => { Route.get('/dashboard', 'MainsController.renderDashboard') Route.post('/logout', 'AuthController.logout') Route.post('/dashboard/student/class', 'StudentsController.setClass') Route.post('/dashboard/teacher/class', 'TeachersController.addClass') Route.get( '/dashboard/my-classes/:classId/:class/:section/:subject', 'TeachersController.classInfo' ) Route.get('/dashboard/students/:studentId', 'TeachersController.getStudent') Route.post('/dashboard/teacher-students/add-mark', 'TeachersController.addStudentMark') Route.post('/dashboard/teacher/session', 'TeachersController.addSession') Route.post('/dashboard/student/attend', 'StudentsController.attend') Route.get('/dashboard/my-sessions/:sessionId', 'TeachersController.sessionInfo') Route.post('/dashboard/student/not-attend', 'TeachersController.userNotAttend') }).middleware('auth')
// 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. // Provides test cases for TextBoxBase properties introduced in Orcas. namespace Test.Uis.TextEditing { #region Using directives using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Threading; using Microsoft.Test; using Microsoft.Test.Discovery; using Test.Uis.Data; using Test.Uis.Loggers; using Test.Uis.Management; using Test.Uis.TestTypes; using Test.Uis.Utils; using Test.Uis.Wrappers; #endregion // DISABLEDUNSTABLETEST: // TestName: UndoLimitTest // Area: Editing SubArea: UndoRedo // Disable this case due to high fail rate, will enable after fix it. // to find all disabled tests in test tree, use: �findstr /snip DISABLEDUNSTABLETEST� /// <summary> /// Tests UndoLimit property in TextBox and RichTextBox /// </summary> [Test(2, "UndoRedo", "UndoLimitTest", MethodParameters = "/TestCaseType=UndoLimitTest", Keywords = "Setup_SanitySuite", Disabled = true)] public class UndoLimitTest : ManagedCombinatorialTestCase { #region Main flow /// <summary>Combination starts here.</summary> protected override void DoRunCombination() { _tbb = (TextBoxBase)_editableType.CreateInstance(); _tbb.AcceptsReturn = true; _tbbWrapper = new UIElementWrapper(_tbb); _tbb.IsUndoEnabled = _isUndoEnabledTestValue; //type "x{ENTER} couple of times so that we have undo units created for each operation. _typedContent = TextUtils.RepeatString("x{ENTER}", TestUndoLimitValue); _expectedTypedContent = TextUtils.RepeatString("x\r\n", TestUndoLimitValue); // _undoActionString = TextUtils.RepeatString("^z", TestUndoLimitValue); _expectedContentAfterUndo = TextUtils.RepeatString("x\r\n", TestUndoLimitValue / 2); _redoActionString = TextUtils.RepeatString("^y", TestUndoLimitValue); Verifier.Verify(_tbb.UndoLimit == DefaultUndoLimitValue, "Verifying the default value of the UndoLimit property", false); Verifier.Verify((_tbb.CanUndo == false) && (_tbb.CanRedo == false), "Verifying that CanUndo & CanRedo is false initially", false); TestElement = _tbb; QueueDelegate(SetTestLimitValue); } private void SetTestLimitValue() { Verifier.Verify(_tbb.UndoLimit == DefaultUndoLimitValue, "Verifying the default value of the UndoLimit property after added to the tree", false); _tbb.UndoLimit = TestUndoLimitValue; Log("Assigning [" + TestUndoLimitValue + "] to UndoLimit property"); Verifier.Verify(_tbb.UndoLimit == TestUndoLimitValue, "Verifying value of UndoLimit property to the assigned value", false); _tbb.Focus(); QueueDelegate(DoType); } private void DoType() { KeyboardInput.TypeString(_typedContent); QueueDelegate(DoUndo); } private void DoUndo() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying initial state - content after before performing undo command: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); KeyboardInput.TypeString(_undoActionString); QueueDelegate(CheckUndoAtTestValue); } private void CheckUndoAtTestValue() { if (_isUndoEnabledTestValue) { _expectedContent = _expectedContentAfterUndo; } else { _expectedContent = _expectedTypedContent; } //extra newline for the last paragraph in RTB if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command: ActualContent [" + _tbbWrapper.Text + "] ExpectedContent [" + _expectedContent + "]", true); //perform undo after limit is reached KeyboardInput.TypeString("^z"); QueueDelegate(CheckUndoAtTestValueAfterLimit); } private void CheckUndoAtTestValueAfterLimit() { Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command with limit reached: " + "ActualContent [" + _tbbWrapper.Text + "] ExpectedContent [" + _expectedContent + "]", true); //perform redo all the way back KeyboardInput.TypeString(_redoActionString); QueueDelegate(CheckRedoAtTestValue); } private void CheckRedoAtTestValue() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing redo command: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); //Perform undo again to make sure things are working after performing redo KeyboardInput.TypeString(_undoActionString); QueueDelegate(CheckUndoAtTestValueAgain); } private void CheckUndoAtTestValueAgain() { if (_isUndoEnabledTestValue) { _expectedContent = _expectedContentAfterUndo; } else { _expectedContent = _expectedTypedContent; } if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command again: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); SetMaxIntValue(); } private void SetMaxIntValue() { //Testing at Int32.MaxValue ClearBox(); Log("Assigning Int32.MaxValue[" + Int32.MaxValue + "] to UndoLimit property"); _tbb.UndoLimit = Int32.MaxValue; Verifier.Verify(_tbb.UndoLimit == Int32.MaxValue, "Verifying value of UndoLimit property to the assigned value", false); Verifier.Verify((_tbb.CanUndo == false) && (_tbb.CanRedo == false), "Verifying that CanUndo & CanRedo is false after UndoLimit property is set to Int.Max", true); Log("Type and perform undo with UndoLimit at Int32.MaxValue"); KeyboardInput.TypeString(_typedContent + _undoActionString); QueueDelegate(CheckContentAtMaxIntAfterUndo); } private void CheckContentAtMaxIntAfterUndo() { if (_isUndoEnabledTestValue) { _expectedContent = _expectedContentAfterUndo; } else { _expectedContent = _expectedTypedContent; } if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command with UndoLimit at Int32.MaxValue: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); KeyboardInput.TypeString(_redoActionString); QueueDelegate(CheckContentAtMaxIntAfterRedo); } private void CheckContentAtMaxIntAfterRedo() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing redo command with UndoLimit at Int32.MaxValue: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); SetMinusOneValue(); } private void SetMinusOneValue() { //Testing with special value of -1 (infinite undostack) ClearBox(); Log("Assigning [-1] to UndoLimit property"); _tbb.UndoLimit = -1; Verifier.Verify(_tbb.UndoLimit == -1, "Verifying value of UndoLimit property to the assigned value", false); Verifier.Verify((_tbb.CanUndo == false) && (_tbb.CanRedo == false), "Verifying that CanUndo & CanRedo is false after UndoLimit property is set to -1", true); Log("Type and perform undo with UndoLimit at -1"); KeyboardInput.TypeString(_typedContent + _undoActionString + _undoActionString); QueueDelegate(CheckContentAtMinusOneAfterUndo); } private void CheckContentAtMinusOneAfterUndo() { if (_isUndoEnabledTestValue) { _expectedContent = string.Empty; } else { _expectedContent = _expectedTypedContent; } if ((_tbb is RichTextBox) && (_expectedContent != string.Empty)) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command with UndoLimit at -1: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); KeyboardInput.TypeString(_redoActionString + _redoActionString); QueueDelegate(CheckContentAtMinusOneAfterRedo); } private void CheckContentAtMinusOneAfterRedo() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing redo command with UndoLimit at -1: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); SetZeroValue(); } private void SetZeroValue() { //Testing with special value of 0 (no undo) ClearBox(); Log("Assigning [0] to UndoLimit property"); _tbb.UndoLimit = 0; Verifier.Verify(_tbb.UndoLimit == 0, "Verifying value of UndoLimit property to the assigned value", false); Verifier.Verify((_tbb.CanUndo == false) && (_tbb.CanRedo == false), "Verifying that CanUndo & CanRedo is false after UndoLimit property is set to 0", true); Log("Type and perform undo with UndoLimit at 0"); KeyboardInput.TypeString(_typedContent + _undoActionString); QueueDelegate(CheckContentAfterUndoAtZero); } private void CheckContentAfterUndoAtZero() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command with UndoLimit at 0: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); KeyboardInput.TypeString(_redoActionString); QueueDelegate(CheckContentAfterRedoAtZero); } private void CheckContentAfterRedoAtZero() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing redo command with UndoLimit at 0: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); ChangeIsUndoEnabledValue(); } private void ChangeIsUndoEnabledValue() { //Change the value of IsUndoEnabled ClearBox(); _tbb.ClearValue(TextBoxBase.UndoLimitProperty); if (_isUndoEnabledTestValue) { _tbb.IsUndoEnabled = false; Verifier.Verify(_tbb.IsUndoEnabled == false, "Verifying that IsUndoEnabled is changed after assignment", false); Log("Type + Undo after IsUndoEnabled is changed from Enabled to Disabled"); } else { _tbb.IsUndoEnabled = true; Verifier.Verify(_tbb.IsUndoEnabled == true, "Verifying that IsUndoEnabled is changed after assignment", false); Log("Type + Undo after IsUndoEnabled is changed from Disabled to Enabled"); } KeyboardInput.TypeString(_typedContent + _undoActionString); QueueDelegate(CheckUndoAfterIsUndoEnabledChanged); } private void CheckUndoAfterIsUndoEnabledChanged() { if (_tbb.IsUndoEnabled) { _expectedContent = _expectedContentAfterUndo; } else { _expectedContent = _expectedTypedContent; } if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing undo command with IsUndoEnabled value changed: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); KeyboardInput.TypeString(_redoActionString); QueueDelegate(CheckRedoAfterIsUndoEnabledChanged); } private void CheckRedoAfterIsUndoEnabledChanged() { _expectedContent = _expectedTypedContent; if (_tbb is RichTextBox) { _expectedContent = _expectedContent + "\r\n"; } Verifier.Verify(_tbbWrapper.Text == _expectedContent, "Verifying content after performing redo command with IsUndoEnabled value changed: " + "Actual [" + _tbbWrapper.Text + "] Expected [" + _expectedContent + "]", true); QueueDelegate(DoNegativeTesting); } private void DoNegativeTesting() { //set the value back to the test value _tbb.IsUndoEnabled = _isUndoEnabledTestValue; //Negative testing with -ve value try { _tbb.UndoLimit = -10; Verifier.Verify(false, "UndoLimit has accepted -ve value of 10", false); } catch (System.ArgumentException) { Log("Exception thrown as expected when -ve value is assigned to UndoLimit"); } //Assigning value inside change block _tbb.ClearValue(TextBoxBase.UndoLimitProperty); using (_tbb.DeclareChangeBlock()) { try { _tbb.UndoLimit = 100; if (_isUndoEnabledTestValue) { Verifier.Verify(false, "UndoLimit value is changed inside a DeclareChangeBlock", false); } } catch (System.InvalidOperationException) { Log("Exception thrown as expected when value is changed inside a DeclareChangeBlock"); } } _tbb.BeginChange(); try { _tbb.UndoLimit = 1000; if (_isUndoEnabledTestValue) { Verifier.Verify(false, "UndoLimit value is changed inside a DeclareChangeBlock", false); } } catch (System.InvalidOperationException) { Log("Exception thrown as expected when value is changed inside a DeclareChangeBlock"); } _tbb.EndChange(); NextCombination(); } private void ClearBox() { if (_tbb is TextBox) { ((TextBox)_tbb).Clear(); } else if (_tbb is RichTextBox) { ((RichTextBox)_tbb).Document.Blocks.Clear(); } } #endregion #region Private fields private TextEditableType _editableType = null; private bool _isUndoEnabledTestValue = true; private TextBoxBase _tbb; private UIElementWrapper _tbbWrapper; private const int DefaultUndoLimitValue = -1; //Has to be even number, otherwise expectedContent calculation logic will go wrong. private const int TestUndoLimitValue = 4; private string _typedContent,_expectedTypedContent,_expectedContent,_expectedContentAfterUndo; private string _undoActionString,_redoActionString; #endregion } }
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:login_test/pages/login.page.dart'; class HomePage extends StatefulWidget { const HomePage({super.key}); @override State<HomePage> createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { int _selectedDestination = 0; void selectDestination(int index) { setState(() { _selectedDestination = index; }); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text("Página inicial"), ), body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ CircleAvatar( backgroundImage: NetworkImage(FirebaseAuth.instance.currentUser!.photoURL!), radius: 60, ), const SizedBox( height: 20, ), Text(FirebaseAuth.instance.currentUser!.displayName!), Text(FirebaseAuth.instance.currentUser!.email!), Text(FirebaseAuth.instance.currentUser!.phoneNumber ?? ""), OutlinedButton( onPressed: () async { await FirebaseAuth.instance.signOut(); if (!mounted) return; Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (_) => const LoginPage()), ); }, child: const Text("Fazer logout"), ) ], ), ), drawer: Drawer( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[ DrawerHeader( decoration: BoxDecoration( color: Colors.blue[200], ), child: Center( child: Column( children: [ CircleAvatar( backgroundImage: FirebaseAuth.instance.currentUser != null ? NetworkImage( FirebaseAuth.instance.currentUser!.photoURL!) : null, radius: 40, ), const SizedBox( height: 10, ), Text(FirebaseAuth.instance.currentUser?.displayName ?? ""), ], ), ), ), ListTile( leading: const Icon(Icons.person), title: const Text('Perfil'), selected: _selectedDestination == 0, onTap: () => selectDestination(0), ), ListTile( leading: const Icon(Icons.favorite), title: const Text('Favoritos'), selected: _selectedDestination == 1, onTap: () => selectDestination(1), ), ListTile( leading: const Icon(Icons.email), title: const Text('Mensagens'), selected: _selectedDestination == 2, onTap: () => selectDestination(2), ), const Divider( height: 1, thickness: 1, ), const Padding( padding: EdgeInsets.all(16.0), child: Text( 'Aplicativo', ), ), ListTile( leading: const Icon(Icons.settings), title: const Text('Configurações'), selected: _selectedDestination == 3, onTap: () => selectDestination(3), ), ListTile( leading: const Icon(Icons.info), title: const Text('Sobre'), selected: _selectedDestination == 4, onTap: () => selectDestination(4), ), ListTile( leading: const Icon(Icons.exit_to_app), title: const Text('Sair'), onTap: () async { await FirebaseAuth.instance.signOut(); if (!mounted) return; Navigator.of(context).pushReplacement( MaterialPageRoute(builder: (_) => const LoginPage()), ); }, ), const Spacer(), const SafeArea( child: Align( child: Text("versão 1.0.0"), ), ) ], ), ), ); } }
import { Injectable } from '@angular/core'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, } from '@angular/common/http'; import { Observable } from 'rxjs'; import { AccountService } from '../_services/account.service'; import { User } from '../_models/user'; import { catchError, take } from 'rxjs/operators'; import { Router } from '@angular/router'; @Injectable() export class JwtInterceptor implements HttpInterceptor { constructor( private accounService: AccountService, private router: Router ) {} intercept( request: HttpRequest<unknown>, next: HttpHandler ): Observable<HttpEvent<unknown>> { let currentUser: User; this.accounService.currentUser$ .pipe(take(1)) .subscribe((user) => (currentUser = user)); if (currentUser) { request = request.clone({ setHeaders: { Authorization: `Bearer ${currentUser.token}`, }, }); } return next.handle(request).pipe( catchError((err) => { console.log(err); if (err.status === 401) { localStorage.removeItem('user'); this.router.navigateByUrl('/login'); } throw err; }) ); } }
#ifndef LIBIM_LOG_LEVEL_H #define LIBIM_LOG_LEVEL_H #include <stdexcept> #include <string_view> namespace libim { struct LogLevel final { enum Level { Verbose = 8, Debug = 4, Info = 2, Warning = 1, Error = 0 }; constexpr LogLevel(Level l) : m_level(l) {} constexpr LogLevel(const LogLevel&) = default; constexpr LogLevel(LogLevel&&) noexcept = default; constexpr LogLevel& operator = (const LogLevel&) = default; constexpr LogLevel& operator = (LogLevel&&) noexcept = default; friend constexpr bool operator == (LogLevel ll1, LogLevel ll2) { return ll1.m_level == ll2.m_level; } friend constexpr bool operator < (LogLevel ll1, LogLevel ll2) { return ll1.m_level < ll2.m_level; } friend constexpr bool operator <= (LogLevel ll1, LogLevel ll2) { return ll1.m_level <= ll2.m_level; } friend constexpr bool operator > (LogLevel ll1, LogLevel ll2) { return ll1.m_level > ll2.m_level; } friend constexpr bool operator >= (LogLevel ll1, LogLevel ll2) { return ll1.m_level == ll2.m_level; } constexpr std::string_view toString() const { using namespace std::string_view_literals; switch(m_level) { case Verbose: return "Verbose"sv; case Debug: return "Debug"sv; case Info: return "Info"sv; case Warning: return "Warning"sv; case Error: return "Error"sv; } //Workaround for GCC bug: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67371 // FIXME: throw std::runtime_error("LogLevel::toString: fatal error"); return ""sv; } private: Level m_level; }; } #endif // LIBIM_LOG_LEVEL_H
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>WeTrip</title> <link rel="icon" type="image/png" href="favicon.png" /> <!-- Bootstrap Core CSS --> <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Montserrat:400,700" rel="stylesheet" type="text/css"> <link href='https://fonts.googleapis.com/css?family=Kaushan+Script' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Droid+Serif:400,700,400italic,700italic' rel='stylesheet' type='text/css'> <link href='https://fonts.googleapis.com/css?family=Roboto+Slab:400,100,300,700' rel='stylesheet' type='text/css'> <!-- Theme CSS --> <link href="css/agency.min.css" rel="stylesheet"> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body id="page-top" class="index"> <!-- Navigation --> <nav id="mainNav" class="navbar navbar-default navbar-custom navbar-fixed-top"> <div class="container"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header page-scroll"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">Toggle navigation</span> Menu <i class="fa fa-bars"></i> </button> <a class="navbar-brand page-scroll" href="#page-top">WeTrip</a> </div> <!-- Collect the nav links, forms, and other content for toggling --> <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> <ul class="nav navbar-nav navbar-right"> <li class="hidden"> <a href="#page-top"></a> </li> <li> <a class="page-scroll" href="#servicos">Serviços</a> </li> <li> <a class="page-scroll" href="#sobre">Sobre</a> </li> <li> <a class="page-scroll" href="#time">Time</a> </li> <li> <a class="page-scroll" href="#contato">Contato</a> </li> </ul> </div> <!-- /.navbar-collapse --> </div> <!-- /.container-fluid --> </nav> <!-- Header --> <header> <div class="container"> <div class="intro-text"> <img src="img/about/wt.png" width="400px"> <div class="intro-lead-in">Uma viagem mais insana que a outra</div> <a href="#servicos" class="page-scroll btn btn-xl">Conheça Mais</a> </div> </div> </header> <!-- Services Section --> <section id="servicos"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Serviços</h2> <h3 class="section-subheading text-muted">Conheça todas as funcionalidades para uma viagem tranquila e segura.</h3> </div> </div> <div class="row text-center"> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-calendar fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Roteiro</h4> <p class="text-muted">Diga seu interesse de lugar e vamos criar um roteiro dia a dia com atividades que são a sua cara, como se seu mãe tivesse montado algo para você!!</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-users fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Encontre companhia</h4> <p class="text-muted">Encontramos pessoas confiáveis e que tenham os mesmos interesses que você para te acompanhar.</p> </div> <div class="col-md-4"> <span class="fa-stack fa-4x"> <i class="fa fa-circle fa-stack-2x text-primary"></i> <i class="fa fa-money fa-stack-1x fa-inverse"></i> </span> <h4 class="service-heading">Economia</h4> <p class="text-muted">E o melhor, todas as sugestões serão feitas conforme o seu bolso! Se a locomoção de um ponto para outro for mais barata de trem que de avião, esta será a sugestão!</p> </div> </div> </div> </section> <!-- About Section --> <section id="sobre"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Sobre</h2> <h3 class="section-subheading text-muted">Conheça um pouco da nossa história.</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <ul class="timeline"> <li> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/master.png" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Nov 2016</h4> <h4 class="subheading">Começo</h4> </div> <div class="timeline-body"> <p class="text-muted">Tudo começou em um final de semana com o time Mastertech, onde tivemos uma ideia de como programar, além de muita ideias em conjunto sobre as funcionalidades do novo aplicativo!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/1.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Nov 2016</h4> <h4 class="subheading">Ideias Surgindo</h4> </div> <div class="timeline-body"> <p class="text-muted">As ideias vieram da nossa própria necessidade!!! Quem já não quis viajar e não encontrou companhia? Como é dificil definir um cronograma de viagem em conjuto....</p> </div> </div> </li> <li> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/baby.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Nov 2016</h4> <h4 class="subheading">Meus gostos</h4> </div> <div class="timeline-body"> <p class="text-muted">Porque não ter alguém faça isso pra mim? De preferência a minha mãe, que já me conhece bem e sabe todas as minhas preferências....</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <img class="img-circle img-responsive" src="img/about/wwt.jpg" alt=""> </div> <div class="timeline-panel"> <div class="timeline-heading"> <h4>Nov 2014</h4> <h4 class="subheading">Novidades</h4> </div> <div class="timeline-body"> <p class="text-muted">Não é só sua mãe capaz de fazer isso!! WeTrip utiliza algorítimos que são capazes de entender seu comportamento e seu momento para te sugerir o melhor passeio nas suas férias. E ainda mais, encontra a melhor companhia para você!!!!</p> </div> </div> </li> <li class="timeline-inverted"> <div class="timeline-image"> <h4>Faça parte <br>da nossa <br>História!</h4> </div> </li> </ul> </div> </div> </div> </section> <!-- Team Section --> <section id="time" class="bg-light-gray"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Time WeTrip</h2> <h3 class="section-subheading text-muted">Um time pequeno que encontra muita gente</h3> </div> </div> <div class="row"> <div class="col-sm-6"> <div class="team-member"> <img src="img/nelson.jpg" class="img-responsive img-circle" alt=""> <h4>Nelson</h4> <p class="text-muted">Marketeiro</p> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a target="_blank" href="https://www.facebook.com/nelson.mkt?fref=ts"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> <div class="col-sm-6"> <div class="team-member text-center img-centered"> <img src="img/dri.jpg" class="img-responsive img-circle" alt=""> <h4>Dri</h4> <p class="text-muted">Estatísta</p> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a target="_blank" href="https://www.facebook.com/dri.chispirita"><i class="fa fa-facebook"></i></a> </li> <li><a target="_blank" href="https://www.linkedin.com/in/adrianamms"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> </div> </div> <div class="row"> <div class="col-lg-8 col-lg-offset-2 text-center"> <p class="large text-muted">Time robusto! huahuahua</p> </div> </div> </div> </section> <!-- Contact Section --> <section id="contato"> <div class="container"> <div class="row"> <div class="col-lg-12 text-center"> <h2 class="section-heading">Contate-nos</h2> <h3 class="section-subheading text-muted">Escreva para nós contando o que está pensando</h3> </div> </div> <div class="row"> <div class="col-lg-12"> <form name="sentMessage" id="contactForm" novalidate> <div class="row"> <div class="col-md-6"> <div class="form-group"> <input type="text" class="form-control" placeholder="Nome *" id="name" required data-validation-required-message="Nome."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="email" class="form-control" placeholder="Email *" id="email" required data-validation-required-message="Email."> <p class="help-block text-danger"></p> </div> <div class="form-group"> <input type="tel" class="form-control" placeholder="Telefone *" id="phone" required data-validation-required-message="Celular."> <p class="help-block text-danger"></p> </div> </div> <div class="col-md-6"> <div class="form-group"> <textarea class="form-control" placeholder="O que está pensando? *" id="message" required data-validation-required-message="Diganos o que está pensando..."></textarea> <p class="help-block text-danger"></p> </div> </div> <div class="clearfix"></div> <div class="col-lg-12 text-center"> <div id="success"></div> <button type="submit" class="btn btn-xl">Enviar o que pensei</button> </div> </div> </form> </div> </div> </div> </section> <footer> <div class="container"> <div class="row"> <div class="col-md-4"> <span class="copyright">Copyright &copy; Your Website 2016</span> </div> <div class="col-md-4"> <ul class="list-inline social-buttons"> <li><a href="#"><i class="fa fa-twitter"></i></a> </li> <li><a href="#"><i class="fa fa-facebook"></i></a> </li> <li><a href="#"><i class="fa fa-linkedin"></i></a> </li> </ul> </div> <div class="col-md-4"> <ul class="list-inline quicklinks"> <li><a href="#">Privacy Policy</a> </li> <li><a href="#">Terms of Use</a> </li> </ul> </div> </div> </div> </footer> <!-- Portfolio Modals --> <!-- Use the modals below to showcase details about your portfolio projects! --> <!-- Portfolio Modal 1 --> <div class="portfolio-modal modal fade" id="portfolioModal1" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/roundicons-free.png" alt=""> <p>Use this area to describe your project. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Est blanditiis dolorem culpa incidunt minus dignissimos deserunt repellat aperiam quasi sunt officia expedita beatae cupiditate, maiores repudiandae, nostrum, reiciendis facere nemo!</p> <p> <strong>Want these icons in this portfolio item sample?</strong>You can download 60 of them for free, courtesy of <a href="https://getdpd.com/cart/hoplink/18076?referrer=bvbo4kax5k8ogc">RoundIcons.com</a>, or you can purchase the 1500 icon set <a href="https://getdpd.com/cart/hoplink/18076?referrer=bvbo4kax5k8ogc">here</a>.</p> <ul class="list-inline"> <li>Date: July 2014</li> <li>Client: Round Icons</li> <li>Category: Graphic Design</li> </ul> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 2 --> <div class="portfolio-modal modal fade" id="portfolioModal2" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <h2>Project Heading</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/startup-framework-preview.png" alt=""> <p><a href="http://designmodo.com/startup/?u=787">Startup Framework</a> is a website builder for professionals. Startup Framework contains components and complex blocks (PSD+HTML Bootstrap themes and templates) which can easily be integrated into almost any design. All of these components are made in the same style, and can easily be integrated into projects, allowing you to create hundreds of solutions for your future projects.</p> <p>You can preview Startup Framework <a href="http://designmodo.com/startup/?u=787">here</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 3 --> <div class="portfolio-modal modal fade" id="portfolioModal3" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/treehouse-preview.png" alt=""> <p>Treehouse is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. This is bright and spacious design perfect for people or startup companies looking to showcase their apps or other projects.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/treehouse-free-psd-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 4 --> <div class="portfolio-modal modal fade" id="portfolioModal4" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/golden-preview.png" alt=""> <p>Start Bootstrap's Agency theme is based on Golden, a free PSD website template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Golden is a modern and clean one page web template that was made exclusively for Best PSD Freebies. This template has a great portfolio, timeline, and meet your team sections that can be easily modified to fit your needs.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/golden-free-one-page-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 5 --> <div class="portfolio-modal modal fade" id="portfolioModal5" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/escape-preview.png" alt=""> <p>Escape is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Escape is a one page web template that was designed with agencies in mind. This template is ideal for those looking for a simple one page solution to describe your business and offer your services.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/escape-one-page-psd-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> </div> <!-- Portfolio Modal 6 --> <div class="portfolio-modal modal fade" id="portfolioModal6" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="close-modal" data-dismiss="modal"> <div class="lr"> <div class="rl"> </div> </div> </div> <div class="container"> <div class="row"> <div class="col-lg-8 col-lg-offset-2"> <div class="modal-body"> <!-- Project Details Go Here --> <h2>Project Name</h2> <p class="item-intro text-muted">Lorem ipsum dolor sit amet consectetur.</p> <img class="img-responsive img-centered" src="img/portfolio/dreams-preview.png" alt=""> <p>Dreams is a free PSD web template built by <a href="https://www.behance.net/MathavanJaya">Mathavan Jaya</a>. Dreams is a modern one page web template designed for almost any purpose. It’s a beautiful template that’s designed with the Bootstrap framework in mind.</p> <p>You can download the PSD template in this portfolio sample item at <a href="http://freebiesxpress.com/gallery/dreams-free-one-page-web-template/">FreebiesXpress.com</a>.</p> <button type="button" class="btn btn-primary" data-dismiss="modal"><i class="fa fa-times"></i> Close Project</button> </div> </div> </div> </div> </div> </div> </div> <!-- jQuery --> <script src="vendor/jquery/jquery.min.js"></script> <!-- Bootstrap Core JavaScript --> <script src="vendor/bootstrap/js/bootstrap.min.js"></script> <!-- Plugin JavaScript --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script> <!-- Contact Form JavaScript --> <script src="js/jqBootstrapValidation.js"></script> <script src="js/contact_me.js"></script> <!-- Theme JavaScript --> <script src="js/agency.min.js"></script> </body> </html>
import {UserSecretKey, UserPublicKey, UserSigner, Mnemonic } from '@elrondnetwork/erdjs-walletcore/out'; import { JsonBIP44CoinTypeNode } from '@metamask/key-tree'; import sha256 from 'crypto-js/sha256'; import Hex from 'crypto-js/enc-hex' import * as bip39 from "bip39" export interface userAccount{ SK: UserSecretKey, PK: UserPublicKey, Signer: UserSigner, name: string, address: string } export class Account{ SK: UserSecretKey PK: UserPublicKey Signer: UserSigner AccountData: null | Record<string, unknown> addr: string async init(): Promise<userAccount>{ this.AccountData = await wallet.request({ method: 'snap_manageState', params: ['get'], }) if(this.AccountData === null){ return await this.createNewAccount(this.AccountData) } return this.getCurrentAccount(this.AccountData) } async createNewAccount(AccountData, name?): Promise<userAccount>{ if(!name){ name = "Account 1"; } const entropy = (await wallet.request({ method: 'snap_getBip44Entropy', params: { coinType: 508, }, }) as JsonBIP44CoinTypeNode).privateKey; console.log(entropy); console.log(typeof entropy); console.log("here") let hashedEntropy = sha256(entropy) console.log("hashed entropy") console.log(hashedEntropy) const textMnemonic = bip39.entropyToMnemonic(Hex.stringify(hashedEntropy)) console.log("text mnemonic generated") const mnemonic = Mnemonic.fromString(textMnemonic) const SK = mnemonic.deriveKey(); const PK = SK.generatePublicKey(); const Signer = new UserSigner(SK); const addr :string = PK.toAddress().bech32() if(AccountData === null){ AccountData = {"currentAccount": "", "Accounts":{}} } AccountData.currentAccount = addr; const mnemonicString : string = mnemonic.toString() AccountData.Accounts[addr] = {name: name, addr: addr, mnemonic: mnemonicString} console.log(AccountData) console.log(JSON.stringify(AccountData)) await wallet.request({ method: 'snap_manageState', params: ['update', AccountData] }) return { SK: SK, PK: PK, Signer: Signer, name: name, address: addr } } getCurrentAccount(state): userAccount{ const addr = state.currentAccount; const data = state.Accounts[addr]; const name = data.name; const mnemonicText = data.mnemonic; const mnemonic = Mnemonic.fromString(mnemonicText) const SK = mnemonic.deriveKey() const PK = SK.generatePublicKey() const Signer = new UserSigner(SK); return { name: name, address: addr, SK: SK, PK: PK, Signer: Signer } } }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; public class World { internal static World world; internal Dictionary<Vector2Int, Chunk> chunks = new(); internal WorldSettings settings; internal WorldData data; internal WorldSettings.Gamerules gamerules => settings.gamerules; internal string worldFolder => Path.Combine(Application.dataPath, Path.Combine("saves", worldName)); internal string worldChunksFolder => Path.Combine(worldFolder, "regions"); internal string worldDataPath => Path.Combine(worldFolder, $"data/data.dat"); internal string worldSettingsPath => Path.Combine(worldFolder, $"data/settings.dat"); private string worldName; /// <summary> /// Get block state using world position /// </summary> /// <param name="x"></param> /// <param name="y"></param> /// <param name="z"></param> /// <returns> returns block state</returns> internal BlockState this[int x, int y, int z] { get { ChunkPosition chunk = new(new Vector3(x, y, z)); Vector3Int local = new BlockPosition(new Vector3(x, y, z)).localPosition; if (chunks.ContainsKey(chunk.position)) { return chunks[chunk.position][local.x, y, local.z]; } return new BlockState(new BlockPosition(new Vector3(x, y, z))); } set { int _x = Mathf.Abs(x % 16); ChunkPosition chunk = new(new Vector3(x, y, z)); if (chunks.ContainsKey(chunk.position)) { Vector3Int local = new BlockPosition(new Vector3(x, y, z)).localPosition; chunks[chunk.position][local.x, y, local.z] = value; } } } public World(string name) { chunks = new Dictionary<Vector2Int, Chunk>(); world = this; worldName = name; LoadWorld(); data.worldName = name; } [System.Serializable] public class WorldData { public string worldName; } [System.Serializable] public class WorldSettings { public Gamerules gamerules; [System.Serializable] public class Gamerules { public bool doFallDamage; public bool doFireDamage; public bool doDaylightCycle; } } public void SaveGame() { foreach(var kvp in chunks) { kvp.Value.Unload(); } FileHandler.SaveObject(data, worldDataPath); FileHandler.SaveObject(settings, worldSettingsPath); } public void LoadWorld() { data = FileHandler.LoadObject<WorldData>(worldDataPath); settings = FileHandler.LoadObject<WorldSettings>(worldSettingsPath); } public void Unload() { SaveGame(); } }
![Installation Guide For Project Elixir](https://i.imgur.com/42LxtAl.png) ### Installation Guide For Project Elixir on Redmi Note 12 Pro Speed / POCO X5 Pro 5G (redwood) ### **Note:** - The device must have an unlocked bootloader. If you are moving from Android 9/10/11/12/13 to Android 14, it is necessary CLEAN FLASH (Format Data). ### Step 1: Download Required Files 1. Download the latest Android platform tools for Windows from the link below: - **Platform Tools Link (Windows)**: [platform-tools-latest-windows.zip](https://dl.google.com/android/repository/platform-tools-latest-windows.zip) 2. Download the Recovery from the link below: - **Recovery Link**: [Tap here to download](https://www.pling.com/p/2118914/) 3. Download the Project Elixir ROM for Redmi Note 12 Pro Speed / POCO X5 Pro 5G from a reliable source. - **Project Elixir ROM Link**: [DOWNLOAD](https://projectelixiros.com/device/redwood) ### Clean Flash - Download the latest build - Take a backup for safe side - Download The Boot , Dtbo And Vendor_boot Images - Connect your phone to PC - Reboot To Fastboot ( Press Both Power_button_key + Vol_down_key) - Once your device is in Fastboot Mode, use the following command to check if Fastboot still detects your device: ``` fastboot devices ``` If your device is listed, you are ready to flash the Elixir Recovery. ``` fastboot flash dtbo dtbo.img ``` ``` fastboot flash vendor_boot vendor_boot.img ``` ``` fastboot flash boot boot.img ``` - After flashing the recovery, use the following command to reboot your Recovery: ``` fastboot reboot recovery ``` - Select Wipe Data/factory Reset & Confirm - Go back and select Apply update from ADB ``` adb sideload Project-Elixir*.zip(or drag down the rom zip to cmd) ``` Then kindly perform a format data in the recovery afterwards. Reboot! ### Dirty Flashing Steps ``` - Reboot to recover by holding power button and volume up simultaneously - In the recovery menu select Apply update through ADB - adb sideload Project-Elixir*.zip(or drag down the rom zip to cmd) - After installation complete Reboot! Enjoy! ``` ### Notes: - A14 recovery and vendor: [Tap here for link](https://sourceforge.net/projects/project-elixir/files/fourteen/redwood) - Rom comes with Gapps inbuilt. - Clean flash always recommended to get the best experience.
# plugin The `plugin` transformer allows you to use a [plugin](../plugins.md) providing a custom transformer in your schema. This transformer has the following properties: - `name`: The name of the plugin. This is the path to the plugin file. - `args`: The arguments to pass to the plugin. This can be empty or any JSON value. ## Example ```json { "type": "string", "value": "hello", "transform": [ { "type": "plugin", "name": "my-plugin", "args": { "foo": "bar" } } ] } ```
<template> <div class="home h-full w-4/5 lg:w-3/4 m-auto"> <section class="flex flex-wrap justify-between mb-8 mt-8 lg:mt-16"> <category-selector v-on:change-category="onChangeCategory" :categorySelected="category" :hasOptionForAll="true" /> <button @click="bulkDelete" class="btn-main bg-red-500 hover:bg-red-400 ml-4 md:mr-auto" > Delete selected </button> <router-link to="/note" class="btn-main bg-green-500 hover:bg-green-400 mt-4 md:mt-0 w-full md:w-auto" :class="{ pulsing: notes.length == 0 }" >Create new</router-link > </section> <section class="grid md:grid-cols-2 lg:grid-cols-3 gap-4"> <div v-show="alert != ''" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative" role="alert" > <span class="block sm:inline">{{ alert }}</span> </div> <div v-for="n in filteredNotes" :key="n._id"> <label class="text-gray-500 font-bold flex items-center"> <input class="leading-tight" type="checkbox" v-model="selectedNotes" :value="n" /> <span class="text-sm"> Select for delete </span> </label> <note-card :note="n" /> </div> </section> </div> </template> <script> import NoteCard from "@/components/NoteCard.vue" import CategorySelector from "@/components/CategorySelector.vue" import { fetchNotes, deleteNote } from "@/api/actions.ts" export default { name: "Home", components: { NoteCard, CategorySelector }, data() { return { notes: [], alert: "", category: "All", selectedNotes: [] } }, computed: { filteredNotes() { if (this.category == "All") return this.notes else return this.notes.filter(n => n.category == this.category) } }, methods: { onChangeCategory(selected) { this.category = selected }, async bulkDelete(e) { e.preventDefault() try { this.alert = "" await Promise.all( this.selectedNotes.map(async x => await deleteNote(x._id)) ) this.notes = await fetchNotes() } catch (e) { this.alert = e } } }, async mounted() { try { this.alert = "" this.notes = await fetchNotes() } catch (e) { this.alert = e } } } </script> <style> .pulsing { animation: pulse 1.5s infinite; } .pulsing:hover { animation: none; } @keyframes pulse { 0% { transform: scale(0.95); } 70% { transform: scale(1); } 100% { transform: scale(0.95); } } </style>
namespace Tempore.Tests.Tempore.Server.Services; extern alias TemporeServer; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using FluentAssertions; using global::Tempore.Storage.Entities; using global::Tempore.Tests.Infraestructure; using Microsoft.Extensions.Logging.Abstractions; using TemporeServer::Tempore.Server.Services; using Xunit; public class DaySchedulerServiceFacts { public class The_ScheduleDayAsync_Method { public static object[] MorningShift() { var timetable = new Timetable { Id = Guid.NewGuid(), Name = nameof(MorningShift), StartTime = new TimeSpan(8, 0, 0), Duration = new TimeSpan(8, 0, 0), CheckInTimeStart = new TimeSpan(0, -15, 0), CheckInTimeDuration = new TimeSpan(0, 30, 0), CheckOutTimeStart = new TimeSpan(0, -15, 0), CheckOutTimeDuration = new TimeSpan(0, 30, 0), EffectiveWorkingTime = TimeSpan.FromHours(8), }; var shiftId = Guid.NewGuid(); var scheduledShiftAssignment = new ScheduledShiftAssignment { Id = Guid.NewGuid(), EmployeeId = Guid.NewGuid(), ScheduledShift = new ScheduledShift { ShiftId = shiftId, StartDate = new DateOnly(2023, 10, 2), ExpireDate = new DateOnly(2023, 10, 2).AddDays(13), Shift = new Shift { Id = shiftId, Name = nameof(MorningShift), }, EffectiveWorkingTime = TimeSpan.FromHours(8 * 12), }, }; var dayList = new List<Day>(); for (var dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { var day = new Day { Id = Guid.NewGuid(), Index = (int)dayOfWeek, TimetableId = dayOfWeek > DayOfWeek.Sunday ? timetable.Id : null, Timetable = dayOfWeek > DayOfWeek.Sunday ? timetable : null, Shift = scheduledShiftAssignment.ScheduledShift.Shift, ShiftId = scheduledShiftAssignment.ScheduledShift.ShiftId, }; dayList.Add(day); } scheduledShiftAssignment.ScheduledShift.Shift.Days = dayList; var date = new DateOnly(2023, 10, 12); var index = ((int)scheduledShiftAssignment.ScheduledShift.StartDate.DayOfWeek + date.DayNumber - scheduledShiftAssignment.ScheduledShift.StartDate.DayNumber) % scheduledShiftAssignment.ScheduledShift.Shift.Days.Count; var first = scheduledShiftAssignment.ScheduledShift.Shift.Days.First(d => d.Index == index); var expectedScheduledDay = new ScheduledDay { Date = date, ScheduledShiftAssignmentId = scheduledShiftAssignment.Id, DayId = first.Id, StartDateTime = new DateTime(2023, 10, 12, 8, 0, 0), EndDateTime = new DateTime(2023, 10, 12, 16, 0, 0), CheckInStartDateTime = new DateTime(2023, 10, 12, 7, 45, 0), CheckInEndDateTime = new DateTime(2023, 10, 12, 8, 15, 0), CheckOutStartDateTime = new DateTime(2023, 10, 12, 15, 45, 0), CheckOutEndDateTime = new DateTime(2023, 10, 12, 16, 15, 0), EffectiveWorkingTime = first.Timetable?.EffectiveWorkingTime ?? TimeSpan.Zero, RelativeEffectiveWorkingTime = TimeSpan.FromHours(8), }; return new object[] { date, scheduledShiftAssignment, expectedScheduledDay }; } public static object[] AfternoonShift() { var timetable = new Timetable { Id = Guid.NewGuid(), Name = nameof(AfternoonShift), StartTime = new TimeSpan(12, 0, 0), Duration = TimeSpan.FromHours(6), CheckInTimeStart = TimeSpan.FromMinutes(-10), CheckInTimeDuration = TimeSpan.FromMinutes(20), CheckOutTimeStart = TimeSpan.FromMinutes(-5), CheckOutTimeDuration = TimeSpan.FromMinutes(10), EffectiveWorkingTime = TimeSpan.FromHours(6), }; var shiftId = Guid.NewGuid(); var scheduledShiftAssignment = new ScheduledShiftAssignment { Id = Guid.NewGuid(), EmployeeId = Guid.NewGuid(), ScheduledShift = new ScheduledShift { ShiftId = shiftId, StartDate = new DateOnly(2023, 10, 2), ExpireDate = new DateOnly(2023, 10, 2).AddDays(6), Shift = new Shift { Id = shiftId, Name = nameof(AfternoonShift), }, EffectiveWorkingTime = TimeSpan.FromHours(6 * 6), }, }; var dayList = new List<Day>(); for (var dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { var day = new Day { Id = Guid.NewGuid(), Index = (int)dayOfWeek, TimetableId = dayOfWeek > DayOfWeek.Sunday ? timetable.Id : null, Timetable = dayOfWeek > DayOfWeek.Sunday ? timetable : null, Shift = scheduledShiftAssignment.ScheduledShift.Shift, ShiftId = scheduledShiftAssignment.ScheduledShift.ShiftId, }; dayList.Add(day); } scheduledShiftAssignment.ScheduledShift.Shift.Days = dayList; var date = new DateOnly(2023, 10, 5); var index = ((int)scheduledShiftAssignment.ScheduledShift.StartDate.DayOfWeek + date.DayNumber - scheduledShiftAssignment.ScheduledShift.StartDate.DayNumber) % scheduledShiftAssignment.ScheduledShift.Shift.Days.Count; var first = scheduledShiftAssignment.ScheduledShift.Shift.Days.First(d => d.Index == index); var expectedScheduledDay = new ScheduledDay { Date = date, ScheduledShiftAssignmentId = scheduledShiftAssignment.Id, DayId = first.Id, StartDateTime = new DateTime(2023, 10, 5, 12, 0, 0), EndDateTime = new DateTime(2023, 10, 5, 18, 0, 0), CheckInStartDateTime = new DateTime(2023, 10, 5, 11, 50, 0), CheckInEndDateTime = new DateTime(2023, 10, 5, 12, 10, 0), CheckOutStartDateTime = new DateTime(2023, 10, 5, 17, 55, 0), CheckOutEndDateTime = new DateTime(2023, 10, 5, 18, 5, 0), EffectiveWorkingTime = first.Timetable?.EffectiveWorkingTime ?? TimeSpan.Zero, RelativeEffectiveWorkingTime = TimeSpan.FromHours(6), }; return new object[] { date, scheduledShiftAssignment, expectedScheduledDay }; } public static object[] NightShift() { var timetable = new Timetable { Id = Guid.NewGuid(), Name = nameof(NightShift), StartTime = new TimeSpan(20, 0, 0), Duration = TimeSpan.FromHours(7), CheckInTimeStart = new TimeSpan(0, -5, 0), CheckInTimeDuration = new TimeSpan(0, 10, 0), CheckOutTimeStart = new TimeSpan(0, -5, 0), CheckOutTimeDuration = new TimeSpan(0, 10, 0), EffectiveWorkingTime = TimeSpan.FromHours(7), }; var shiftId = Guid.NewGuid(); var scheduledShiftAssignment = new ScheduledShiftAssignment { Id = Guid.NewGuid(), EmployeeId = Guid.NewGuid(), ScheduledShift = new ScheduledShift { ShiftId = shiftId, StartDate = new DateOnly(2023, 10, 2), ExpireDate = new DateOnly(2023, 10, 2).AddDays(20), Shift = new Shift { Id = shiftId, Name = nameof(NightShift), }, EffectiveWorkingTime = TimeSpan.FromHours(126), }, }; var dayList = new List<Day>(); for (var dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { var day = new Day { Id = Guid.NewGuid(), Index = (int)dayOfWeek, TimetableId = dayOfWeek > DayOfWeek.Sunday ? timetable.Id : null, Timetable = dayOfWeek > DayOfWeek.Sunday ? timetable : null, Shift = scheduledShiftAssignment.ScheduledShift.Shift, ShiftId = scheduledShiftAssignment.ScheduledShift.ShiftId, }; dayList.Add(day); } scheduledShiftAssignment.ScheduledShift.Shift.Days = dayList; var date = new DateOnly(2023, 10, 14); var index = ((int)scheduledShiftAssignment.ScheduledShift.StartDate.DayOfWeek + date.DayNumber - scheduledShiftAssignment.ScheduledShift.StartDate.DayNumber) % scheduledShiftAssignment.ScheduledShift.Shift.Days.Count; var expectedScheduledDay = new ScheduledDay { Date = date, ScheduledShiftAssignmentId = scheduledShiftAssignment.Id, DayId = scheduledShiftAssignment.ScheduledShift.Shift.Days.First(d => d.Index == index).Id, StartDateTime = new DateTime(2023, 10, 14, 20, 0, 0), EndDateTime = new DateTime(2023, 10, 15, 3, 0, 0), CheckInStartDateTime = new DateTime(2023, 10, 14, 19, 55, 0), CheckInEndDateTime = new DateTime(2023, 10, 14, 20, 05, 0), CheckOutStartDateTime = new DateTime(2023, 10, 15, 2, 55, 0), CheckOutEndDateTime = new DateTime(2023, 10, 15, 3, 5, 0), EffectiveWorkingTime = TimeSpan.FromHours(7), RelativeEffectiveWorkingTime = TimeSpan.FromHours(7), }; return new object[] { date, scheduledShiftAssignment, expectedScheduledDay }; } public static object[] NoWorkingDayShift() { var timetable = new Timetable { Id = Guid.NewGuid(), Name = nameof(NoWorkingDayShift), StartTime = new TimeSpan(8, 0, 0), Duration = new TimeSpan(8, 0, 0), CheckInTimeStart = new TimeSpan(0, -15, 0), CheckInTimeDuration = new TimeSpan(0, 30, 0), CheckOutTimeStart = new TimeSpan(0, -15, 0), CheckOutTimeDuration = new TimeSpan(0, 30, 0), }; var shiftId = Guid.NewGuid(); var scheduledShiftAssignment = new ScheduledShiftAssignment { Id = Guid.NewGuid(), EmployeeId = Guid.NewGuid(), ScheduledShift = new ScheduledShift() { ShiftId = shiftId, StartDate = new DateOnly(2023, 10, 2), ExpireDate = new DateOnly(2023, 10, 2).AddDays(25), Shift = new Shift { Id = shiftId, Name = nameof(NoWorkingDayShift), }, }, }; var dayList = new List<Day>(); for (var dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { var day = new Day { Id = Guid.NewGuid(), Index = (int)dayOfWeek, TimetableId = dayOfWeek > DayOfWeek.Sunday ? timetable.Id : null, Timetable = dayOfWeek > DayOfWeek.Sunday ? timetable : null, Shift = scheduledShiftAssignment.ScheduledShift.Shift, ShiftId = scheduledShiftAssignment.ScheduledShift.ShiftId, }; dayList.Add(day); } scheduledShiftAssignment.ScheduledShift.Shift.Days = dayList; var date = new DateOnly(2023, 10, 15); var index = ((int)scheduledShiftAssignment.ScheduledShift.StartDate.DayOfWeek + date.DayNumber - scheduledShiftAssignment.ScheduledShift.StartDate.DayNumber) % scheduledShiftAssignment.ScheduledShift.Shift.Days.Count; var expectedScheduledDay = new ScheduledDay { Date = date, ScheduledShiftAssignmentId = scheduledShiftAssignment.Id, DayId = scheduledShiftAssignment.ScheduledShift.Shift.Days.First(d => d.Index == index).Id, }; return new object[] { date, scheduledShiftAssignment, expectedScheduledDay }; } public static IEnumerable<object[]> RealisticShifts() { var weekdaysTimetable = new Timetable { Id = Guid.NewGuid(), Name = DefaultValues.WeekdaysTimetableName, StartTime = new TimeSpan(8, 0, 0), Duration = TimeSpan.FromHours(9), CheckInTimeStart = new TimeSpan(0, -15, 0), CheckInTimeDuration = new TimeSpan(0, 30, 0), CheckOutTimeStart = new TimeSpan(0, -15, 0), CheckOutTimeDuration = new TimeSpan(0, 30, 0), EffectiveWorkingTime = TimeSpan.FromHours(8), }; var saturdayTimetable = new Timetable { Id = Guid.NewGuid(), Name = DefaultValues.SaturdayTimetableName, StartTime = new TimeSpan(8, 0, 0), Duration = TimeSpan.FromHours(5), CheckInTimeStart = new TimeSpan(0, -15, 0), CheckInTimeDuration = new TimeSpan(0, 30, 0), CheckOutTimeStart = new TimeSpan(0, -15, 0), CheckOutTimeDuration = new TimeSpan(0, 30, 0), EffectiveWorkingTime = TimeSpan.FromHours(5), }; var shiftId = Guid.NewGuid(); var scheduledShiftAssignment = new ScheduledShiftAssignment { Id = Guid.NewGuid(), EmployeeId = Guid.NewGuid(), ScheduledShift = new ScheduledShift { ShiftId = shiftId, StartDate = new DateOnly(2023, 10, 2), ExpireDate = new DateOnly(2023, 10, 2).AddDays(13), Shift = new Shift { Id = shiftId, Name = nameof(RealisticShifts), }, EffectiveWorkingTime = TimeSpan.FromHours(97.77), }, }; var dayList = new List<Day>(); for (var dayOfWeek = DayOfWeek.Sunday; dayOfWeek <= DayOfWeek.Saturday; dayOfWeek++) { var day = new Day { Id = Guid.NewGuid(), Index = (int)dayOfWeek, Shift = scheduledShiftAssignment.ScheduledShift.Shift, ShiftId = scheduledShiftAssignment.ScheduledShift.ShiftId, }; if (dayOfWeek == DayOfWeek.Saturday) { day.Timetable = saturdayTimetable; day.TimetableId = saturdayTimetable.Id; } if (dayOfWeek is >= DayOfWeek.Monday and < DayOfWeek.Saturday) { day.Timetable = weekdaysTimetable; day.TimetableId = weekdaysTimetable.Id; } dayList.Add(day); } scheduledShiftAssignment.ScheduledShift.Shift.Days = dayList; var date = new DateOnly(2023, 10, 12); var index = ((int)scheduledShiftAssignment.ScheduledShift.StartDate.DayOfWeek + date.DayNumber - scheduledShiftAssignment.ScheduledShift.StartDate.DayNumber) % scheduledShiftAssignment.ScheduledShift.Shift.Days.Count; var firstDay = scheduledShiftAssignment.ScheduledShift.Shift.Days.First(d => d.Index == index); var expectedScheduledDay = new ScheduledDay { Date = date, ScheduledShiftAssignmentId = scheduledShiftAssignment.Id, DayId = firstDay.Id, StartDateTime = new DateTime(2023, 10, 12, 8, 0, 0), EndDateTime = new DateTime(2023, 10, 12, 17, 0, 0), CheckInStartDateTime = new DateTime(2023, 10, 12, 7, 45, 0), CheckInEndDateTime = new DateTime(2023, 10, 12, 8, 15, 0), CheckOutStartDateTime = new DateTime(2023, 10, 12, 16, 45, 0), CheckOutEndDateTime = new DateTime(2023, 10, 12, 17, 15, 0), EffectiveWorkingTime = firstDay.Timetable?.EffectiveWorkingTime ?? TimeSpan.Zero, RelativeEffectiveWorkingTime = TimeSpan.FromHours(8.69067), }; yield return new object[] { date, scheduledShiftAssignment, expectedScheduledDay }; date = new DateOnly(2023, 10, 7); index = ((int)scheduledShiftAssignment.ScheduledShift.StartDate.DayOfWeek + date.DayNumber - scheduledShiftAssignment.ScheduledShift.StartDate.DayNumber) % scheduledShiftAssignment.ScheduledShift.Shift.Days.Count; firstDay = scheduledShiftAssignment.ScheduledShift.Shift.Days.First(d => d.Index == index); expectedScheduledDay = new ScheduledDay { Date = date, ScheduledShiftAssignmentId = scheduledShiftAssignment.Id, DayId = firstDay.Id, StartDateTime = new DateTime(2023, 10, 7, 8, 0, 0), EndDateTime = new DateTime(2023, 10, 7, 13, 0, 0), CheckInStartDateTime = new DateTime(2023, 10, 7, 7, 45, 0), CheckInEndDateTime = new DateTime(2023, 10, 7, 8, 15, 0), CheckOutStartDateTime = new DateTime(2023, 10, 7, 12, 45, 0), CheckOutEndDateTime = new DateTime(2023, 10, 7, 13, 15, 0), EffectiveWorkingTime = firstDay.Timetable?.EffectiveWorkingTime ?? TimeSpan.Zero, RelativeEffectiveWorkingTime = TimeSpan.FromHours(5.43167), }; yield return new object[] { date, scheduledShiftAssignment, expectedScheduledDay }; } public static IEnumerable<object[]> Data() { yield return MorningShift(); yield return AfternoonShift(); yield return NightShift(); yield return NoWorkingDayShift(); foreach (var realisticShift in RealisticShifts()) { yield return realisticShift; } } public static IEnumerable<object[]> OutOfShiftAssignmentDateRageData() { var shiftAssignment = new ScheduledShiftAssignment { Id = Guid.NewGuid(), EmployeeId = Guid.NewGuid(), ScheduledShift = new ScheduledShift { ShiftId = Guid.NewGuid(), StartDate = new DateOnly(2023, 10, 2), ExpireDate = new DateOnly(2023, 10, 10), }, }; yield return new object[] { shiftAssignment.ScheduledShift.ExpireDate.AddDays(1), shiftAssignment }; yield return new object[] { shiftAssignment.ScheduledShift.StartDate.AddDays(-1), shiftAssignment }; } [Theory] [MemberData(nameof(Data))] [Trait(Traits.Category, Category.Unit)] public async Task Creates_A_ScheduledDay_With_The_Expected_DateTime_Values_Async( DateOnly date, ScheduledShiftAssignment scheduledShiftAssignment, ScheduledDay expectedScheduledDay) { var daySchedulerService = new DaySchedulerService(NullLogger<DaySchedulerService>.Instance); var scheduledDay = await daySchedulerService.ScheduleDayAsync(date, scheduledShiftAssignment); scheduledDay.Should().BeEquivalentTo( expectedScheduledDay, options => options.Excluding(s => s.Id).Excluding(s => s.Day).Excluding(s => s.Timestamps) .Excluding(s => s.ScheduledShiftAssignment).Excluding(s => s.RelativeEffectiveWorkingTime)); scheduledDay.RelativeEffectiveWorkingTime.TotalHours.Should().BeApproximately( expectedScheduledDay.RelativeEffectiveWorkingTime.TotalHours, 0.001); } [Theory] [MemberData(nameof(OutOfShiftAssignmentDateRageData))] [Trait(Traits.Category, Category.Unit)] public async Task Throws_ArgumentException_Async(DateOnly date, ScheduledShiftAssignment scheduledShiftAssignment) { var daySchedulerService = new DaySchedulerService(NullLogger<DaySchedulerService>.Instance); await Assert.ThrowsAsync<ArgumentException>( () => daySchedulerService.ScheduleDayAsync(date, scheduledShiftAssignment)); } [Fact] [Trait(Traits.Category, Category.Unit)] public async Task Throws_ArgumentNullException_When_ShiftAssignment_Argument_Is_Null_Async() { var daySchedulerService = new DaySchedulerService(NullLogger<DaySchedulerService>.Instance); await Assert.ThrowsAsync<ArgumentNullException>( () => daySchedulerService.ScheduleDayAsync(new DateOnly(2023, 12, 12), null!)); } } }
import fs from 'fs'; import path from 'path'; import { ethers } from 'ethers'; import { initRpcApi, loadProvider } from './utils'; import ExchangeContract from './ExchangeContract'; import IERC20Contract from './IERC20Contract'; import FactoryContract from './FactoryContract'; import FarmContract from './FarmContract'; import FaucetTokenContract from './FaucetTokenContract'; import MigratorContract from './MigratorContract'; import PairContract from './PairContract'; import WETHContract from './WETHContract'; export { initRpcApi, ExchangeContract, IERC20Contract, FactoryContract, FarmContract, FaucetTokenContract, MigratorContract, PairContract, WETHContract, }; export type LibraryName = | 'AssetRegistry' | 'Depositing' | 'LiquidityPoolAdmin' | 'LiquidityPools' | 'NonceInvalidations' | 'Trading' | 'Withdrawing'; export async function deployLibrary( name: LibraryName, ownerWalletPrivateKey: string, ): Promise<string> { const bytecode = loadLibraryBytecode(name); const owner = new ethers.Wallet(ownerWalletPrivateKey, loadProvider()); const library = await new ethers.ContractFactory( [], bytecode, owner, ).deploy(); await library.deployTransaction.wait(); return library.address; } const libraryNameToBytecodeMap = new Map<LibraryName, string>(); function loadLibraryBytecode(name: LibraryName): string { if (!libraryNameToBytecodeMap.has(name)) { const { bytecode } = JSON.parse( fs .readFileSync( path.join(__dirname, '..', '..', 'contracts', `${name}.json`), ) .toString('utf8'), ); libraryNameToBytecodeMap.set(name, bytecode); } return libraryNameToBytecodeMap.get(name) as string; // Will never be undefined as it gets set above }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>模块</title> </head> <body> <script> function createModule(str1, str2) { // 第一种方法:字面量定义对象 // let obj = { // greeting:str1, // name:str2, // sayIt(){ // return this["greeting"] + "," + this["name"]; // // return `this[${str1}]` // } // } // return obj; // 第二种方法:工厂模式 class Obj{ // constructor这是一个构造函数 constructor(){ this.greeting = str1; this.name = str2; } // 次方法定义在对象原型上面 sayIt(){ return this.greeting + ", " + this.name; } } return new Obj; } console.log(createModule(1,2)) </script> </body> </html>
import dotenv from 'dotenv'; dotenv.config(); import express from 'express'; import { fileURLToPath } from 'url'; import path, { dirname } from 'path'; import cookieParser from 'cookie-parser'; import favicon from 'serve-favicon'; import fs from 'fs'; import passport from 'passport'; import { Strategy as LocalStrategy } from 'passport-local'; import bcrypt from 'bcryptjs'; import session from 'express-session'; import { connectDB, getDB } from './config.js'; // Імпорт з'єднання з MongoDB import { findUserByEmail, createUser, findUserById, insertManyUsers, updateOneUser, updateManyUsers, replaceOneUser, deleteOneUser, deleteManyUsers, findUsers, getUsersWithCursor, getUserStatistics } from './models/User.js'; // Імпорт функцій з файлу User.js import flash from 'express-flash'; const __filename = fileURLToPath(import.meta.url); const __dirname = dirname(__filename); const usersFolder = path.join(__dirname, 'users'); const usersFilePath = path.join(usersFolder, 'user.json'); const app = express(); const PORT = 3000; const secretKey = 'your_secret_key'; // Використовуйте реальний секретний ключ const sessionSecret = 'your_session_secret'; // Використовуйте реальний секретний ключ для сесій // Підключення до бази даних connectDB(); // Перевірка чи існує тека users, якщо ні - створюємо if (!fs.existsSync(usersFolder)) { fs.mkdirSync(usersFolder); } // Middleware app.use(express.urlencoded({ extended: true })); app.use(express.json()); app.use(cookieParser()); app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(express.static(path.join(__dirname, 'public'))); // Налаштування сесій app.use(session({ secret: sessionSecret, resave: false, saveUninitialized: false, cookie: { httpOnly: true, secure: process.env.NODE_ENV === 'production', // Використовуйте secure cookies у виробничому середовищі maxAge: 1000 * 60 * 60 * 24 // 1 день } })); app.use(flash()); // Passport.js налаштування app.use(passport.initialize()); app.use(passport.session()); passport.use(new LocalStrategy({ usernameField: 'email', passwordField: 'password' }, async (email, password, done) => { try { const user = await findUserByEmail(email); if (!user) { return done(null, false, { message: 'Incorrect email.' }); } const isMatch = await bcrypt.compare(password, user.password); if (!isMatch) { return done(null, false, { message: 'Incorrect password.' }); } return done(null, user); } catch (err) { return done(err); } })); passport.serializeUser((user, done) => { done(null, user._id); // Замінено user.id на user._id }); passport.deserializeUser(async (id, done) => { try { const user = await findUserById(id); // Використовуйте знайдення користувача за його id done(null, user); } catch (err) { done(err); } }); // Маршрут для збереження улюбленої теми app.get('/set-theme/:theme', (req, res) => { const { theme } = req.params; res.cookie('theme', theme, { maxAge: 900000, httpOnly: true }); res.redirect('back'); }); // Маршрут для отримання списку користувачів з MongoDB app.get('/users', async (req, res) => { try { const db = getDB(); const users = await db.collection('users').find().toArray(); res.json(users); } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Маршрути Pug // app.get('/users', (req, res) => { // const users = [ // { name: 'John Doe', email: '[email protected]' }, // { name: 'Jane Smith', email: '[email protected]' } // ]; // res.render(path.join(__dirname, 'views-pug', 'users.pug'), { users, theme: req.cookies.theme || 'light' }); // }); app.get('/users/:userId', (req, res) => { const user = { name: 'John Doe', email: '[email protected]' }; res.render(path.join(__dirname, 'views-pug', 'user-details.pug'), { user, theme: req.cookies.theme || 'light' }); }); // Маршрути EJS app.get('/articles', (req, res) => { const articles = [ { title: 'Article 1', author: 'Author 1', content: 'Content of article 1' }, { title: 'Article 2', author: 'Author 2', content: 'Content of article 2' } ]; res.render(path.join(__dirname, 'views-ejs', 'articles.ejs'), { articles, theme: req.cookies.theme || 'light' }); }); app.get('/articles/:articleId', (req, res) => { const article = { title: 'Article 1', author: 'Author 1', content: 'Content of article 1' }; res.render(path.join(__dirname, 'views-ejs', 'article-details.ejs'), { article, theme: req.cookies.theme || 'light' }); }); // Обробка кореневого шляху app.get('/', (req, res) => { res.send('Get root route'); }); app.get('/register', (req, res) => { res.render(path.join(__dirname, 'views-pug', 'register.pug')); }); // Реєстрація app.post('/register', async (req, res) => { const { email, password } = req.body; try { const userExists = await findUserByEmail(email); if (userExists) { return res.status(400).send('User already exists.'); } const newUser = await createUser({ email, password: await bcrypt.hash(password, 10), }); res.status(201).send('User registered successfully.'); } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Вхід app.get('/login', (req, res) => { res.render(path.join(__dirname, 'views-pug', 'login.pug'), { message: req.flash('error') }); }); app.post('/login', passport.authenticate('local', { successRedirect: '/profile', // Перенаправлення при успішному вході failureRedirect: '/login', // Перенаправлення при невдачі failureFlash: true // Включити flash messages у випадку невдалих спроб })); // Вихід app.post('/logout', (req, res, next) => { req.logout((err) => { if (err) { return next(err); } req.session.destroy((err) => { if (err) { return next(err); } res.clearCookie('connect.sid'); res.redirect('/login'); }); }); }); // Мідлвар для перевірки автентифікації const isAuthenticated = (req, res, next) => { if (req.method === 'POST' && !req.isAuthenticated()) { res.redirect('/login'); } else { return next(); } }; // Профіль користувача app.get('/profile', isAuthenticated, (req, res) => { res.send(` <h1>Welcome to your profile, ${req.user ? req.user.email : 'Guest'}</h1> <form action="/logout" method="POST"> <button type="submit">Logout</button> </form> `); }); // Захищений маршрут app.get('/protected', isAuthenticated, (req, res) => { res.send('This is a protected route'); }); // Додавання одного користувача app.post('/users', async (req, res) => { try { const userData = req.body; const newUser = await createUser(userData); res.status(201).json(newUser); } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Додавання багатьох користувачів app.post('/users/many', async (req, res) => { try { const userDataArray = req.body; // Перевірка, чи userDataArray є масивом if (!Array.isArray(userDataArray)) { return res.status(400).send('Invalid input, expected an array of user data.'); } const insertedIds = await insertManyUsers(userDataArray); res.status(201).json({ insertedIds }); } catch (err) { console.error("Error inserting many users:", err); res.status(500).send('Server Error'); } }); // Оновлення одного користувача app.put('/users/:id', async (req, res) => { try { const { id } = req.params; const updateData = req.body; const modifiedCount = await updateOneUser(id, updateData); if (modifiedCount > 0) { res.status(200).send('User updated successfully.'); } else { res.status(404).send('User not found.'); } } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Оновлення багатьох користувачів app.put('/users/', async (req, res) => { const updateDataArray = req.body; if (!Array.isArray(updateDataArray)) { return res.status(400).send('Invalid input, expected an array of user data.'); } try { const results = await updateManyUsers(updateDataArray); res.status(200).json(results); } catch (err) { console.error("Error updating many users:", err); res.status(500).send('Server Error'); } }); // Заміна одного користувача app.put('/users/replace/:id', async (req, res) => { try { const { id } = req.params; const newData = req.body; const modifiedCount = await replaceOneUser(id, newData); if (modifiedCount > 0) { res.status(200).send('User replaced successfully.'); } else { res.status(404).send('User not found.'); } } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Видалення одного користувача app.delete('/users/:id', async (req, res) => { try { const { id } = req.params; const deletedCount = await deleteOneUser(id); if (deletedCount > 0) { res.status(200).send('User deleted successfully.'); } else { res.status(404).send('User not found.'); } } catch (err) { console.error(err); res.status(500).send('Server Error'); } }); // Видалення багатьох користувачів app.delete('/users', async (req, res) => { const { ids } = req.body; if (!Array.isArray(ids) || ids.length === 0) { return res.status(400).send('Invalid input, expected an array of user ids.'); } try { const result = await deleteManyUsers(ids); res.status(200).json(result); } catch (err) { console.error("Error deleting users:", err); res.status(500).send('Server Error'); } }); // // Пошук користувачів з проекцією // app.get('/users', async (req, res) => { // try { // const filter = req.query.filter ? JSON.parse(req.query.filter) : {}; // const projection = req.query.projection ? JSON.parse(req.query.projection) : {}; // const users = await findUsers(filter, projection); // res.status(200).json(users); // } catch (err) { // console.error(err); // res.status(500).send('Server Error'); // } // }); app.get('/users', async (req, res) => { try { const cursor = await getUsersWithCursor(); const users = []; await cursor.forEach(user => { users.push(user); }); res.status(200).json(users); } catch (err) { console.error("Error fetching users with cursor:", err); res.status(500).send('Server Error'); } }); app.get('/user-stats', async (req, res) => { try { const stats = await getUserStatistics(); res.status(200).json(stats); } catch (err) { console.error("Error fetching user statistics:", err); res.status(500).send('Server Error'); } }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
from pygame import * from random import randint mixer.init() mixer.music.load('space.ogg') fire_sound = mixer.Sound('fire.ogg') font.init() font2 = font.Font(None,36) img_back = "galaxy.jpg" img_hero = "rocket.png" img_enemy = "ufo.png" img_bullet = 'bullet.png' score = 0 lost = 0 window = display.set_mode((700,500)) display.set_caption("Космос") back=transform.scale(image.load("galaxy.jpg"),(700,500)) clock = time.Clock() FPS = 61 class GameSprite(sprite.Sprite): def __init__(self, player_image, player_x, player_y, player_speed): super().__init__() self.image = transform.scale(image.load(player_image),(65,65)) self.speed = player_speed self.rect = self.image.get_rect() self.rect.x = player_x self.rect.y = player_y def reset(self): window.blit(self.image, (self.rect.x, self.rect.y)) class Player(GameSprite): def fire(self): bullet = Bullet(img_bullet, self.rect.centerx, self.rect.top, -15) bullets.add(bullet) def update(self): keys = key.get_pressed() if keys[K_LEFT] and self.rect.x > 5: self.rect.x -= self.player_speed if keys[K_RIGHT] and self.rect.x < WIGTH - 80: self.rect.x += self.player_speed class Enemy(GameSprite): def update(self): global lost self.rect.y += self.speed if self.rect.y > win_height: self.rect.x = randint(80, win_width - 80) self.rect.x = 0 lost += 1 class Bullet(GameSprite): def __init__(self, player_image, player_x, player_y, player_speed): super().__init__(player_image, player_x, player_y, player_speed) self.image = transform.scale(image.load(player_image), (15,15)) def update(self): self.rect.y += self.speed if self.rect.y <0: self.kill() win_width = 900 win_height = 700 FPS = 60 display.set_caption("Shooter") window = display.set_mode((win_width, win_height)) background = transform.scale(image.load(img_back), (win_width, win_height)) clock = time.Clock() ship = Player(img_hero, 5, win_height - 100, 10) monsters = sprite.Group() for i in range(1, 6): monster = Enemy(img_enemy, randint(80, win_width - 80), -40, randint(1,3)) monsters.add(monster) bullets = sprite.Group() finish = False run = True while run: for e in event.get(): if e.type == QUIT: run = False elif e.type == KEYDOWN: if e.key == K_SPACE: fire_sound.play() ship.fire() if not finish: window.blit(background, (0,0)) text = font2.render("Счет::" + str(score), 1, (255,255,255)) window.blit(text,(10,20)) text_lose = font2.render("Пропущено:" + str(lost), 1, (255, 255, 255)) window.blit(text_lose, (10,50)) ship.update() monsters.update() bullets.update() ship.reset() monsters.draw(window) bullets.draw(window) collides = sprite.groupcollide(monsters, bullets, True, True) for c in collides: score += 1 monster display.update() clock.tick(FPS)
# Load Packages lapply(c("dplyr", "ggplot2", "move", "sf", "lubridate", "raster", "tidyr"), require, character.only = TRUE) # ################################################################################################################# # ### LOAD DATA ### # ################# # # Load Capture Data # trap.raw <- read.csv("Trapping - Data.csv") # trap.slim <- trap.raw %>% # dplyr::select(BirdID = AlumBand, BirdID2 = Rivet.Band, CapLoc = Location, CapDate = Date, Recapture, Sex, Age, Flock.Size) # # # Load Harvest Data # harvest.raw <- read.csv("Harvests - Harvested Birds.csv") # harvest.slim <- harvest.raw %>% # dplyr::select(BirdID = Alum.Band.ID, BirdID2 = Rivet.ID, EndYear = Year, HarvSeason = Season, # EndTown = Town.of.Harvest) # # # Load Nest Data # nest.raw <- read.csv("Nest Monitoring - Nest Info.csv") # nest.slim <- nest.raw %>% # filter(Nest.Attempt == 1) %>% # dplyr::select(BirdID = Alum.Band.ID, EndYear = Year, EndLat = NestLat, EndLong = NestLong, estDate = Est.Laying.Initiation) %>% # filter(!is.na(BirdID)) # # # # Load Capture Site Information # capsites.raw <- read.csv("CaptureSites - Sheet1.csv") # capsites.slim <- capsites.raw %>% # dplyr::select(Town, CapLoc = Location.Name, Lat = Latitude, Long = Longitude) # capsites.sf <- st_as_sf(capsites.slim, coords = c("Long", "Lat"), crs = 4326) %>% # dplyr::select(-Town) # # # Load Town Boundaries Shapefile # townbound <- st_read("E:/Maine Drive/GIS/Maine_Town_and_Townships_Boundary_Polygons_Feature.shp") %>% # group_by(TOWN) %>% # filter(TArea_KM2 == max(TArea_KM2)) %>% # dplyr::select(Town = TOWN) # townbound <- st_transform(townbound, crs = 4326) # townbound.center.sf <- st_centroid(townbound) # towncenter.df <- data.frame(Town = townbound.center.sf$Town, # EndLong = st_coordinates(townbound.center.sf)[,1], # EndLat = st_coordinates(townbound.center.sf)[,2]) # # #Correct CapSite Names # capsites.sf <- st_join(capsites.sf, townbound, join = st_within) %>% # mutate(CapLong = st_coordinates(capsites.sf)[,1], # CapLat = st_coordinates(capsites.sf)[,2]) # capsites.df <- capsites.sf %>% st_drop_geometry() # # Hex Polygons hexcovs <- st_read("./GIS/HexCovs.shp") %>% st_transform(crs = 4326) # # ################################################################################################################# # ### MERGE DATA ### # ################## # ### Starting Location # caplocs1 <- merge(capsites.sf, trap.slim, by = "CapLoc", all.y = T) %>% # dplyr::select(BirdID, BirdID2, StartDate = CapDate) %>% # mutate(StartDate = as.Date(StartDate, format = "%m/%d/%Y")) %>% # mutate(StartYear = year(StartDate)) # caplocs2 <- st_join(caplocs1, hexcovs %>% dplyr::select(GridID), join = st_within) %>% # rename(StartHex = GridID) %>% # mutate(StartX = st_coordinates(.)[,1], # StartY = st_coordinates(.)[,2]) %>% # st_drop_geometry() # # ### Combine with End Points # #Harvest # hasbirdID1 <- harvest.slim %>% filter(!is.na(BirdID)) %>% dplyr::select(-BirdID2) # nobirdID1 <- harvest.slim %>% filter(is.na(BirdID)) %>% dplyr::select(-BirdID) # # caplocs.harv1 <- merge(caplocs2, hasbirdID1, by = "BirdID", all.y = T) %>% # dplyr::select(-HarvSeason) # caplocs.harv2 <- merge(caplocs2, nobirdID1, by = "BirdID2", all.y = T) %>% # dplyr::select(-HarvSeason) # caplocs.harv3 <- rbind(caplocs.harv1, caplocs.harv2) %>% # filter(StartYear == EndYear) %>% # rename(Town = EndTown) # caplocs.harv4 <- merge(caplocs.harv3, towncenter.df, by = "Town", all.x = T) # caplocs.harv.sf <- st_as_sf(caplocs.harv4, coords = c("EndLong", "EndLat"), crs = 4326) # startend.harv <- st_join(caplocs.harv.sf, hexcovs %>% dplyr::select(GridID), join = st_within) %>% # rename(EndHex = GridID) %>% # filter(StartHex != EndHex) %>% # mutate(EndX = st_coordinates(.)[,1], # EndY = st_coordinates(.)[,2]) %>% # st_drop_geometry() %>% # dplyr::select(BirdID, Year = StartYear, StartHex, EndHex, StartX, StartY, EndX, EndY) # # #Nests # nest.ready <- nest.slim %>% # filter(!is.na(EndLat)) %>% # filter(!is.na(estDate)) %>% # rename(EndDate = estDate) %>% # mutate(EndDate = as.Date(EndDate, format = "%m/%d/%Y")) %>% # st_as_sf(coords = c("EndLong", "EndLat"), crs = 4326) # # nestends <- st_join(nest.ready, hexcovs %>% dplyr::select(GridID), join = st_within) %>% # mutate(EndX = st_coordinates(.)[,1], # EndY = st_coordinates(.)[,2]) %>% # st_drop_geometry() %>% # rename(EndHex = GridID) %>% # mutate(EndYear = year(EndDate)) # startend.nest <- merge(caplocs2, nestends, by = "BirdID", all.y = T) %>% # filter(StartYear == EndYear) %>% # filter(StartHex != EndHex) %>% # dplyr::select(BirdID, Year = StartYear, StartHex, EndHex, StartX, StartY, EndX, EndY) # # #RBind # startend.full <- rbind(startend.harv, startend.nest) %>% # filter(BirdID != 359 & EndX != -68.41931) #2nd attempt ignored # # ################################################################################################################# # ### IDENTIFY AVAILABLE TOWNS ### # ################################ # ### Draw Line between start and end town # lines.start <- startend.full %>% # dplyr::select(BirdID, Year, X = StartX, Y = StartY, Hex = StartHex) %>% # mutate(SE = "Start") # lines.end <- startend.full %>% # dplyr::select(BirdID, Year, X = EndX, Y = EndY, Hex = EndHex) %>% # mutate(SE = "End") # # #Combine nest and capture/first of year locations and create shapefiles # lines <- rbind(lines.start, lines.end) %>% # arrange(BirdID, Year) %>% # group_by(BirdID, Year) %>% # split(.,.[,"BirdID"]) # lines.mat <- lapply(lines, function(x) as.matrix(x[names(x) %in% c("X","Y")])) # lines.multilines.sfg <- st_multilinestring(lines.mat, dim = "XY") # lines.multilines.sfc <- st_sfc(lines.multilines.sfg, crs = 4326) # lines.multilines.sfc <- st_transform(lines.multilines.sfc, 32619) # lines.lines.sfc <- st_cast(lines.multilines.sfc, "LINESTRING") # captoobs.line <- st_sf(data.frame(lines.lines.sfc, data.frame(BirdID = names(lines)))) # st_write(captoobs.line, "./GIS/SettleAvailLine_HEX.shp", delete_layer = T) # # # ### Buffer line based on average town size # # Mean town size # mean.town.area <- mean(st_area(townbound)) # mean.town.radius <- (mean.town.area^(1/2))/pi # captoobs.poly <- st_buffer(captoobs.line, 2*mean.town.radius) %>% # st_transform(4326) # st_write(captoobs.poly, "./GIS/SettleAvailPoly.shp", delete_layer = T) # # ### Identify which towns overlap each buffer, these are the available # hexoverlap <- st_intersects(captoobs.poly, hexcovs %>% dplyr::select(GridID)) # # hexoverlaploop <- function(x){ # nhexs <- length(hexoverlap[[x]]) # hexlist <- c() # for(i in 1:nhexs){ # hexlist[i] <- hexcovs[hexoverlap[[x]][i],]$GridID # } # return(hexlist) # } # # hexnames.overlap <- lapply(1:length(hexoverlap), FUN = hexoverlaploop) # names(hexnames.overlap) <- paste(captoobs.poly$BirdID, "_", sep ="") # # ncol.merge <- max(unlist(lapply(1:length(hexoverlap), FUN = function(x){length(hexnames.overlap[[x]])}))) # # mergeid <- lines.end %>% mutate(ID = paste(BirdID, Hex, sep = "_")) # # settled.hexs <- data.frame(GridID = unlist(hexnames.overlap), # ListID = names(unlist(hexnames.overlap))) %>% # mutate(BirdID = stringr::str_extract(ListID, ".+?(?=_)")) %>% # dplyr::select(-ListID) %>% # mutate(ID = paste(BirdID, GridID, sep = "_")) %>% # mutate(Settled = ifelse(ID %in% mergeid$ID, 1, 0)) %>% # filter(BirdID %in% mergeid$BirdID) %>% # filter(!is.na(GridID)) # # ################################################################################################################# # ### COLLECT TOWN HABITAT DATA ### # ################################# # ind.covs1 <- merge(settled.hexs, hexcovs, by = "GridID", all.x = T) %>% # dplyr::select(-geometry, -GridID, -ID) %>% # arrange(BirdID, desc(Settled)) %>% # rename(Agriculture = Agrcltr, # Developed = Develpd, # Grassland = Herbacs, # Wetland = Wetlnds, # Connectance = Cnnctnc) # # # Sex # sex.cov <- trap.slim %>% dplyr::select(BirdID, Sex) # settle.input <- merge(ind.covs1, sex.cov, by = "BirdID", all.x = T) %>% # filter(!is.na(Developed)) # # ################################################################################################################# # ### DISTANCE TO START ### # ################################# # disttostart1 <- settled.hexs %>% dplyr::select(BirdID, GridID) # disttostart2 <- hexcovs %>% dplyr::select(GridID) %>% # mutate(HexX = st_coordinates(st_centroid(hexcovs))[,1], # HexY = st_coordinates(st_centroid(hexcovs))[,2]) %>% # st_drop_geometry() # disttostart3 <- merge(disttostart1, disttostart2, by = "GridID", all.x = T) # disttostart4 <- lines.start %>% dplyr::select(BirdID, X, Y) # disttostart5 <- merge(disttostart3, disttostart4, by = "BirdID", all.x = T) # # disttostart <- pointDistance(disttostart5[,3:4], disttostart5[,5:6], lonlat = T) # settle.input$DisttoStart <- disttostart # # write.csv(settle.input, "SettDesc_input_HEX.csv", row.names = F) ################################################################################################################# ### RUN CONDITIONAL LOGISTIC REGRESSIONS ### ############################################ require(survival) require(AICcmodavg) settle.input <- read.csv("SettDesc_input_HEX.csv") settle.input[,3:15] <- sapply(3:15, FUN = function(x){scale(settle.input[,x], center = T, scale = T)}) settle.input[,17] <- scale(settle.input[,17], center = T, scale = T) cand.models <- list() cand.models[[1]] <- settmodel.null <- clogit(Settled ~ strata(BirdID), settle.input) cand.models[[2]] <- settmodel.X <- clogit(Settled ~ X + strata(BirdID), settle.input) cand.models[[3]] <- settmodel.Y <- clogit(Settled ~ Y + strata(BirdID), settle.input) cand.models[[4]] <- settmodel.XY <- clogit(Settled ~ X*Y+strata(BirdID), settle.input) cand.models[[5]] <- settmodel.Dev <- clogit(Settled ~ Developed + strata(BirdID), settle.input) cand.models[[6]] <- settmodel.Dev2 <- clogit(Settled ~ poly(Developed,2) + strata(BirdID), settle.input) cand.models[[7]] <- settmodel.DevSex <- clogit(Settled ~ Developed + Developed:Sex + strata(BirdID), settle.input) cand.models[[8]] <- settmodel.Dev2Sex <- clogit(Settled ~ Developed + I(Developed^2) + Developed:Sex +I(Developed^2):Sex + strata(BirdID), settle.input) cand.models[[9]] <- settmodel.Ag <- clogit(Settled ~ Agriculture + strata(BirdID), settle.input) cand.models[[10]] <- settmodel.Ag2 <- clogit(Settled ~ poly(Agriculture,2) + strata(BirdID), settle.input) cand.models[[11]] <- settmodel.AgSex <- clogit(Settled ~ Agriculture + Agriculture:Sex + strata(BirdID), settle.input) cand.models[[12]] <- settmodel.Ag2Sex <- clogit(Settled ~ Agriculture + I(Agriculture^2) + Agriculture:Sex +I(Agriculture^2):Sex + strata(BirdID), settle.input) cand.models[[13]] <- settmodel.Wet <- clogit(Settled ~ Wetland + strata(BirdID), settle.input) cand.models[[14]] <- settmodel.Wet2 <- clogit(Settled ~ poly(Wetland,2) + strata(BirdID), settle.input) cand.models[[15]] <- settmodel.WetSex <- clogit(Settled ~ Wetland + Wetland:Sex + strata(BirdID), settle.input) cand.models[[16]] <- settmodel.Wet2Sex <- clogit(Settled ~ Wetland + I(Wetland^2) + Wetland:Sex +I(Wetland^2):Sex + strata(BirdID), settle.input) cand.models[[17]] <- settmodel.Grass <- clogit(Settled ~ Grassland + strata(BirdID), settle.input) cand.models[[18]] <- settmodel.Grass2 <- clogit(Settled ~ poly(Grassland,2) + strata(BirdID), settle.input) cand.models[[19]] <- settmodel.GrassSex <- clogit(Settled ~ Grassland + Grassland:Sex + strata(BirdID), settle.input) cand.models[[20]] <- settmodel.Grass2Sex <- clogit(Settled ~ Grassland + I(Grassland^2)+ Grassland:Sex +I(Grassland^2):Sex + strata(BirdID), settle.input) cand.models[[21]] <- settmodel.Road <- clogit(Settled ~ Road_KM + strata(BirdID), settle.input) cand.models[[22]] <- settmodel.Road2 <- clogit(Settled ~ poly(Road_KM,2) + strata(BirdID), settle.input) cand.models[[23]] <- settmodel.RoadSex <- clogit(Settled ~ Road_KM + Road_KM:Sex + strata(BirdID), settle.input) cand.models[[24]] <- settmodel.Road2Sex <- clogit(Settled ~ Road_KM + I(Road_KM^2) + Road_KM:Sex +I(Road_KM^2):Sex + strata(BirdID), settle.input) cand.models[[25]] <- settmodel.AgInd <- clogit(Settled ~ Ag_Indx + strata(BirdID), settle.input) cand.models[[26]] <- settmodel.AgInd2 <- clogit(Settled ~ poly(Ag_Indx,2) + strata(BirdID), settle.input) cand.models[[27]] <- settmodel.AgIndSex <- clogit(Settled ~ Ag_Indx + Ag_Indx:Sex + strata(BirdID), settle.input) cand.models[[28]] <- settmodel.AgInd2Sex <- clogit(Settled ~ Ag_Indx + I(Ag_Indx^2) + Ag_Indx:Sex +I(Ag_Indx^2):Sex + strata(BirdID), settle.input) cand.models[[29]] <- settmodel.Connect <- clogit(Settled ~ Connectance + strata(BirdID), settle.input) cand.models[[30]] <- settmodel.Connect2 <- clogit(Settled ~ poly(Connectance,2) + strata(BirdID), settle.input) cand.models[[31]] <- settmodel.ConnectSex <- clogit(Settled ~ Connectance + Connectance:Sex + strata(BirdID), settle.input) cand.models[[32]] <- settmodel.Connect2Sex <- clogit(Settled ~ Connectance + I(Connectance^2) + Connectance:Sex +I(Connectance^2):Sex + strata(BirdID), settle.input) cand.models[[33]] <- settmodel.EdgeDens <- clogit(Settled ~ Edg_Dns + strata(BirdID), settle.input) cand.models[[34]] <- settmodel.EdgeDens2 <- clogit(Settled ~ poly(Edg_Dns,2) + strata(BirdID), settle.input) cand.models[[35]] <- settmodel.EdgeDensSex <- clogit(Settled ~ Edg_Dns + Edg_Dns:Sex + strata(BirdID), settle.input) cand.models[[36]] <- settmodel.EdgeDens2Sex <- clogit(Settled ~ Edg_Dns + I(Edg_Dns^2) + Edg_Dns:Sex +I(Edg_Dns^2):Sex + strata(BirdID), settle.input) aictab(cand.set = cand.models) cand.models[[37]] <- settmodel.Full <- clogit(Settled ~ Wetland + I(Wetland^2) + Wetland:Sex +I(Wetland^2):Sex + Agriculture + I(Agriculture^2) + Agriculture:Sex +I(Agriculture^2):Sex + Developed + Developed:Sex + X + strata(BirdID), settle.input) aictab(cand.set = cand.models) settmodel.Full cand.models[[38]] <- settmodel.Final <- clogit(Settled ~ Wetland + I(Wetland^2) + Wetland:Sex +I(Wetland^2):Sex + Agriculture + I(Agriculture^2) + Agriculture:Sex +I(Agriculture^2):Sex + + strata(BirdID), settle.input) aictab(cand.set = cand.models) ### Produce Probability of settling for each settle.input.raw <- read.csv("SettDesc_input_HEX.csv") wetmean <- mean(settle.input.raw$Wetland) wetsd <- sd(settle.input.raw$Wetland) agmean <- mean(settle.input.raw$Agriculture) agsd <- sd(settle.input.raw$Agriculture) x <- settmodel.Final$coefficients settle.predict <- hexcovs %>% st_drop_geometry() %>% dplyr::select(GridID, Wetland = Wetlnds, Agriculture = Agrcltr) %>% mutate(Wetland = (Wetland - wetmean)/wetsd, Agriculture = (Agriculture - agmean)/agsd) %>% mutate(PreLinkF = x[1]*Wetland + x[2]*(Wetland^2) + x[3]*Agriculture + x[4]*(Agriculture^2)) %>% mutate(PreLinkM = PreLinkF + x[5]*Wetland + x[6]*(Wetland^2) + x[7]*Agriculture + x[8]*(Agriculture^2)) %>% mutate(SettleProbF = exp(PreLinkF)/(1+exp(PreLinkF)), SettleProbM = exp(PreLinkM)/(1+exp(PreLinkM))) %>% dplyr::select(GridID, SettleProbF, SettleProbM) summary(settle.predict) write.csv(settle.predict, "HexCov_Settle.csv", row.names = F) ###Examine Model outputs settle.input.raw <- read.csv("SettDesc_input_HEX.csv") wetmean <- mean(settle.input.raw$Wetland) wetsd <- sd(settle.input.raw$Wetland) agmean <- mean(settle.input.raw$Agriculture) agsd <- sd(settle.input.raw$Agriculture) preddf <- data.frame(Agriculture = 0, Sex = rep(c(1, 0), each = length(seq(-2,2,.1))), Wetland = rep(seq(-2,2,.1),2)) x <- settmodel.Final$coefficients settle.predict <- preddf %>% mutate(PreLink = x[1]*Wetland + x[2]*(Wetland^2) + x[5]*Sex*(Wetland^2) + x[3]*Agriculture + x[4]*(Agriculture^2) + x[6]*Sex*(Agriculture^2)) %>% mutate(SettleProb = exp(PreLink)/(1+exp(PreLink))) %>% mutate(Wetland = (Wetland*wetsd)+wetmean) wetplot <- ggplot(data = settle.predict, aes(x = Wetland, y = SettleProb, color = as.factor(Sex))) + geom_line(size = 2) + xlim(0,0.35) + theme_classic(base_size = 25) + labs(x = "Proportion Wetland") + scale_color_manual(values = c("darkorchid4", "deeppink2")) + theme(axis.title.y = element_blank(), legend.position = "none") preddf <- data.frame(Agriculture = rep(seq(-2,2,.1),2), Sex = rep(c(1, 0), each = length(seq(-2,2,.1))), Wetland = 0) x <- settmodel.Final$coefficients settle.predict <- preddf %>% mutate(PreLink = x[1]*Wetland + x[2]*(Wetland^2) + x[5]*Sex*(Wetland^2) + x[3]*Agriculture + x[4]*(Agriculture^2) + x[6]*Sex*(Agriculture^2)) %>% mutate(SettleProb = exp(PreLink)/(1+exp(PreLink))) %>% mutate(Agriculture = (Agriculture*agsd)+agmean) agplot <- ggplot(data = settle.predict, aes(x = Agriculture, y = SettleProb, color = as.factor(Sex))) + geom_line(size = 2) + xlim(0,0.15) + theme_classic(base_size = 25) + labs(x = "Proportion Agriculture") + scale_color_manual(values = c("darkorchid4", "deeppink2")) + theme(axis.title.y = element_blank(), legend.position = "none") require(patchwork) combo.plot <- wetplot + agplot + plot_layout(ncol = 2) + plot_annotation(tag_levels = 'A') & theme(plot.tag = element_text(size = 20), plot.tag.position = c(0.15,.95)) ggsave(combo.plot, filename = "./Figures/SettleDecisionPlot.jpg", width = 12, height = 6) ################################################################################################################# ### CREATE PLOTS ### #################### ### Plot settling probability across grid require(ggplot2) settlehexplot <- merge(hexcovs, settle.predict, by = "GridID", all.x = T) ggplot(data = settlehexplot) + geom_sf(aes(fill = SettleProbF)) ggplot(data = settlehexplot) + geom_sf(aes(fill = SettleProbM)) # m.cf <- log(summary(settmodel.Full)$conf.int) # # #Agriculture # ag.data.plot <- data.frame(Ag = seq(min(settle.input$Agriculture), max(settle.input$Agriculture), .01), # Dev = mean(settle.input$Developed), # Wet = mean(settle.input$Wetland)) %>% # mutate(Est = exp((Ag*m.cf[1,1]) + ((Ag^2)*m.cf[2,1]) + (Dev*m.cf[3,1]) + (Wet*m.cf[4,1]) + ((Wet^2)*m.cf[5,1]))) %>% # mutate(LCL = exp((Ag*m.cf[1,3]) + ((Ag^2)*m.cf[2,3]) + (Dev*m.cf[3,3]) + (Wet*m.cf[4,3]) + ((Wet^2)*m.cf[5,3]))) %>% # mutate(UCL = exp((Ag*m.cf[1,4]) + ((Ag^2)*m.cf[2,4]) + (Dev*m.cf[3,4]) + (Wet*m.cf[4,4]) + ((Wet^2)*m.cf[5,4]))) # # SD.ag2.plot <- ggplot(data = ag.data.plot) + # geom_line(aes(x = Ag, y = Est)) + # geom_line(aes(x = Ag, y = LCL), linetype = "dashed") + # geom_line(aes(x = Ag, y = UCL), linetype = "dashed") + # theme_classic() + # labs(x = "Proportion Agriculture", y = "log(RSF)") + # scale_y_continuous(trans = 'log10') # # #Developed # dev.data.plot <- data.frame(Dev = seq(min(settle.input$Developed), max(settle.input$Developed), .01), # Ag = mean(settle.input$Agriculture), # Wet = mean(settle.input$Wetland)) %>% # mutate(Est = exp((Ag*m.cf[1,1]) + ((Ag^2)*m.cf[2,1]) + (Dev*m.cf[3,1]) + (Wet*m.cf[4,1]) + ((Wet^2)*m.cf[5,1]))) %>% # mutate(LCL = exp((Ag*m.cf[1,3]) + ((Ag^2)*m.cf[2,3]) + (Dev*m.cf[3,3]) + (Wet*m.cf[4,3]) + ((Wet^2)*m.cf[5,3]))) %>% # mutate(UCL = exp((Ag*m.cf[1,4]) + ((Ag^2)*m.cf[2,4]) + (Dev*m.cf[3,4]) + (Wet*m.cf[4,4]) + ((Wet^2)*m.cf[5,4]))) # # SD.dev.plot <- ggplot(data = dev.data.plot) + # geom_line(aes(x = Dev, y = Est)) + # geom_line(aes(x = Dev, y = LCL), linetype = "dashed") + # geom_line(aes(x = Dev, y = UCL), linetype = "dashed") + # theme_classic() + # labs(x = "Proportion Developed", y = element_blank()) + # scale_y_continuous(trans = 'log10') # # #Wetland # wet.data.plot <- data.frame(Wet = seq(min(settle.input$Wetland), max(settle.input$Wetland), .01), # Dev = mean(settle.input$Developed), # Ag = mean(settle.input$Agriculture)) %>% # mutate(Est = exp((Ag*m.cf[1,1]) + ((Ag^2)*m.cf[2,1]) + (Dev*m.cf[3,1]) + (Wet*m.cf[4,1]) + ((Wet^2)*m.cf[5,1]))) %>% # mutate(LCL = exp((Ag*m.cf[1,3]) + ((Ag^2)*m.cf[2,3]) + (Dev*m.cf[3,3]) + (Wet*m.cf[4,3]) + ((Wet^2)*m.cf[5,3]))) %>% # mutate(UCL = exp((Ag*m.cf[1,4]) + ((Ag^2)*m.cf[2,4]) + (Dev*m.cf[3,4]) + (Wet*m.cf[4,4]) + ((Wet^2)*m.cf[5,4]))) # # SD.wet2.plot <- ggplot(data = wet.data.plot) + # geom_line(aes(x = Wet, y = Est)) + # geom_line(aes(x = Wet, y = LCL), linetype = "dashed") + # geom_line(aes(x = Wet, y = UCL), linetype = "dashed") + # theme_classic() + # labs(x = "Proportion Wetland", y = element_blank()) + # scale_y_continuous(trans = 'log10') # # ### Group Plots # require(patchwork) # # top.model.plots <- SD.ag2.plot + SD.dev.plot + SD.wet2.plot + # plot_annotation(tag_levels = 'A') + plot_layout(ncol = 3) # # ggsave(top.model.plots, file = "./Results/SettlingDecision_topmodels.jpg", # height = 5, width = 12)
package org.ccs.app.core.authenticate.domain; import jakarta.persistence.*; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; import org.ccs.app.core.authenticate.domain.converter.RoleCodeToStringConverter; import org.ccs.app.core.share.domain.BaseCreatedAndUpdatedDateTime; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; @NoArgsConstructor @Entity @Table(name = "user_account_role") @DynamicInsert @DynamicUpdate @Getter @ToString(exclude = "account") public class UserAccountRole extends BaseCreatedAndUpdatedDateTime { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "role") @Convert(converter = RoleCodeToStringConverter.class) private RoleCode roleCode; @ManyToOne @JoinColumn(name = "user_account_id") private UserAccount account; public UserAccountRole(RoleCode roleCode) { this.roleCode = roleCode; } }
/** * Copyright 2008 - 2015 The Loon Game Engine Authors * * 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. * * @project loon * @author cping * @email:[email protected] * @version 0.5 */ package loon.geom; import loon.LSystem; import loon.action.collision.CollisionHelper; import loon.utils.MathUtils; import loon.utils.TArray; /*最简化的整型坐标处理类,以减少对象大小*/ public class PointI implements XY, SetXY { public static boolean pointEquals(int x1, int y1, int x2, int y2, int tolerance) { int dx = x2 - x1; int dy = y2 - y1; return dx * dx + dy * dy < tolerance * tolerance; } public int x = 0; public int y = 0; public PointI() { this(0, 0); } public PointI(int size) { set(size, size); } public PointI(int x1, int y1) { set(x1, y1); } public PointI(PointI p) { this.x = p.x; this.y = p.y; } public PointI set(int v) { return set(v, v); } public PointI set(int x1, int y1) { this.x = x1; this.y = y1; return this; } public PointF getF() { return new PointF(this.x, this.y); } public PointI toRoundPoint() { return new PointI(MathUtils.floor(this.x), MathUtils.floor(this.y)); } public PointI empty() { return this.set(0, 0); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; PointI other = (PointI) obj; return equals(other); } public final boolean equals(PointI point) { return equals(point.x, point.y); } public final boolean equals(int x, int y) { return MathUtils.equal(x, this.x) && MathUtils.equal(y, this.y); } public final int length() { return (int) MathUtils.sqrt(MathUtils.mul(x, x) + MathUtils.mul(y, y)); } public final PointI negate() { x = -x; y = -y; return this; } public final PointI offset(int x, int y) { this.x += x; this.y += y; return this; } public final PointI set(PointI p) { this.x = p.x; this.y = p.y; return this; } public final int distanceTo(PointI p) { final int tx = this.x - p.x; final int ty = this.y - p.y; return (int) MathUtils.sqrt(MathUtils.mul(tx, tx) + MathUtils.mul(ty, ty)); } public final int distanceTo(int x, int y) { final int tx = this.x - x; final int ty = this.y - y; return (int) MathUtils.sqrt(MathUtils.mul(tx, tx) + MathUtils.mul(ty, ty)); } public final int distanceTo(PointI p1, PointI p2) { final int tx = p2.x - p1.x; final int ty = p2.y - p1.y; final int u = MathUtils.div(MathUtils.mul(x - p1.x, tx) + MathUtils.mul(y - p1.y, ty), MathUtils.mul(tx, tx) + MathUtils.mul(ty, ty)); final int ix = p1.x + MathUtils.mul(u, tx); final int iy = p1.y + MathUtils.mul(u, ty); final int dx = ix - x; final int dy = iy - y; return (int) MathUtils.sqrt(MathUtils.mul(dx, dx) + MathUtils.mul(dy, dy)); } public PointI cpy(PointI p) { return new PointI(p.x, p.y); } public PointI cpy() { return cpy(this); } @Override public float getX() { return x; } @Override public float getY() { return y; } @Override public void setX(float x) { this.x = MathUtils.floor(x); } @Override public void setY(float y) { this.y = MathUtils.floor(y); } public PointI random() { this.x = MathUtils.random(0, LSystem.viewSize.getWidth()); this.y = MathUtils.random(0, LSystem.viewSize.getHeight()); return this; } public float[] toArray() { return new float[] { x, y }; } public String toCSS() { return this.x + "px " + this.y + "px"; } public ObservableXY<PointI> observable(XYChange<PointI> v) { return ObservableXY.at(v, this, this); } public boolean inCircle(XYZ cir) { return CollisionHelper.checkPointvsCircle(this.x, this.y, cir); } public boolean inCircle(Circle c) { return CollisionHelper.checkPointvsCircle(this.x, this.y, c.getRealX(), c.getRealY(), c.getDiameter()); } public boolean inCircle(float cx, float cy, float d) { return CollisionHelper.checkPointvsCircle(this.x, this.y, cx, cy, d); } public boolean inEllipse(float ex, float ey, float ew, float eh) { return CollisionHelper.checkPointvsEllipse(this.x, this.y, ex, ey, ew, eh); } public boolean inEllipse(Ellipse e) { if (e == null) { return false; } return CollisionHelper.checkPointvsEllipse(this.x, this.y, e.getRealX(), e.getRealY(), e.getDiameter1(), e.getDiameter2()); } public boolean inEllipse(XYZW rect) { if (rect == null) { return false; } return CollisionHelper.checkPointvsEllipse(this.x, this.y, rect.getX(), rect.getY(), rect.getZ(), rect.getW()); } public boolean inArc(float ax, float ay, float arcRadius, float arcHeading, float arcAngle) { return CollisionHelper.checkPointvsArc(this.x, this.y, ax, ay, arcRadius, arcHeading, arcAngle); } public boolean inRect(XYZW rect) { if (rect == null) { return false; } return CollisionHelper.checkPointvsAABB(this.x, this.y, rect); } public boolean inRect(RectBox rect) { if (rect == null) { return false; } return CollisionHelper.checkPointvsAABB(this.x, this.y, rect.getX(), rect.getY(), rect.getWidth(), rect.getHeight()); } public boolean inRect(float rx, float ry, float rw, float rh) { return CollisionHelper.checkPointvsAABB(this.x, this.y, rx, ry, rw, rh); } public boolean inLine(XYZW line) { if (line == null) { return false; } return CollisionHelper.checkPointvsLine(this.x, this.y, line.getX(), line.getY(), line.getZ(), line.getW()); } public boolean inLine(Line line) { if (line == null) { return false; } return CollisionHelper.checkPointvsLine(this.x, this.y, line.getX1(), line.getY1(), line.getX2(), line.getY2()); } public boolean inLine(Line line, float size) { if (line == null) { return false; } return CollisionHelper.checkPointvsLine(this.x, this.y, line.getX1(), line.getY1(), line.getX2(), line.getY2(), size); } public boolean inLine(float x1, float y1, float x2, float y2, float size) { return CollisionHelper.checkPointvsLine(this.x, this.y, x1, y1, x2, y2, size); } public boolean inTriangle(Triangle2f t) { if (t == null) { return false; } return CollisionHelper.checkPointvsTriangle(this.x, this.y, t.getX1(), t.getY1(), t.getX2(), t.getY2(), t.getX3(), t.getY3()); } public boolean inTriangle(float x1, float y1, float x2, float y2, float x3, float y3) { return CollisionHelper.checkPointvsTriangle(this.x, this.y, x1, y1, x2, y2, x3, y3); } public boolean inPolygon(Polygon poly) { if (poly == null) { return false; } return CollisionHelper.checkPointvsPolygon(this.x, this.y, poly.getVertices()); } public <T extends XY> boolean inPolygon(TArray<T> poly) { if (poly == null) { return false; } return CollisionHelper.checkPointvsPolygon(this.x, this.y, poly); } public boolean collided(Shape shape) { if (shape instanceof Polygon) { return inPolygon((Polygon) shape); } else if (shape instanceof Line) { return inLine((Line) shape); } else if (shape instanceof RectBox) { return inRect((RectBox) shape); } else if (shape instanceof Triangle2f) { return inTriangle((Triangle2f) shape); } else if (shape instanceof Circle) { return inCircle((Circle) shape); } else if (shape instanceof Ellipse) { return inEllipse((Ellipse) shape); } return CollisionHelper.checkPointvsPolygon(this.x, this.y, shape.getPoints(), 1f); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * LSystem.unite(hashCode,x); hashCode = prime * LSystem.unite(hashCode,y); return hashCode; } @Override public String toString() { return "(" + x + "," + y + ")"; } }
import { NextApiRequest, NextApiResponse } from "next"; import withHandler, { ResponseType } from "@libs/server/withHandler"; import client from "@libs/server/client"; import { withApiSession } from "@libs/server/withSession"; async function handler( req: NextApiRequest, res: NextApiResponse<ResponseType> ) { if (req.method === "GET") { const { query: { id }, } = req; const post = await client.myBlog.findUnique({ where: { id: +id, }, }); const categories = await client.category.findMany({ where: { posts: { some: { id: post.id, }, }, }, }); const prevPost = await client.myBlog.findFirst({ take: -1, skip: 1, cursor: { id: +id, }, select: { id: true, title: true, }, }); const nextPost = await client.myBlog.findFirst({ take: 1, skip: 1, cursor: { id: +id, }, select: { id: true, title: true, }, }); res.json({ ok: true, post, categories, prevPost, nextPost, }); } if (req.method === "POST") { if (!req.session.user?.admin) return res.json({ ok: false, message: "You are Not Admin! Don't hack me!", }); const { query: { id }, body, } = req; const { title, content, categories, summary, }: { title: string; content: string; categories: string[]; summary: string; } = body; const allCategories = await client.category.findMany({}); const existedCategories = await client.category.findMany({ where: { posts: { some: { id: +id, }, }, }, }); const deleteCategories = existedCategories.filter( (item) => !categories.includes(item.category) ); const newCategories = categories.filter( (category) => !existedCategories.map((item) => item.category).includes(category) ); const alreadyCategories = allCategories .filter((item) => newCategories.includes(item.category)) .map((item) => ({ ...item })); const nonExistedCategories = newCategories.filter( (existed) => !allCategories.map((item) => item.category).includes(existed) ); const updatePost = await client.myBlog.update({ where: { id: +id, }, data: { title, summary, content, category: { disconnect: deleteCategories.map((category) => ({ id: category.id })), create: nonExistedCategories.map((category) => ({ category, })), connect: alreadyCategories.map((category) => ({ id: category.id })), }, }, }); res.revalidate(`/blog/${updatePost.id}`); return res.json({ ok: true, updatePost }); } } export default withApiSession( withHandler({ methods: ["GET", "POST"], handler, isPrivate: false, }) );
'use client' import React from 'react' import CardAdminItem from './CardAdminItem' import ClassIcon from '../icons/ClassIcon' import UsersIcon from '../icons/UsersIcon' import PremiumIcon from '../icons/PremiumIcon' import { useCategory } from '@/utils/swr' import { useSession } from 'next-auth/react' import { usePathname, useParams } from 'next/navigation' import CardAdminLoading from '../loading/CardAdminLoading' export default function CardAdmin() { const { id } = useParams() const { data: session } = useSession() const token = session?.user?.accessToken const pathName = usePathname() const urlShould = pathName === `/admin/course/${id}` const { data: categories, error } = useCategory(token, true) return ( <div className={`grid gap-4 px-4 mt-8 mb-8 md:mb-10 md:mt-8 md:px-12 md:grid-cols-2 lg:grid-cols-3 md:gap-5 ${ urlShould ? 'hidden' : '' }`} > {error ? ( <p>error: {error}</p> ) : categories ? ( <> <CardAdminItem bg={'bg-alert-green'} icon={<UsersIcon />} total={categories?.activeUsers} text={'Active Users'} /> <CardAdminItem bg={'bg-secondary-dark-blue'} icon={<ClassIcon />} total={categories?.activeClass} text={'Active Class'} /> <CardAdminItem bg={'bg-light-green'} icon={<PremiumIcon />} total={categories?.premiumClass} text={'Premium Class'} /> </> ) : ( <CardAdminLoading /> )} </div> ) }
import { useEffect, useState } from 'react'; import './mainApp.css' import Loading from './components/Loading'; import Job from './components/Job'; // API URL const apiURL = "https://course-api.com/react-tabs-project"; const TabsApp = () => { const [data, setData] = useState([]); const [loading, setIsLoading] = useState(false); const [singleData, setSingledata] = useState([]) // Fetch Data Function async function fetchData() { setIsLoading(true); try { const response = await fetch(apiURL); const responseData = await response.json(); setData(responseData); setSingledata(responseData[0]) setIsLoading(false); } catch (error) { console.log(error.message); } setIsLoading(false); } useEffect(() => { fetchData(); }, []); useEffect(() => { const buttons = document.querySelectorAll('.company-name button') for (let i = 0; i < buttons.length; i++) { buttons[i].addEventListener('click', () => { for (let j = 0; j < buttons.length; j++) { buttons[j].classList.remove('clicked') buttons[i].classList.add('clicked') } }) } }, [data]) const getCompanyNames = data.map((dataItem) => { const { company } = dataItem; return company; }); const getUniqueCompanyNames = Array.from(new Set(getCompanyNames)); function dataTabButton(id) { console.log(id) setSingledata(data[id]) } if (loading) { return ( <div className="container"> <Loading /> </div> ); } return ( <div className="container"> <section id="main"> <div className="company-name"> {getUniqueCompanyNames.map((companyName, id) => ( <button className={id === 0 ? 'clicked' : null} key={id} onClick={() => dataTabButton(id)}>{companyName}</button> ))} </div> <div className="company-info"> {singleData && <Job dataProps={singleData} />} </div> </section> </div> ); } export default TabsApp
import axios from "axios"; import React from "react"; import { setLoading, showMessage } from "../utils"; import "../css/other.css"; export default class Other extends React.Component { componentDidUpdate(props) { if (!props.display && this.props.display) { window.location.hash = "other"; } } render() { const display = this.props.display; return ( <div id="other" style={{"display": display ? "" : "none"}}> <SettingAnnouncement /> </div> ); } } class SettingAnnouncement extends React.Component { constructor(props) { super(props); this.state = { context: "" }; this.editBlock = React.createRef(); this.getAnnouncement = this.getAnnouncement.bind(this); this.sendAnnouncement = this.sendAnnouncement.bind(this); } componentDidMount() { this.getAnnouncement(); } getAnnouncement() { axios.get("/api/announce?raw=true") .then( (response) => { this.editBlock.current.textContent = response.data.data; } ); } sendAnnouncement() { setLoading(true); let data = new FormData(); data.append("context", this.editBlock.current.textContent) axios.put( `/api/announce`, data ) .then( (response) => { this.setState({ context: response.data.data }); showMessage("更改成功", "公告更改成功。", "success"); } ) .catch( () => { showMessage("更改失敗", "公告更改失敗。", "error"); } ) .finally( () => { setLoading(false); } ); } render() { return ( <div className="announcement block"> <div className="title">變更公告</div> <hr /> <div className="description">換行時請使用"Shift"+"Enter"</div> <div ref={this.editBlock} className="edit-block" contentEditable /> <div className="tool-bar"> <button onClick={this.getAnnouncement}>還原</button> <button onClick={this.sendAnnouncement}>儲存</button> </div> </div> ); } }
import Link from "next/link" import type { CreatureCategory } from "@prisma/client" import { prisma } from "@/server/db" import ImageCard from "../ui/ImageCard/ImageCard" import { ReactNode } from "react" type Props = { categorySlug: CreatureCategory["slug"] categoryTitle: CreatureCategory["title"] } const CreaturesList = async ({ categorySlug, categoryTitle }: Props) => { const creatures = await prisma.creature.findMany({ where: { categorySlug }, orderBy: { name: "asc" }, }) let content: ReactNode if (creatures.length === 0) { content = <div>Список {categoryTitle} порожній.</div> } else { content = creatures.map(creature => ( <Link href={`${categorySlug}/${creature.id}`} key={creature.id}> <ImageCard title={creature.name} imageSrc={creature.mainImage} /> </Link> )) } return ( <div className="mb-6 mt-3 flex flex-1 flex-wrap content-start items-start justify-center gap-3 overflow-auto"> {content} </div> ) } export default CreaturesList
""" Создать базовый шаблон для интернет-магазина, содержащий общие элементы дизайна (шапка, меню, подвал), и дочерние шаблоны для страниц категорий товаров и отдельных товаров. Например, создать страницы «Одежда», «Обувь» и «Куртка», используя базовый шаблон. """ from flask import Flask from flask import render_template app = Flask(__name__) category = [ {"title": 'Одежда', "func_name": 'dress'}, {"title": 'Обувь', "func_name": 'shoes'}, {"title": 'Игрушки', "func_name": 'toys'} ] @app.route('/') @app.route('/index/') def index(): return render_template('store_index.html', category=category) @app.route('/info/') def info(): return render_template('store_info.html') @app.route('/contacts/') def contacts(): return render_template('store_contacts.html') @app.route('/dress/') def dress(): return render_template('store_dress.html') @app.route('/shoes/') def shoes(): return render_template('store_shoes.html') @app.route('/toys/') def toys(): return render_template('store_toys.html') if __name__ == '__main__': app.run()
package sqlite import ( "database/sql" _ "github.com/mattn/go-sqlite3" "github.com/pkg/errors" ) var ErrMetisTxNotFound = errors.New("metis tx not found") type MetisTx struct { ID uint64 `json:"id" sql:"id"` TxHash string `json:"tx_hash" sql:"tx_hash"` TxData string `json:"tx_data" sql:"tx_data"` Pushed bool `json:"pushed" sql:"pushed"` // pushed to l2 Mined bool `json:"mined" sql:"mined"` // l2 mined } type MetisTxTable struct { db *sql.DB rdb *sql.DB } func InitMetisTxTable(db *sql.DB) error { var create = `CREATE TABLE IF NOT EXISTS metis_tx_table(id INTEGER PRIMARY KEY AUTOINCREMENT, tx_hash VARCHAR(128) NOT NULL, tx_data LONGTEXT, pushed BOOLEAN,mined BOOLEAN); CREATE UNIQUE INDEX IF NOT EXISTS uidx_tx_hash ON metis_tx_table(tx_hash);` _, err := db.Exec(create) return err } func NewMetisTxTable(db, rdb *sql.DB) *MetisTxTable { return &MetisTxTable{ db: db, rdb: rdb, } } func (c *MetisTxTable) Insert(tx *MetisTx) (int, error) { res, err := c.db.Exec("INSERT INTO metis_tx_table(tx_hash,tx_data,pushed,mined) VALUES(?,?,?,?)", tx.TxHash, tx.TxData, tx.Pushed, tx.Mined) if err != nil { return 0, err } var id int64 if id, err = res.LastInsertId(); err != nil { return 0, err } return int(id), nil } func (c *MetisTxTable) DeleteExpiredDataByID(minID uint64) error { _, err := c.db.Exec("DELETE FROM metis_tx_table where id<=?", minID) if err != nil { return err } return nil } func (c *MetisTxTable) DeleteByID(id uint64) error { _, err := c.db.Exec("DELETE FROM metis_tx_table where id=?", id) if err != nil { return err } return nil } func (c *MetisTxTable) DeleteByTxHash(txHash string) error { _, err := c.db.Exec("DELETE FROM metis_tx_table where tx_hash=?", txHash) if err != nil { return err } return nil } func (c *MetisTxTable) GetMetisTxByID(id uint64) (*MetisTx, error) { // Query DB row based on ID row := c.rdb.QueryRow("SELECT id,tx_hash,tx_data,pushed,mined FROM metis_tx_table WHERE id=?", id) // Parse row into Activity struct var metisTx MetisTx var err error if err = row.Scan(&metisTx.ID, &metisTx.TxHash, &metisTx.TxData, &metisTx.Pushed, &metisTx.Mined); err == sql.ErrNoRows { return nil, ErrMetisTxNotFound } return &metisTx, nil } func (c *MetisTxTable) GetMetisTxByTxHash(txHash string) (*MetisTx, error) { // Query DB row based on ID row := c.rdb.QueryRow("SELECT * FROM metis_tx_table WHERE tx_hash=?", txHash) // Parse row into Activity struct var metisTx MetisTx if err := row.Scan(&metisTx.ID, &metisTx.TxHash, &metisTx.TxData, &metisTx.Pushed, &metisTx.Mined); err == sql.ErrNoRows { return nil, ErrMetisTxNotFound } return &metisTx, nil } func (c *MetisTxTable) GetLatestOne() (*MetisTx, error) { row := c.db.QueryRow("SELECT * FROM metis_tx_table ORDER BY id desc limit 1") // Parse row into Activity struct var metisTx MetisTx if err := row.Scan(&metisTx.ID, &metisTx.TxHash, &metisTx.TxData, &metisTx.Pushed, &metisTx.Mined); err == sql.ErrNoRows { return nil, ErrMetisTxNotFound } return &metisTx, nil } func (c *MetisTxTable) GetAllWaitPushMetisTxs(limit, offset, startID int64) ([]*MetisTx, error) { rows, err := c.rdb.Query("SELECT * FROM metis_tx_table WHERE id>? ORDER BY id ASC LIMIT ? OFFSET ?", startID, limit, offset) if err != nil { return nil, err } defer rows.Close() var allMetisTxs []*MetisTx for rows.Next() { // Parse row into Activity struct var metisTx MetisTx if err = rows.Scan(&metisTx.ID, &metisTx.TxHash, &metisTx.TxData, &metisTx.Pushed, &metisTx.Mined); err != nil { return nil, err } allMetisTxs = append(allMetisTxs, &metisTx) } return allMetisTxs, nil } func (c *MetisTxTable) GetAllWaitPushMetisTxsByStartID(startID int64) ([]*MetisTx, error) { rows, err := c.rdb.Query("SELECT * FROM metis_tx_table WHERE id > ? ", startID) if err != nil { return nil, err } defer rows.Close() var allMetisTxs []*MetisTx for rows.Next() { // Parse row into Activity struct var metisTx MetisTx if err = rows.Scan(&metisTx.ID, &metisTx.TxHash, &metisTx.TxData, &metisTx.Pushed, &metisTx.Mined); err != nil { return nil, err } allMetisTxs = append(allMetisTxs, &metisTx) } return allMetisTxs, nil }
import type * as T from "../types/openapi.js"; import { getSchemaId } from "./announce.js"; import { AnnouncementType, BroadcastAnnouncement } from "./dsnp.js"; import { getApi } from "./frequency.js"; import { bases } from "multiformats/basics"; import { hexToString } from "@polkadot/util"; import axios from "axios"; import { ParquetReader } from "@dsnp/parquetjs"; import { MessageResponse } from "@frequency-chain/api-augment/interfaces"; import { ipfsUrl } from "./ipfs.js"; type Post = T.Components.Schemas.BroadcastExtended; interface CachedPosts { [blockNumber: number]: Promise<[number, Post][]>; } type BlockRange = { from: number; to: number }; interface MsgParsed { cid: string; provider_msa_id: number; msa_id: number | null; index: number; block_number: number; payload_length: number; } const getPostsForBlockRange = async ({ from, to }: BlockRange): Promise<[number, Post][]> => { // Get the events from the block const api = await getApi(); const schemaId = getSchemaId(AnnouncementType.Broadcast); // TODO: Support when > 10_000 messages come back // TODO: to_block - self.from_block <= 50000 const resp = await api.rpc.messages.getBySchemaId(schemaId, { from_block: from, // Inclusive from_index: 0, to_block: to + 1, // Exclusive page_size: 10_000, }); const messages: MsgParsed[] = resp.content.map((msg: any) => { const parsed = msg.toJSON() as unknown as MessageResponse; return { ...parsed, cid: hexToString(parsed.cid as any), }; }); const posts: [number, Post][] = []; // Fetch the parquet files for await (const msg of messages) { try { const parquetFileUrl = ipfsUrl(msg.cid); const resp = await axios.get(parquetFileUrl, { responseType: "arraybuffer", timeout: 10_000, }); const reader = await ParquetReader.openBuffer(Buffer.from(resp.data)); // Fetch the individual posts const cursor = reader.getCursor(); let announcement: null | BroadcastAnnouncement = null; while ((announcement = (await cursor.next()) as null | BroadcastAnnouncement)) { try { // TODO: Validate Hash const postResp = await axios.get(announcement.url, { responseType: "text", timeout: 10_000, }); posts.push([ msg.block_number, { fromId: announcement.fromId.toString(), contentHash: bases.base58btc.encode(announcement.contentHash as any), content: postResp.data as unknown as string, timestamp: new Date().toISOString(), // TODO: Use Block timestamp replies: [], // TODO: Support replies }, ]); } catch (e) { // Skip this announcement // TODO: Try again sometime? console.error("Failed Content", e); } } } catch (e) { // Skip this parquet file. // TODO: Try again sometime? console.error("Failed Parquet File", e); return []; } } // Return the posts return posts; }; const toRanges = (prev: BlockRange[], cur: number): BlockRange[] => { if (!prev[0]) { return [ { from: cur, to: cur, }, ]; } const priorTo = prev[0].to; if (priorTo === cur || priorTo + 1 === cur) { prev[0].to = cur; } else { prev.unshift({ from: cur, to: cur }); } return prev; }; const fetchAndCachePosts = (newestBlockNumber: number, oldestBlockNumber: number): void => { // Create the range Array.from({ length: Math.abs(newestBlockNumber - oldestBlockNumber) + 1 }, (_x, i) => oldestBlockNumber + i) // Skip those already in the cache .filter((x) => !(x in cache)) // Create ranges .reduce(toRanges, []) // TODO: Handle single block requests // Cache the posts for each range and apply to the cache .map((range) => { const pending = getPostsForBlockRange(range); for (let i = range.from; i <= range.to; i++) { cache[i] = pending.then((x) => x.filter(([n]) => n === i)); } }); }; const cache: CachedPosts = {}; export const getPostsInRange = async (newestBlockNumber: number, oldestBlockNumber: number): Promise<Post[]> => { // Trigger the fetch and caching fetchAndCachePosts(newestBlockNumber, oldestBlockNumber); const posts: Post[] = []; for (let i = newestBlockNumber; i >= oldestBlockNumber; i--) { const blockPosts = ((await cache[i]) || []).map(([_x, p]) => p); posts.push(...blockPosts); } return posts; };
import { Component } from '@angular/core'; import { state, style, trigger } from '@angular/animations'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], animations: [ trigger('box', [ state('start', style({ background: 'blue' })), state( 'end', style({ background: 'red', transform: 'scale(1.2)', }) ), ]), ], }) export class AppComponent { boxState = 'end'; animate() { this.boxState = this.boxState === 'end' ? 'start' : 'end'; } }
import { Box, Heading, Img, HStack, VStack, Text, Stack, keyframes } from '@chakra-ui/react' import React from 'react' import { DiHtml5, DiCss3, DiJavascript1, DiReact, DiNodejsSmall, } from 'react-icons/di' import { SiMongodb, SiExpress } from 'react-icons/si' import frontend from '../assets/frontend.jpg' import backened from '../assets/backened.jpg' import database from '../assets/database.jpg' import { motion } from 'framer-motion' let a = 0; const Skills = () => { return ( <Box bgColor={'#090c31'} paddingTop={5} h={'fit-content'}> <Heading textAlign={'center'} color={'white'} textDecoration={'underline'} marginBottom={10} id='skills' > SKILLS </Heading> <VStack p={'10px'}> <VStack gap={'10vh'}> <Stack flexDirection={['column', 'row']} justifyContent={'space-between'} w={'100vw'} alignItems={'center'} > <Field name={'FRONTEND'} image={frontend} size={30} /> <MyComponent head={'FRONTEND'} arr={[ { 'name': 'HTML', 'Icon': DiHtml5 }, { 'name': 'CSS', 'Icon': DiCss3 }, { 'name': 'JSCRIPT', 'Icon': DiJavascript1 }, { 'name': 'REACT', 'Icon': DiReact }]} /> </Stack> <Stack flexDirection={['column-reverse', 'row']} justifyContent={'space-between'} w={'100vw'} alignItems={'center'} > <MyComponent head={'DATABASE'} arr={[{ 'name': 'MONGODB', 'Icon': SiMongodb }]} po='left' /> <Field name={'DATABASE'} image={database} size={25} po="right" /> </Stack> <Stack flexDirection={['column', 'row']} justifyContent={'space-between'} w={'100vw'} alignItems={'center'} > <Field name={'BACKEND'} image={backened} size={25} /> <MyComponent arr={[{ 'name': 'EXPRESS', 'Icon': SiExpress }, { 'name': 'NODE JS', 'Icon': DiNodejsSmall }]} head={'BACKEND'} /> </Stack> </VStack> </VStack> </Box> ) } const Field = ({ name, image, size, po = "left" }) => { return ( <VStack bgColor={'white'} p={2} h={'fit-content'} borderRadius={'10px'} marginLeft={po === 'left' ? '5vw' : '0vw'} marginRight={po === 'right' ? '5vw' : '0vw'} borderBottom={'6px solid grey'}> <Box as={motion.div} w={['60vw', `${size}vw`]} h={'fit-content'} > <Img src={image} objectFit={'contain'} /> <Text fontWeight={'bold'} textAlign={'center'} bgColor={'white'} marginTop={'2vh'} borderRadius={'10px'} fontSize={'1rem'} p={2}> {name}</Text> </Box> </VStack> ); } const IconCard = ({ name, Icon }) => { a += 0.3 const updown = keyframes` to{ transform:translateY(20px) }`; const updownAnimation = `${updown} 1s linear ${a}s infinite alternate` return ( <motion.div initial={{ x: `${name}`==='MONGODB'? '-100%':'100%', opacity: 0 }} whileInView={{ x: 0, opacity: 1, transition:{ type: 'spring', stiffness: 300, } }} whileTap={{ rotate:-360, scale:1.2 }} > <VStack boxSize={['100px', '150px']} bgColor={'white'} borderRadius={'50%'} justifyContent={'center'} transition={'all 0.7s'} filter={'drop-shadow(10px 10px 10px black)'} animation={updownAnimation} css={{ "&:hover": { filter: 'invert(1) drop-shadow(10px 10px 10px black)' } }}> <Icon fontSize={'5vmax'} /> <Text fontWeight={'900'} fontStyle={'italic'} fontSize={['0.9rem', '1.2rem']}> {name} </Text> </VStack> </motion.div> ); } const MyComponent = ({ arr, po = 'right', head }) => { return ( <VStack m={['auto', 0]} borderLeftRadius={['10px', po === 'right' ? '200px' : 0]} borderRightRadius={['10px', po === 'left' ? '200px' : 0]} minH={['60vh', '70vh']} w={['90vw', '60vw']} bgColor={'blueviolet'} justifyContent={'center'} gap={'30px'} p={'20px'} overflowX={'hidden'} > <Heading color={'white'} textDecoration={'underline'} > {head} </Heading> <HStack gap={'2rem'} flexWrap={'wrap'} justifyContent={'center'} > { arr.map((Item, index) => ( <IconCard name={Item.name} Icon={Item.Icon} key={index} /> )) } </HStack> </VStack> ); } export default Skills
import { CornerType, ParticleType, RectangleType } from "./ParticleTypes"; import { addCenterGravity, addForce, update } from "./ParticleUtils"; import { MUTUAL_REPULSION_MULTIPLE } from "./constants"; export function getNewParticleArray(particles: ParticleType[]): ParticleType[] { return particles.map((particle) => Object.assign(particle)); } export function updateParticles( particles: ParticleType[], setParticles: (_: ParticleType[]) => void ) { let newParticles = getNewParticleArray(particles); for (let i = 0; i < particles.length; i++) { newParticles[i] = addCenterGravity(newParticles[i]); newParticles[i] = update(newParticles[i]); } newParticles = addMutualRepulsion(newParticles); newParticles = addEdgeForces(newParticles, rects); setParticles(addMutualRepulsion(newParticles)); } function addEdgeForce( particle: ParticleType, otherParticle: ParticleType, distance: number ): [ParticleType, ParticleType] { const dx = particle.px - otherParticle.px; const dy = particle.py - otherParticle.py; const dh = Math.sqrt(dx * dx + dy * dy); if (dh > 1) { const distention = dh - distance; const restorativeForce = 0.5 * distention; // F = -kx const fx = (dx / dh) * restorativeForce; const fy = (dy / dh) * restorativeForce; return [addForce(particle, -fx, -fy), addForce(otherParticle, fx, fy)]; } return [particle, otherParticle]; } function getCorners( stampId: string, particles: ParticleType[] ): [ParticleType, ParticleType, ParticleType, ParticleType] | undefined { //[NW, NE, SE, SW] const particlesForRect = particles.filter( (particle) => particle.stampId === stampId ); const cornerMap = new Map( particlesForRect.map((particle) => [particle.corner, particle]) ); const NE = cornerMap.get("NE"); if (!NE) return; const SE = cornerMap.get("SE"); if (!SE) return; const NW = cornerMap.get("NW"); if (!NW) return; const SW = cornerMap.get("SW"); if (!SW) return; return [NW, NE, SE, SW]; } function getIndexMap(particles: ParticleType[]): Map<string, number> { return new Map( particles.map((particle, index) => [getParticleId(particle), index]) ); } function getParticleId(particle: ParticleType): string { return `${particle.stampId}-${particle.corner}`; } export function addEdgeForces( particles: ParticleType[], rects: RectangleType[] ): ParticleType[] { const newParticles = getNewParticleArray(particles); const indexMap = getIndexMap(newParticles); for (let rect of rects) { const corners = getCorners(rect.stampId, particles); if (!corners) continue; const diagLen = Math.sqrt( Math.pow(rect.width, 2) + Math.pow(rect.height, 2) ); const [NW, NE, SE, SW] = corners; const [NW1, NE1] = addEdgeForce(NW, NE, rect.width); const [NE2, SE1] = addEdgeForce(NE1, SE, rect.height); const [SE2, SW1] = addEdgeForce(SE1, SW, rect.width); const [SW2, NW2] = addEdgeForce(SW1, NW1, rect.height); const [SW3, NE3] = addEdgeForce(SW2, NE2, diagLen); const [SE3, NW3] = addEdgeForce(SE2, NW2, diagLen); setParticleInList(NW3, indexMap, particles); setParticleInList(NE3, indexMap, particles); setParticleInList(SE3, indexMap, particles); setParticleInList(SW3, indexMap, particles); } return particles; } function setParticleInList( particle: ParticleType, indexMap: Map<string, number>, particles: ParticleType[] ) { const id = getParticleId(particle); const index = indexMap.get(id); if (index !== undefined && index < particles.length) { particles[index] = particle; } } export function addMutualRepulsion(particles: ParticleType[]): ParticleType[] { const newParticles = getNewParticleArray(particles); for (let i = 0; i < newParticles.length; i++) { const particle = newParticles[i]; for (let j = 0; j < i; j++) { const otherParticle = newParticles[j]; const dx = particle.px - otherParticle.px; const dy = particle.py - otherParticle.py; const dhRaw = Math.sqrt(dx * dx + dy * dy); const dh = Math.max(dhRaw, 1); const componentInX = dx / dh; const componentInY = dy / dh; const proportionToDistanceSquared = 1.0 / (dh * dh); const repulsionForceX = componentInX * proportionToDistanceSquared; const repulsionForceY = componentInY * proportionToDistanceSquared; newParticles[i] = addForce( particle, repulsionForceX * MUTUAL_REPULSION_MULTIPLE, repulsionForceY * MUTUAL_REPULSION_MULTIPLE ); newParticles[j] = addForce( otherParticle, -repulsionForceX * MUTUAL_REPULSION_MULTIPLE, -repulsionForceY * MUTUAL_REPULSION_MULTIPLE ); } } return newParticles; }
#include "lists.h" /** * add_nodeint - adds a new node at the beginning of a linked list * * @head: pointer to header pointer * @n: the number to insert * * Return: the address of the new elments, null otherwise. */ listint_t *add_nodeint(listint_t **head, const int n) { listint_t *start = NULL; if (head == NULL) return (NULL); start = malloc(sizeof(listint_t)); if (start == NULL) return (NULL); start->n = n; start->next = *head; *head = start; return (start); }
import React, { createContext, useReducer, useContext, useEffect, useCallback, ReactNode, } from "react"; type AuthState = { isAuthenticated: boolean; }; type AuthAction = { type: "LOGIN" } | { type: "LOGOUT" }; type AuthContextType = { state: AuthState; dispatch: React.Dispatch<AuthAction>; signIn: () => void; signOut: () => void; }; const AuthContext = createContext<AuthContextType | undefined>(undefined); type AuthProviderProps = { children: ReactNode }; const authReducer = (state: AuthState, action: AuthAction): AuthState => { switch (action.type) { case "LOGIN": return { isAuthenticated: true }; case "LOGOUT": return { isAuthenticated: false }; default: return state; } }; export const useAuth = (): AuthContextType => { const context = useContext(AuthContext); if (!context) throw new Error("useAuth must be used within an AuthProvider"); return context; }; export const AuthProvider = ({ children }: AuthProviderProps): JSX.Element => { const [state, dispatch] = useReducer(authReducer, { isAuthenticated: false }); useEffect(() => { const token = localStorage.getItem("authToken"); if (token) dispatch({ type: "LOGIN" }); }, []); useEffect(() => { if (state.isAuthenticated) { localStorage.setItem("authToken", "yourAuthTokenHere"); } else { localStorage.removeItem("authToken"); } }, [state.isAuthenticated]); const signIn = useCallback(() => { dispatch({ type: "LOGIN" }); }, [dispatch]); const signOut = useCallback(() => { dispatch({ type: "LOGOUT" }); }, [dispatch]); return ( <AuthContext.Provider value={{ state, dispatch, signIn, signOut }}> {children} </AuthContext.Provider> ); };
// // ViewController.swift // Todoey // // Created by Angela Yu on 16/11/2017. // Copyright © 2017 Angela Yu. All rights reserved. // import UIKit import RealmSwift class TodoListViewController: UITableViewController, UIGestureRecognizerDelegate { var todoItems : Results<Item>? let realm = try! Realm(); var selectedCategory : Category? { didSet{ loadItems() } } override func viewDidLoad() { super.viewDidLoad() let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress)) longPressGesture.minimumPressDuration = 1; self.tableView.addGestureRecognizer(longPressGesture) //print(FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)) } //MARK: - Tableview Datasource Methods override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return todoItems?.count ?? 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "ToDoItemCell", for: indexPath) if let item = todoItems?[indexPath.row] { cell.textLabel?.text = item.title //Ternary operator ==> // value = condition ? valueIfTrue : valueIfFalse cell.accessoryType = item.done ? .checkmark : .none } else { cell.textLabel?.text = "No Items Added" } return cell } //MARK: - TableView Delegate Methods override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // context.delete(itemArray[indexPath.row]) // itemArray.remove(at: indexPath.row) // todoItems[indexPath.row].done = !todoItems[indexPath.row].done //saveItems() if let item = todoItems?[indexPath.row] { do { try realm.write { item.done = !item.done } } catch { print("Error saving done status! \(error)") } } tableView.reloadData() tableView.deselectRow(at: indexPath, animated: true) } // func remove(item: Item) { // do { // try! realm.write { // realm.add(item) // } // } catch { // print("Error saving context \(error)") // } // self.tableView.reloadData() // } //MARK: - Add New Items @IBAction func addButtonPressed(_ sender: UIBarButtonItem) { var textField = UITextField() let alert = UIAlertController(title: "Add New Todoey Item", message: "", preferredStyle: .alert) let action = UIAlertAction(title: "Add Item", style: .default) { (action) in //what will happen once the user clicks the Add Item button on our UIAlert if let currentCategory = self.selectedCategory { do { try self.realm.write { let newItem = Item() newItem.title = textField.text! newItem.done = false currentCategory.items.append(newItem) } } catch { print("Error saving new items \(error)") } } self.tableView.reloadData() } alert.addTextField { (alertTextField) in alertTextField.placeholder = "Create new item" textField = alertTextField } alert.addAction(action) present(alert, animated: true, completion: nil) } //MARK: - Model Manupulation Methods func save(item: Item) { do { try! realm.write { realm.add(item) } } catch { print("Error saving context \(error)") } self.tableView.reloadData() } func loadItems() { todoItems = selectedCategory?.items.sorted(byKeyPath: "title", ascending: true); // let categoryPredicate = NSPredicate(format: "parentCategory.name MATCHES %@", selectedCategory!.name!) // // if let addtionalPredicate = predicate { // request.predicate = NSCompoundPredicate(andPredicateWithSubpredicates: [categoryPredicate, addtionalPredicate]) // } else { // request.predicate = categoryPredicate // } // // // do { // itemArray = try context.fetch(request) // } catch { // print("Error fetching data from context \(error)") // } tableView.reloadData() } //MARK: Handle long gesture @objc func handleLongPress(longPressGesture: UILongPressGestureRecognizer) { let p = longPressGesture.location(in: self.tableView) let indexPath = self.tableView.indexPathForRow(at: p) if indexPath == nil { print("Long press on table view, not row.") } else if longPressGesture.state == UIGestureRecognizer.State.began { print("Long press on row, at \(indexPath!.row)") if let item = todoItems?[indexPath!.row] { do { try realm.write { realm.delete(item) } } catch { print("Error saving done status! \(error)") } } tableView.reloadData() } } } //MARK: - Search bar methods //extension TodoListViewController: UISearchBarDelegate { // // func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { // // let request : NSFetchRequest<Item> = Item.fetchRequest() // // let predicate = NSPredicate(format: "title CONTAINS[cd] %@", searchBar.text!) // // request.sortDescriptors = [NSSortDescriptor(key: "title", ascending: true)] // // loadItems(with: request, predicate: predicate) // // } // // func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { // if searchBar.text?.count == 0 { // loadItems() // // DispatchQueue.main.async { // searchBar.resignFirstResponder() // } // // } // } //}
<?php if ( !function_exists('WPBaseTheme__PostTypeNoticia') ) { function WPBaseTheme__PostTypeNoticia() { $labels = array( 'name' => _x( 'Notícias', 'Post Type General Name', 'wpbasetheme' ), 'singular_name' => _x( 'Notícia', 'Post Type Singular Name', 'wpbasetheme' ), 'menu_name' => __( 'Notícias', 'wpbasetheme' ), 'name_admin_bar' => __( 'Notícia', 'wpbasetheme' ), 'archives' => __( 'Item Archives', 'wpbasetheme' ), 'attributes' => __( 'Item Attributes', 'wpbasetheme' ), 'parent_item_colon' => __( 'Parent Item:', 'wpbasetheme' ), 'all_items' => __( 'Todos os posts', 'wpbasetheme' ), 'add_new_item' => __( 'Add New Item', 'wpbasetheme' ), 'add_new' => __( 'Adcionar novo', 'wpbasetheme' ), 'new_item' => __( 'Novo', 'wpbasetheme' ), 'edit_item' => __( 'Edit Item', 'wpbasetheme' ), 'update_item' => __( 'Update Item', 'wpbasetheme' ), 'view_item' => __( 'View Item', 'wpbasetheme' ), 'view_items' => __( 'View Items', 'wpbasetheme' ), 'search_items' => __( 'Search Item', 'wpbasetheme' ), 'not_found' => __( 'Not found', 'wpbasetheme' ), 'not_found_in_trash' => __( 'Not found in Trash', 'wpbasetheme' ), 'featured_image' => __( 'Imagem destacada', 'wpbasetheme' ), 'set_featured_image' => __( 'Set featured image', 'wpbasetheme' ), 'remove_featured_image' => __( 'Remove featured image', 'wpbasetheme' ), 'use_featured_image' => __( 'Use as featured image', 'wpbasetheme' ), 'insert_into_item' => __( 'Insert into item', 'wpbasetheme' ), 'uploaded_to_this_item' => __( 'Uploaded to this item', 'wpbasetheme' ), 'items_list' => __( 'Items list', 'wpbasetheme' ), 'items_list_navigation' => __( 'Items list navigation', 'wpbasetheme' ), 'filter_items_list' => __( 'Filter items list', 'wpbasetheme' ), ); $args = array( 'label' => __( 'noticias', 'wpbasetheme' ), 'description' => __( 'Postagem de Notícias', 'wpbasetheme' ), 'labels' => $labels, 'supports' => ['title', 'editor', 'excerpt', 'author', 'thumbnail', 'revisions'], 'taxonomies' => [ 'category' ], 'hierarchical' => true, 'public' => true, 'show_ui' => true, 'show_in_menu' => true, 'menu_position' => 5, 'menu_icon' => 'dashicons-media-text', 'show_in_admin_bar' => true, 'show_in_nav_menus' => true, 'can_export' => true, 'has_archive' => 'noticias', 'exclude_from_search' => false, 'publicly_queryable' => true, 'capability_type' => 'post', ); register_post_type( 'noticia', $args ); flush_rewrite_rules(); } add_action( 'init', 'WPBaseTheme__PostTypeNoticia', 0 ); }
package main import ( "backend/models" "context" "database/sql" "flag" "fmt" _ "github.com/lib/pq" "log" "net/http" "os" "time" ) const version = "1.0.0" type config struct { port int env string db struct { dsn string } jwt struct { secret string } } type AppStatus struct { Status string `json:"status"` Environment string `json:"environment"` Version string `json:"version"` } //application struct: have all the information we need to share with our handler and other //components of our application type application struct { config config logger *log.Logger models models.Models } func main() { var cfg config flag.IntVar(&cfg.port, "port", 4000, "Server port to listen on") flag.StringVar(&cfg.env, "env", "development", "Application environment (development|production") flag.StringVar(&cfg.db.dsn, "dsn", "postgres://postgres:password@localhost/go-movies?sslmode=disable", "Postgres connection") flag.StringVar(&cfg.jwt.secret, "jwt-secret", "2dce505d96a53c5768052ee90f3df2055657518dad489160df9913f66042e160", "secret") // parse the flags flag.Parse() logger := log.New(os.Stdout, "", log.Ldate|log.Ltime) db, err := openDB(cfg) if err != nil { logger.Fatal(err) } app := &application{ config: cfg, logger: logger, models: models.NewModels(db), } defer db.Close() // accomplish basic web server running and serve some json to the browser srv := &http.Server{ Addr: fmt.Sprintf(":%d", cfg.port), Handler: app.routes(), ReadTimeout: 10 * time.Second, WriteTimeout: 30 * time.Second, IdleTimeout: time.Minute, } logger.Println("Starting server on port", cfg.port) err = srv.ListenAndServe() if err != nil { log.Println(err) } } func openDB(cfg config) (*sql.DB, error) { db, err := sql.Open("postgres", cfg.db.dsn) if err != nil { return nil, err } ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err = db.PingContext(ctx) if err != nil { return nil, err } return db, nil }
#!/bin/bash # Function to check if a directory exists function check_directory() { local expanded_path=$(eval echo $1) if [ -d "$expanded_path" ]; then return 0 # Directory exists else return 1 # Directory does not exist fi } _load_completion() { CONFIG_DIR="$HOME/.config/tmuxp" local cur_word COMPREPLY=() cur_word="${COMP_WORDS[COMP_CWORD]}" YAML_FILES=("$CONFIG_DIR"/*.yaml) # Filter YAML files based on the start_directory key VALID_YAML_FILES=() for yaml_file in "${YAML_FILES[@]}"; do start_directory=$(yq e '.start_directory' "$yaml_file" | awk 'NR==1') if [ -z "$start_directory" ] || check_directory "$start_directory"; then VALID_YAML_FILES+=("$yaml_file") fi done # Extract just the file names without the path or extension YAML_FILES_BASENAMES=() for file in "${VALID_YAML_FILES[@]}"; do file_basename=$(basename "$file" .yaml) YAML_FILES_BASENAMES+=("$file_basename") done # Generate autocomplete suggestions COMPREPLY=($(compgen -W "${YAML_FILES_BASENAMES[*]}" -- "$cur_word")) } complete -F _load_completion load function tm() { CONFIG_DIR="$HOME/.config/tmuxp" # Check if there are any arguments if [ "$#" -gt 0 ]; then # Execute tmux commands passed as arguments tmux "$@" else # Get a list of YAML files in the CONFIG_DIR YAML_FILES=("$CONFIG_DIR"/*.yaml) # Filter YAML files based on start_directory existence FILTERED_YAML=() for yaml_file in "${YAML_FILES[@]}"; do start_directory=$(yq e '.start_directory' "$yaml_file" | awk 'NR==1') if [ -z "$start_directory" ] || check_directory "$start_directory"; then FILTERED_YAML+=("$yaml_file") fi done # If there are valid YAML files, choose one using gum choose if [ ${#FILTERED_YAML[@]} -gt 0 ]; then SESSIONS="$(gum choose --header "Choose which sessions to load" --no-limit "${FILTERED_YAML[@]}")" eval "CONFIG_FILES=($SESSIONS)" for config_path in $CONFIG_FILES; do # Check if the tmuxp config file exists if [ -f "$config_path" ]; then # Load the tmuxp session using the config file tmuxp load -d "$config_path" fi done tmux attach -t Dotfiles else echo "No valid YAML files found in '$CONFIG_DIR' or start directories do not exist." fi fi } # To use this function, source this script from your shell or add it to your .bashrc or .zshrc file. # Then you can call it from the terminal by typing `tm` or `tm <tmux command>`.
import React from 'react'; import GlobalStyle from './globalStyles'; import Home from './pages/HomePage/Home'; import Services from './pages/Services/Services'; import Players from './pages/Players/Players'; import SignUp from './pages/SignUp/SignUp'; import Contact from './pages/Contact/Contact'; import Terms from './pages/Terms/Terms'; import Leagues from './pages/Leagues/Leagues'; import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'; import ScrollToTop from './components/ScrollToTop'; import { Navbar, Footer } from './components'; function App() { return ( <Router> <GlobalStyle /> <ScrollToTop /> <Navbar /> <Switch> <Route path='/' exact component={Home} /> <Route path='/services' component={Services} /> <Route path='/Contact' component={Contact} /> <Route path='/sign-up' component={SignUp} /> <Route path='/terms' component={Terms} /> <Route path='/leagues' component={Leagues} /> </Switch> <Footer /> </Router> ); } export default App;
package invest.megalo.adapter import android.content.Context import android.util.TypedValue import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import android.widget.Toast import androidx.core.content.ContextCompat import androidx.recyclerview.widget.RecyclerView import invest.megalo.R import invest.megalo.controller.activity.VerticalListActivity import invest.megalo.data.TitleSubtitleListData import java.text.DecimalFormat class TitleSubtitleListAdapter( private val context: Context, private val data: ArrayList<TitleSubtitleListData> ) : RecyclerView.Adapter<RecyclerView.ViewHolder>() { private var loadMoreView = 0 private var isLoadMoreViewAdded = false override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder { return if (viewType == loadMoreView) { LoadMoreViewHolder( LayoutInflater.from(context) .inflate(R.layout.content_title_subtitle_load_more, parent, false) ) } else { ViewHolder( LayoutInflater.from(context).inflate(R.layout.list_title_subtitle, parent, false) ) } } override fun onBindViewHolder(viewHolder: RecyclerView.ViewHolder, position: Int) { if (getItemViewType(position) == 1) { val holder = viewHolder as ViewHolder val dataItem = data[position] if (dataItem.titleResource != null) { holder.title.text = context.getString(dataItem.titleResource) } else if (dataItem.titleValue != null) { holder.title.text = dataItem.titleValue } else { holder.title.text = "" } holder.title.setTextColor(ContextCompat.getColor(context, R.color.black_white)) holder.title.setTextSize( TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(R.dimen.big_text) ) if (dataItem.subtitleResource != null) { holder.subtitle.text = context.getString(dataItem.subtitleResource) } else if (dataItem.subtitleValue != null) { holder.subtitle.text = dataItem.subtitleValue } else { holder.subtitle.text = "" } holder.subtitle.setTextColor( ContextCompat.getColor( context, R.color.darkGrey_lightGrey ) ) holder.subtitle.setTextSize( TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(R.dimen.normal_text) ) if (dataItem.endTextResource != null || dataItem.endTextValue != null) { holder.endText.visibility = View.VISIBLE holder.forward.visibility = View.GONE holder.notificationDot.visibility = View.GONE holder.endText.setTextSize( TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(R.dimen.normal_text) ) holder.endText.setTextColor( ContextCompat.getColor( context, R.color.darkGrey_lightGrey ) ) if (dataItem.endTextResource != null && dataItem.endTextValue != null) { if (context is VerticalListActivity && context.heading != R.string.notifications) { if (dataItem.endTextValue != "0") { holder.endText.setTextColor( ContextCompat.getColor( context, R.color.successGreen ) ) } else { holder.endText.setTextColor( ContextCompat.getColor( context, R.color.darkRed_lightRed ) ) } } if (context is VerticalListActivity && context.heading == R.string.total_referrals || context is VerticalListActivity && context.heading == R.string.total_completed || context is VerticalListActivity && context.heading == R.string.total_pending) { val df = DecimalFormat("#,##0.0#") df.minimumFractionDigits = 2 holder.endText.text = context.getString( dataItem.endTextResource, df.format(dataItem.endTextValue.toDouble()) ) } else { holder.endText.text = context.getString( dataItem.endTextResource, dataItem.endTextValue ) } } else if (dataItem.endTextResource != null) { holder.endText.text = context.getString(dataItem.endTextResource) } else { holder.endText.text = dataItem.endTextValue } } else if (dataItem.showArrowForwardIcon) { holder.endText.visibility = View.GONE holder.notificationDot.visibility = View.GONE holder.forward.visibility = View.VISIBLE holder.forward.contentDescription = context.getString(R.string.go_forward) holder.forward.setImageResource(R.drawable.arrow_forward) } else if (dataItem.showNotificationDot) { holder.endText.visibility = View.GONE holder.forward.visibility = View.GONE holder.notificationDot.visibility = View.VISIBLE holder.notificationDot.background = ContextCompat.getDrawable( context, R.drawable.notification_dot ) } } else { val holder = viewHolder as LoadMoreViewHolder holder.title.background = ContextCompat.getDrawable( context, R.drawable.dark_grey_light_grey_solid_curved_corners ) holder.title.setTextSize( TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(R.dimen.big_text) ) holder.subtitle.background = ContextCompat.getDrawable( context, R.drawable.dark_grey_light_grey_solid_curved_corners ) holder.subtitle.setTextSize( TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(R.dimen.normal_text) ) holder.endItem.background = ContextCompat.getDrawable( context, R.drawable.dark_grey_light_grey_solid_curved_corners ) holder.endItem.setTextSize( TypedValue.COMPLEX_UNIT_PX, context.resources.getDimension(R.dimen.normal_text) ) } } override fun getItemViewType(position: Int): Int { return if (position == data.size - 1 && isLoadMoreViewAdded) { loadMoreView } else { 1 } } override fun getItemCount(): Int { return data.size } fun addLoadMoreView() { data.add(TitleSubtitleListData(null, null, null, null, null, null, null)) isLoadMoreViewAdded = true notifyItemInserted(data.size - 1) if (context is VerticalListActivity) { Toast.makeText(context, "added", Toast.LENGTH_SHORT).show() context.fetchReferree( context.pageLimit, context.currentPage + 1 ) } } fun removeLoadMoreView() { if (context is VerticalListActivity) { val index = data.map { x -> x.id }.indexOf(null) if (index != -1) { data.removeAt(index) notifyItemRemoved(index) } Toast.makeText(context, index, Toast.LENGTH_SHORT).show() isLoadMoreViewAdded = false } } class LoadMoreViewHolder(v: View) : RecyclerView.ViewHolder(v) { val title: TextView = v.findViewById(R.id.title) val subtitle: TextView = v.findViewById(R.id.sub_title) val endItem: TextView = v.findViewById(R.id.end_item) } class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { val title: TextView = v.findViewById(R.id.title) val subtitle: TextView = v.findViewById(R.id.sub_title) val endText: TextView = v.findViewById(R.id.end_text) val forward: ImageView = v.findViewById(R.id.forward) val notificationDot: TextView = v.findViewById(R.id.notifications_dot) } }
import './App.css'; import dayjs from 'dayjs'; import { useState, useEffect } from 'react'; import { enUS } from "@mui/material/locale"; import { LocalizationProvider } from '@mui/x-date-pickers'; import { AdapterDayjs } from '@mui/x-date-pickers/AdapterDayjs'; import Container from "@mui/material/Container"; import Box from "@mui/material/Box"; import Typography from "@mui/material/Typography"; import Alarm from './Alarm'; function App() { const [alarm, setAlarm] = useState(dayjs('2022-04-17T15:30')); const [alarmSet, setAlarmSet] = useState(false); const [loading, setLoading] = useState(true); const [time, setTime] = useState(new Date()); async function getAPI(url) { const response = await fetch(url); let data = await response.json(); console.log(data); if (response) { setLoading(false); setAlarm(data.alarm); if (data.alarm !== "") { setAlarmSet(true); } else { setAlarmSet(false); } } } useEffect(() => { const interval = setInterval(() => { setTime(new Date()); getAPI("https://ps70-final.vercel.app/alarm"); }, 1000); return () => clearInterval(interval); }, []); function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; } function process(newValue) { setAlarmSet(true); setLoading(true); const jsonData = JSON.stringify({ alarm: newValue.format('h:mm A'), }); fetch('https://ps70-final.vercel.app/alarm', { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: jsonData }) .then(response => console.log(response)) } function cancel() { setAlarmSet(false); setAlarm(""); const jsonData = JSON.stringify({ alarm: "" }); fetch('https://ps70-final.vercel.app/alarm', { method: 'POST', mode: 'cors', headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, body: jsonData }) .then(response => console.log(response)) } return ( <div className="App"> <LocalizationProvider dateAdapter={AdapterDayjs} localeText={ { ...enUS, okButtonLabel: "Set Alarm", cancelButtonLabel: "Cancel", } }> <Container component="main" maxWidth="sm"> <Box sx={{ marginTop: 8, display: "flex", flexDirection: "column", alignItems: "center", }} > <h2>The Current Time Is:</h2> <Typography component="h1" variant="h1"> {time.toLocaleTimeString()} </Typography> <Alarm alarm={alarm} setAlarm={alarmSet} cancel={cancel} process={process} loading={loading}/> </Box> </Container> <div className="footer"> <h5>Created by Jackson Moody for PS70, May 2023</h5> </div> </LocalizationProvider> </div> ); } export default App;
using HospitalCrud.Model; namespace HospitalCrud.Repositories { /// <summary> /// Interface for a data repository containing patients /// </summary> public interface IPatientRepository : IRepository<Patient> { /// <summary> /// Retrieve a patient by their CPF number /// </summary> /// <param name="cpf">The CPF number to look for</param> /// <returns>The patient with the specified CPF, if found</returns> Task<Patient> GetPatientByCpf(string cpf); } }
var db = require('../config'); var bcrypt = require('bcrypt-nodejs'); var Promise = require('bluebird'); var mongoose = require('mongoose'); var userSchema = mongoose.Schema({ username: { type: String, index: {unique:true}}, password: String }); var User = mongoose.model('User', userSchema); userSchema.pre('save', function(next) { var cipher = Promise.promisify(bcrypt.hash); return cipher(this.password, null, null).bind(this) .then(function(hash) { this.password = hash; next(); }); }); User.prototype.comparePassword = function(attemptedPassword, callback) { bcrypt.compare(attemptedPassword, this.password, function(err, isMatch) { if(err){ callback(err); }else{ callback(null, isMatch); } }); }, // var User = db.Model.extend({ // tableName: 'users', // hasTimestamps: true, // initialize: function() { // this.on('creating', this.hashPassword); // }, // comparePassword: function(attemptedPassword, callback) { // bcrypt.compare(attemptedPassword, this.get('password'), function(err, isMatch) { // callback(isMatch); // }); // }, // hashPassword: function() { // var cipher = Promise.promisify(bcrypt.hash); // return cipher(this.get('password'), null, null).bind(this) // .then(function(hash) { // this.set('password', hash); // }); // } // }); module.exports = User;
/* * Copyright (c) 2023 Oracle and/or its affiliates. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v. 2.0, which is available at * http://www.eclipse.org/legal/epl-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception, which is available at * https://www.gnu.org/software/classpath/license.html. * * SPDX-License-Identifier: EPL-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 */ package org.glassfish.tyrus.core; import org.glassfish.tyrus.spi.CompletionHandler; import org.glassfish.tyrus.spi.Writer; import org.glassfish.tyrus.spi.WriterInfo; import org.junit.Assert; import org.junit.Test; import javax.websocket.CloseReason; import javax.websocket.DeploymentException; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.Session; import java.io.IOException; import java.io.UncheckedIOException; import java.net.SocketException; import java.nio.ByteBuffer; import java.util.Collections; import java.util.concurrent.CountDownLatch; public class ProtocolHandlerTest { public static class ProtocolHandlerOnCloseEndpoint extends Endpoint { CountDownLatch onCloseLatch = new CountDownLatch(1); public void onClose(Session session, CloseReason closeReason) { onCloseLatch.countDown(); } @Override public void onOpen(Session session, EndpointConfig config) { } } @Test public void testOnCloseIsCalledWhenCloseThrowsError() throws DeploymentException { ProtocolHandler handler = new ProtocolHandler(false, null); handler.setWriter(new Writer() { @Override public void write(ByteBuffer buffer, CompletionHandler<ByteBuffer> completionHandler) { throw new IllegalStateException("Not Expected"); } @Override public void write(ByteBuffer buffer, CompletionHandler<ByteBuffer> completionHandler, WriterInfo writerInfo) { if (writerInfo.getMessageType() == WriterInfo.MessageType.CLOSE) { throw new UncheckedIOException(new SocketException("Connection reset")); } } @Override public void close() throws IOException { } }); ProtocolHandlerOnCloseEndpoint endpoint = new ProtocolHandlerOnCloseEndpoint(); TyrusEndpointWrapper endpointWrapper = new TyrusEndpointWrapper( endpoint, null, ComponentProviderService.create(), null, "path", null, new TyrusEndpointWrapper.SessionListener() {}, null, null, null); TyrusWebSocket tyrusWebSocket = new TyrusWebSocket(handler, endpointWrapper); handler.setWebSocket(tyrusWebSocket); endpointWrapper.createSessionForRemoteEndpoint(tyrusWebSocket, null, Collections.emptyList(), new DebugContext()); handler.close(1000, "TEST"); Assert.assertEquals(0, endpoint.onCloseLatch.getCount()); } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <!-- RESPONSIVE --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- SEO --> <!-- KEYWORDS --> <meta name="keywords" content="Restaurante,comida,carta,reservas"> <!-- TITULO --> <title>Restaurante aSSao</title> <!-- Descripcion --> <meta name="description" content="Es un restaurante de comida variada de diferentes partes del mundo,reconocido mundialmente"> <!-- FIN SEO --> <!-- LETRA TITULO1 --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Zen+Kurenaido&display=swap" rel="stylesheet"> <!-- CSS LOCAL --> <link rel="stylesheet" href="CSS/style.css"> <!-- CSS BOOTSTRAP --> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> </head> <body> <!--HEADER--> <header> <nav> <ul class="menuFlex"> <li><a href="#inicio">Inicio</a></li> <li><a href="#nosotros">Nosotros</a></li> <li><a href="#carta">Carta</a></li> <li><a href="#reservas">Reservas</a></li> <li><a href="#formularioContacto">Contacto</a></li> </ul> </nav> </header> <main> <!-- SECCION NOSOTROS --> <section id="inicio"> <article class="flexInicio"> <div class="div1"> <h1 class="tituloYsub">aSSao</h1> <h2 class="tituloYsub subTitulo" >Restaurante</h2> </div> <div id="carouselExampleControls" class="carousel slide div2" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img style="border-radius: 40px;" src="IMAGENES/imagenParaCarrousel1.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img style="border-radius: 40px;" src="IMAGENES/imagenParaCarrousel4.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img style="border-radius: 40px;" src="IMAGENES/imagenParaCarrousel3.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img style="border-radius: 40px;" src="IMAGENES/imagenParaCarrousel4.jpg" class="d-block w-100"> </div> </div> </div> </article> </section> <!-- SECCION NOSOTROS --> <section id="nosotros"> <h2 class="tamanoLetraTitulos tituloNosotros" >Nosotros</h2> <article class="articuloNosotros "> <p class="letraGrande"> Somos un restaurante de comidas tipicas de todas las partes del mundo,esta iniciativa comienza cuando nuestros dos dueños,amantes de viajar,se les ocurrio esta gran idea de abrir este restaurante en la provincia de Tierra del Fuego en 1997.Nuestra propuesta es brindarle un lugar cálido para compartir y disfrutar en familia, con amigos o en reuniones de trabajo. Somos especialistas en pizzas, fabadas y paellas. Además de las mejores pastas, parrilla, postres y completa carta de vinos. "Lo que te contaron de nosotros es real: nuestros variados platos son todos para compartir"</p> </article> </section> <!-- SECCION CARTA --> <section id="carta"> <h2 class="tamanoLetraTitulos tituloCarta">Carta</h2> <!-- CARDS --> <article class="flexCards"> <div class="card" style="width: 25rem; padding: 5px; "> <img src="IMAGENES/imagenCard1.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h3 class="card-title">Carne asada</h3> <a href="Producto1.html" id="color" class="btn btn-outline-secondary">Reseña</a> </div> </div> <div class="card" style="width: 25rem; padding: 5px;"> <img src="IMAGENES/imagenCard2.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h3 class="card-title">Pizza</h3> <a href="Producto2.html" id="color" class="btn btn-outline-secondary">Reseña</a> </div> </div> <div class="card" style="width: 25rem; padding: 5px;"> <img src="IMAGENES/imagenCard3.png" id="color" class="card-img-top" alt="..."> <div class="card-body"> <h3 class="card-title">Fabada Asturiana</h3> <a href="Producto3.html" id="color" class="btn btn-outline-secondary">Reseña</a> </div> </div> <div class="card" style="width: 25rem; padding: 5px;"> <img src="IMAGENES/imagenCard4.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h3 class="card-title">Paella Valenciana</h3> <a href="Producto4.html" id="color" class="btn btn-outline-secondary">Reseña</a> </div> </div> <div class="card" style="width: 25rem; padding: 5px;"> <img src="IMAGENES/imagenCard5.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h3 class="card-title">Pulpo a la Gallega</h3> <a href="Producto5.html" id="color" class="btn btn-outline-secondary">Reseña</a> </div> </div> <div class="card" style="width: 25rem; padding: 5px;"> <img src="IMAGENES/imagenCard6.jpg" class="card-img-top" alt="..."> <div class="card-body"> <h3 class="card-title">Fideos con salsa</h3> <a href="Producto6.html" id="color" class="btn btn-outline-secondary">Reseña</a> </div> </div> </article> <!-- CARDS --> </section> <!-- SECCION RESERVAS --> <section id="reservas"> <h3 class="tamanoLetraTitulos tituloNosotros">Reservas</h3> <!-- FORMULARIO RESERVAS --> <article class="articForm"> <form class="row g-3"> <div class="col-md-9"> <label for="validationDefault01" class="form-label">Tu nombre y apellido</label> <input type="text" class="form-control" id="validationDefault01" required> </div> <div class="col-md-9"> <label for="validationDefault02" class="form-label">Cantidad de personas</label> <input type="number" class="form-control" id="validationDefault02" required> </div> <div class="col-md-9"> <label for="validationDefault01" class="form-label">Nombre de los acompañantes</label> <input type="text" class="form-control" id="validationDefault01" required> </div> <div class="col-md-9"> <label for="validationDefaultUsername" class="form-label">Tu correo electronico</label> <div class="input-group"> <span class="input-group-text" id="inputGroupPrepend2">@</span> <input type="text" class="form-control" id="validationDefaultUsername" aria-describedby="inputGroupPrepend2" required> </div> </div> <div class="col-md-9"> <label for="validationDefault01" class="form-label">Numero de telefono</label> <input type="text" class="form-control" id="validationDefault01" required> </div> <div class="col-12"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required> <label class="form-check-label" for="invalidCheck2"> Acepto terminos y condiciones </label> </div> </div> <div class="col-12"> <button id="color" class="btn btn-outline-secondary" type="submit">Enviar</button> </div> </form> </article> <!-- FIN FORMULARIO RESERVAS --> </section> <!-- SECCION CONTACTO --> <section id="formularioContacto"> <h2 class="tamanoLetraTitulos centrarTexto">Contacto</h2> <article class="articleFormularioContacto"> <form class="row g-3"> <div class="col-md-9"> <label for="validationDefault01" class="form-label">Nombre completo</label> <input type="text" class="form-control" id="validationDefault01" required> </div> <div class="col-md-9"> <label for="validationDefaultUsername" class="form-label">Correo electronico</label> <div class="input-group"> <span class="input-group-text" id="inputGroupPrepend2">@</span> <input type="text" class="form-control" id="validationDefaultUsername" aria-describedby="inputGroupPrepend2" required> </div> <div class="col-md-12"> <label for="validationDefault01" class="form-label">Numero de telefono</label> <input type="text" class="form-control" id="validationDefault01" required> </div> <div class="col-md-12"> <label for="validationDefault01" class="form-label">Cual es su problema?</label> <div class="input-group mb-3"> <select class="form-select" id="inputGroupSelect01"> <option selected>Eliga una opcion</option> <option value="1">Tuvo un problema para hacer una reserva</option> <option value="2">No pude contactarme por telefono</option> <option value="3">La pagina anda lenta</option> <option value="4">No se muestran correctamente los productos que muestran</option> </select> </div> </div> <div class="mb-3"> <label for="exampleFormControlTextarea1" class="form-label">Si su problema no se encuentra arriba,escribalo aqui</label> <textarea class="form-control" id="exampleFormControlTextarea1" rows="3"></textarea> </div> <div class="col-12"> <div class="form-check"> <input class="form-check-input" type="checkbox" value="" id="invalidCheck2" required> <label class="form-check-label" for="invalidCheck2"> Acepto terminos y condiciones </label> </div> </div> <div class="col-12"> <button id="color" class="btn btn-outline-secondary" type="submit">Enviar</button> </div> </form> </article> </section> <!-- FOOTER --> <footer> Resaturante aSSao &copy;</footer> </main> <!-- SCRIPT BOOTSTRAP --> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html>
import { ExtractJwt, Strategy } from 'passport-jwt'; import { PassportStrategy } from '@nestjs/passport'; import { Injectable } from '@nestjs/common'; import { jwtConstants } from '../jwt.constants'; import { AuthService } from '../service/auth.service'; // This code defines a JWT (JSON Web Token) strategy for authentication in a Nest.js application. //The JwtStrategy class extends the PassportStrategy class from the @nestjs/passport package //The JwtStrategy class uses the Strategy class from the passport-jwt package to define a JWT-based authentication strategy. The jwtFromRequest property is set to ExtractJwt.fromAuthHeaderAsBearerToken(), indicating that the JWT will be extracted from the Authorization header in the form of a bearer token. The ignoreExpiration property is set to false to ensure that expired tokens are not accepted. The secretOrKey property is set to the value of the secret property from the jwtConstants file, which is used to sign and verify JWTs. //The validate method is called by Passport when a user is trying to authenticate with a JWT. The method takes the JWT payload as an argument and returns an object containing the sub and email properties from the payload. In this example, the method logs the payload to the console, but in a real-world scenario, it might perform additional validation or retrieve additional data from a database. @Injectable() export class JwtStrategy extends PassportStrategy(Strategy) { constructor(private authService: AuthService) { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), ignoreExpiration: false, secretOrKey: jwtConstants.secret, }); } async isAdmin(email:string){ return this.authService.validateRole(email); } async validate(payload: any) { return payload; } }
import { Component, OnInit } from '@angular/core'; import { IHotel } from './models/hotel.model'; import { HotelsService } from './services/hotels.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'], }) export class AppComponent implements OnInit { title = 'test-task'; public hotels: IHotel[] = []; public activeHotelPosition!: { lat: number, lng: number }; public showModal = false; public hotelToBook!: IHotel; constructor( private hotelsService: HotelsService, ) {} ngOnInit(): void { this.getHotels(); } private getHotels() { this.hotelsService.getHotels().subscribe((hotels) => { this.hotels = hotels.map((hotel, index) => ({ ...hotel, id: index, active: false })); }); } public onMarkerClick(markerHotelData: IHotel): void { this.setHotelActive(markerHotelData); this.goToMarker(markerHotelData); } public setHotelActive(markerHotelData: IHotel): void { if (!markerHotelData) { return; } this.hotels = this.hotels.map((hotel) => hotel.id === markerHotelData.id ? { ...hotel, active: true } : { ...hotel, active: false }); this.activeHotelPosition = markerHotelData.position; } private goToMarker(markerHotelData: IHotel): void { const list = document.querySelector('.hotels-list'); const element = document.getElementById(`hotelCard-${markerHotelData.id}`); if (element && list) { list.scrollLeft = element.offsetLeft - 10; } } public onBookHotel(hotel: IHotel): void { this.openModal(); this.hotelToBook = hotel; } public openModal(): void { this.showModal = true; } public closeModal(): void { this.showModal = false; } }
// /**************************************************************************** // ** // ** Copyright (C) 2015-2022 M-Way Solutions GmbH // ** Contact: https://www.blureange.io/licensing // ** // ** This file is part of the Bluerange/FruityMesh implementation // ** // ** $BR_BEGIN_LICENSE:GPL-EXCEPT$ // ** Commercial License Usage // ** Licensees holding valid commercial Bluerange licenses may use this file in // ** accordance with the commercial license agreement provided with the // ** Software or, alternatively, in accordance with the terms contained in // ** a written agreement between them and M-Way Solutions GmbH. // ** For licensing terms and conditions see https://www.bluerange.io/terms-conditions. For further // ** information use the contact form at https://www.bluerange.io/contact. // ** // ** GNU General Public License Usage // ** Alternatively, this file may be used under the terms of the GNU // ** General Public License version 3 as published by the Free Software // ** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT // ** included in the packaging of this file. Please review the following // ** information to ensure the GNU General Public License requirements will // ** be met: https://www.gnu.org/licenses/gpl-3.0.html. // ** // ** $BR_END_LICENSE$ // ** // ****************************************************************************/ #pragma once #include <Module.h> //This should be set to the correct vendor and subId constexpr VendorModuleId {{upper module_name}}_ID = GET_VENDOR_MODULE_ID({{vendor_id}}, {{vendor_module_id}}); #if IS_ACTIVE({{upper module_name}}) /* * This is a template for a FruityMesh module. * A comment should be here to provide a least a short description of its purpose. */ constexpr u8 {{upper module_name}}_CONFIG_VERSION = 1; #pragma pack(push) #pragma pack(1) //Module configuration that is saved persistently (size must be multiple of 4) struct {{module_name}}Configuration : VendorModuleConfiguration { //Insert more persistent config values here u8 exampleValue; }; #pragma pack(pop) class {{module_name}} : public Module { public: enum {{module_name}}TriggerActionMessages { COMMAND_ONE_MESSAGE = 0, COMMAND_TWO_MESSAGE = 1, }; enum {{module_name}}ActionResponseMessages { COMMAND_ONE_MESSAGE_RESPONSE = 0, COMMAND_TWO_MESSAGE_RESPONSE = 1, }; //####### Module messages (these need to be packed) #pragma pack(push) #pragma pack(1) static constexpr int SIZEOF_{{upper module_name}}_COMMAND_ONE_MESSAGE = 1; typedef struct { //Insert values here u8 exampleValue; } {{module_name}}CommandOneMessage; STATIC_ASSERT_SIZE({{module_name}}CommandOneMessage, SIZEOF_{{upper module_name}}_COMMAND_ONE_MESSAGE); #pragma pack(pop) //####### Module messages end //Declare the configuration used for this module DECLARE_CONFIG_AND_PACKED_STRUCT({{module_name}}Configuration); {{module_name}}(); void ConfigurationLoadedHandler(u8* migratableConfig, u16 migratableConfigLength) override; void ResetToDefaultConfiguration() override; void TimerEventHandler(u16 passedTimeDs) override; void MeshMessageReceivedHandler(BaseConnection* connection, BaseConnectionSendData* sendData, ConnPacketHeader const * packetHeader) override; #ifdef TERMINAL_ENABLED TerminalCommandHandlerReturnType TerminalCommandHandler(const char* commandArgs[], u8 commandArgsSize) override; #endif CapabilityEntry GetCapability(u32 index, bool firstCall) override; }; #endif //IS_ACTIVE({{upper module_name}})
package mr import ( "fmt" "log" "sync" "time" ) func (t *task) ToReply(nReduce int, r *RequestTaskReply) { r.InputFiles = make([]string, len(t.inputFiles)) copy(r.InputFiles, t.inputFiles) r.TaskNum = t.tid.id r.NumReducers = nReduce r.Type = t.ttype r.WorkerId = t.assignedId r.ReduceTaskNum = t.tid.reducerId } /* func (t *taskmanager) checkComplete(workerId, taskId int) bool { // check the filesystem to see if worker has written the files for all reducers for i := 0; i < t.numReducers; i++ { if _, err := os.Stat(MapOutputFilename(workerId, taskId, i)); errors.Is(err, os.ErrNotExist) { return false } } return true } */ type taskId struct { id int reducerId int } type task struct { ttype TaskType tid taskId status TaskStatus inputFiles []string assignedId int } type taskmanager struct { l *sync.Mutex assignments map[int]int tasks []task totalCompleted int mapTasksCompleted int numMapTasks int numReducers int } func (t *taskmanager) manageTask(task task) { // start timer for i := 0; i < 10; i++ { time.Sleep(1 * time.Second) switch task.ttype { case Map: if CheckMapComplete(task.tid.id, t.numReducers) { err := t.completeTask(task.assignedId) if err != nil { log.Fatalf(err.Error()) } return } case Reduce: if CheckReduceComplete(task.tid.reducerId) { err := t.completeTask(task.assignedId) if err != nil { log.Fatalf(err.Error()) } return } } } time.Sleep(1 * time.Second) t.unassignTask(task.assignedId) } func (t *taskmanager) isDone() bool { t.l.Lock() defer t.l.Unlock() return t.totalCompleted >= len(t.tasks) } func (t *taskmanager) isMapPhase() bool { return t.mapTasksCompleted < t.numMapTasks } // these are non-thread safe helper functions func (t *taskmanager) findIdleMapTaskId() int { for i := 0; i < t.numMapTasks; i++ { if t.tasks[i].status == IDLE { return i } } return -1 } func (t *taskmanager) findIdleReduceTaskId() int { for i := t.numMapTasks; i < len(t.tasks); i++ { if t.tasks[i].status == IDLE { return i } } return -1 } func (t *taskmanager) assignTask(taskId, workerId int) task { t.tasks[taskId].status = INPROGRESS t.tasks[taskId].assignedId = workerId t.assignments[workerId] = taskId go t.manageTask(t.tasks[taskId]) return t.tasks[taskId] } // thread safe func (t *taskmanager) assignNextTask(workerId int) (task, bool) { t.l.Lock() defer t.l.Unlock() // If worker is already assigned a task then // don't assign a task _, ok := t.assignments[workerId] if ok { return task{}, false } var taskId int if t.isMapPhase() { taskId = t.findIdleMapTaskId() } else { taskId = t.findIdleReduceTaskId() } if taskId < 0 { return task{}, false } task := t.assignTask(taskId, workerId) return task, true } func (t *taskmanager) unassignTask(workerId int) error { t.l.Lock() defer t.l.Unlock() taskId, ok := t.assignments[workerId] if !ok { return fmt.Errorf("no assignment for worker %d found, unassignTask()", workerId) } t.tasks[taskId].status = IDLE delete(t.assignments, workerId) return nil } func (t *taskmanager) completeTask(workerId int) error { t.l.Lock() defer t.l.Unlock() taskId, ok := t.assignments[workerId] if !ok { return fmt.Errorf("no assignment for worker %d found, completeTask()", workerId) } t.tasks[taskId].status = COMPLETED task := t.tasks[taskId] if task.ttype == Map { t.mapTasksCompleted++ } t.totalCompleted++ delete(t.assignments, workerId) //fmt.Printf("completed task %d\n", task.tid.id) return nil } func NewTaskManager(input []string, numReducers int) *taskmanager { l := &sync.Mutex{} numMapTasks := len(input) numTasks := numMapTasks + numReducers tasks := make([]task, numTasks) assignments := map[int]int{} for i, fname := range input { tasks[i].inputFiles = append(tasks[i].inputFiles, fname) tasks[i].status = IDLE tasks[i].ttype = Map tasks[i].tid.id = i } reducerId := 0 // initialize the reduce tasks for i := numMapTasks; i < len(tasks); i++ { reduceInput := generateReduceInput(numMapTasks, reducerId) tasks[i].inputFiles = make([]string, len(reduceInput)) copy(tasks[i].inputFiles, reduceInput) tasks[i].status = IDLE tasks[i].ttype = Reduce tasks[i].tid.id = i tasks[i].tid.reducerId = reducerId reducerId++ //fmt.Printf("reduce input files are: %v", tasks[i].inputFiles) } return &taskmanager{ l, assignments, tasks, 0, 0, numMapTasks, numReducers, } }
<template> <div class="Feed"> <content-input class="Feed_editor Feed_item p-15 mb-20 br-s bg-bg-weak shadow-s" :placeholder="placeholder" :read="read" :constellation="constellation" :is-trigger="true" @focus="isEditorActive = true" v-if="!disableCreate" /> <client-only> <content-editor :is-active="isEditorActive" :placeholder="placeholder" :read="read" :constellation="constellation" :is-loading="isSubmitLoading" :errors="errors" :enable-tags="enableTags" :default-tags="tags" @submit="onSubmit" @open="isEditorActive = true" @close="isEditorActive = false" v-if="!disableCreate" ref="editor" /> </client-only> <transition-group name="fade"> <component :is="'content-' + status.type" v-for="status in displayedStatuses.filter(c => !isLoading)" class="Feed_item" v-bind="status" :active-gathering="gathering" :active-constellation="constellation" :disableCreate="disableInteract" :key="status._id" ref="posts" /> <placeholder class="Feed_item outflow@xs" v-for="i in 10" :ratio="$smallerThan('xs') ? 65 : 45" v-show="isLoading" :key="i" /> </transition-group> <div class="Feed_item color-ft-xweak ft-s mt-20 text-center" v-if="displayedStatuses.length <= 0 && !isLoading"> Aucun message sur ce fil. </div> <div class="Feed_loader mt-20" v-if="isLoading || isSubmitLoading"> <button-base :modifiers="['light']" > <fa icon="far fa-spinner-third" class="spin mr-5" /> Mise à jour du fil... </button-base> </div> <div class="text-center mt-20" v-if="checkingNext"> <button-base :modifiers="['light']" :loading="true">Chargement</button-base> </div> <div class="text-center color-ft-xweak mt-20" v-else-if="displayedStatuses.length > 0"> <p>Fin du fil.</p> </div> </div> </template> <script> export default { name: 'Feed', props: { read: { type: String, default: 'friends' }, max: { type: Number, default: 10 }, gathering: { type: String }, tag: { type: String }, constellation: { type: String }, author: { type: String }, enableTags: { type: Boolean, default: false }, placeholder: { type: String, default: 'Publier quelque chose...' }, disableInteract: { type: Boolean, default: false }, disableCreate: { type: Boolean, default: false }, autoStatuses: { type: Array, default: () => [] } }, data: () => ({ isEditorActive: false, statusesData: [], errors: [], tags: [], isSubmitLoading: false, isLoading: true, page: 0, checkedNext: false, checkingNext: false }), async fetch () { if (this.tag) this.tags = [ this.tag ] if (this.$store.getters['status/isFetched'](this.feedType)) { this.isLoading = false this.softRefresh() } else { this.isLoading = true await this.refresh() this.isLoading = false } }, computed: { statuses () { let statuses = [] let query = { ...this.query } delete query.$updateUser let userPosts = this.$store.getters['status/find']({ ...query }).map(s => ({ ...s, type: 'post' })) statuses = [ ...userPosts, ...this.autoStatuses ].filter(s => s.createdAt && this.$moment(s.createdAt).isBefore(this.$moment().add(30, 'seconds'))) return statuses.sort((a, b) => { return this.$moment(b.createdAt).valueOf() - this.$moment(a.createdAt).valueOf() }) }, displayedStatuses () { return this.statuses.slice(0, this.max * (this.page + 1)) }, feedType () { if (this.gathering) return 'gathering' if (this.constellation) return 'constellation' return 'feed' }, query () { let query = { parent: '$null', $updateUser: true } if (this.tag) query.tags = { $broad: this.tag } if (this.gathering) { query.gathering = this.gathering } else if (this.constellation) { query.constellation = this.constellation query.gathering = '$null' } return query } }, watch: { async ['$store.state.page.isEnd'] (v) { if (v && !this.checkingNext) { this.checkingNext = true await this.$store.dispatch('status/fetch', { type: this.feedType, query: this.query, softRefresh: true, options: { sort: { createdAt: 'desc' }, limit: this.max * (this.page + 2), skip: this.max * (this.page + 1) } }) this.page += 1 this.checkingNext = false } }, page (v) { this.checkedNext = false } }, methods: { openEditor (params = {}) { if (params.tags) this.tags = params.tags this.isEditorActive = true }, async softRefresh () { await this.$store.dispatch('status/fetch', { type: this.feedType, query: this.query, softRefresh: true, options: { sort: { createdAt: 'desc' }, limit: this.max * (this.page + 1), skip: this.max * this.page } }) }, async refresh () { return new Promise(async resolve => { try { await this.$store.dispatch('status/fetch', { type: this.feedType, query: this.query, options: { sort: { createdAt: 'desc' }, limit: this.max * (this.page + 1), skip: this.max * this.page } }) if (this.statuses) { await this.$store.dispatch('user/softFetch', this.statuses.reduce((all, s) => [ ...all, s.owner, ...(s.reactions ? s.reactions : []).map(r => r.owner), ...(s.children ? s.children : []).reduce((children, c) => [ ...children, c.owner, ...c.reactions.map(r => r.owner) ], []) ] , []) ) } } catch (e) { console.error(e) } resolve(true) }) }, async onSubmit (formData) { this.isSubmitLoading = true this.errors = [] try { let data = { ...formData, read: this.read } if (this.gathering) { data.gathering = this.gathering data.read = 'public' } if (this.constellation) { data.constellation = this.constellation } const response = await this.$store.dispatch('status/create', data) if (response.status == 0) { this.errors = [ response.error ] throw Error(response.error) } if (formData.tags && formData.tags.includes('présentations')) { this.$emit('introduced') } if (this.$refs.editor) this.$refs.editor.reset() this.isEditorActive = false if (response.data.parent) { // RESET COMMENT EDITOR let parent = this.$refs.posts.find(p => p._id == response.data.parent._id) if (parent) parent.reset() } } catch (e) { console.error(e) } this.isSubmitLoading = false } } } </script> <style lang="scss" scoped> .Feed_item { & + & { margin-top: 20px; } } .Feed_loader { position: sticky; z-index: 15; bottom: calc(var(--sticky-height) + 20px); text-align: center; } @include breakpoint-xs { .Feed_editor { margin: 0 -20px 10px; border-radius: 0; padding: 20px; background-color: var(--color-bg-weak); } .Feed_item { & + & { margin-top: 10px; } } } </style>
#ifndef AST_H #define AST_H #include "src/token.h" #include "llvm/ADT/APFloat.h" #include "llvm/ADT/STLExtras.h" #include "llvm/IR/BasicBlock.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DerivedTypes.h" #include "llvm/IR/Function.h" #include "llvm/IR/IRBuilder.h" #include "llvm/IR/Type.h" #include "llvm/IR/Verifier.h" namespace Kaleidoscope { class CodegenContext; class Parser; class Block; using namespace llvm; using llvm::Value; #define UPtr(name) std::unique_ptr<name> // AST Node types: // Expression, Variable, Number, BinaryOp, Call, Prototype, Function #define STATEMENT_NODE_LIST(V) \ V(EmptyStatement) \ V(IfStatement) \ V(ForLoopStatement) \ V(Block) \ V(ReturnStatement) \ V(ExpressionStatement) \ V(VariableDeclaration) \ V(FunctionDeclaration) #define EXPRESSION_NODE_LIST(V) \ V(Identifier) \ V(SmiLiteral) \ V(NumberLiteral) \ V(BinaryExpression) \ V(UnaryExpression) \ V(Assignment) \ V(CallExpression) \ V(Prototype) \ V(UnaryOperation) \ V(CountOperation) \ V(InitListExpr) #define AST_TYPE_LIST(V) \ STATEMENT_NODE_LIST(V) \ EXPRESSION_NODE_LIST(V) class AstNode { public: enum ASTType : uint8_t { #define DECLARE_AST_TYPES(type) k##type, AST_TYPE_LIST(DECLARE_AST_TYPES) #undef DECLARE_AST_TYPES }; AstNode(int pos, ASTType type) : pos_(pos), type_(type) {} virtual ~AstNode() = default; virtual Value* codegen(CodegenContext& ctx) = 0; ASTType getType() const { return type_; } #define CHECK_AST_TYPES(type) \ bool Is##type() const \ { return getType() == k##type; } AST_TYPE_LIST(CHECK_AST_TYPES) #undef CHECK_AST_TYPES int pos() const { return pos_; } private: int pos_; protected: ASTType type_; }; class Statement : public AstNode { public: Statement(int pos, ASTType type) : AstNode(pos, type) {} virtual ~Statement() = default; }; class Expression : public AstNode { public: Expression(int pos, ASTType type) : AstNode(pos, type) {} virtual ~Expression() = default; #define IS_SOME_EXPR_FUNC(type) \ bool Is##type() const { \ return type_ == k##type; \ } EXPRESSION_NODE_LIST(IS_SOME_EXPR_FUNC) #undef IS_SOME_EXPR_FUNC }; typedef std::vector<std::unique_ptr<Statement>> StmtsList; class ExpressionStatement : public Statement { std::unique_ptr<Expression> expr_; public: ExpressionStatement(std::unique_ptr<Expression> expr) : Statement(expr->pos(), kExpressionStatement), expr_(std::move(expr)) {} Value* codegen(CodegenContext& ctx) override; const Expression* expresssion() const { return expr_.get(); } }; class Identifier : public Expression { std::string name_; public: Identifier(int pos, std::string& name) : Expression(pos, kIdentifier), name_(name) {} Value* codegen(CodegenContext& ctx) override; const std::string& var_name() const { return name_; } }; class SmiLiteral : public Expression { public: SmiLiteral(int pos, uint32_t val) : Expression(pos, kSmiLiteral), val_(val) {} virtual ~SmiLiteral() = default; Value* codegen(CodegenContext& ctx) override; uint32_t value() const { return val_; } private: uint32_t val_; }; class NumberLiteral : public Expression { double val_; public: NumberLiteral(int pos, double val) : Expression(pos, kNumberLiteral), val_(val) {} Value* codegen(CodegenContext& ctx) override; double value() const { return val_; } }; class BinaryExpression : public Expression { Token::Value op_; std::unique_ptr<Expression> lhs_, rhs_; public: BinaryExpression(Token::Value op, std::unique_ptr<Expression> lhs, std::unique_ptr<Expression> rhs) : Expression(lhs->pos(), kBinaryExpression), op_(op), lhs_(std::move(lhs)), rhs_(std::move(rhs)) {} Value* codegen(CodegenContext& ctx) override; const Expression* left_expr() const { return lhs_.get(); } const Expression* right_expr() const { return rhs_.get(); } Token::Value operator_token() const { return op_; } }; class UnaryExpression : public Expression { Token::Value op_; std::unique_ptr<Expression> val_; public: UnaryExpression(Token::Value op, std::unique_ptr<Expression> val) : Expression(val->pos(), kUnaryExpression), op_(op), val_(std::move(val)) {} Value* codegen(CodegenContext& ctx) override; Token::Value operator_token() const { return op_; } const Expression* target_expr() const { return val_.get(); } }; class CallExpression : public Expression { std::string callee_; std::vector<std::unique_ptr<Expression> > args_; public: CallExpression(int pos, const std::string& callee, std::vector<std::unique_ptr<Expression>> args) : Expression(pos, kCallExpression), callee_(callee), args_(std::move(args)) {} Value* codegen(CodegenContext& ctx) override; const std::string& callee() const { return callee_; } const std::vector<std::unique_ptr<Expression> >* args() const { return &args_; } }; class CountOperation : public Expression { Token::Value tok_; bool is_postfix_; std::unique_ptr<Expression> expr_; public: CountOperation(int pos, Token::Value tok, bool is_postfix, std::unique_ptr<Expression> expr) : Expression(pos, kCountOperation), tok_(tok), is_postfix_(is_postfix), expr_(std::move(expr)) {} Value* codegen(CodegenContext& ctx) override; Token::Value get_operator() const { return tok_; } const Expression* target_expr() const { return expr_.get(); } }; class Prototype : public Expression { private: friend class FunctionDeclaration; std::string name_; std::vector<std::string> args_; std::vector<Token::Value> arg_types_; Token::Value ret_type_; // store operator info and precedence uint32_t flags = 0; static constexpr int kPrecedenceOffset = 8; static constexpr int kTokenValueOffset = 16; public: Prototype(int pos, const std::string& name, std::vector<std::string> args, std::vector<Token::Value> arg_types, Token::Value retTy = Token::VOID) : Expression(pos, kPrototype), name_(name), args_(std::move(args)), arg_types_(std::move(arg_types)), ret_type_(retTy) {} const std::string& getName() const { return name_; } Function* codegen(CodegenContext& ctx) override; bool isOperator() const { return flags & 0xFF; } // we only support one-char operator currently Token::Value getOperator() const { assert(isOperator()); return static_cast<Token::Value>((flags >> kTokenValueOffset) & 0xFF); } bool isBinaryOp() const { return isOperator() && args_.size() == 2; } bool isUnaryOp() const { return isOperator() && args_.size() == 1; } uint32_t getPrecedence() const { return (flags >> kPrecedenceOffset) & 0xFF; } const std::vector<std::string>& args() const { return args_; } }; class FunctionDeclaration : public Statement { std::unique_ptr<Prototype> proto_; std::unique_ptr<Block> body_; public: FunctionDeclaration (std::unique_ptr<Prototype> proto, std::unique_ptr<Block> body) : Statement(proto->pos(), kFunctionDeclaration), proto_(std::move(proto)), body_(std::move(body)) {} Function* codegen(CodegenContext& ctx) override; const Prototype* prototype() const { return proto_.get(); } const Block* body() const { return body_.get(); } }; class IfStatement : public Statement { std::unique_ptr<Expression> condition_; std::unique_ptr<Statement> thenB_; std::unique_ptr<Statement> elseB_; public: IfStatement(int pos, std::unique_ptr<Expression> condition, std::unique_ptr<Statement> thenB, std::unique_ptr<Statement> elseB) : Statement(pos, kIfStatement), condition_(std::move(condition)), thenB_(std::move(thenB)), elseB_(std::move(elseB)) {} Value* codegen(CodegenContext& ctx) override; const Expression* condition() const { return condition_.get(); } const Statement* then_stmt() const { return thenB_.get(); } const Statement* else_stmt() const { return elseB_.get(); } }; class ForLoopStatement : public Statement { std::unique_ptr<Expression> condition_; std::unique_ptr<Statement> init_, next_, body_; public: ForLoopStatement (int pos, std::unique_ptr<Statement> init, std::unique_ptr<Expression> condition, std::unique_ptr<Statement> next, std::unique_ptr<Statement> body) : Statement(pos, kForLoopStatement), init_(std::move(init)), condition_(std::move(condition)), next_(std::move(next)), body_(std::move(body)) {} Value* codegen(CodegenContext& ctx) override; const Expression* condition() const { return condition_.get(); } const Statement* init() const { return init_.get(); } const Statement* next() const { return next_.get(); } const Statement* body() const { return body_.get(); } }; // only handle intrinsic unary operator for now class UnaryOperation : public Expression { Token::Value op_; std::unique_ptr<Expression> operand_; public: UnaryOperation(int pos, Token::Value op, std::unique_ptr<Expression> operand) : Expression(pos, kUnaryOperation), op_(op), operand_(std::move(operand)) {} Value* codegen(CodegenContext& ctx) override; Token::Value operator_token() const { return op_; } const Expression* operand() const { return operand_.get(); } }; class Assignment : public Expression { Token::Value op_; std::unique_ptr<Expression> target_; std::unique_ptr<Expression> value_; public: Assignment(int pos, Token::Value op, std::unique_ptr<Expression> target, std::unique_ptr<Expression> value) : Expression(pos, kAssignment), op_(op), target_(std::move(target)), value_(std::move(value)) {} Value* codegen(CodegenContext& ctx) override; const Expression* target() const { return target_.get(); } const Expression* value() const { return value_.get(); } const Token::Value op_type() const { return op_; } ASTType valueType() const { return value_->getType();} }; // Initializer List Expression // Example: {1,2,3} // Only support array currently class InitListExpr : public Expression { typedef std::vector<std::unique_ptr<Expression>> ExprVec; Token::Value element_ty_; int desired_size_; ExprVec init_exprs_; public: InitListExpr(int pos, Token::Value element_ty, int desired_size, ExprVec init_exprs) : Expression(pos, kInitListExpr), element_ty_(element_ty), desired_size_(desired_size), init_exprs_(std::move(init_exprs)) {} size_t size() const { return desired_size_; } Value* codegen(CodegenContext& ctx) override; Expression* get_expr(size_t i) const { return init_exprs_[i].get(); } }; class VariableDeclaration : public Statement { std::string name_; Token::Value decl_type_; bool is_array_; int array_size_ = -1; std::unique_ptr<Expression> init_val_ = nullptr; std::unique_ptr<VariableDeclaration> next_ = nullptr; public: VariableDeclaration(int pos, std::string& var_name, Token::Value decl_type) : Statement(pos, kVariableDeclaration), name_(var_name), decl_type_(decl_type) {} Value* codegen(CodegenContext& ctx) override; void set_next(std::unique_ptr<VariableDeclaration> next) { next_ = std::move(next); } const VariableDeclaration* next() const { return next_.get(); } const std::string& var_name() const { return name_; } const Expression* init_val() const { return init_val_.get(); } const bool is_array() const { return is_array_; } void set_init_val(std::unique_ptr<Expression> init_val) { init_val_ = std::move(init_val); } void set_array_size(int size) { array_size_ = size; } int array_size() const { return array_size_; } void set_is_array() { is_array_ = true; } Token::Value declared_type() const { return decl_type_; } }; class Block : public Statement { StmtsList* statements_; public: Block(int pos, StmtsList* statements) : Statement(pos, kBlock), statements_(std::move(statements)) {} Value* codegen(CodegenContext& ctx) override; const StmtsList* statements() const { return statements_; } }; class EmptyStatement : public Statement { public: EmptyStatement(int pos) : Statement(pos, kEmptyStatement) {} Value* codegen(CodegenContext& ctx); }; class ReturnStatement : public Statement { std::unique_ptr<Expression> expression_; public: ReturnStatement(int pos, std::unique_ptr<Expression> expr) : Statement(pos, kReturnStatement), expression_(std::move(expr)) {} Value* codegen(CodegenContext& ctx) override; const Expression* expression() const { return expression_.get(); } }; template<typename SubClass> class AstVisitor { public: void Visit(AstNode* ast_node) { impl()->Visit(ast_node); } protected: SubClass* impl() { return static_cast<SubClass*>(this); } }; #define AST_VISIT_CASAES(NodeType) \ case AstNode::k##NodeType: \ this->impl()->Visit##NodeType( \ static_cast<const NodeType*>(node)); break; #define AST_VISITOR_BIG_SWITCH() \ switch(node->getType()) { \ AST_TYPE_LIST(AST_VISIT_CASAES) \ default: UNREACHABLE();} #define DECLARE_VISITOR_FUNC(AstNode) \ void Visit##AstNode(AstNode *node); #define DECLARE_VISITOR_FUNC_CONST(AstNode) \ void Visit##AstNode(const AstNode *node); // #define AST_VISITOR_MEMBERS_DECL(NodeType) } // Kaleidoscope #endif // AST_H
#pragma once #include "nn_layer.h" class LinearLayer : public NNLayer { private: const float weights_init_threshold = 0.01; Matrix W; Matrix b; Matrix Z; Matrix A; Matrix dA; void initializeBiasWithZeros(); void initializeWeightsRandomly(); void computeAndStoreBackpropError(Matrix& dZ); void computeAndStoreLayerOutput(Matrix& A); void updateWeights(Matrix& dZ, float learning_rate); void updateBias(Matrix& dZ, float learning_rate); public: LinearLayer(std::string name, Shape W_shape); ~LinearLayer(); /// <summary> /// Calculates z = W * A + b /// </summary> /// <param name="A">Input of the layer</param> /// <returns></returns> Matrix& forward(Matrix& A); /// <summary> /// Computes the errors and updates wieghts and bias. /// dA = W' * dZ /// dW = 1 / m * dZ * A' /// db = 1 / m * Sum(dZ[i]) /// </summary> /// <param name="dZ">Error from the previous layers</param> /// <param name="learningRate">The learning rate.</param> /// <returns>dA</returns> Matrix& backprop(Matrix& dZ, float learning_rate = 0.01); int getXDim() const; int getYDim() const; Matrix getWeightsMatrix() const; Matrix getBiasVector() const; };
// importar la función sum del archivo app.js const { sum } = require('./app.js'); // comienza tu primera prueba test('adds 14 + 9 to equal 23', () => { //dentro de la prueba llamamos a nuestra función sum con 2 números let total = sum(14, 9); // esperamos que la suma de esos 2 números sea 23 expect(total).toBe(23); }); test("One euro should be 1.206 dollars", function(){ // importo la funcion desde app.js const { fromEuroToDollar } = require('./app.js') // hago mi comparacion (la prueba) expect(fromEuroToDollar(3.5)).toBe(4.2); //1 euro son 1.2 dolares, entonces 3.5 euros deberian ser = (3.5 * 1.2) }) test("1.206 dollars should be 127.9 yens", function(){ // importo la funcion desde app.js const { fromDollarToYen } = require('./app.js') // hago mi comparacion (la prueba) expect(fromDollarToYen(1.2)).toBe(153.48); //1.206 dolares son 127.9 yenes, entonces 1.206 dolares deberian ser = (1.206 * 127.9) }) test("127.9 yens should be 0.8 pounds", function(){ // importo la funcion desde app.js const { fromYenToPound } = require('./app.js') // hago mi comparacion (la prueba) expect(fromYenToPound(127.9)).toBe(102.32000000000001); //127.9 yenes son 0.8 libras, entonces 127.9 libras deberian ser = (127.9 * 0.8) })
import React, { useState } from 'react'; import { useDispatch } from "react-redux"; import { Link, useNavigate } from 'react-router-dom'; import portalogo from "../../assets/image/learningportal.svg"; import { useRegisterMutation } from "../../features/auth/authApi"; export default function StudentRegistration() { const [register,{ data, isLoading, error: responseError }] = useRegisterMutation(); const dispatch = useDispatch(); const [name,setName] = useState(""); const [email,setEmail] = useState(""); const [password,setPassword] = useState(""); const [cpassword,setCpassword] = useState(""); const [role,setRole] = useState("student"); const navigate = useNavigate(); const handleSubmit = () => { if(cpassword===password){ register({name,email,password,role}); alert("Registered Successfully!!!"); navigate("/student/player"); } else{ alert("Password Dose not Match!!!"); } } return ( <section className="py-6 bg-primary h-screen grid place-items-center"> <div className="mx-auto max-w-md px-5 lg:px-0"> <div> <img className="h-12 mx-auto" src={portalogo} alt="portal logo"/> <h2 className="mt-6 text-center text-3xl font-extrabold text-slate-100"> Create Your New Account </h2> </div> <form className="mt-8 space-y-6" onSubmit={handleSubmit}> <input type="hidden" name="remember" value="true" /> <div className="rounded-md shadow-sm -space-y-px"> <div> <label for="name" className="sr-only">Name</label> <input id="name" name="name" type="name" autocomplete="name" required className="login-input rounded-t-md" placeholder="Student Name" value={name} onChange={(e)=>setName(e.target.value)}/> </div> <div> <label for="email-address" className="sr-only">Email address</label> <input id="email-address" name="email" type="email" autocomplete="email" required className="login-input " placeholder="Email address" value={email} onChange={(e)=>setEmail(e.target.value)} /> </div> <div> <label for="password" className="sr-only">Password</label> <input id="password" name="password" type="password" autocomplete="current-password" required className="login-input" placeholder="Password" value={password} onChange={(e)=>setPassword(e.target.value)} /> </div> <div> <label for="confirm-password" className="sr-only">Confirm Password</label> <input id="confirm-password" name="cpassword" type="password" autocomplete="confirm-password" required className="login-input rounded-b-md" placeholder="Confirm Password" value={cpassword} onChange={(e)=>setCpassword(e.target.value)} /> </div> </div> <div className="flex justify-between"> <Link to="/" className="font-medium text-violet-600 hover:text-violet-500"> Student Login </Link> <div className="text-sm"> <Link to="/admin/login" className="font-medium text-violet-600 hover:text-violet-500"> Admin Login </Link> </div> </div> <div> <button type="submit" className="group relative w-full flex justify-center py-2 px-4 border border-transparent text-sm font-medium rounded-md text-white bg-violet-600 hover:bg-violet-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-violet-500"> Create Account </button> </div> </form> </div> </section> ) }