text
stringlengths
27
775k
package com.gromyk.api.dtos.artist import com.google.gson.annotations.SerializedName data class Stats( @SerializedName("listeners") var listeners: String, @SerializedName("playcount") var playcount: String )
'use strict'; describe('Service: api', function () { // load the service's module beforeEach(module('clinikoApp')); // instantiate service var api; beforeEach(inject(function (_api_) { api = _api_; })); it('should work', function () { expect(!!api).toBe(true); }); it('should return configured headers', function () { expect(api.headers).toBeDefined(); }); it('should return a properly configured url', inject(function (settings) { var url = api.getUrl('/test/url/1'); expect(url).toBe(settings.clinikoApiBase + '/test/url/1'); })); });
import { AppComponent } from './../app.component'; import { AppModule } from './../app.module'; import { HttpModule } from '@angular/http'; import { servicioHttp } from './app.usuarios.servicio'; import { serviciovalidador } from './app.validador.servicio' import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { FormsModule, ReactiveFormsModule } from '@angular/forms'; import { ComponenteNuevo } from './app.usuarioN.componente'; import { ComponenteUsuarios } from './app.usuarios.componente'; import { Componentevalidador } from './app.validador.componente'; import { RouterModule } from '@angular/router'; import { CommonModule } from '@angular/common'; import { PipeNombres } from './usuarios.pipe'; @NgModule({ imports: [ BrowserModule, FormsModule, HttpModule, ReactiveFormsModule, RouterModule.forRoot([ { path: 'usuarios', component: ComponenteUsuarios }, { path: 'nuevo-usuario', component: ComponenteNuevo }, { path: 'inicio', component: AppComponent } ]) ], exports: [ ComponenteUsuarios ], declarations: [ ComponenteUsuarios, ComponenteNuevo, PipeNombres, Componentevalidador], bootstrap: [ ComponenteUsuarios ], providers: [ servicioHttp, serviciovalidador ] }) export class ModuloUsuarios { }
# Copyright (c) 2020-2021 CRS4 # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. from __future__ import annotations import abc import datetime import logging import uuid as _uuid from typing import List from authlib.integrations.sqla_oauth2 import OAuth2TokenMixin from flask_bcrypt import check_password_hash, generate_password_hash from flask_login import AnonymousUserMixin, UserMixin from lifemonitor import utils as lm_utils from lifemonitor.db import db from lifemonitor.models import UUID, ModelMixin from sqlalchemy.ext.hybrid import hybrid_property # Set the module level logger logger = logging.getLogger(__name__) class Anonymous(AnonymousUserMixin): def __init__(self): self.username = 'Guest' @property def id(self): return None def get_user_id(self): return None class User(db.Model, UserMixin): id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(256), unique=True, nullable=False) password_hash = db.Column(db.LargeBinary, nullable=True) picture = db.Column(db.String(), nullable=True) permissions = db.relationship("Permission", back_populates="user", cascade="all, delete-orphan") authorizations = db.relationship("ExternalServiceAccessAuthorization", cascade="all, delete-orphan") subscriptions = db.relationship("Subscription", cascade="all, delete-orphan") def __init__(self, username=None) -> None: super().__init__() self.username = username def get_user_id(self): return self.id def get_authorization(self, resource: Resource): auths = ExternalServiceAccessAuthorization.find_by_user_and_resource(self, resource) # check for sub-resource authorizations for subresource in ["api"]: if hasattr(resource, subresource): auths.extend(ExternalServiceAccessAuthorization .find_by_user_and_resource(self, getattr(resource, subresource))) return auths @property def current_identity(self): from .services import current_registry, current_user if not current_user.is_anonymous: return self.oauth_identity if current_registry: for p, i in self.oauth_identity.items(): if i.provider == current_registry.server_credentials: return {p: i} return None @property def password(self): raise AttributeError("password is not a readable attribute") @password.setter def password(self, password): self.password_hash = generate_password_hash(password) @password.deleter def password(self): self.password_hash = None @property def has_password(self): return bool(self.password_hash) def has_permission(self, resource: Resource) -> bool: return self.get_permission(resource) is not None def get_permission(self, resource: Resource) -> Permission: return next((p for p in self.permissions if p.resource == resource), None) def verify_password(self, password): return check_password_hash(self.password_hash, password) def get_subscription(self, resource: Resource) -> Subscription: return next((s for s in self.subscriptions if s.resource == resource), None) def subscribe(self, resource: Resource) -> Subscription: s = self.get_subscription(resource) if not s: s = Subscription(resource, self) return s def unsubscribe(self, resource: Resource): s = self.get_subscription(resource) if s: self.subscriptions.remove(s) return s def save(self): db.session.add(self) db.session.commit() def to_dict(self): return { "id": self.id, "username": self.username, "identities": { n: i.user_info for n, i in self.oauth_identity.items() } } @classmethod def find_by_username(cls, username): return cls.query.filter(cls.username == username).first() @classmethod def all(cls): return cls.query.all() class ApiKey(db.Model, ModelMixin): SCOPES = ["read", "write"] key = db.Column(db.String, primary_key=True) user_id = db.Column( db.Integer, db.ForeignKey('user.id', ondelete='CASCADE') ) user = db.relationship( 'User', backref=db.backref("api_keys", cascade="all, delete-orphan"), ) scope = db.Column(db.String, nullable=False) def __init__(self, key=None, user=None, scope=None) -> None: super().__init__() self.key = key self.user = user self.scope = scope or "" def __repr__(self) -> str: return "ApiKey {} (scope: {})".format(self.key, self.scope) def set_scope(self, scope): if scope: for s in scope.split(" "): if s not in self.SCOPES: raise ValueError("Scope '{}' not valid".format(s)) self.scope = "{} {}".format(self.scope, s) def check_scopes(self, scopes: list or str): if isinstance(scopes, str): scopes = scopes.split(" ") supported_scopes = self.scope.split(" ") for scope in scopes: if scope not in supported_scopes: return False return True @classmethod def find(cls, api_key) -> ApiKey: return cls.query.filter(ApiKey.key == api_key).first() @classmethod def all(cls) -> List[ApiKey]: return cls.query.all() class Resource(db.Model, ModelMixin): id = db.Column('id', db.Integer, primary_key=True) uuid = db.Column(UUID, default=_uuid.uuid4) type = db.Column(db.String, nullable=False) name = db.Column(db.String, nullable=True) uri = db.Column(db.String, nullable=False) version = db.Column(db.String, nullable=True) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) modified = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow) permissions = db.relationship("Permission", back_populates="resource", cascade="all, delete-orphan") __mapper_args__ = { 'polymorphic_identity': 'resource', 'polymorphic_on': type, } def __init__(self, uri, uuid=None, name=None, version=None) -> None: assert uri, "URI cannot be empty" self.uri = uri.strip('/') self.name = name self.version = version self.uuid = uuid def __repr__(self): return '<Resource {}: {} -> {} (type={}))>'.format( self.id, self.uuid, self.uri, self.type) @hybrid_property def authorizations(self): return self._authorizations def get_authorization(self, user: User): auths = ExternalServiceAccessAuthorization.find_by_user_and_resource(user, self) # check for sub-resource authorizations for subresource in ["api"]: if hasattr(self, subresource): auths.extend(ExternalServiceAccessAuthorization .find_by_user_and_resource(self, getattr(self, subresource))) return auths @classmethod def find_by_uuid(cls, uuid): return cls.query.filter(cls.uuid == lm_utils.uuid_param(uuid)).first() resource_authorization_table = db.Table( 'resource_authorization', db.Model.metadata, db.Column('resource_id', db.Integer, db.ForeignKey("resource.id", ondelete="CASCADE")), db.Column('authorization_id', db.Integer, db.ForeignKey("external_service_access_authorization.id", ondelete="CASCADE")) ) class Subscription(db.Model, ModelMixin): id = db.Column(db.Integer, primary_key=True) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) modified = db.Column(db.DateTime, default=datetime.datetime.utcnow, onupdate=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey("user.id"), nullable=False) user: User = db.relationship("User", uselist=False, back_populates="subscriptions", foreign_keys=[user_id]) resource_id = db.Column(db.Integer, db.ForeignKey("resource.id"), nullable=False) resource: Resource = db.relationship("Resource", uselist=False, backref=db.backref("subscriptions", cascade="all, delete-orphan"), foreign_keys=[resource_id]) def __init__(self, resource: Resource, user: User) -> None: self.resource = resource self.user = user class HostingService(Resource): id = db.Column(db.Integer, db.ForeignKey(Resource.id), primary_key=True) __mapper_args__ = { 'polymorphic_identity': 'hosting_service' } @abc.abstractmethod def get_external_id(self, uuid: str, version: str, user: User) -> str: pass @abc.abstractmethod def get_external_link(self, external_id: str, version: str) -> str: pass @abc.abstractmethod def get_rocrate_external_link(self, external_id: str, version: str) -> str: pass class RoleType: owner = "owner" viewer = "viewer" class Permission(db.Model): user_id = db.Column(db.Integer, db.ForeignKey('user.id', ondelete='CASCADE'), primary_key=True) resource_id = db.Column(db.Integer, db.ForeignKey('resource.id', ondelete='CASCADE'), primary_key=True) roles = db.Column(db.ARRAY(db.String), nullable=True) user = db.relationship("User", back_populates="permissions") resource = db.relationship("Resource", back_populates="permissions") def __repr__(self): return '<Permission of user {} for resource {}: {}>'.format( self.user, self.resource, self.roles) def __init__(self, user: User = None, resource: Resource = None, roles=None) -> None: self.user = user self.resource = resource self.roles = [] if roles: for r in roles: self.roles.append(r) class ExternalServiceAccessAuthorization(db.Model): id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String, nullable=False) user_id = db.Column(db.Integer, db.ForeignKey(User.id, ondelete='CASCADE'), nullable=True) resources = db.relationship("Resource", secondary=resource_authorization_table, backref="_authorizations", passive_deletes=True) user = db.relationship("User", back_populates="authorizations", cascade="all, delete") __mapper_args__ = { 'polymorphic_identity': 'authorization', 'polymorphic_on': type, } def __init__(self, user) -> None: super().__init__() self.user = user def as_http_header(self): return "" @staticmethod def find_by_user_and_resource(user: User, resource: Resource): return [a for a in user.authorizations if resource in a.resources] class ExternalServiceAuthorizationHeader(ExternalServiceAccessAuthorization): id = db.Column(db.Integer, db.ForeignKey('external_service_access_authorization.id'), primary_key=True) __mapper_args__ = { 'polymorphic_identity': 'authorization_header' } header = db.Column(db.String, nullable=False) def __init__(self, user, header) -> None: super().__init__(user) self.header = header def as_http_header(self): return self.header class ExternalServiceAccessToken(ExternalServiceAccessAuthorization, OAuth2TokenMixin): id = db.Column(db.Integer, db.ForeignKey('external_service_access_authorization.id'), primary_key=True) __mapper_args__ = { 'polymorphic_identity': 'access_token' } def is_expired(self) -> bool: return self.check_token_expiration(self.expires_at) def is_refresh_token_valid(self) -> bool: return self if not self.revoked else None def save(self): db.session.add(self) db.session.commit() def delete(self): db.session.delete(self) db.session.commit() def as_http_header(self): return f"{self.token_type} {self.access_token}" @classmethod def find(cls, access_token): return cls.query.filter(cls.access_token == access_token).first() @classmethod def find_by_user(cls, user: User) -> List[ExternalServiceAccessToken]: return cls.query.filter(cls.user == user).all() @classmethod def all(cls): return cls.query.all() @staticmethod def check_token_expiration(expires_at) -> bool: return datetime.utcnow().timestamp() - expires_at > 0
var _verification_helpers_8hpp = [ [ "CHECK_VALID_SIZE", "_verification_helpers_8hpp.xhtml#a479b2821a7a2cbb8fa8eb7f60a47065d", null ], [ "CHECKED_INT32", "_verification_helpers_8hpp.xhtml#aa693ef8620e450b6362938828002f2a6", null ], [ "CHECKED_NON_NEGATIVE", "_verification_helpers_8hpp.xhtml#aaef93dc9a69f51b59f3cdd0ff0165927", null ], [ "CheckValidSize", "_verification_helpers_8hpp.xhtml#a97dc68ae76f04b81c833184724836c9a", null ], [ "NonNegative", "_verification_helpers_8hpp.xhtml#ab075020544612cd151ebdd08db537396", null ], [ "VerifyInt32", "_verification_helpers_8hpp.xhtml#a2e0aa273755368a1bf5fc65102df4a92", null ] ];
import { Box, Center, GridItem, Heading, SimpleGrid, Tab, TabList, TabPanel, TabPanels, Tabs, Text, } from "@chakra-ui/react"; import React from "react"; import { useAuthState } from "react-firebase-hooks/auth"; import { auth, db } from "../../firebase.config"; import { useCollectionData } from "react-firebase-hooks/firestore"; import { CreateSession } from "./CreateSession"; import { collection, orderBy, query } from "firebase/firestore"; import { Session } from "../../types"; import { SessionRenderer } from "./SessionRenderer"; import { PersonalStats } from "./PersonalStats"; interface SessionsProps {} export const Sessions: React.FC<SessionsProps> = ({}) => { // eslint-disable-next-line @typescript-eslint/no-unused-vars const [user, loading, error] = useAuthState(auth); // eslint-disable-next-line @typescript-eslint/no-unused-vars const [sessions, loadingSessions, errorSessions] = useCollectionData( query(collection(db, user.uid), orderBy("createdAt", "desc")) ); if (loadingSessions) { return <Text>Loading sessions data...</Text>; } if (error) { return ( <Text> There was an error fetching your sessions! Please reload the page. </Text> ); } return ( <Box> <Tabs variant="solid-rounded" colorScheme="yellow" pt="5"> <Center> <TabList border="1px" borderRadius="xl" p="4" borderColor="yellow.500" > <Tab>Sessions</Tab> <Tab>Stats</Tab> </TabList> </Center> <TabPanels pt="5"> <TabPanel> <Heading fontSize="4xl" fontWeight="bold" textAlign="center"> My Practice Sessions </Heading>{" "} <Center> <CreateSession /> </Center> <SimpleGrid columns={[1, 1, 1, 2, 3]} spacingY={6} // spacingX={} pt="10" pl="5" pr="5" > {sessions.map((session: Session) => ( <GridItem key={session.uuid}> <Center> <SessionRenderer session={session} /> </Center> </GridItem> ))} </SimpleGrid> {sessions.length === 0 && ( <> <Center> <Text pt="10"> Nothing here yet! Create a session, time yourself and add your solve times to get started! </Text> </Center> </> )} </TabPanel> <TabPanel> <Center> <PersonalStats user={user} /> </Center> </TabPanel> </TabPanels> </Tabs> </Box> ); };
// DUPLICATED FROM types.ts export interface DatastoreRecord { createdAt: number; modifiedAt: number; } // END DUPLICATES export interface ErrorResponse { message?: string; } export interface EmptyResponse {} export interface PostUserResponse { accessToken: string; refreshToken: string; user: { email: string; name: string; userId: string; }; } export interface PostTeamResponse extends DatastoreRecord { teamId: string; userId: string; name: string; } export interface PostMealResponse extends DatastoreRecord { mealId: string; userId: string; name: string; unsplashImageData?: { thumbUrl: string; imageUrl: string; author: string; authorUrl: string; }; } export interface GetMealsResponse { meals: PostMealResponse[]; } export interface PostRestaurantResponse extends DatastoreRecord { restaurantId: string; userId: string; name: string; } export interface GetRestaurantsResponse { restaurants: PostRestaurantResponse[]; } export interface PostPollResponse extends DatastoreRecord { pollId: string; teamId: string; userId: string; name: string; } export interface GetPollResponse extends DatastoreRecord { pollId: string; teamId: string; userId: string; name: string; mealOptions: PostMealResponse[]; restaurantOptions: PostRestaurantResponse[]; } export interface GetPollsResponse { polls: PostPollResponse[]; } export interface GetTeamsResponse { ownedTeams: PostTeamResponse[]; joinedTeams: PostTeamResponse[]; } export interface PostTeammateResponse extends DatastoreRecord { userId: string; name: string; email: string; accepted: boolean; } export interface GetImageResponse { presignedUrl: string; } export interface GetSubscriptionResponse { userId: string; subscriptionId: string; subscriptionType: string; subscriptionTier: string; subscriptionVersion: string; marketplace: string; productId: string; createdAt: number; modifiedAt: number; } export interface GetSubscriptionsResponse { subscriptions: GetSubscriptionResponse[]; } export interface PresignedPostResponse { url: string; fields: { Policy: string; "X-Amz-Algorithm": string; "X-Amz-Credential": string; "X-Amz-Date": string; "X-Amz-Signature": string; bucket: string; key: string; }; } export interface ImageSearchResponse { searchResults: { id: string; created_at: string; width: number; height: number; color: string; blur_hash: string; likes: number; liked_by_user: boolean; description: string; user: { id: string; username: string; name: string; first_name: string; last_name: string; instagram_username: string; twitter_username: string; portfolio_url: string; profile_image: { small: string; medium: string; large: string; }; links: { self: string; html: string; photos: string; likes: string; }; }; urls: { raw: string; full: string; regular: string; small: string; thumb: string; }; links: { self: string; html: string; download: string; }; }[]; } export interface GetPollVotesResponse {} export interface RestaurantSearchItem { rating: number; price: string; phone: string; id: string; alias: string; is_closed: boolean; categories?: | { alias: string; title: string; }[] | null; review_count: number; name: string; url: string; coordinates: { latitude: number; longitude: number; }; image_url: string; location: { city: string; country: string; address2: string; address3: string; state: string; address1: string; zip_code: string; }; distance: number; transactions?: string[] | null; } export interface RestaurantSearchResponse { searchResults: RestaurantSearchItem[]; } export interface GeolocationIpLookupResponse { ip: string; version: string; city: string; region: string; region_code: string; country_code: string; country_code_iso3: string; country_name: string; country_capital: string; country_tld: string; continent_code: string; in_eu: boolean; postal: string; latitude: number; longitude: number; timezone: string; utc_offset: string; country_calling_code: string; currency: string; currency_name: string; languages: string; country_area: number; country_population: number; asn: string; org: string; hostname: string; } export interface RestaurantDetailsResponse { id: string; alias: string; name: string; image_url: string; is_claimed: boolean; is_closed: boolean; url: string; phone: string; display_phone: string; review_count: number; categories?: | { alias: string; title: string; }[] | null; rating: number; location: { address1: string; address2: string; address3: string; city: string; zip_code: string; country: string; state: string; display_address?: string[] | null; cross_streets: string; }; coordinates: { latitude: number; longitude: number; }; photos?: string[] | null; price: string; hours?: | { open?: | { is_overnight: boolean; start: string; end: string; day: number; }[] | null; hours_type: string; is_open_now: boolean; }[] | null; transactions?: null[] | null; special_hours?: | { date: string; is_closed?: null; start: string; end: string; is_overnight: boolean; }[] | null; }
package com.jscisco.lom.dungeon import com.jscisco.lom.builders.EntityFactory import com.jscisco.lom.data.TestData import com.jscisco.lom.extensions.position import org.assertj.core.api.Assertions import org.hexworks.cobalt.logging.api.Logger import org.hexworks.cobalt.logging.api.LoggerFactory import org.hexworks.zircon.api.data.impl.Position3D import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Nested import org.junit.jupiter.api.Test class TestDungeon { private val logger: Logger = LoggerFactory.getLogger(javaClass) val dungeon: Dungeon = TestData.newTestDungeon() val player = dungeon.player @Nested inner class DungeonMovement { private val initialPosition = Position3D.create(5, 5, 0) @BeforeEach fun init() { dungeon.moveEntity(player, initialPosition) } @Test fun `move an entity to an unoccupied position should succeed`() { val newPosition = Position3D.create(20, 20, 0) val previousGameBlock = dungeon.fetchBlockAt(player.position).get() val entityMoved = dungeon.moveEntity(player, newPosition) Assertions.assertThat(entityMoved).isTrue() // The game block that held the player should no longer Assertions.assertThat(previousGameBlock.entities.toList().contains(player)).isFalse() Assertions.assertThat(player.position).isEqualTo(newPosition) // The new game block should have the entity Assertions.assertThat(dungeon.fetchBlockAt(newPosition).get().entities.toList().contains(player)).isTrue() } @Test fun `moving an entity to an unoccupied position should fail`() { val currentPosition = dungeon.player.position val newPosition = Position3D.create(-1, -1, 0) val entityMoved = dungeon.moveEntity(player, newPosition) Assertions.assertThat(entityMoved).isFalse() Assertions.assertThat(dungeon.player.position).isEqualTo(currentPosition) } } @Test fun `Entities added at a particular location should be there`() { val goblin = EntityFactory.newMonster() val position = Position3D.create(15, 15, 0) dungeon.addEntity(goblin, position) Assertions.assertThat(dungeon.fetchBlockAt(position).get().entities.contains(goblin)).isTrue() Assertions.assertThat(goblin.position).isEqualTo(position) } // @Nested // inner class FOVTests { // @Test // fun `The resistance map should be calculate as expected`() { // val wallPosition = Position3D.create(10, 10, 0) // dungeon.fetchBlockAt(wallPosition).ifPresent { // it.addEntity(EntityFactory.newWall()) // } // // dungeon.calculateResistanceMap(dungeon.player) // // val firstFloorResistanceMap = dungeon.calculateResistanceMap(dungeon.player) // // Assertions.assertThat(firstFloorResistanceMap).isNotNull // if (firstFloorResistanceMap != null) { // Assertions.assertThat(firstFloorResistanceMap[10][10]).isEqualTo(1.0) // Assertions.assertThat(firstFloorResistanceMap[0][0]).isEqualTo(0.0) // } // } // @Test // fun `Game block in FOV should have in_fov toggled & seen`() { // dungeon.player.fieldOfView.fov[0][0] = 1.0 // dungeon.updateGameBlocks(dungeon.player) // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().inFov).isTrue() // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().seen).isTrue() // } // // @Test // fun `Game block not in FOV should not be inFov`() { // dungeon.player.fieldOfView.fov[0][0] = 0.0 // dungeon.updateGameBlocks(dungeon.player) // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().inFov).isFalse() // } // // @Test // fun `Game block that was in FOV but is no longer should be seen`() { // dungeon.player.fieldOfView.fov[0][0] = 1.0 // dungeon.updateGameBlocks(dungeon.player) // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().inFov).isTrue() // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().seen).isTrue() // dungeon.player.fieldOfView.fov[0][0] = 0.0 // dungeon.updateGameBlocks(dungeon.player) // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().inFov).isFalse() // Assertions.assertThat(dungeon.fetchBlockAt(Position3D.create(0, 0, 0)).get().seen).isTrue() // } // } }
## Android 平台手动集成 ### 拷贝文件 从插件安装包中的 `plugin/android/libs` 目录拷贝下列 __jar__ 文件到您的工程的 __proj.android/libs__ 目录。 > vungle-publisher-adaptive-id-3.3.0..jar > PluginVungle.jar > sdkbox.jar > android-support-v4.jar > nineoldandroids-2.4.0.jar > javax.inject-1.jar > dagger-1.2.2.jar 从 `plugin/android/jni` 目录拷贝 `pluginvungle` 以及 `sdkbox` 目录到您的工程的 `proj.android/jni` 目录。如果 `sdkbox` 目录在工程中已经存在,请覆盖它。 ### 编辑 `AndroidManifest.xml` 在标签 __application tag__ 上添加下列权限: ```xml <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> ``` 在接近文件底部的位置,拷贝并且粘贴下列 activity 定义到 __application tags__ 标签结尾处。 ```xml <activity android:name="com.vungle.publisher.FullScreenAdActivity" android:configChanges="keyboardHidden|orientation" android:theme="@android:style/Theme.NoTitleBar.Fullscreen"/> ``` __Note:__ 如果您的 app targets 版本低于 __API 13__,您可能需要从上面的 __activity tags__ 的 __configChanges__ 属性里删除 `screenSize` 。 ### 编辑 `Android.mk` 编辑 `proj.android/jni/Android.mk`: 为 __LOCAL_STATIC_LIBRARIES__ 添加额外的库: ``` LOCAL_STATIC_LIBRARIES += android_native_app_glue LOCAL_LDLIBS += -landroid LOCAL_LDLIBS += -llog LOCAL_STATIC_LIBRARIES += PluginVungle LOCAL_STATIC_LIBRARIES += sdkbox ``` 在所有 __import-module__ 语句之前添加一条 call 语句: ``` $(call import-add-path,$(LOCAL_PATH)) ``` 在最后添加额外的 __import-module__ 语句: ``` $(call import-module, ./sdkbox) $(call import-module, ./pluginvungle) ``` 这意味着您的语句顺序看起来像是这样: ``` $(call import-add-path,$(LOCAL_PATH)) $(call import-module, ./sdkbox) $(call import-module, ./pluginvungle) ``` ### 编辑 `Application.mk` 编辑 `proj.android/jni/Application.mk`: 为 __APP_PATFORM__ 添加版本: ``` APP_PLATFORM := android-9 ```
package com.compomics.util.experiment.io.mass_spectrometry.cms; /** * Placeholder for the temp folder to use for cms files. * * @author Marc Vaudel */ public class CmsFolder { /** * The folder to use when creating cms files. */ private static String parentFolder = null; /** * The sub folder where the cms files should be stored. */ private static final String SUB_FOLDER = ".cms_temp"; /** * Returns the parent folder where to write cms files. Null if not set. * * @return The parent folder where to write cms files. */ public static String getParentFolder() { return parentFolder; } /** * Returns the sub-folder where to write cms files. Null if not set. * * @return the sub-folder where to write cms files */ public static String getSubFolder() { return SUB_FOLDER; } /** * Sets the parent folder where to write cms files to. * * @param newParentFolder The parent folder where to write cms files to. */ public static void setParentFolder( String newParentFolder ) { parentFolder = newParentFolder; } }
package io.cucumber.core.resource; import io.cucumber.core.logging.LogRecordListener; import io.cucumber.core.logging.LoggerFactory; import io.cucumber.core.resource.test.ExampleClass; import io.cucumber.core.resource.test.ExampleInterface; import io.cucumber.core.resource.test.OtherClass; import org.hamcrest.CoreMatchers; import org.hamcrest.Matchers; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; import java.net.URI; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; import java.util.Arrays; import java.util.Collections; import java.util.Enumeration; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.LogRecord; import static java.util.Arrays.asList; import static java.util.Collections.enumeration; import static java.util.Collections.singletonList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.collection.IsEmptyCollection.empty; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.hamcrest.collection.IsIterableContainingInOrder.contains; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class ClasspathScannerTest { private final ClasspathScanner scanner = new ClasspathScanner( ClasspathScannerTest.class::getClassLoader); private LogRecordListener logRecordListener; @BeforeEach void setup() { logRecordListener = new LogRecordListener(); LoggerFactory.addListener(logRecordListener); } @AfterEach void tearDown() { LoggerFactory.removeListener(logRecordListener); } @Test void scanForSubClassesInPackage() { List<Class<? extends ExampleInterface>> classes = scanner.scanForSubClassesInPackage("io.cucumber", ExampleInterface.class); assertThat(classes, contains(ExampleClass.class)); } @Test void scanForSubClassesInNonExistingPackage() { List<Class<? extends ExampleInterface>> classes = scanner .scanForSubClassesInPackage("io.cucumber.core.resource.does.not.exist", ExampleInterface.class); assertThat(classes, empty()); } @Test void scanForClassesInPackage() { List<Class<?>> classes = scanner.scanForClassesInPackage("io.cucumber.core.resource.test"); assertThat(classes, containsInAnyOrder( ExampleClass.class, ExampleInterface.class, OtherClass.class)); } @Test void scanForClassesInNonExistingPackage() { List<Class<?>> classes = scanner.scanForClassesInPackage("io.cucumber.core.resource.does.not.exist"); assertThat(classes, empty()); } @Test void scanForResourcesInUnsupportedFileSystem() throws IOException { ClassLoader classLoader = mock(ClassLoader.class); ClasspathScanner scanner = new ClasspathScanner(() -> classLoader); URLStreamHandler handler = new URLStreamHandler() { @Override protected URLConnection openConnection(URL u) { return null; } }; URL resourceUrl = new URL(null, "bundle-resource:com/cucumber/bundle", handler); when(classLoader.getResources("com/cucumber/bundle")).thenReturn(enumeration(singletonList(resourceUrl))); assertThat(scanner.scanForClassesInPackage("com.cucumber.bundle"), empty()); assertThat(logRecordListener.getLogRecords().get(0).getMessage(), containsString("Failed to find resources for 'bundle-resource:com/cucumber/bundle'")); } }
package memethespire.shoppatches; import com.evacipated.cardcrawl.modthespire.lib.SpirePatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePostfixPatch; import com.evacipated.cardcrawl.modthespire.lib.SpirePrefixPatch; import com.megacrit.cardcrawl.cards.AbstractCard; import com.megacrit.cardcrawl.dungeons.AbstractDungeon; import com.megacrit.cardcrawl.shop.ShopScreen; import memethespire.cardmemes.CardModification; @SpirePatch(clz = ShopScreen.class, method = "purchaseCard") public class ShopCardPurchasePatch { // The revert has to be a prefix patch as the method is called when the // player *attempts* to purchase a card, thus the price is not checked. // The method also deducts gold and sets the hoveredCard to null, so a // postfix is impossible, as the card and the gold has to be checked // beforehand. @SpirePrefixPatch // Cards stay changed after they get added to the deck, thus their names // and descriptions will be reset when they are selected. public static void revertAndUpdate(ShopScreen _instance, AbstractCard hoveredCard) { if (AbstractDungeon.player.gold >= hoveredCard.price) { CardModification.restore(hoveredCard); } } // When a card is purchased, instead of directly adding it to the deck // instantly, the instruction is carried by a FastCardObtainEffect, which // adds the card to the deck after a very short delay. However, due to // the delay it is not possible to update the shop immediately after the // method is called. Instead, the current instance of the shop will be // stored as a static variable which will be accessed by the patch to // FastCardObtainEffect. public static ShopScreen currentScreen; @SpirePostfixPatch public static void storeShopScreen(ShopScreen instance, AbstractCard _hoveredCard) { currentScreen = instance; } }
# Run instructions Make sure you run this application on Java 9. To verify your Java version open a console and enter `java --version`. You should get something like this: java 9.0.4 Java(TM) SE Runtime Environment (build 9.0.4+11) Java HotSpot(TM) 64-Bit Server VM (build 9.0.4+11, mixed mode) ## Run the client Open a console and run the following command: java -jar \ --add-modules jdk.incubator.httpclient \ <path>/geocoder-0.0.1-all.jar \ <Google API KEY> ### Run the client on a specific postal code` You can run the client for a specific postal code. This requires a client version of at least `0.0.6. java -jar \ -Dgeocode.zip=6979 \ --add-modules jdk.incubator.httpclient \ <path>/geocoder-0.0.6-all.jar \ <Google API KEY>
import ROOTURL from '../ROOTURL'; import axios from 'axios' // API call for signingup of user const signupURL = ROOTURL + "/websignup" export const signup = (userData)=> axios.post(signupURL, userData)
export read_settings read_settings(x) = as_namedtuple(x) read_settings(x::String) = as_namedtuple(TOML.parsefile(x)) as_namedtuple(xs) = xs function as_namedtuple(xs::Dict{<:AbstractString,<:Any}) kt = Tuple((Symbol(x) for x in keys(xs))) vt = Tuple(values(xs)) NamedTuple{kt}(as_namedtuple.(vt)) end read_params(x) = x function read_params(x::DataFrameRow) Dict(k => x[k][1] for k in names(x)) end function read_params(x::DataFrame) @assert size(x,1) == 1 "Only a single row of parameters can be provided." Dict(k => x[!,k][1] for k in names(x)) end function checkunits(params::Dict,unit,key) try uconvert(unit,params[key]) catch e error("parameter $key with value $(params[key]) incompatible with unit $unit.") end end
"""Test utilities used across packages This code is only used in other modules' tests """ from .base_exporter_integration_test import BaseExporterIntegrationTest
package ru.alexmaryin.deter_rev.engine.audio import ru.alexmaryin.deter_rev.values.MusicAssets import ru.alexmaryin.deter_rev.values.SoundAssets interface AudioService { fun play(sound: SoundAssets, volume: Float = 1f) fun play(music: MusicAssets, loop: Boolean = true) fun pause() fun resume() suspend fun stop(clear: Boolean = true) fun update(delta: Float) fun changeVolume(volume: Float) }
<?php namespace App; use Illuminate\Database\Eloquent\Model; use App\productsCatagories; class Products extends Model { protected $table = 'products'; public function getCatagory() { return productsCatagories::where('id',$this->catagory_id)->FirstOrFail(); } public function relateProduct() { $relateProduct = Products::where('catagory_id',$this->catagory_id)->get(); return $relateProduct; } }
import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; /// Extends the [Cubic] curve class to allow for more precise calculation of /// the curve. class PreciseCubic extends Cubic { /// Creates a precise cubic curve. const PreciseCubic( double a, double b, double c, double d, { double? errorBound, }) : errorBound = errorBound ?? 0.00000001, super(a, b, c, d); factory PreciseCubic.fromCubic(Cubic cubic, {double? errorBound}) => PreciseCubic( cubic.a, cubic.b, cubic.c, cubic.d, errorBound: errorBound, ); final double errorBound; double _evaluateCubic(double a, double b, double m) { return 3 * a * (1 - m) * (1 - m) * m + 3 * b * (1 - m) * m * m + m * m * m; } @override double transformInternal(double t) { double start = 0.0; double end = 1.0; while (true) { final double midpoint = (start + end) / 2; final double estimate = _evaluateCubic(a, c, midpoint); if ((t - estimate).abs() < errorBound) return _evaluateCubic(b, d, midpoint); if (estimate < t) start = midpoint; else end = midpoint; } } @override String toString() { return '${objectRuntimeType(this, 'PreciseCubic')}(${a.toStringAsFixed(2)}, ' '${b.toStringAsFixed(2)}, ${c.toStringAsFixed(2)}, ' '${d.toStringAsFixed(2)}, errorBound: ${errorBound})'; } }
;%1=fat_segment %macro Read_FAT 1 mov ax, %1 mov es, ax mov ax, word [Reserved_Sectors] ;add reserved sectors add ax, word [Hidden_Sectors] ;add hidden sectors adc ax, word [Hidden_Sectors + 2] mov cx, word [Sectors_Per_FAT] ;number of sectors per FAT xor bx, bx read_next_fat_sector: push cx push ax call Read_Sector pop ax pop cx inc ax add bx, word [Bytes_Per_Sector] jnz read_next_fat_sector %endmacro
import 'package:clock_checker/models/time_sources.dart'; import 'package:clock_checker/repository/timezones.dart'; import 'views/main_menu.dart'; import 'package:flutter/material.dart'; void main() { Timezones tzones = new Timezones(); TimeSources ts = new TimeSources(); runApp(MainMenu()); }
# マップコンバーター エクセルやスプレッドシートでマップを作成して、tsvファイルにコピペし、makeすることで、C#のコードになります。 # 依存関係 make, python を使用しています。 # 使い方 1. エクセルや、スプレッドでマップを作成します。 ![Stage01](doc/Stage01.png) 1. メモ帳などにコピペして tsv/ に保存します。ファイルの拡張子をtsvにします。 [例 Stage01.tsv](tsv/Stage01.tsv) 1. リポジトリのルートでmakeを実行します。 1. cs/にC#のコードが出力されます。 [例 Stage01.cs](doc/Stage01.cs)
class Fisk module Errors class Error < StandardError end # Raised when a temporary register is released more than once class AlreadyReleasedError < Error end # Raised when a temporary register is used after it has been released class UseAfterInvalidationError < Error end # Raised when a temporary register hasn't been released, but local register # allocation was requested class UnreleasedRegisterError < Error end # Raised when a temporary register hasn't been assigned a real register, # but it's used in the encoding process. class UnassignedRegister < Error end # Raised when a label is used but the location is never defined. For # example, the `label` method is called, but there is no corresponding # `put_label` class MissingLabel < Error end # Raised when a label is defined multiple times. For example, calling # `put_label` with the same name twice class LabelAlreadyDefined < Error end # Raised when the performance check is enabled, and suboptimal instructions # are found. class SuboptimalPerformance < Error attr_reader :warnings def initialize(warnings) super "Suboptimal instructions found!" @warnings = warnings end end end end
using System; namespace SQLiteAbstractCrud { internal class Field { public string Name { get; private set; } internal string TypeCSharp { get; set; } public string TypeSQLite { get; private set; } public string Quote { get; private set; } public bool IsPrimaryKey { get; } public bool IsAutoincrement { get; } public Field(string name, string typeCSharp) { CtorConfig(name, typeCSharp); } public Field(string name, string typeCSharp, bool isPrimaryKey, bool isAutoincrement) { IsPrimaryKey = isPrimaryKey; IsAutoincrement = isAutoincrement; CtorConfig(name, typeCSharp); } private void CtorConfig(string name, string typeCSharp) { Name = name; TypeCSharp = typeCSharp; switch(typeCSharp) { case "String": case "DateTime": TypeSQLite = "TEXT"; Quote = "'"; break; case "Int32": case "Int16": case "Boolean": TypeSQLite = "INTEGER"; Quote = ""; break; default: throw new ArgumentOutOfRangeException(nameof(typeCSharp), "TypeCSharp not found"); } } } }
package coms362.cards.fiftytwo; import java.io.IOException; import coms362.cards.abstractcomp.Move; import coms362.cards.abstractcomp.Player; import coms362.cards.abstractcomp.Table; import coms362.cards.app.ViewFacade; import events.remote.AddToPileRemote; import events.remote.HideCardRemote; import events.remote.RemoveFromPileRemote; import events.remote.ShowCardRemote; import events.remote.ShowPlayerScore; import model.Card; public class PickupMove implements Move { private Card c; private Player p; public PickupMove(Card c, Player p){ this.c = c; this.p = p; } public void apply(Table table){ table.removeFromPile("discardPile", c); table.addToPile("Tidy", c); table.addToScore(p, 1); } public void apply(ViewFacade view){ view.send(new HideCardRemote(c)); view.send(new RemoveFromPileRemote("Random", c)); view.send(new AddToPileRemote("Tidy", c)); view.send(new ShowCardRemote(c)); view.send(new ShowPlayerScore(p, null)); } }
module OptimaForHasql.Param where import OptimaForHasql.Prelude import Optima import qualified Data.Text.Encoding as Text {-| Amount of connections in the pool. -} poolSize :: Param Int poolSize = value "Amount of connections in the pool" (showable 1) unformatted implicitlyParsed {-| Amount of seconds for which the unused connections are kept open. -} poolTimeout :: Param NominalDiffTime poolTimeout = value "Amount of seconds for which the unused connections are kept open" (showable 10) unformatted implicitlyParsed {-| Server host. -} host :: Param ByteString host = fmap Text.encodeUtf8 $ value "Server host" (explicitlyRepresented id "127.0.0.1") unformatted implicitlyParsed {-| Server port. -} port :: Param Word16 port = value "Server port" (showable 5432) unformatted implicitlyParsed {-| Username. -} user :: Param ByteString user = fmap Text.encodeUtf8 $ value "Username" (explicitlyRepresented id "postgres") unformatted implicitlyParsed {-| Password. -} password :: Param ByteString password = fmap Text.encodeUtf8 $ value "Password" (explicitlyRepresented id "") unformatted implicitlyParsed {-| Database name. -} database :: Param ByteString database = fmap Text.encodeUtf8 $ value "Database name" (explicitlyRepresented id "postgres") unformatted implicitlyParsed
#!/bin/sh wget -O - www.reddit.com/r/EarthPorn > file #1 Get all the post links from the subreddit r/wallpaper grep -Po '(?<=href="https://www.reddit.com/r/EarthPorn/comments/)[^"]*' file > links #2 Fix the links sed -i -e 's~^~www.reddit.com/r/EarthPorn/comments/~' links #3 Count the # of posts there are POST_NUMBER="$(wc -l < links)" #4 Choose a random number to pick which wallpaper we're going to use NUMBER=$(shuf -i 1-$POST_NUMBER -n 1) LINK=$(sed -n ${NUMBER}p < links) wget -O - "${LINK}" > picture #5 Get the picture link and save it PICTURE_LINK=$(grep -m1 -Po '(?<=https://i.redd.it/)[^"]*' picture) echo $PICTURE_LINK > picturelink sed -i -e 's~^~i.redd.it/~' picturelink wget -i picturelink -O wallpaper.jpg #6 Resize the image to the desktop size and set it as background #convert -crop 1920X1080 wallpaper.jpg wallpaper.jpg gsettings set org.gnome.desktop.background picture-uri file://$(pwd)/wallpaper.jpg #cleanup rm file links picture picturelink
package Handler; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.UnknownHostException; /** * used to send requests to the server */ public class Sender { //send a serialised object to the server public static void sendTo(Object object, DatagramPacket packet, DatagramSocket clientSocket) { String log; try { // Obtain Client's IP address and the port InetAddress clientAddress = packet.getAddress(); int clientPort = packet.getPort(); //make object into bit stream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(outputStream); out.writeObject(object); //log into file Writer.sendResponse(object, clientAddress.toString(), clientPort); //send request to server byte[] data = outputStream.toByteArray(); DatagramPacket sendPacket = new DatagramPacket(data, data.length, clientAddress, clientPort); clientSocket.send(sendPacket); } catch (UnknownHostException e) { //e.printStackTrace(); log = "HOST ID not found.... "; log += "\nSending file failed... Try again later\n "; Writer.log(log); } catch (IOException e) { //e.printStackTrace(); log = "IOException.... "; log += "\nSending file failed... Try again later\n "; Writer.log(log); } } }
using eilang.Interpreting; namespace eilang.OperationCodes { public class Pop : IOperationCode { public void Execute(State state) { state.Stack.Pop(); } } }
import subscription from './addressBook'; import { ENOREMOVEDEFAULT } from '../constants/Pipelines'; let mockUpdateAddress; let mockGetAddresses; let mockShowModal; jest.mock('../actions/updateAddress', () => (...args) => mockUpdateAddress(...args)); jest.mock('../actions/getAddresses', () => () => mockGetAddresses()); jest.mock('@shopgate/pwa-common/actions/modal/showModal', () => (...args) => mockShowModal(...args)); jest.mock('@shopgate/pwa-common/streams/user', () => ({ userDidUpdate$: { debounceTime: () => jest.fn(), }, })); describe('AddressBook subscriptions', () => { const subscribe = jest.fn(); subscription(subscribe); const [ addressFormLeave$, userAddressValidationFailed$, userAddressChanged$, userAddressBookEnter$, userDidUpdateDebounced$, userAddressesDelete$, userAddressesDeleted$, userSetDefaultAddress$, userAddressesDeleteFailed$, ] = subscribe.mock.calls; let dispatch; beforeEach(() => { dispatch = jest.fn(); dispatch.mockReturnValue(Promise.resolve()); mockUpdateAddress = jest.fn(); mockGetAddresses = jest.fn(); mockShowModal = jest.fn(); }); it('should subscribe to the streams', () => { expect(subscribe.mock.calls.length).toEqual(9); }); it('should dispatch action on address form leave', () => { addressFormLeave$[1]({ dispatch }); }); it('should create toast message when validation is failed ', () => { const events = jest.fn(); events.emit = jest.fn(); // noinspection JSCheckFunctionSignatures jest.spyOn(events, 'emit'); userAddressValidationFailed$[1]({ events }); expect(events.emit).toHaveBeenCalledWith('toast_add', { id: 'address.validationFailed', message: 'address.validationFailedToastMessage', }); }); it('should fetch addresses when single address is changed', () => { const action = { silent: true }; // eslint-disable-next-line extra-rules/no-single-line-objects userAddressChanged$[1]({ dispatch, action }); expect(mockGetAddresses).toHaveBeenCalledTimes(1); }); it('should fetch addresses when address book enter', () => { userAddressBookEnter$[1]({ dispatch }); expect(mockGetAddresses).toHaveBeenCalledTimes(1); }); it('should fetch addresses when user is updated', () => { userDidUpdateDebounced$[1]({ dispatch, getState: () => ({ user: { data: { id: 1 } } }), }); expect(mockGetAddresses).toHaveBeenCalledTimes(1); }); it('should show modal when address request is received', () => { const action = { addressIds: [1] }; // eslint-disable-next-line extra-rules/no-single-line-objects userAddressesDelete$[1]({ dispatch, action }); expect(mockShowModal).toHaveBeenCalledTimes(1); }); it('should create toast message when addresses are deleted', () => { const events = jest.fn(); events.emit = jest.fn(); // noinspection JSCheckFunctionSignatures jest.spyOn(events, 'emit'); // eslint-disable-next-line extra-rules/no-single-line-objects userAddressesDeleted$[1]({ dispatch, events }); expect(events.emit).toHaveBeenCalledWith('toast_add', { id: 'address.delete', message: 'address.delete.successMessage', }); }); it('should add tags when marked as default', () => { const state = { extensions: { '@shopgate/user/UserReducers': { addressBook: { addresses: [ // eslint-disable-next-line extra-rules/no-single-line-objects { id: 1, tags: [], firstName: 'foo' }, ], }, }, }, }; // eslint-disable-next-line extra-rules/no-single-line-objects const action = { addressId: 1, tag: 'shipping' }; // eslint-disable-next-line extra-rules/no-single-line-objects userSetDefaultAddress$[1]({ dispatch, action, getState: () => state }); // eslint-disable-next-line extra-rules/no-single-line-objects expect(mockUpdateAddress).toHaveBeenCalledWith({ id: 1, firstName: 'foo', tags: ['default_shipping'] }, true); }); it('should create toast message when default address can not be deleted', () => { const events = jest.fn(); events.emit = jest.fn(); // noinspection JSCheckFunctionSignatures jest.spyOn(events, 'emit'); // eslint-disable-next-line extra-rules/no-single-line-objects userAddressesDeleteFailed$[1]({ action: { error: { code: ENOREMOVEDEFAULT } }, events }); expect(events.emit).toHaveBeenCalledWith('toast_add', { id: 'address.delete', message: 'address.delete.noRemoveDefault', }); }); });
# unstoppable Resources to control stopPropagation. Event.stopped, "unstoppable" event listener option, scoped stopPropagation(). todo 1.have only the chapters relevant for stopPropagation in the docs.
import * as React from 'react'; type Props = { // Injected by HtmlOverlay x?: number; y?: number; // User provided coordinates: number[]; children: any; style?: Record<string, any>; }; export default class HtmlOverlayItem extends React.Component<Props> { render() { const { x, y, children, style, coordinates, ...props } = this.props; return ( // Using transform translate to position overlay items will result in a smooth zooming // effect, whereas using the top/left css properties will cause overlay items to // jiggle when zooming <div style={{ transform: `translate(${x}px, ${y}px)` }}> <div style={{ position: 'absolute', userSelect: 'none', ...style }} {...props}> {children} </div> </div> ); } }
var searchData= [ ['value_813',['value',['../struct_bl_string_vector.html#a32dbb13b79c255f7254dd2c776c31305',1,'BlStringVector']]], ['variances_814',['variances',['../struct_p_c_a_result.html#a6ff0c0d61bdf5efae4a97ad7bdeb9ae3',1,'PCAResult']]] ];
<?php namespace Anomaly\BlocksModule\Test\Unit\Area; class AreaFormBuilderTest extends \TestCase { }
<?php use Ccovey\LdapAuth; use Mockery as m; /** * User Provider Test. */ class LdapAuthUserProviderTest extends PHPUnit_Framework_TestCase { public function setUp() { $this->ad = m::mock(\adLDAP\adLDAP::class); $this->ad->shouldReceive('close') ->zeroOrMoreTimes() ->andReturn(null); $this->ident = 'strebel'; $this->ad->shouldReceive('user')->atLeast(1) ->andReturn($this->ad); $this->config = [ 'fields' => [ 'groups' => 'groups', 'primarygroup' => 'primarygroup', ], 'userlist' => false, 'group' => [], ]; } public function tearDown() { m::close(); } public function testRetrieveByIDWithoutModelReturnsLdapUser() { $this->ad->shouldReceive('getRecursiveGroups')->atLeast(1) ->andReturn(false); $this->ad->shouldReceive('infoCollection') ->once()->with($this->ident, ['*'])->andReturn(false); $user = new LdapAuth\LdapAuthUserProvider($this->ad, $this->config); $returned = $user->retrieveByID($this->ident); $this->assertNull($returned); } public function testModelResolved() { $user = new LdapAuth\LdapAuthUserProvider($this->ad, $this->config, User::class); $this->assertInstanceOf(User::class, $user->createModel()); } public function testRetrieveByIDWithModelAndNoUserReturnsNull() { $this->ad->shouldReceive('getRecursiveGroups')->atLeast(1) ->andReturn(false); $this->ad->shouldReceive('infoCollection') ->once()->with($this->ident, ['*'])->andReturn(false); $user = $this->getProvider($this->ad, User::class); $mock = m::mock('stdClass'); $mock->shouldReceive('newQuery')->once()->andReturn($mock); $mock->shouldReceive('find')->once()->with($this->ident)->andReturn(null); $user->expects($this->once())->method('createModel')->will($this->returnValue($mock)); $retrieved = $user->retrieveByID($this->ident); $this->assertNull($retrieved); } public function testRetrieveByIDWithModelAndLdapInfo() { $this->ad->shouldReceive('getRecursiveGroups')->atLeast(1) ->andReturn(false); $this->ad->shouldReceive('infoCollection') ->once()->with($this->ident, ['*'])->andReturn($this->getLdapInfoCollection()); $user = $this->getProvider($this->ad, User::class); $mock = m::mock('stdClass'); $mock->shouldReceive('newQuery')->once()->andReturn($mock); $modelMock = m::mock('stdClass'); $modelMock->username = 'strebel'; $modelMock->shouldReceive('getAttributes')->once()->andReturn(['foo' => 'bar']); $modelMock->shouldReceive('fill')->once()->andReturn(['foo' => 'bar', $this->ident]); $mock->shouldReceive('find')->once()->with($this->ident)->andReturn($modelMock); $user->expects($this->once())->method('createModel')->will($this->returnValue($mock)); $retrieved = $user->retrieveByID($this->ident); $this->assertContains('bar', $retrieved); $this->assertContains('strebel', $retrieved); } public function testValidateCredentials() { $credentials = ['username' => 'strebel', 'password' => 'password']; $this->ad->shouldReceive('authenticate')->once()->andReturn(true); $user = $this->getProvider($this->ad, User::class); $model = m::mock(LdapUser::class, Illuminate\Contracts\Auth\Authenticatable::class); $validate = $user->validateCredentials($model, $credentials); $this->assertTrue($validate); } public function testGroupParsingWithoutRecursiveGroups() { $this->ad->shouldReceive('getRecursiveGroups')->atLeast(1) ->andReturn(false); $this->ad->shouldReceive('infoCollection') ->once()->with($this->ident, ['*'])->andReturn($this->getLdapInfoCollection()); $user = $this->getProvider($this->ad, null); $this->assertEquals([ 'gg_test_bms_lehrer' => 'gg_test_bms_lehrer', 'gg_test_gdl_lehrer' => 'gg_test_gdl_lehrer', ], $user->retrieveByID('strebel')->groups); } public function testGroupParsingWithRecursiveGroups() { $this->ad->shouldReceive('getRecursiveGroups')->atLeast(1) ->andReturn(true); $this->ad->shouldReceive('info') ->once()->with($this->ident, ['*'])->andReturn($this->getLdapInfo()); $this->ad->shouldReceive('groups') ->once()->with($this->ident)->andReturn([ 'gg_test_bms_lehrer', 'gg_test_gdl_lehrer', ]); $user = $this->getProvider($this->ad, null); $this->assertEquals([ 'gg_test_bms_lehrer' => 'gg_test_bms_lehrer', 'gg_test_gdl_lehrer' => 'gg_test_gdl_lehrer', ], $user->retrieveByID('strebel')->groups); } public function testGroupReturnsEmptyStringIfAUserHasNoGroups() { $this->ad->shouldReceive('getRecursiveGroups')->atLeast(1) ->andReturn(false); $infoCollection = $this->getLdapInfoCollection(); $infoCollection->memberof = null; $this->ad->shouldReceive('infoCollection') ->once()->with($this->ident, ['*'])->andReturn($infoCollection); $user = $this->getProvider($this->ad, null); $this->assertEquals('', $user->retrieveByID('strebel')->groups); } protected function getProvider($conn, $model = null) { return $this->getMock(Ccovey\LdapAuth\LdapAuthUserProvider::class, ['createModel'], [$conn, $this->config, $model]); } protected function getLdapInfoCollection() { $info = new stdClass(); $info->samaccountname = 'strebel'; $info->displayName = 'Manuel Strebel'; $info->distinguishedname = 'DC=LDAP,OU=AUTH,OU=FIRST GROUP'; $info->memberof = [ 'CN=gg_test_bms_lehrer,OU=Groups,OU=BMS,OU=gibb-Test,DC=gibb,DC=int', 'CN=gg_test_gdl_lehrer,OU=Groups,OU=GDL,OU=gibb-Test,DC=gibb,DC=int', ]; return $info; } protected function getLdapInfo() { $info = []; $info['samaccountname']['count'] = 1; $info['samaccountname'][0] = 'strebel'; $info['displayName']['count'] = 1; $info['displayName'][0] = 'Manuel Strebel'; $info['distinguishedname']['count'] = 1; $info['distinguishedname'][0] = 'DC=LDAP,OU=AUTH,OU=FIRST GROUP'; $info['memberof']['count'] = 2; $info['memberof'] = [ 'CN=gg_test_bms_lehrer,OU=Groups,OU=BMS,OU=gibb-Test,DC=gibb,DC=int', 'CN=gg_test_gdl_lehrer,OU=Groups,OU=GDL,OU=gibb-Test,DC=gibb,DC=int', ]; return $info; } } class User { }
class Movie { // contents of a regular movie that shows up in the default result page num id; String backdrop_path; String poster_path; String title; Movie (Map<String, dynamic> json) { id = json['id']; backdrop_path = json['backdrop_path']; poster_path = json['poster_path']; title = json['title']; } // Movie.fromJSON(Map<String, dynamic> json) { // id = json['id']; // } }
import { parseISO, format } from 'date-fns' export default function Date({ dateString }: { dateString: string }) { const date = parseISO(dateString) // See options at: https://date-fns.org/v2.12.0/docs/format return ( <time dateTime={dateString} itemProp="datePublished"> {format(date, 'EEEE, do MMMM yyyy')} </time> ) }
require_relative 'bonus_rolls' require_relative 'frames' require_relative 'frame_creator' class Bowling def initialize(frame_creator = FrameCreator.new) @frame_creator = frame_creator @rolls = Array.new(0) {0} end def score total = 0 index = 0 10.times do frame = frame_creator.create(rolls, index) total += frame.score_with_bonus index += frame.frame_size end total end def roll(pins) rolls << pins end private attr_reader :frame_creator, :rolls end
import cadquery as cq from plugins.more_selectors.more_selectors import ( HollowCylinderSelector, InfiniteCylinderSelector, CylinderSelector, InfHollowCylinderSelector, SphereSelector, HollowSphereSelector, ) def test_CylinderSelector(): """ Test that the CylinderSelector selects the right number of entities """ boxes = cq.Workplane().box(10, 10, 10).moveTo(15, 0).box(5, 5, 5) vertices = boxes.vertices(CylinderSelector((5, 0, 3), "Z", 8, 6)) edges = boxes.edges(CylinderSelector((0, 0, 3), "Z", 8, 8)) faces = boxes.faces(CylinderSelector((0, 0, 3), "Z", 8, 8)) solids = boxes.solids(CylinderSelector((-10, 0, 0), "X", 30, 8)) assert vertices.size() == 2 assert edges.size() == 4 assert faces.size() == 1 assert solids.size() == 2 def test_HollowCylinderSelector(): """ Test that the HollowCylinderSelector selects the right number of entities """ innerbox = cq.Workplane().box(5, 5, 10) boxes = ( cq.Workplane() .box(10, 10, 10) .box(3, 3, 3) .cut(innerbox) .moveTo(10, 0) .box(2, 2, 10) ) vertices = boxes.vertices( HollowCylinderSelector((0, 0, 3), "Z", 8, 8, 4, debug=True) ) edges = boxes.edges(HollowCylinderSelector((0, 0, 3), "Z", 8, 8, 4, debug=True)) faces = boxes.faces(HollowCylinderSelector((0, 0, -10), "Z", 20, 4, 2, debug=True)) solids = boxes.solids( HollowCylinderSelector((0, 0, -6), "Z", 12, 15, 2, debug=True) ) assert vertices.size() == 4 assert edges.size() == 4 assert faces.size() == 4 assert solids.size() == 1 def test_InfiniteCylinderSelector(): """ Test that the InfiniteCylinderSelector selects the right number of entities """ boxes = cq.Workplane().box(10, 10, 10).moveTo(15, 0).box(5, 5, 5) vertices = boxes.vertices(InfiniteCylinderSelector((5, 0, 3), "Z", 6, debug=True)) edges = boxes.edges(InfiniteCylinderSelector((-3, 0, 0), "Z", 7, debug=True)) faces = boxes.faces(InfiniteCylinderSelector((0, 0, 0), "X", 2, debug=True)) solids = boxes.solids(InfiniteCylinderSelector((0, 0, 0), (1, 1, 0), 3, debug=True)) assert vertices.size() == 4 assert edges.size() == 8 assert faces.size() == 4 assert solids.size() == 1 def test_InfHollowCylinderSelector(): """ Test that the InfHollowCylinderSelector selects the right number of entities """ innerbox = cq.Workplane().box(5, 5, 10) boxes = ( cq.Workplane() .box(10, 10, 10) .box(3, 3, 3) .cut(innerbox) .moveTo(10, 0) .box(2, 2, 10) ) vertices = boxes.vertices( InfHollowCylinderSelector((0, 0, 3), "Z", 4, 2, debug=True) ) edges = boxes.edges(InfHollowCylinderSelector((0, 0, 3), "Z", 8, 4, debug=True)) faces = boxes.faces(InfHollowCylinderSelector((0, 0, -10), "Z", 8, 2, debug=True)) solids = boxes.solids(InfHollowCylinderSelector((0, 0, -6), "Z", 15, 2, debug=True)) assert vertices.size() == 8 assert edges.size() == 12 assert faces.size() == 8 assert solids.size() == 1 def test_SphereSelector(): """ Test that the SphereSelector selects the right number of entities """ sphere = ( cq.Workplane().sphere(5).polarArray(7, 30, 120, 2, rotate=True).box(1, 2, 1) ) vertices = sphere.vertices(SphereSelector((0, 0, 0), 7, debug=True)) edges = sphere.edges(SphereSelector((0, 0, 0), 7, debug=True)) faces = sphere.faces(SphereSelector((0, 0, 0), 7.5, debug=True)) solids = sphere.solids(SphereSelector((0, 0, 0), 6, debug=True)) assert vertices.size() == 10 assert edges.size() == 9 assert faces.size() == 11 assert solids.size() == 1 def test_HollowSphereSelector(): """ Test that the HollowSphereSelector selects the right number of entities """ sphere = ( cq.Workplane().sphere(5).polarArray(7, 30, 120, 2, rotate=True).box(1, 2, 1) ) vertices = sphere.vertices(HollowSphereSelector((0, 0, 0), 7, 5.5, debug=True)) edges = sphere.edges(HollowSphereSelector((0, 0, 0), 9, 7.5, debug=True)) faces = sphere.faces(HollowSphereSelector((0, 0, 0), 9, 7.5, debug=True)) solids = sphere.solids(HollowSphereSelector((0, 0, 0), 9, 6, debug=True)) assert vertices.size() == 8 assert edges.size() == 8 assert faces.size() == 2 assert solids.size() == 2
const ConfigurerBase = require('../configurer-base.js'); const { setup } = require('./sqlserver-setup.js'); const { test } = require('./sqlserver-test.js'); class SQLServerConfigurer extends ConfigurerBase { isMine(dbImage) { return dbImage.toLowerCase().includes('mssql'); } setup(config) { return setup(config); } test(config) { return test(config); } } module.exports = new SQLServerConfigurer();
# mysql 总结 ## 简介 以下默认innodb引擎, 事务级别为RC或者RR 的一些总结。 mysql在应用层面需要关注的点: + 锁机制 + 索引机制 ## mysql 索引 mysql 主要有两种索引,聚簇索引(Clustered Index)与 非聚簇索引(Secondary Index)。 聚簇索引行会包含所有数据,位于B+数叶子节点。 每一个非聚簇索引行都会包含primary key,方便回扫聚簇索引行。 ![avatar](index.png) ### mysql 索引扫描原则 索引扫描原则就是B+树的特点决定,联合索引需要按照索引位置进行匹配。 ## mysql 锁 + 行锁 + 共享锁(允许事务在读时候hold锁) + 间隙锁(RR 级别下为了避免幻读,需要锁住前后gap) + 排他锁(允许事务在更新和删除hold锁) + 表锁 + 意向锁 (为了解决锁表需要查询行锁效率问题产生的锁,不与行锁冲突) + next key锁(行锁+gap锁) ## mysql 锁机制 RC事务级别与RR级别最大的区别是不需要gap锁,一般在普通index时候进行当前读会产生, primary key与unique key查询一致。 锁范围根据where提取的index key决定 ## mysql mvcc mysql mvcc多版本控制在readview 时候RC与RR的区别在于 RC是语句级别的readview,RR是事务级别 ## mysql 事务总结 RC vs RR: + RC > + 优势: >> + 高并发,低锁开销,semi-consistent read >> + 没有gap锁,释放锁比较快 > + 劣势: >> + 语句级快照,每条语句都需要新建readview,存在幻读 + RR > + 优势: >> + 与RC相反 > + 劣势: >> + 与RC相反
import { Component, OnInit, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core'; @Component({ selector: 'app-question-list', templateUrl: './app-question-list.component.html', styleUrls: ['./app-question-list.component.scss'], changeDetection: ChangeDetectionStrategy.OnPush }) export class AppQuestionListComponent implements OnInit { @Input() questions; @Input() canEdit; @Output() delete = new EventEmitter(); @Output() edit = new EventEmitter(); @Output() openQuotesBrowser = new EventEmitter(); questionMenu; constructor() { } ngOnInit() { } get checked() { return this.questions && this.questions.every(question => question.checked); } deleteQuestions() { this.delete.emit(this.questions.filter(question => question.checked)); } editQuestion(question) { this.edit.emit(question); } get indeterminate() { return this.questions ? !this.checked && this.questions.some(question => question.checked === true) : false; } toggleCheckAllQuestions() { if (this.questions.every(question => question.checked)) { this.questions.forEach(question => { question.checked = false; }); } else { this.questions.forEach(question => { question.checked = true; }); } } canDelete() { return this.questions ? this.questions.some(question => question.checked) : false; } getSelectedQuestions() { return ( (this.questions && this.questions.filter(question => question.checked)) || [] ); } openQuotes(question) { this.openQuotesBrowser.emit(question); } }
<?php include "sections/header.php"?> <div class="container"> <div class="row"> <div class='col-md-12 text-center mb-2 mt-3' id='top5'> <div>Welcome to <?php echo $user;?>'s blog!</div> </div> <?php foreach ($posts as $post) { $username = $post['Username']; $title = $post['Title']; $description = $post['Description']; $tags = $post['Tag']; ?> <div class="row"> <div class="col m-3"> <div class="card bg-light mb-3" style="max-width: 50rem;"> <div class="card-header"><?php echo $username; ?></div> <div class="card-body"> <h5 class="card-title"><?php echo $title; ?></h5> <p class="card-text"><?php echo $description; ?></p> <p class="card-text">#<?php echo $tags; ?></p> </div> </div> </div> </div> <?php } ?> </div> <?php include "sections/footer.php"?>
module Dom require 'happymapper' class PlaneItem; end class Planes; end class PlaneAmmunition; end class PlaneParameters; end class PlaneType; end class HumType; end class MilitaryType; end class Planes include HappyMapper tag 'planes' attribute :xmlns, String has_many :planes, PlaneItem, tag: 'planeItem' end class PlaneAmmunition include HappyMapper tag 'ammunition' element :rockets, Integer end class PlaneParameters include HappyMapper tag 'parameters' element :h, Integer element :l, Integer element :w, Integer def set_w w unless w > 0 self.w = w end end def set_h h unless h > 0 self.h = h end end def set_l l unless l > 0 self.l = l end end end class MilitaryType include HappyMapper tag 'militaryType' element :places, Integer element :radar, Boolean element :ammunition, PlaneAmmunition def set_places places unless places < 1 && places > 2 self.places = places end end end class HumType include HappyMapper tag 'humType' element :places, Integer element :radar, Boolean def set_places places unless places < 1 && places > 2 self.places = places end end end class PlaneType include HappyMapper tag 'chars' element :htype, HumType element :mtype, MilitaryType def get_type if self.htype return self.htype end if self.mtype return self.mtype end end end class PlaneItem include HappyMapper tag 'planeItem' element :id, Integer element :model, String element :origin, String element :price, Integer element :chars, PlaneType def set_price price unless price >= 0 self.price = price end end end class Parser def run(xml) parsed = Planes.parse xml, single: true puts "Number of devices #{parsed.planes.count}" puts 'Sorted by the price:' parsed.planes.sort_by(& :price) .each do |plane| puts "#{plane.model} with price #{plane.price} Places: #{plane.chars.get_type.places}" end end end end
/** * Datart * * Copyright 2021 * * 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. */ import { memo, useContext } from 'react'; import { BoardType, MediaWidgetType } from '../../pages/Board/slice/types'; import { WidgetDataProvider } from '../WidgetProvider/WidgetDataProvider'; import { WidgetContext } from '../WidgetProvider/WidgetProvider'; import { IframeWidget } from '../Widgets/IframeWidget/IframeWidget'; import { ImageWidget } from '../Widgets/ImageWidget/ImageWidget'; import { RichTextWidget } from '../Widgets/RichTextWidget/RichTextWidget'; import { TabWidget } from '../Widgets/TabWidget/TabWidget'; import { TimerWidget } from '../Widgets/TimerWidget/TimerWidget'; import { VideoWidget } from '../Widgets/VideoWidget/VideoWidget'; export const FullScreenWidgetMapper: React.FC<{ boardType: BoardType; boardEditing: boolean; }> = memo(({ boardEditing }) => { const widget = useContext(WidgetContext); const widgetType = widget.config.type; switch (widgetType) { case 'chart': return ( <WidgetDataProvider widgetId={widget.id} boardId={widget.dashboardId} boardEditing={boardEditing} > {/* <DataChartWidget hideTitle={true} /> */} </WidgetDataProvider> ); case 'media': const mediaSubType: MediaWidgetType = widget.config.content.type; return MediaMapper(mediaSubType); case 'container': return <TabWidget hideTitle={true} />; default: return <div>default widget</div>; } }); export const MediaMapper = (subType: MediaWidgetType) => { switch (subType) { case 'richText': return <RichTextWidget hideTitle={true} />; case 'image': return <ImageWidget hideTitle={true} />; case 'video': return <VideoWidget hideTitle={true} />; case 'iframe': return <IframeWidget hideTitle={true} />; case 'timer': return <TimerWidget hideTitle={true} />; default: return <div>default media</div>; } };
package com.vin.imc import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.view.MotionEvent import kotlinx.android.synthetic.main.activity_main.* import java.lang.Float.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) var calcular = btn_calcular var deletar = icon_delete calcular.setOnClickListener{ var peso = edit_peso.text.toString() var altura = edit_altura.text.toString() if(peso.isEmpty()){ view_resultado.setText("Insira seu peso") } else if(altura.isEmpty()){ view_resultado.setText("Insira sua altura") } else{ calcIMC() } } deletar.setOnTouchListener { v, event -> if(event.action == MotionEvent.ACTION_DOWN){ deleteValuesOfFields() } false } } fun calcIMC(){ var peso = Integer.parseInt(edit_peso.text.toString()) var altura = parseFloat(edit_altura.text.toString()) var resultado = view_resultado val imc = peso / (altura * altura) val _mensagem = when { imc <= 18.5 -> "Abaixo do peso" imc <= 24.9 -> "Peso normal" imc <= 29.9 -> "Sobrepeso" imc <= 34.9 -> "Obesidade (grau 1)" imc <= 39.9 -> "Obesidade (grau 2)" else -> "Obsedidade Mórbida (grau 3)" } resultado.text = "IMC: ${imc.toString()}\n$_mensagem" } fun deleteValuesOfFields(){ edit_peso.setText("") edit_altura.setText("") view_resultado.setText("") } }
using AutoBlogProgramistyPosts.Dto; namespace AutoBlogProgramistyPosts { public interface IPostEngine { PostDto PublishPost(IPostCreator postCreator); void PublishPost(PostDto postDto); } }
module Negroku class Feature include Virtus.value_object values do attribute :name, String attribute :required, Boolean, default: false attribute :enabled, Boolean, default: false, :writer => :public end end end class Negroku::ConfigFactory include Virtus.model def self.loaded_in_bundler(*names) Bundler.locked_gems.dependencies.any? { |a| names.include?(a.name) } end attribute :bower, Negroku::Feature, default: { name: 'bower', enabled: File.exist?('bower.json') } attribute :bundler, Negroku::Feature, default: { name: 'bundler', enabled: File.exist?('Gemfile') } attribute :delayed_job, Negroku::Feature, default: { name: 'delayed_job', enabled: loaded_in_bundler('delayed_job', 'delayed_job_active_record') } attribute :nginx, Negroku::Feature, default: { name: 'nginx', enabled: true, required: true } attribute :nodenv, Negroku::Feature, default: { name: 'nodenv', enabled: true, required: true } attribute :rails, Negroku::Feature, default: { name: 'rails', enabled: loaded_in_bundler('rails') } attribute :rbenv, Negroku::Feature, default: { name: 'rbenv', enabled: true, required: true } attribute :sphinx, Negroku::Feature, default: { name: 'sphinx', enabled: loaded_in_bundler('thinking-sphinx') } attribute :unicorn, Negroku::Feature, default: { name: 'unicorn', enabled: loaded_in_bundler('unicorn') } attribute :puma, Negroku::Feature, default: { name: 'puma', enabled: loaded_in_bundler('puma') } attribute :whenever, Negroku::Feature, default: { name: 'whenever', enabled: File.exist?('config/schedule.rb') } # private end Negroku::Config = Negroku::ConfigFactory.new
module CF module Explorer module Resources class App include Virtus.model attribute :status, Integer attribute :name, String attribute :metadata_guid, String attribute :metadata_url, String attribute :metadata_created_at, DateTime attribute :metadata_updated_at, DateTime attribute :entity_name, String attribute :entity_production, Boolean attribute :entity_space_guid, String attribute :entity_stack_guid, String attribute :entity_buildpack, String attribute :entity_detected_buildpack, String attribute :entity_environment_json, Hash attribute :entity_memory, Integer attribute :entity_instances, Integer attribute :entity_disk_quota, Integer attribute :entity_state, String attribute :entity_version, String attribute :entity_command, String attribute :entity_console, Boolean attribute :entity_debug, String attribute :entity_staging_task_id, String attribute :entity_package_state, String attribute :entity_health_check_timeout, String attribute :entity_staging_failed_reason, String attribute :entity_docker_image, Boolean attribute :entity_package_updated_at, DateTime attribute :entity_space_url, String attribute :entity_events_url, String attribute :entity_service_bindings_url, String attribute :entity_routes_url, String end end end end
package com.github.ozsie import org.apache.maven.model.Dependency import org.apache.maven.model.Plugin import org.apache.maven.plugin.AbstractMojo import org.apache.maven.plugin.logging.Log import org.apache.maven.plugins.annotations.Parameter import org.apache.maven.project.MavenProject import java.io.File const val CREATE_BASELINE = "-cb" const val DEBUG = "--debug" const val DISABLE_DEFAULT_RULE_SET = "-dd" const val PARALLEL = "--parallel" const val BASELINE = "-b" const val CONFIG = "-c" const val CONFIG_RESOURCE = "-cr" const val FILTERS = "-f" const val INPUT = "-i" const val PLUGINS = "-p" const val PRINT_AST = "--print-ast" const val RUN_RULE = "--run-rule" const val REPORT = "-r" const val MDP_ID = "com.github.ozsie:detekt-maven-plugin" const val DOT = "." const val SLASH = "/" const val SEMICOLON = ";" abstract class DetektMojo : AbstractMojo() { @Parameter(defaultValue = "false") var skip = false @Parameter(property = "detekt.baseline", defaultValue = "") var baseline = "" @Parameter(property = "detekt.config", defaultValue = "") var config: String = "" @Parameter(property = "detekt.config-resource", defaultValue = "") var configResource = "" @Parameter(property = "detekt.debug", defaultValue = "false") var debug = false @Parameter(property = "detekt.disable-default-rulesets", defaultValue = "false") var disableDefaultRuleSets = false @Parameter(property = "detekt.filters") var filters = ArrayList<String>() @Parameter(property = "detekt.help", defaultValue = "false") var help = false @Parameter(property = "detekt.input", defaultValue = "\${basedir}/src") var input = "\${basedir}/src" @Parameter(property = "detekt.parallel", defaultValue = "false") var parallel = false @Parameter(property = "detekt.printAst", defaultValue = "false") var printAst = false @Parameter(property = "detekt.disableDefaultRuleset", defaultValue = "false") var disableDefaultRuleset = false @Parameter(property = "detekt.runRule", defaultValue = "") var runRule = "" @Parameter(property = "detekt.plugins") var plugins = ArrayList<String>() @Parameter(defaultValue = "\${project}", readonly = true) var mavenProject: MavenProject? = null @Parameter(defaultValue = "\${settings.localRepository}", readonly = true) var localRepoLocation = "\${settings.localRepository}" internal fun getCliSting() = ArrayList<String>().apply { useIf(debug, DEBUG) .useIf(disableDefaultRuleSets, DISABLE_DEFAULT_RULE_SET) .useIf(parallel, PARALLEL) .useIf(baseline.isNotEmpty(), BASELINE, baseline) .useIf(config.isNotEmpty(), CONFIG, config) .useIf(configResource.isNotEmpty(), CONFIG_RESOURCE, configResource) .useIf(filters.isNotEmpty(), FILTERS, filters.joinToString(SEMICOLON)) .useIf(input.isNotEmpty(), INPUT, input) .useIf(runRule.isNotEmpty(), RUN_RULE, runRule) .useIf(printAst, PRINT_AST) .useIf(disableDefaultRuleset, DISABLE_DEFAULT_RULE_SET) .useIf(plugins.isNotEmpty(), PLUGINS, plugins.buildPluginPaths(mavenProject, localRepoLocation)) } internal fun <T> ArrayList<T>.log(): ArrayList<T> = log([email protected]) } internal fun <T> ArrayList<T>.log(log: Log): ArrayList<T> = apply { StringBuilder().apply { forEach { append(it).append(" ") } log.info("Args: $this".trim()) } } internal fun <T> ArrayList<T>.useIf(w: Boolean, vararg value: T) = apply { if (w) addAll(value) } internal fun ArrayList<String>.buildPluginPaths(mavenProject: MavenProject?, localRepoLocation: String) = StringBuilder().apply { mavenProject?.let { this.buildPluginPaths(this@buildPluginPaths, it.getPlugin(MDP_ID), localRepoLocation) } }.toString().removeSuffix(SEMICOLON) internal fun StringBuilder.buildPluginPaths(plugins: ArrayList<String>, mdp: Plugin, root: String) { plugins.forEach { plugin -> if (File(plugin).exists()) { append(plugin).append(SEMICOLON) } else { mdp.dependencies ?.filter { plugin == it.getIdentifier() } ?.forEach { append(it asPath root).append(SEMICOLON) } } } } internal infix fun Dependency.asPath(root: String) = "$root/${groupId.asPath()}/$artifactId/$version/$artifactId-$version.jar" internal fun Dependency.getIdentifier() = "$groupId:$artifactId" internal fun String.asPath() = replace(DOT, SLASH)
title: Recipes --- # Our recipes Whisk the chicken lard with puréed basil, cinnamon, rum, and sugar making sure to cover all of it.
<?php namespace CWP\AgencyExtensions\Forms; use SilverStripe\Forms\SingleSelectField; class FontPickerField extends SingleSelectField { public function __construct($name, $title = null, $source = array(), $value = null) { parent::__construct($name, $title, $source, $value); $this->addExtraClass('font-picker-field'); } public function getSchemaDataDefaults() { $schemaData = parent::getSchemaDataDefaults(); $fonts = []; foreach ($this->getSource() as $css => $title) { $fonts[] = [ 'CSSClass' => $css, 'Title' => $title, ]; } $schemaData['source'] = $fonts; $schemaData['name'] = $this->getName(); $schemaData['value'] = $this->Value(); return $schemaData; } }
package p; class A{ void m(){ boolean b = (new A()) instanceof A; }; }
class TotpSetupForm include ActiveModel::Model validate :name_is_unique validates :name, presence: true attr_reader :name_taken def initialize(user, secret, code, name) @user = user @secret = secret @code = code @name = name @auth_app_config = nil end def submit @success = valid? && valid_totp_code? process_valid_submission if success FormResponse.new(success: success, errors: errors, extra: extra_analytics_attributes) end private attr_reader :user, :code, :secret, :success, :name def valid_totp_code? # The two_factor_authentication gem raises an error if the secret is nil. return false if secret.nil? new_timestamp = Db::AuthAppConfiguration.confirm(secret, code) if new_timestamp create_auth_app(user, secret, new_timestamp, name) if new_timestamp event = PushNotification::RecoveryInformationChangedEvent.new(user: user) PushNotification::HttpPush.deliver(event) end new_timestamp.present? end def process_valid_submission user.save! end def extra_analytics_attributes { totp_secret_present: secret.present?, multi_factor_auth_method: 'totp', auth_app_configuration_id: @auth_app_config&.id, } end def create_auth_app(user, secret, new_timestamp, name) @auth_app_config = Db::AuthAppConfiguration.create(user, secret, new_timestamp, name) end def name_is_unique return unless AuthAppConfiguration.exists?(user_id: @user.id, name: @name) errors.add :name, I18n.t('errors.piv_cac_setup.unique_name'), type: :unique_name @name_taken = true end end
#!/bin/bash # The following bash functions are from # https://github.com/travis-ci/travis-build/tree/master/lib/travis/build/bash travis_wait() { local timeout="${1}" if [[ "${timeout}" =~ ^[0-9]+$ ]]; then shift else timeout=20 fi local cmd=("${@}") local log_file="travis_wait_${$}.log" "${cmd[@]}" &>"${log_file}" & local cmd_pid="${!}" travis_jigger "${!}" "${timeout}" "${cmd[@]}" & local jigger_pid="${!}" local result { wait "${cmd_pid}" 2>/dev/null result="${?}" ps -p"${jigger_pid}" &>/dev/null && kill "${jigger_pid}" } if [[ "${result}" -eq 0 ]]; then printf "\\n${ANSI_GREEN}The command %s exited with ${result}.${ANSI_RESET}\\n" "${cmd[*]}" else printf "\\n${ANSI_RED}The command %s exited with ${result}.${ANSI_RESET}\\n" "${cmd[*]}" fi echo -e "\\n${ANSI_GREEN}Log:${ANSI_RESET}\\n" cat "${log_file}" return "${result}" } travis_jigger() { local cmd_pid="${1}" shift local timeout="${1}" shift local count=0 echo -e "\\n" while [[ "${count}" -lt "${timeout}" ]]; do count="$((count + 1))" echo -ne "Still running (${count} of ${timeout}): ${*}\\r" sleep 60 done echo -e "\\n${ANSI_RED}Timeout (${timeout} minutes) reached. Terminating \"${*}\"${ANSI_RESET}\\n" kill -9 "${cmd_pid}" } travis_retry() { local result=0 local count=1 while [[ "${count}" -le 3 ]]; do [[ "${result}" -ne 0 ]] && { echo -e "\\n${ANSI_RED}The command \"${*}\" failed. Retrying, ${count} of 3.${ANSI_RESET}\\n" >&2 } "${@}" && { result=0 && break; } || result="${?}" count="$((count + 1))" sleep 1 done [[ "${count}" -gt 3 ]] && { echo -e "\\n${ANSI_RED}The command \"${*}\" failed 3 times.${ANSI_RESET}\\n" >&2 } return "${result}" } travis_fold() { local action="${1}" local name="${2}" echo -en "travis_fold:${action}:${name}\\r${ANSI_CLEAR}" } travis_nanoseconds() { local cmd='date' local format='+%s%N' if hash gdate >/dev/null 2>&1; then cmd='gdate' elif [[ "${TRAVIS_OS_NAME}" == osx ]]; then format='+%s000000000' fi "${cmd}" -u "${format}" } travis_time_start() { TRAVIS_TIMER_ID="$(printf %08x $((RANDOM * RANDOM)))" TRAVIS_TIMER_START_TIME="$(travis_nanoseconds)" export TRAVIS_TIMER_ID TRAVIS_TIMER_START_TIME echo -en "travis_time:start:$TRAVIS_TIMER_ID\\r${ANSI_CLEAR}" } travis_time_finish() { local result="${?}" local travis_timer_end_time local event="${1}" travis_timer_end_time="$(travis_nanoseconds)" local duration duration="$((travis_timer_end_time - TRAVIS_TIMER_START_TIME))" echo -en "travis_time:end:${TRAVIS_TIMER_ID}:start=${TRAVIS_TIMER_START_TIME},finish=${travis_timer_end_time},duration=${duration},event=${event}\\r${ANSI_CLEAR}" return "${result}" } fold_cmd() { local name="${1}" shift local cmd=("${@}") travis_fold start ${name} "${cmd[@]}" local result="${?}" travis_fold end ${name} return "${result}" } title() { echo -e "\033[1m\033[33m${1}\033[0m" } subtitle() { echo -e "\033[34m${1}\033[0m" } # TODO: rewrite this function fold_timer_cmd() { local name="${1}" local title="${2}" shift 2 local cmd=("${@}") echo -en "travis_fold:start:${name}\\r${ANSI_CLEAR}" title "${title}" travis_time_start "${cmd[@]}" local result="${?}" travis_time_finish echo -en "travis_fold:end:${name}\\r${ANSI_CLEAR}" return "${result}" }
// Copyright 2015 Stellar Development Foundation and contributors. Licensed // under the Apache License, Version 2.0. See the COPYING file at the root // of this distribution or at http://www.apache.org/licenses/LICENSE-2.0 #include "catchup/ApplyLedgerChainWork.h" #include "herder/LedgerCloseData.h" #include "history/FileTransferInfo.h" #include "history/HistoryManager.h" #include "historywork/Progress.h" #include "invariant/InvariantDoesNotHold.h" #include "ledger/CheckpointRange.h" #include "ledger/LedgerManager.h" #include "lib/xdrpp/xdrpp/printer.h" #include "main/Application.h" #include "main/ErrorMessages.h" #include <lib/util/format.h> #include <medida/meter.h> #include <medida/metrics_registry.h> namespace stellar { ApplyLedgerChainWork::ApplyLedgerChainWork( Application& app, WorkParent& parent, TmpDir const& downloadDir, LedgerRange range, LedgerHeaderHistoryEntry& lastApplied) : Work(app, parent, std::string("apply-ledger-chain"), RETRY_NEVER) , mDownloadDir(downloadDir) , mRange(range) , mCurrSeq( mApp.getHistoryManager().checkpointContainingLedger(mRange.first())) , mLastApplied(lastApplied) , mApplyLedgerSuccess(app.getMetrics().NewMeter( {"history", "apply-ledger-chain", "success"}, "event")) , mApplyLedgerFailure(app.getMetrics().NewMeter( {"history", "apply-ledger-chain", "failure"}, "event")) { } ApplyLedgerChainWork::~ApplyLedgerChainWork() { clearChildren(); } std::string ApplyLedgerChainWork::getStatus() const { if (mState == WORK_RUNNING) { std::string task = "applying checkpoint"; return fmtProgress(mApp, task, mRange.first(), mRange.last(), mCurrSeq); } return Work::getStatus(); } void ApplyLedgerChainWork::onReset() { mLastApplied = mApp.getLedgerManager().getLastClosedLedgerHeader(); auto& lm = mApp.getLedgerManager(); auto& hm = mApp.getHistoryManager(); CLOG(INFO, "History") << "Replaying contents of " << CheckpointRange{mRange, hm}.count() << " transaction-history files from LCL " << LedgerManager::ledgerAbbrev( lm.getLastClosedLedgerHeader()); mCurrSeq = mApp.getHistoryManager().checkpointContainingLedger(mRange.first()); mHdrIn.close(); mTxIn.close(); } void ApplyLedgerChainWork::openCurrentInputFiles() { mHdrIn.close(); mTxIn.close(); FileTransferInfo hi(mDownloadDir, HISTORY_FILE_TYPE_LEDGER, mCurrSeq); FileTransferInfo ti(mDownloadDir, HISTORY_FILE_TYPE_TRANSACTIONS, mCurrSeq); CLOG(DEBUG, "History") << "Replaying ledger headers from " << hi.localPath_nogz(); CLOG(DEBUG, "History") << "Replaying transactions from " << ti.localPath_nogz(); mHdrIn.open(hi.localPath_nogz()); mTxIn.open(ti.localPath_nogz()); mTxHistoryEntry = TransactionHistoryEntry(); } TxSetFramePtr ApplyLedgerChainWork::getCurrentTxSet() { auto& lm = mApp.getLedgerManager(); auto seq = lm.getLastClosedLedgerNum() + 1; do { if (mTxHistoryEntry.ledgerSeq < seq) { CLOG(DEBUG, "History") << "Skipping txset for ledger " << mTxHistoryEntry.ledgerSeq; } else if (mTxHistoryEntry.ledgerSeq > seq) { break; } else { assert(mTxHistoryEntry.ledgerSeq == seq); CLOG(DEBUG, "History") << "Loaded txset for ledger " << seq; return std::make_shared<TxSetFrame>(mApp.getNetworkID(), mTxHistoryEntry.txSet); } } while (mTxIn && mTxIn.readOne(mTxHistoryEntry)); CLOG(DEBUG, "History") << "Using empty txset for ledger " << seq; return std::make_shared<TxSetFrame>(lm.getLastClosedLedgerHeader().hash); } bool ApplyLedgerChainWork::applyHistoryOfSingleLedger() { LedgerHeaderHistoryEntry hHeader; LedgerHeader& header = hHeader.header; if (!mHdrIn || !mHdrIn.readOne(hHeader)) { return false; } auto& lm = mApp.getLedgerManager(); auto const& lclHeader = lm.getLastClosedLedgerHeader(); // If we are >1 before LCL, skip if (header.ledgerSeq + 1 < lclHeader.header.ledgerSeq) { CLOG(DEBUG, "History") << "Catchup skipping old ledger " << header.ledgerSeq; return true; } // If we are one before LCL, check that we knit up with it if (header.ledgerSeq + 1 == lclHeader.header.ledgerSeq) { if (hHeader.hash != lclHeader.header.previousLedgerHash) { throw std::runtime_error( fmt::format("replay of {:s} failed to connect on hash of LCL " "predecessor {:s}", LedgerManager::ledgerAbbrev(hHeader), LedgerManager::ledgerAbbrev( lclHeader.header.ledgerSeq - 1, lclHeader.header.previousLedgerHash))); } CLOG(DEBUG, "History") << "Catchup at 1-before LCL (" << header.ledgerSeq << "), hash correct"; return true; } // If we are at LCL, check that we knit up with it if (header.ledgerSeq == lclHeader.header.ledgerSeq) { if (hHeader.hash != lm.getLastClosedLedgerHeader().hash) { mApplyLedgerFailure.Mark(); throw std::runtime_error( fmt::format("replay of {:s} at LCL {:s} disagreed on hash", LedgerManager::ledgerAbbrev(hHeader), LedgerManager::ledgerAbbrev(lclHeader))); } CLOG(DEBUG, "History") << "Catchup at LCL=" << header.ledgerSeq << ", hash correct"; return true; } // If we are past current, we can't catch up: fail. if (header.ledgerSeq != lclHeader.header.ledgerSeq + 1) { mApplyLedgerFailure.Mark(); throw std::runtime_error( fmt::format("replay overshot current ledger: {:d} > {:d}", header.ledgerSeq, lclHeader.header.ledgerSeq + 1)); } // If we do not agree about LCL hash, we can't catch up: fail. if (header.previousLedgerHash != lm.getLastClosedLedgerHeader().hash) { mApplyLedgerFailure.Mark(); throw std::runtime_error(fmt::format( "replay at current ledger {:s} disagreed on LCL hash {:s}", LedgerManager::ledgerAbbrev(header.ledgerSeq - 1, header.previousLedgerHash), LedgerManager::ledgerAbbrev(lclHeader))); } auto txset = getCurrentTxSet(); CLOG(DEBUG, "History") << "Ledger " << header.ledgerSeq << " has " << txset->sizeTx() << " transactions"; // We've verified the ledgerHeader (in the "trusted part of history" // sense) in CATCHUP_VERIFY phase; we now need to check that the // txhash we're about to apply is the one denoted by that ledger // header. if (header.scpValue.txSetHash != txset->getContentsHash()) { mApplyLedgerFailure.Mark(); throw std::runtime_error(fmt::format( "replay txset hash differs from txset hash in replay ledger: hash " "for txset for {:d} is {:s}, expected {:s}", header.ledgerSeq, hexAbbrev(txset->getContentsHash()), hexAbbrev(header.scpValue.txSetHash))); } LedgerCloseData closeData(header.ledgerSeq, txset, header.scpValue); lm.closeLedger(closeData); CLOG(DEBUG, "History") << "LedgerManager LCL:\n" << xdr::xdr_to_string( lm.getLastClosedLedgerHeader()); CLOG(DEBUG, "History") << "Replay header:\n" << xdr::xdr_to_string(hHeader); if (lm.getLastClosedLedgerHeader().hash != hHeader.hash) { mApplyLedgerFailure.Mark(); throw std::runtime_error(fmt::format( "replay of {:s} produced mismatched ledger hash {:s}", LedgerManager::ledgerAbbrev(hHeader), LedgerManager::ledgerAbbrev(lm.getLastClosedLedgerHeader()))); } mApplyLedgerSuccess.Mark(); mLastApplied = hHeader; return true; } void ApplyLedgerChainWork::onStart() { openCurrentInputFiles(); } void ApplyLedgerChainWork::onRun() { try { if (!applyHistoryOfSingleLedger()) { mCurrSeq += mApp.getHistoryManager().getCheckpointFrequency(); openCurrentInputFiles(); } scheduleSuccess(); } catch (InvariantDoesNotHold&) { // already displayed e.what() CLOG(ERROR, "History") << "Replay failed"; throw; } catch (std::exception& e) { CLOG(ERROR, "History") << "Replay failed: " << e.what(); scheduleFailure(); } } Work::State ApplyLedgerChainWork::onSuccess() { mApp.getCatchupManager().logAndUpdateCatchupStatus(true); auto& lm = mApp.getLedgerManager(); auto const& lclHeader = lm.getLastClosedLedgerHeader(); if (lclHeader.header.ledgerSeq == mRange.last()) { return WORK_SUCCESS; } return WORK_RUNNING; } }
namespace Hyperledger.Aries.AspNetCore.Features.CredentialDefinitions { using BlazorState; using Hyperledger.Aries.Models.Records; using System.Collections.Generic; using System.Linq; using System.Text.Json.Serialization; internal partial class CredentialDefinitionState : State<CredentialDefinitionState> { private Dictionary<string, DefinitionRecord> _CredentialDefinitionRecords; [JsonIgnore] public IReadOnlyDictionary<string, DefinitionRecord> CredentialDefinitions => _CredentialDefinitionRecords; public IReadOnlyList<DefinitionRecord> CredentialDefinitionsAsList => _CredentialDefinitionRecords.Values.ToList(); public CredentialDefinitionState() { } public override void Initialize() { _CredentialDefinitionRecords = new Dictionary<string, DefinitionRecord>(); } } }
""" Evaluators are used to assess the success or performance of candidate solutions on some predetermined set of search objectives. Unlike most other evolutionary computation frameworks, evaluators do not immediately calculate the fitness values for individuals. Instead, the raw objective scores for a given set of individuals is first calculated and stored, before the fitness values for each individual are computed according to those values according to some fitness scheme. This difference in treatment makes implementing dynamic problems, co-evolution, diversity promotion techniques, multi-objective problems, and fuzzy evaluation much easier! """ module evaluator importall common using criterion, state, core, utility, fitness, population, _deme_ export Evaluator, EvaluatorDefinition, evaluate!, call """ The base type used by all evaluators. """ abstract Evaluator """ The base type used by all evaluator definitions. """ abstract EvaluatorDefinition """ Evaluates a given phenome using a provided fitness scheme, according to a specified evaluation method. This function should be implemented by each evaluator. """ evaluate!(ev::Evaluator, ::FitnessScheme, ::Any) = error("Unimplemented evaluate!(::Evaluator, ::FitnessScheme, phenome) for evaluator: $(typeof(ev)).") """ Evaluates all unevaluated individuals within a provided deme according to a provided evaluation method. """ function evaluate!(ev::Evaluator, s::State, d::Deme) for (id, phenome) in enumerate(d.offspring.stages[ev.stage]) d.offspring.fitnesses[id] = evaluate!(ev, d.species.fitness, get(phenome)) end s.evaluations += length(d.offspring.stages[ev.stage]) end """ Evaluates all unevaluated individuals contained within a given state according to a provided evaluation method.. """ evaluate!(ev::Evaluator, s::State) = for deme in s.population.demes; evaluate!(ev, s, deme); end # Load each of the evaluators. include("evaluator/_simple.jl") include("evaluator/_tsp.jl") include("evaluator/_regression.jl") #include("evaluator/_multiplexer.jl") #include("evaluator/_ant.jl") end
/* eslint-disable no-unused-expressions */ import React from 'react'; export const navigationRef = React.createRef(); export function navigate(name, params) { navigationRef.current?.navigate(name, params, { key: Math.random().toString(), }); } export function reset(routes) { navigationRef.current?.reset(routes); } export function goBack() { navigationRef.current?.goBack(); }
import * as morgan from 'morgan'; export { morgan as log };
--- title: Algorithm author: Yuchao date: 2021-03-27 11:33:00 +0800 categories: [dev] tags: [leetcode, java, python] math: true mermaid: true --- [Link](https://leetcode.com/problems/two-sum/) JAVA HashMap ```java Map<Integer, Integer> map = new HashMap<>(); map.containskey(), map.get(), ``` Python HashMap - https://docs.python.org/3/tutorial/datastructures.html#dictionaries
import * as React from 'react'; import { storiesOf } from '@storybook/react'; import { IconHome, IconLock, IconClear, IconTickCircle, IconTick, IconClose, IconCaretUp } from '@douyinfe/semi-icons'; const stories = storiesOf('Icon', module); stories.add('Icon', () => ( <div> <div> <IconHome size="large" /> <IconLock size="small" /> <IconLock /> <IconClear /> <IconTickCircle /> <IconTick /> <IconClose /> <IconCaretUp /> </div> <div style={{ color: 'red', }} > <IconHome size="large" /> <IconLock size="small" /> <IconLock /> <IconClear /> <IconTickCircle /> <IconTick /> <IconClose /> <IconCaretUp /> </div> <div style={{ color: 'pink', }} > <IconHome size="large" /> <IconLock size="small" /> <IconLock /> <IconClear /> <IconTickCircle /> <IconTick /> <IconClose /> <IconCaretUp /> </div> </div> ));
require "winston" describe Winston::Backtrack do let(:csp) { Winston::CSP.new } subject { described_class.new(csp) } describe "#search" do context "simple assigment" do before do csp.add_variable :a, domain: [1, 2, 3, 4] csp.add_variable :b, domain: [1, 2, 3, 4] csp.add_variable :c, domain: [1, 2, 3, 4] end it "should assign variables to the first acceptable value" do expect(subject.search).to eq(a: 1, b: 1, c: 1) end it "should assign variables to the first acceptable value respecting variables that already have a value" do expect(subject.search(b: 3)).to eq(a: 1, b: 3, c: 1) end context "with constraints" do before do csp.add_constraint(:a, :b) { |a,b| a > b } csp.add_constraint(:b, :c) { |b,c| b > c } end it "should assign variables to the first acceptable value" do expect(subject.search).to eq(a: 3, b: 2, c: 1) end it "should assign variables to the first acceptable value" do expect(subject.search(b: 3)).to eq(a: 4, b: 3, c: 1) end it "should return false when it cannot fufill the constraints" do expect(subject.search(c: 3)).to be(false) end it "should return false when it cannot fufill the constraints" do csp.add_constraint(:a, :c) { |a,c| a == c * 10 } expect(subject.search).to be(false) end end end end end
<?php namespace App\Http\Controllers; use App\resulation; use Illuminate\Http\Request; use App\Http\Requests; use Redirect; use Session; use DB; session_start(); class ResulationController extends Controller { public function index(){ $data = array(); $data['title'] = "Manage Movie Resulation"; $data['resulations'] = resulation::get(); return view('admin.movie_resulation',$data); } public function store(Request $request){ $this->validate($request,["resulation_name" => "required|unique:resulations"]); $data = array(); $data['resulation_name'] = $request->resulation_name; $save = resulation::create($data); if($save){ Session::flash("success","Successfully Saved"); }else{ Session::flash("error","Failed to Saved"); } return Redirect::to("/manage-resulation"); } public function edit($resulation_id){ $data = array(); $data['title'] = "Edit-Movie-Resulation"; $data['resulations'] = resulation::get(); $data['resulation'] = resulation::find($resulation_id); return view('admin.movie_resulation',$data); } public function update(Request $request){ $this->validate($request,["resulation_name" => "required"]); $resulation_id = $request->resulation_id; $single = resulation::find($resulation_id); $single->resulation_name = $request->resulation_name; $update = $single->save(); if($update){ Session::flash("success","Successfully Updated"); }else{ Session::flash("error","Failed to Update"); } return Redirect::to("/manage-resulation"); } public function delete($resulation_id){ $delete = resulation::where("resulation_id",$resulation_id)->delete(); if($delete){ Session::flash("success","Successfully Deleted"); }else{ Session::flash("error","Failed to Delete"); } return Redirect::to("/manage-resulation"); } }
#!/bin/bash bash Do.sh "$1" "$(cat $2)"
#ifndef MATRIX_H #define MATRIX_H #include "../problem-1/array.h" // Put your class declaration here #endif
{-# language DeriveFoldable #-} {-# language DeriveFunctor #-} {-# language DeriveTraversable #-} module Core where import Protolude hiding (Type) import Data.HashSet (HashSet) import Common data Expr v = Var !v | Global !Global | Con !Constr | Lam !NameHint (Type v) (Scope1 Expr v) | Pi !NameHint (Type v) v (HashSet v) (Scope1 Expr v) | App (Expr v) (Expr v) | Let !NameHint (Type v) (Expr v) (Scope1 Expr v) | LetRegion !NameHint (Scope1 Expr v) | Box !v (Expr v) | Unbox !v (Expr v) | Keep !v (Expr v) | Remember !(HashSet v) (Expr v) deriving (Eq, Show, Foldable) type Type = Expr
#include "helper.h" #include "multimediamessage.h" #include "textmessage.h" #include <QDateTime> const QString cssMsgSend = "style=\"width:100%;margin:8px 0px 8px 60px;background-color:#cc33ff;color:#000000;\""; const QString cssMsgRecv = "style=\"width:100%;margin:8px 60px 8px 0px;background-color:#3399ff;color:#000000;\""; const QString cssImgSend = "style=\"width:100%;margin:8px 0px 8px 60px;\""; const QString cssImgRecv = "style=\"width:100%;margin:8px 60px 8px 0px;\""; const QString cssImg = "style=\"max-width:50%;height:auto;\""; const QString Helper::formatMessageForHtml(const Message* msg) { QString line; const TextMessage* tmsg = (TextMessage*) msg; const MultimediaMessage *mmsg = (MultimediaMessage*) msg; QString css = msg->isOutgoing() ? cssMsgSend : cssMsgRecv; if (msg->isMultimediaMessage() && !mmsg->getParts().last()->getContentType().startsWith("text")) { css = msg->isOutgoing() ? cssImgSend : cssImgRecv; } line.append("<div ").append(css).append(">"); if (msg->isTextMessage()) { if (tmsg->getBody().startsWith("http")) { line.append("<a href=\"").append(tmsg->getBody()).append("\">").append(tmsg->getBody()).append("</a>"); } else line.append(tmsg->getBody()); } else { Part* part = mmsg->getParts().last(); if (part->getContentType().startsWith("text")) { line.append(part->getText()); } else { const QString ctype = part->getContentType(); if (ctype.startsWith("image")) { line.append("<img ") .append(cssImg) .append(" width=\"400\" height-=\"400\" src=\"data:") .append(ctype) .append(";base64,") .append(part->getData()) .append("\" />"); } else line.append(part->getContentType()); } } line.append("</div>\n"); return line; }
#include<stdio.h> float power(float,float); int main() { float i,j,p; printf(" enter any no any power u want it to be raised"); scanf("%f %f",&i,&j); p=power(i,j); printf("%f \n",p); } float power(float i,float j) { float p; for(p=1;j>=1;j--) {p=p*i; } return (p); }
#!/bin/tcsh set PWD = $1 set ID = `cat $PWD/INFILE |grep TASK_NAME |awk '{print $2}'` set WORKDIR = `cat $PWD/INFILE |grep WORKDIR |awk '{print $2}'` if($ID == "") then echo "ERROR ID is empty!" exit 0 endif mkdir -p $WORKDIR set DATADIR = $WORKDIR/$ID set PLOTDIR = $PWD/PLOTDIR/$ID /bin/rm -rf $DATADIR /bin/rm -rf $PLOTDIR mkdir -p $DATADIR mkdir -p $PLOTDIR ## copy INFILE and INPUT into WORKDIR cp $PWD/INFILE $DATADIR/ cp $PWD/LSM_record_input $DATADIR/ set logfile = $PWD/LOG/logfile.${ID} cat /dev/null >! $logfile #echo " --> running task for $ID" #echo "WORKDIR is $WORKDIR" #csh $PWD/code_dir/c00.forward_tomography.sh $PWD $ID csh $PWD/code_dir/c00.forward_tomography.sh $PWD $ID >> & $logfile ##csh $PWD/code_dir/c00.forward_tomography.sh $PWD $ID # Convert Tomo into standard format #csh $PWD/code_dir/c02.convert_model_into_standard_format.sh $PWD $ID >>& $logfile & # to hongyu ##to_hongyu $PLOTDIR/$ID sleep 3s
/* * Copyright 2020 Nathaniel Reline * * This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. * To view a copy of this license, visit http://creativecommons.org/licenses/by-sa/4.0/ or * send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA. */ package com.github.reline.jisho import com.github.reline.jisho.dictmodels.Radical import java.io.File class RadKParser { fun parse(file: File): List<Radical> { val radk = ArrayList<Radical>() var currentRadical: Char? = null var strokes = 0 var kanji = ArrayList<Char>() file.forEachLine loop@{ if (it.startsWith('#') || it.isBlank()) { return@loop } if (it.startsWith('$')) { // new radical, save the previous one currentRadical?.let { radical -> radk.add(Radical(radical, strokes, kanji)) kanji = ArrayList() strokes = 0 } // new radical currentRadical = it[2] val start = nextNonWhitespace(3, it) val end = nextWhitespace(start, it) strokes = Integer.parseInt(it.substring(start, end)) } else { // line with just kanji on it kanji.addAll(it.toList()) } } // save the last radical. I know, nasty. currentRadical?.let { radical -> radk.add(Radical(radical, strokes, kanji)) } return radk } private fun nextNonWhitespace(startIndex: Int, s: String): Int { if (s.length <= startIndex) { throw IllegalArgumentException("No non-whitespace character after $startIndex in $s") } val c = s[startIndex] return if (c == '\n' || c == ' ' || c == '\r' || c == '\t') { nextNonWhitespace(startIndex + 1, s) } else { startIndex } } private fun nextWhitespace(startIndex: Int, s: String): Int { if (s.length <= startIndex) { return startIndex } val c = s[startIndex] return if (c == '\n' || c == ' ' || c == '\r' || c == '\t') { startIndex } else { nextWhitespace(startIndex + 1, s) } } }
using AWSBatch: JobState, SUBMITTED, PENDING, RUNNABLE, STARTING, RUNNING, SUCCEEDED, FAILED @testset "JobState" begin @testset "parse" begin @test length(instances(JobState)) == 7 @test parse(JobState, "SUBMITTED") == SUBMITTED @test parse(JobState, "PENDING") == PENDING @test parse(JobState, "RUNNABLE") == RUNNABLE @test parse(JobState, "STARTING") == STARTING @test parse(JobState, "RUNNING") == RUNNING @test parse(JobState, "SUCCEEDED") == SUCCEEDED @test parse(JobState, "FAILED") == FAILED end @testset "order" begin @test SUBMITTED < PENDING < RUNNABLE < STARTING < RUNNING < SUCCEEDED < FAILED end end
#!/bin/bash PREFIX=$1 echo "adapt rand conll" cd .. && bash ./domain_tuning_glue_all_75_25.sh adapt-glue-all-rand$PREFIX --mask_strategy=random
// Consider below. declare module MergedModule { function A(): void; } declare module MergedModule { function B(): void; } // TypeScript compiler will merge these two modules as if they were //a single definition as if it were like below; // declare module MergedModule { // function A(): void; // function B(): void; // } MergedModule.A(); MergedModule.B();
export interface ActDominioOU { Dominio: string, OU: string }
package org.cirrus.messaging.core.message; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.immutables.value.Value; import org.immutables.value.Value.Style.ImplementationVisibility; @Target({ElementType.PACKAGE, ElementType.TYPE}) @Retention(RetentionPolicy.CLASS) @Value.Style( get = {"is*", "get*"}, init = "set*", strictBuilder = true, builder = "newBuilder", typeAbstract = "Abstract*", typeImmutable = "*", deepImmutablesDetection = true, depluralize = true, visibility = ImplementationVisibility.PUBLIC, of = "new", defaults = @Value.Immutable(prehash = true)) @interface ImmutableStyle {}
# Cálculo de números primos com Fork Este algoritmo é uma implementação do cálculo de números primos com os benefícios da programação paralela usando Fork
namespace ZMM.Data.Repositories { public class PyModelRepository { } }
#![warn(clippy::all)] #![allow(clippy::new_without_default)] #![allow(clippy::unneeded_field_pattern)] pub mod client; pub mod error; pub mod raft; pub mod server; pub mod sql; pub mod storage; pub use client::Client; pub use server::Server;
import { Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { Repository } from 'typeorm'; import { Airframe } from '../entities/airframe.entity'; import { Flight } from '../entities/flight.entity'; import { Message } from '../entities/message.entity'; import { Station } from '../entities/station.entity'; @Injectable() export class AirframesService { constructor( @InjectRepository(Airframe) private readonly airframeRepository: Repository<Airframe>, @InjectRepository(Flight) private readonly flightRepository: Repository<Station>, @InjectRepository(Message) private readonly messageRepository: Repository<Message>, @InjectRepository(Station) private readonly stationRepository: Repository<Station>, ) { } async getAllAirframes(): Promise<Object> { return await this.airframeRepository .find({ order: { tail: 'ASC' }, }); } async getAirframe(id): Promise<Object> { return await this.airframeRepository .findOne(id, { relations: ["flights", "messages"] }); } }
unit SettingsFile; interface uses Winapi.ActiveX, PluginAPI_TLB, JSON; type /// <summary> /// Represents config file functionality /// </summary> TSettingsFile = class private FFilePath: string; FJSONConfig: TJSONObject; public constructor Create(const Path: string); overload; /// <param name="SettingsName"> /// %APPDATA%/ProductName/SettingsName.json /// </param> /// <param name="ProductName"> /// %APPDATA%/ProductName/SettingsName.json /// </param> /// <param name="CheckProgramDir"> /// if True checks ProgramDir/SettingsName.json and if exist use it /// </param> constructor Create(const SettingsName: string; const ProductName: string; CheckProgramDir: Boolean = False); overload; destructor Destroy; override; property ConfigNode: TJSONObject read FJSONConfig; end; implementation uses SysUtils, IOUtils; { TSettingsFile } constructor TSettingsFile.Create(const SettingsName: string; const ProductName: string; CheckProgramDir: Boolean = False); var Path: string; begin Path := TPath.Combine(ExtractFilePath((paramstr(0))), SettingsName + '.json'); if CheckProgramDir and FileExists(Path) then begin Create(Path); exit; end; Path := TPath.Combine(TPath.GetHomePath, ProductName); if not DirectoryExists(Path) then CreateDir(Path); Path := TPath.Combine(Path, SettingsName + '.json'); Create(Path); end; constructor TSettingsFile.Create(const Path: string); var Data: TBytes; begin FFilePath := Path; FJSONConfig := TJSONObject.Create; if TFile.Exists(FFilePath) then begin Data := TFile.ReadAllBytes(FFilePath); FJSONConfig.Parse(Data, 0); end; inherited Create; end; destructor TSettingsFile.Destroy; var Data: TBytes; DataSize: Integer; begin SetLength(Data, FJSONConfig.EstimatedByteSize); DataSize := FJSONConfig.ToBytes(Data, 0); FJSONConfig.Free; SetLength(Data, DataSize); TFile.WriteAllBytes(FFilePath, Data); inherited; end; end.
using MoneyFox.Foundation.Resources; using MvvmCross.Forms.Presenters.Attributes; using Xamarin.Forms.Xaml; namespace MoneyFox.Presentation.Views { [XamlCompilation(XamlCompilationOptions.Compile)] [MvxTabbedPagePresentation(WrapInNavigationPage = false, Title = "Statistics", Icon = "ic_statistics_black")] public partial class StatisticSelectorPage { public StatisticSelectorPage () { InitializeComponent(); StatisticSelectorList.ItemTapped += (sender, args) => { StatisticSelectorList.SelectedItem = null; ViewModel.GoToStatisticCommand.Execute(args.Item); }; Title = Strings.StatisticsTitle; } } }
package com.example.munchkinhelper.recycler import android.view.ViewGroup import androidx.recyclerview.widget.RecyclerView import com.example.munchkinhelper.R class PlayerRecyclerViewAdapter: RecyclerView.Adapter<PlayerRecyclerViewHolder>() { var items = listOf<PlayerRecyclerViewItem>() set(value) { field = value notifyDataSetChanged() } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): PlayerRecyclerViewHolder { if(viewType== R.layout.player_item){ PlayerRecyclerViewHolder } } override fun onBindViewHolder(holder: PlayerRecyclerViewHolder, position: Int) { TODO("Not yet implemented") } override fun getItemViewType(position: Int): Int { return super.getItemViewType(position) } override fun getItemCount(): Int { TODO("Not yet implemented") } }
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\User; use App\Alumni; use App\Req; use App\Alert; use Auth; use App\Mail\ApprovedAlumniRequest; use Session; class AlumniController extends Controller { public function showAlumniRequests(){ $user = User::findOrFail(auth()->id()); if($user->role!= 1){ abort(403); } $reqs = Req::paginate(8); $userCollections = array(); // foreach($reqs as $req){ $userCollections[] = User::findOrFail($req->user_id); }//loop return view('alumni-actions.alumni_request')->withUsers($userCollections); }//func public function applyForAlumni(){ $current_user = User::findOrFail(auth()->id()); if($current_user->role!= 3){ abort(403); } $get = Req::find(auth()->id()); if(is_null($get)){ $apply = new Req(); $apply->user_id = auth()->id(); $apply->save(); Session::flash('success', 'You application is submitted, wait for approval'); } // //return view('alumni_actions.alumni_requests')->with return redirect('get-form')->with(auth()->id()); }//func public function showAlumniForm(){ $current_user = User::findOrFail(auth()->id()); if($current_user->role!= 3){ abort(403); } $user = Req::where('user_id', auth()->id())->first(); return view('alumni-actions.alumni_form')->withUser($user); }//func public function acceptAlumniRequest($user_id){ $current_user = User::findOrFail(auth()->id()); if($current_user->role!= 1){ abort(403); } $user = User::findOrFail($user_id); $user->role = 2; $user->save(); //send mail \Mail::to($user->email)->send( new ApprovedAlumniRequest() ); //make a record on alumni table $alumni = new Alumni(); $alumni->user_id = $user->id; $alumni->save(); Session::flash('success','Successfully accepted an student as an alumni'); //Session::flash('success', 'Job post is created successfully'); //created notification $alert = new Alert(); $alert->type = 1; $alert->owner_id = $user_id; $alert->save(); return redirect("delete-req/$user->id"); } //func public function deleteAlumniRequest($user_id){ $current_user = User::findOrFail(auth()->id()); if($current_user->role!= 1){ abort(403); } // dd('inside delete func'); $req = Req::where('user_id', $user_id)->first(); if(is_null($req) == false) { $req->delete(); return redirect('show-reqs'); } return back(); }//func } //class
//package com.github.ddth.kafka.test; // //import java.util.Arrays; //import java.util.HashSet; //import java.util.Set; //import java.util.concurrent.Future; //import java.util.concurrent.TimeUnit; // //import com.github.ddth.kafka.IKafkaMessageListener; //import com.github.ddth.kafka.KafkaMessage; // //import junit.framework.Test; //import junit.framework.TestSuite; // //public class KafkaClientTest extends BaseKafkaTest { // // public KafkaClientTest(String testName) { // super(testName); // } // // public static Test suite() { // return new TestSuite(KafkaClientTest.class); // } // // private final static String TOPIC = "test"; // private final String CONSUMER_GROUP_ID = "mygroupid"; // // @org.junit.Test // public void testNewInstance() throws Exception { // assertNotNull(kafkaClient); // } // // @org.junit.Test // public void testSendSyncConsumeOneByOne() throws Exception { // createTopic(TOPIC); // warnup(TOPIC, CONSUMER_GROUP_ID); // // final Set<String> TEST_MSGS = new HashSet<String>(Arrays.asList("message - 0", // "message - 1", "message - 2", "message - 3", "message - 4", "message - 5", // "message - 6", "message - 7", "message - 8", "message - 9")); // for (String content : TEST_MSGS) { // KafkaMessage msg = new KafkaMessage(TOPIC, content, content); // KafkaMessage result = kafkaClient.sendMessage(msg); // assertNotNull(result); // } // // for (int i = 0, n = TEST_MSGS.size(); i < n; i++) { // KafkaMessage msg = kafkaClient.consumeMessage(CONSUMER_GROUP_ID, true, TOPIC, 5000, // TimeUnit.MILLISECONDS); // String strMsg = msg.contentAsString(); // assertTrue(TEST_MSGS.contains(strMsg)); // TEST_MSGS.remove(strMsg); // } // } // // @org.junit.Test // public void testSendAsyncConsumeOneByOne() throws Exception { // createTopic(TOPIC); // warnup(TOPIC, CONSUMER_GROUP_ID); // // final Set<String> TEST_MSGS = new HashSet<String>(Arrays.asList("message - 0", // "message - 1", "message - 2", "message - 3", "message - 4", "message - 5", // "message - 6", "message - 7", "message - 8", "message - 9")); // for (String content : TEST_MSGS) { // KafkaMessage msg = new KafkaMessage(TOPIC, content, content); // Future<KafkaMessage> result = kafkaClient.sendMessageAsync(msg); // assertNotNull(result); // } // // for (int i = 0, n = TEST_MSGS.size(); i < n; i++) { // KafkaMessage msg = kafkaClient.consumeMessage(CONSUMER_GROUP_ID, true, TOPIC, 10000, // TimeUnit.MILLISECONDS); // String strMsg = msg.contentAsString(); // assertTrue(TEST_MSGS.contains(strMsg)); // TEST_MSGS.remove(strMsg); // } // } // // @org.junit.Test // public void testSendSyncConsumeListenerAfter() throws Exception { // createTopic(TOPIC); // warnup(TOPIC, CONSUMER_GROUP_ID); // // final Set<String> TEST_MSGS = new HashSet<String>(Arrays.asList("message - 0", // "message - 1", "message - 2", "message - 3", "message - 4", "message - 5", // "message - 6", "message - 7", "message - 8", "message - 9")); // for (String content : TEST_MSGS) { // KafkaMessage msg = new KafkaMessage(TOPIC, content); // KafkaMessage result = kafkaClient.sendMessage(msg); // assertNotNull(result); // } // // final Set<String> RECEIVED_MSG = new HashSet<String>(); // IKafkaMessageListener msgListener = new IKafkaMessageListener() { // @Override // public void onMessage(KafkaMessage message) { // String msgStr = message != null ? message.contentAsString() : null; // RECEIVED_MSG.add(msgStr); // } // }; // kafkaClient.addMessageListener(CONSUMER_GROUP_ID, true, TOPIC, msgListener); // long t = System.currentTimeMillis(); // while (RECEIVED_MSG.size() < TEST_MSGS.size() && System.currentTimeMillis() - t < 30000) { // Thread.sleep(1); // } // // assertEquals(TEST_MSGS.size(), RECEIVED_MSG.size()); // assertEquals(TEST_MSGS, RECEIVED_MSG); // } // // @org.junit.Test // public void testSendAsyncConsumeListenerAfter() throws Exception { // createTopic(TOPIC); // warnup(TOPIC, CONSUMER_GROUP_ID); // // final Set<String> TEST_MSGS = new HashSet<String>(Arrays.asList("message - 0", // "message - 1", "message - 2", "message - 3", "message - 4", "message - 5", // "message - 6", "message - 7", "message - 8", "message - 9")); // for (String content : TEST_MSGS) { // KafkaMessage msg = new KafkaMessage(TOPIC, content); // Future<KafkaMessage> result = kafkaClient.sendMessageAsync(msg); // assertNotNull(result); // } // // final Set<String> RECEIVED_MSG = new HashSet<String>(); // IKafkaMessageListener msgListener = new IKafkaMessageListener() { // @Override // public void onMessage(KafkaMessage message) { // String msgStr = message != null ? message.contentAsString() : null; // RECEIVED_MSG.add(msgStr); // } // }; // kafkaClient.addMessageListener(CONSUMER_GROUP_ID, true, TOPIC, msgListener); // long t = System.currentTimeMillis(); // while (RECEIVED_MSG.size() < TEST_MSGS.size() && System.currentTimeMillis() - t < 30000) { // Thread.sleep(1); // } // // assertEquals(TEST_MSGS.size(), RECEIVED_MSG.size()); // assertEquals(TEST_MSGS, RECEIVED_MSG); // } // // @org.junit.Test // public void testSendSyncConsumeListenerBefore() throws Exception { // createTopic(TOPIC); // warnup(TOPIC, CONSUMER_GROUP_ID); // // final Set<String> RECEIVED_MSG = new HashSet<String>(); // IKafkaMessageListener msgListener = new IKafkaMessageListener() { // @Override // public void onMessage(KafkaMessage message) { // String msgStr = message != null ? message.contentAsString() : null; // RECEIVED_MSG.add(msgStr); // } // }; // kafkaClient.addMessageListener(CONSUMER_GROUP_ID, true, TOPIC, msgListener); // // final Set<String> TEST_MSGS = new HashSet<String>(Arrays.asList("message - 0", // "message - 1", "message - 2", "message - 3", "message - 4", "message - 5", // "message - 6", "message - 7", "message - 8", "message - 9")); // for (String content : TEST_MSGS) { // KafkaMessage msg = new KafkaMessage(TOPIC, content); // KafkaMessage result = kafkaClient.sendMessage(msg); // assertNotNull(result); // } // long t = System.currentTimeMillis(); // while (RECEIVED_MSG.size() < TEST_MSGS.size() && System.currentTimeMillis() - t < 30000) { // Thread.sleep(1); // } // // assertEquals(TEST_MSGS.size(), RECEIVED_MSG.size()); // assertEquals(TEST_MSGS, RECEIVED_MSG); // } // // @org.junit.Test // public void testSendAsyncConsumeListenerBefore() throws Exception { // createTopic(TOPIC); // warnup(TOPIC, CONSUMER_GROUP_ID); // // final Set<String> RECEIVED_MSG = new HashSet<String>(); // IKafkaMessageListener msgListener = new IKafkaMessageListener() { // @Override // public void onMessage(KafkaMessage message) { // String msgStr = message != null ? message.contentAsString() : null; // RECEIVED_MSG.add(msgStr); // } // }; // kafkaClient.addMessageListener(CONSUMER_GROUP_ID, true, TOPIC, msgListener); // // final Set<String> TEST_MSGS = new HashSet<String>(Arrays.asList("message - 0", // "message - 1", "message - 2", "message - 3", "message - 4", "message - 5", // "message - 6", "message - 7", "message - 8", "message - 9")); // for (String content : TEST_MSGS) { // KafkaMessage msg = new KafkaMessage(TOPIC, content); // Future<KafkaMessage> result = kafkaClient.sendMessageAsync(msg); // assertNotNull(result); // } // long t = System.currentTimeMillis(); // while (RECEIVED_MSG.size() < TEST_MSGS.size() && System.currentTimeMillis() - t < 30000) { // Thread.sleep(1); // } // // assertEquals(TEST_MSGS.size(), RECEIVED_MSG.size()); // assertEquals(TEST_MSGS, RECEIVED_MSG); // } //}
<div> <a class="dropdown-item" wire:click="logout" style="cursor: pointer">Keluar</a> </div>
export const ENHANCER_ATTRIBUTE = 'faceit-enhancer' export const setFeatureAttribute = (featureName, element) => element.setAttribute(`${ENHANCER_ATTRIBUTE}-${featureName}`, '') export const hasFeatureAttribute = (featureName, element) => element.hasAttribute(`${ENHANCER_ATTRIBUTE}-${featureName}`) export const setStyle = (element, style) => element.setAttribute( 'style', typeof style === 'string' ? `${style}` : style.join(';') )
package runner import ( "strings" ) // ExposedPorts is a simple type that holds port mappings. type ExposedPorts map[string]string // ToEnvVars returns a map that represents these port mappings as environment // variables, in the form ${LABEL}_PORT=${PORT_NUMBER}. // // The result can be piped through conv.ToOptionsSlice to turn it into a slice. func (e ExposedPorts) ToEnvVars() map[string]string { ret := make(map[string]string, len(e)) for label, port := range e { k := strings.ToUpper(strings.TrimSpace(label)) + "_PORT" ret[k] = port } return ret }
#!/bin/bash for i in $(seq 1 10000); do echo -n "RUN $i: " cp -r model run_$i cp testcases/$i/outG.txt run_$i/. cp testcases/$i/test.c run_$i/test.cpp cd run_$i ./run.sh >run_$i.log 2>&1 if [[ "$?" -eq "0" ]]; then echo "PASSED" cd .. rm -rf run_$i else echo "FAILED" cd .. cp -r run_$i failed/failed_$i rm -rf run_$i fi done
; was there a DO event ? include win1_keys_wstatus include win1_keys_qdos_pt section utility xdef xwm_done ; you DID it ;+++ ; was there a DO event ? ; (it gets cleared) ; ; Entry Exit ; a1 status area preserved ; ; CCR: Z yes, there was a DO ;--- xwm_done bclr #pt..do,wsp_weve(a1) rts end
/*----------------------------------------------------------------------- Copyright (c) Microsoft Corporation. Licensed under the MIT license. -----------------------------------------------------------------------*/ INSERT INTO [dbo].[ActivityAudit] ([ExecutionUid] ,[TaskInstanceId] ,[AdfRunUid] ,[LogTypeId] ,[LogSource] ,[LogDateUTC] ,[LogDateTimeOffSet] ,[Status] ,[Comment]) SELECT [ExecutionUid] ,[TaskInstanceId] ,[AdfRunUid] ,[LogTypeId] ,[LogSource] ,[LogDateUTC] ,[LogDateTimeOffSet] ,[Status] ,[Comment] FROM {tmpActivityAudit}
import { h, defineComponent } from "vue"; import { Icon as IconifyIcon } from "@iconify/vue"; // Iconify Icon在Vue里在线使用(用于外网环境) // https://docs.iconify.design/icon-components/vue/offline.html export default defineComponent({ name: "IconifyIcon", components: { IconifyIcon }, props: { icon: { type: String, default: "" }, type: { type: String, default: "ep:" } }, render() { return h( IconifyIcon, { icon: `${this.type}${this.icon}` }, { default: () => [] } ); } });
require "spec_helper" describe "Number Utils" do describe 'should return same length value using default text' do let(:random_float) { DataAnon::Utils::RandomFloat.generate(5,10) } it { random_float.should be_between(5,10) } it { random_float.should be_a_kind_of Float } end end
module Aws.S3.Commands.CopyObject where import Aws.Core import Aws.S3.Core import Control.Applicative import Control.Arrow (second) import Control.Monad.Trans.Resource (throwM) import qualified Data.CaseInsensitive as CI import Data.Maybe import qualified Data.Text as T import qualified Data.Text.Encoding as T import Data.Time import qualified Network.HTTP.Conduit as HTTP import Text.XML.Cursor (($/), (&|)) import System.Locale data CopyMetadataDirective = CopyMetadata | ReplaceMetadata [(T.Text,T.Text)] deriving (Show) data CopyObject = CopyObject { coObjectName :: T.Text , coBucket :: Bucket , coSource :: ObjectId , coMetadataDirective :: CopyMetadataDirective , coIfMatch :: Maybe T.Text , coIfNoneMatch :: Maybe T.Text , coIfUnmodifiedSince :: Maybe UTCTime , coIfModifiedSince :: Maybe UTCTime , coStorageClass :: Maybe StorageClass , coAcl :: Maybe CannedAcl } deriving (Show) copyObject :: Bucket -> T.Text -> ObjectId -> CopyMetadataDirective -> CopyObject copyObject bucket obj src meta = CopyObject obj bucket src meta Nothing Nothing Nothing Nothing Nothing Nothing data CopyObjectResponse = CopyObjectResponse { corVersionId :: Maybe T.Text , corLastModified :: UTCTime , corETag :: T.Text } deriving (Show) -- | ServiceConfiguration: 'S3Configuration' instance SignQuery CopyObject where type ServiceConfiguration CopyObject = S3Configuration signQuery CopyObject {..} = s3SignQuery S3Query { s3QMethod = Put , s3QBucket = Just $ T.encodeUtf8 coBucket , s3QObject = Just $ T.encodeUtf8 coObjectName , s3QSubresources = [] , s3QQuery = [] , s3QContentType = Nothing , s3QContentMd5 = Nothing , s3QAmzHeaders = map (second T.encodeUtf8) $ catMaybes [ Just ("x-amz-copy-source", oidBucket `T.append` "/" `T.append` oidObject `T.append` case oidVersion of Nothing -> T.empty Just v -> "?versionId=" `T.append` v) , Just ("x-amz-metadata-directive", case coMetadataDirective of CopyMetadata -> "COPY" ReplaceMetadata _ -> "REPLACE") , ("x-amz-copy-source-if-match",) <$> coIfMatch , ("x-amz-copy-source-if-none-match",) <$> coIfNoneMatch , ("x-amz-copy-source-if-unmodified-since",) <$> textHttpDate <$> coIfUnmodifiedSince , ("x-amz-copy-source-if-modified-since",) <$> textHttpDate <$> coIfModifiedSince , ("x-amz-acl",) <$> writeCannedAcl <$> coAcl , ("x-amz-storage-class",) <$> writeStorageClass <$> coStorageClass ] ++ map ( \x -> (CI.mk . T.encodeUtf8 $ T.concat ["x-amz-meta-", fst x], snd x)) coMetadata , s3QOtherHeaders = map (second T.encodeUtf8) $ catMaybes [] , s3QRequestBody = Nothing } where coMetadata = case coMetadataDirective of CopyMetadata -> [] ReplaceMetadata xs -> xs ObjectId{..} = coSource instance ResponseConsumer CopyObject CopyObjectResponse where type ResponseMetadata CopyObjectResponse = S3Metadata responseConsumer _ mref = flip s3ResponseConsumer mref $ \resp -> do let vid = T.decodeUtf8 `fmap` lookup "x-amz-version-id" (HTTP.responseHeaders resp) (lastMod, etag) <- xmlCursorConsumer parse mref resp return $ CopyObjectResponse vid lastMod etag where parse el = do let parseHttpDate' x = case parseTime defaultTimeLocale iso8601UtcDate x of Nothing -> throwM $ XmlException ("Invalid Last-Modified " ++ x) Just y -> return y lastMod <- forceM "Missing Last-Modified" $ el $/ elContent "LastModified" &| (parseHttpDate' . T.unpack) etag <- force "Missing ETag" $ el $/ elContent "ETag" return (lastMod, etag) instance Transaction CopyObject CopyObjectResponse instance AsMemoryResponse CopyObjectResponse where type MemoryResponse CopyObjectResponse = CopyObjectResponse loadToMemory = return
import pathlib # import some important classes to the main module from .sim_finger import SimFinger # noqa from .action import Action # noqa from .observation import Observation # noqa from .trifinger_platform import ( # noqa TriFingerPlatform, ObjectPose, CameraObservation, TriCameraObjectObservation, ) def get_data_dir() -> pathlib.Path: """Get path to the data directory of this package.""" p = pathlib.Path(__file__) return p.parent / "data"
1. Mom 2. Dad 3. Anime 1. One Piece 2. Naruto
package com.acmerobotics.roadrunner.trajectory import com.acmerobotics.roadrunner.Pose2d /** * Generic trajectory segment. */ interface TrajectorySegment { /** * Returns the duration of the segment. */ fun duration(): Double /** * Returns the pose at the given [time]. */ operator fun get(time: Double): Pose2d /** * Returns the pose velocity at the given [time]. */ fun velocity(time: Double): Pose2d /** * Returns the pose acceleration at the given [time]. */ fun acceleration(time: Double): Pose2d }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Windows.Input; using Hanselman.Helpers; using Xamarin.Essentials; using Xamarin.Forms; namespace Hanselman.Models { public class SocialItem { public SocialItem() { OpenUrlCommand = new Command(async () => await OpenSocialUrl()); } public string Icon { get; set; } public string Url { get; set; } public ICommand OpenUrlCommand { get; } async Task OpenSocialUrl() { if (Url.Contains("twitter")) { var launch = DependencyService.Get<ILaunchTwitter>(); if (launch?.OpenUserName("shanselman") ?? false) return; } await Browser.OpenAsync(Url); } } }
#!/usr/bin/env bash set -e COMMANDDIR="${PWD}/bin" COMMAND=$COMMANDDIR/xxx declare -a ARGS=( \ "-foo bar" \ ) for ARG in ${ARGS[@]} do PREARGS="$PREARGS $ARG" done set -x ${COMMAND} ${PREARGS} $@ set +x
<?php defined('BASEPATH') OR exit('No direct script access allowed'); class Sampah_model extends CI_Model { public function getAllSampah() { // return $this->db->get('sampah')->result_array(); $query = $this->db->select('*')->from('sampah') ->join('tps', 'tps.id_tps = sampah.id_tps') ->join('tpa', 'tpa.id_tpa = tps.id_tpa') ->join('jenis_sampah', 'jenis_sampah.id_jenis_sampah = sampah.id_jenis_sampah') ->get()->result_array(); return $query; } public function getSampahByIdSampah($id_sampah) { $query = $this->db->select("*") ->from("sampah") ->where('id_sampah', $id_sampah) ->get() ->result_array(); if (!empty($query)) { return $query; } else { return false; } } public function getAllSampahByIdTps($id_tps) { $query = $this->db->select('*')->from('sampah')->where('id_tps', $id_tps) ->where('tertampung', 1) ->or_where('tertampung', 2) ->get(); if ($query->num_rows() > 0) { return $query->result_array(); } else { return null; } } public function getAllSampahByIdTpa($id_tpa) { $query = $this->db->select('*')->from('sampah') ->join('tps', 'tps.id_tps = sampah.id_tps') ->join('tpa', 'tpa.id_tpa = tps.id_tpa') ->where('tpa.id_tpa', $id_tpa) ->where('tertampung', 1) ->or_where('tertampung', 2) ->get(); if ($query->num_rows() > 0) { return $query->result_array(); } else { return null; } } public function getSampahDetail($id_sampah) { $query = $this->db->select('*')->from('sampah') ->join('jenis_sampah', 'sampah.id_jenis_sampah = jenis_sampah.id_jenis_sampah') ->join('tps', 'sampah.id_tps = tps.id_tps') ->where('id_sampah', $id_sampah) ->get(); if ($query->num_rows() > 0) { return $query->result_array(); } else { return null; } } public function getAllSampahByIdTpsCount($id_tps) { $query = $this->db->select('*')->from('sampah')->where('id_tps', $id_tps) ->where('tertampung', 1) ->or_where('tertampung', 2) ->get()->result_array(); $jenis_sampah = $this->db->get('jenis_sampah')->result_array(); $data = []; $index = 0; foreach ( $jenis_sampah as $js ) { $data[$index]['nama_jenis_sampah'] = null; foreach($query as $s) { if ($s['id_jenis_sampah'] == $js['id_jenis_sampah']) { // $data[$index][$js['nama_jenis_sampah']] += 1; // $data[$index]['nama_jenis_sampah'] += 1; $data[$index]['nama_jenis_sampah'] += $s['berat']; } } $index++; } return $data; } public function getAllSampahByIdTpaCount($id_tpa) { $query = $this->db->select('*')->from('sampah') ->join('jenis_sampah', 'sampah.id_jenis_sampah = jenis_sampah.id_jenis_sampah') ->join('tps', 'sampah.id_tps = tps.id_tps') ->where('id_tpa', $id_tpa) ->where('tertampung', 1) ->or_where('tertampung', 2) ->get()->result_array(); $jenis_sampah = $this->db->get('jenis_sampah')->result_array(); $data = []; $index = 0; foreach ( $jenis_sampah as $js ) { $data[$index]['nama_jenis_sampah'] = null; foreach($query as $s) { if ($s['id_jenis_sampah'] == $js['id_jenis_sampah']) { // $data[$index][$js['nama_jenis_sampah']] += 1; // $data[$index]['nama_jenis_sampah'] += 1; $data[$index]['nama_jenis_sampah'] += $s['berat']; } } $index++; } return $data; } public function addSampah($data) { if ($this->form_validation->run() == TRUE) { // $data['gambar'] = $this->do_upload('sampah', 'gambar'); $this->db->insert('sampah', $data); return $this->db->affected_rows(); } else { return 0; } } public function do_upload($type, $gambar) { $this->load->helper(array('form', 'url')); $now = date('dmYHis'); $config['upload_path'] = "./assets/$type"; $config['allowed_types'] = 'gif|jpg|png'; $config['max_size'] = 10000; $config['file_name'] = $now; $this->load->library('upload',$config); if ( ! $this->upload->do_upload($gambar)) { $error = array('error' => $this->upload->display_errors()); $this->response($error, REST_Controller::HTTP_BAD_REQUEST); } else { $data = array('upload_data' => $this->upload->data()); $data = array('upload_data' => $this->upload->data()); return $type . '/' . $data['upload_data']['file_name']; } } public function getSampahByIdTpsNotTertampung($id_tps) { $query = $this->db->select('*')->from('sampah')->where('id_tps', $id_tps)->where('tertampung', 0)->get(); if ($query->num_rows() > 0) { return $query->result_array(); } else { return null; } } public function getSampahByIdTpaAndTps($id_tpa, $id_tps) { $query = $this->db->select('*')->from('sampah') ->join('tps', 'tps.id_tps = sampah.id_tps') ->where('tps.id_tpa', $id_tpa) ->where('sampah.id_tps', $id_tps) ->where('tertampung', 1)->get(); if ($query->num_rows() > 0) { return $query->result_array(); } else { return null; } } public function getSampahInTps($id_tps) { $query = $this->db->select('*')->from('sampah')->where('id_tps', $id_tps) ->where('tertampung', 1) ->or_where('tertampung !=', 2) ->get(); if ($query->num_rows() > 0) { return $query->result_array(); } else { return null; } } public function adminGetGrafik() { $query = $this->db->select('*')->from('sampah') ->join('jenis_sampah', 'sampah.id_jenis_sampah = jenis_sampah.id_jenis_sampah') ->join('tps', 'sampah.id_tps = tps.id_tps') ->where('tertampung', 1) ->or_where('tertampung', 2) ->get()->result_array(); $jenis_sampah = $this->db->get('jenis_sampah')->result_array(); $data = []; $index = 0; foreach ( $jenis_sampah as $js ) { $data[$index]['nama_jenis_sampah'] = null; foreach($query as $s) { if ($s['id_jenis_sampah'] == $js['id_jenis_sampah']) { // $data[$index][$js['nama_jenis_sampah']] += 1; $data[$index]['nama_jenis_sampah'] += $s['berat']; } } $index++; } return $data; } public function deleteSampah($id_sampah) { $this->db->delete('sampah', ["id_sampah" => $id_sampah]); return $this->db->affected_rows(); } } /* End of file Sampah_model.php */