text
stringlengths 27
775k
|
---|
package main
// autoformat-ignore (gofmt chokes on invalid programs)
// Example file with a syntax error to demonstrate use of consistency queries
This is not a valid Go program
|
Rails.application.routes.draw do
resources:users
resources:products
resources:orders
end
|
### [UnrealEngine.Framework](./UnrealEngine-Framework.md 'UnrealEngine.Framework').[MaterialInstanceDynamic](./MaterialInstanceDynamic.md 'UnrealEngine.Framework.MaterialInstanceDynamic')
## MaterialInstanceDynamic.SetTextureParameterValue(string, UnrealEngine.Framework.Texture) Method
Sets the texture parameter value
```csharp
public void SetTextureParameterValue(string parameterName, UnrealEngine.Framework.Texture value);
```
#### Parameters
<a name='UnrealEngine-Framework-MaterialInstanceDynamic-SetTextureParameterValue(string_UnrealEngine-Framework-Texture)-parameterName'></a>
`parameterName` [System.String](https://docs.microsoft.com/en-us/dotnet/api/System.String 'System.String')
<a name='UnrealEngine-Framework-MaterialInstanceDynamic-SetTextureParameterValue(string_UnrealEngine-Framework-Texture)-value'></a>
`value` [Texture](./Texture.md 'UnrealEngine.Framework.Texture')
|
import mysql.connector.pooling
from util.db.config import config_dict
db_pool = mysql.connector.pooling.MySQLConnectionPool(**config_dict, charset="utf8mb4", pool_name="pool", pool_size=32)
|
import React from 'react'
import './style.css'
import { useTranslation } from 'react-i18next'
import Parser from 'html-react-parser'
const Foot = () => {
const { t } = useTranslation()
const links = t('foot.links', { returnObjects: true })
return (
<footer id="Foot">
<p>{Parser(t('foot.text'))}</p>
<div className="links">
{links.map((link, key) => {
return (
<a href={t(link.url)} key={key} target="_blank" rel="noreferrer">
{t(link.name)}
</a>
)
})}
</div>
</footer>
)
}
export default Foot
|
#!/bin/bash
if [ -z ${PLUGIN_WEBHOOK+x} ]; then
if [ -z ${TEAMS_WEBHOOK+x} ]; then
echo "Need to set teams_webhook URL"
exit 1
else
WEBHOOK="$TEAMS_WEBHOOK"
fi
else
WEBHOOK="$PLUGIN_WEBHOOK"
fi
if [ "$DRONE_TAG" = "" ]; then
PROJECT_VERSION="$DRONE_COMMIT_SHA"
else
PROJECT_VERSION="$DRONE_TAG"
fi
DATE='+%d.%m.%Y %H:%M'
datestr=$(date --date=@${DRONE_BUILD_FINISHED} "${DATE}")
cp /tmp/basic_card.json /tmp/card_to_send.json
sed -i "s/TEMPLATE_BUILD_URL/${DRONE_BUILD_LINK//\//\\/}/" /tmp/card_to_send.json
sed -i "s;TEMPLATE_PROJECT_NAME;${DRONE_REPO};" /tmp/card_to_send.json
sed -i "s/TEMPLATE_PROJECT_VERSION/${PROJECT_VERSION}/" /tmp/card_to_send.json
COMMIT_MSG_ESCAPED=$(echo ${DRONE_COMMIT_MESSAGE} |sed "s/;/\;/g")
sed -i "s;TEMPLATE_COMMIT_MESSAGE;${COMMIT_MSG_ESCAPED};" /tmp/card_to_send.json
sed -i "s;TEMPLATE_COMMIT_URL;${DRONE_COMMIT_LINK};" /tmp/card_to_send.json
sed -i "s/TEMPLATE_AUTHOR/${DRONE_COMMIT_AUTHOR}/" /tmp/card_to_send.json
sed -i "s/TEMPLATE_FULLNAME/${DRONE_COMMIT_AUTHOR_NAME}/" /tmp/card_to_send.json
sed -i "s/TEMPLATE_FINISHED/${datestr}/" /tmp/card_to_send.json
sed -i "s;TEMPLATE_IMAGE_AUTHOR;${DRONE_COMMIT_AUTHOR_AVATAR};" /tmp/card_to_send.json
if [ "$DRONE_BUILD_STATUS" = "failure" ]
then
sed -i 's/TEMPLATE_STATUS_ICON/\❌ Failed /' /tmp/card_to_send.json
sed -i 's/TEMPLATE_COLOR/c60000/' /tmp/card_to_send.json
else
sed -i 's/TEMPLATE_STATUS_ICON/\✔ Succesful /' /tmp/card_to_send.json
sed -i 's/TEMPLATE_COLOR/00c61e/' /tmp/card_to_send.json
fi
sed -i "s/TEMPLATE_TITLE/$PLUGIN_TITLE/" /tmp/card_to_send.json
cat /tmp/card_to_send.json
curl -H "Content-Type: application/json" -X POST -d @/tmp/card_to_send.json "$WEBHOOK"
|
# timeline
Timeline Techphoria 2018
Live preview: https://dinaskoding.github.io/timeline/
|
# Temp sensor poller for raspberry pi
This is an attempt to be a pure golang program to poll a temperature sensor on
a raspberry pi. This is designed to work with a DHT22/AM2302 sensor that can
sense temperature and humidity.
This program uses go channels for timeouts, because the underlying libraries
that I'm using are buggy and will sometimes just hang or report mismatches. To
work around that (and not have to fall back to python), we simply time out if
the result isn't returned fast enough and bubble up other errors.
# Usage
build the program
$ make deps
$ make
From there, you can run `./sensor_poll`.
Currently, valid data is output on stdout. Errors and exceptions (of which
there appear to be several) are logged on stderr.
# Installation
If you want to install it, the program sensor_poll will be placed in
`/usr/local/bin`. A systemd unit will be placed in `/etc/systemd/system`. You can
then use standard systemd interactions for start/stop/journal query etc.
# GPIO PIN
This program assumes your GPIO sensor pin is pin 4. To change that, set the
GPIO_PIN environment variable prior to running.
# License

WTFPL
|
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
class creation_model extends CI_Model
{
public function ListOfAdmin(){
$this->db->select("*");
$this->db->from('admin');
$query = $this->db->get();
return $query->result();
}
var $table_admin = 'admin';
public function AdminCreateRequest($CreateAdminData){
$this->db->insert($this->table_admin, $CreateAdminData);
return $this->db->insert_id();
}
function getAll(){
$query=$this->db->query("SELECT * FROM admin");
return $query->result();
//returns from this string in the db, converts it into an array
}
function GetAdminDetails($id){
$query=$this->db->query("SELECT * FROM admin where admin_id='$id'");
return $query->result();
//returns from this string in the db, converts it into an array
}
public function signleadmindetails(){
$id = $this->input->get('id');
$this->db->where('admin_id', $id);
$query = $this->db->get('admin');
if($query->num_rows() > 0){
return $query->row();
}else{
return false;
}
}
public function updateAdminIndividual(){
$id = $this->input->post('admin_id');
$field = array(
'username'=>$this->input->post('username'),
'password'=>$this->input->post('password'),
//'updated_at'=>date('Y-m-d H:i:s')
);
$this->db->where('admin_id', $id);
$this->db->update('admin', $field);
if($this->db->affected_rows() > 0){
return true;
}else{
return false;
}
}
} |
// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package net
import (
"os"
"syscall"
)
func FileConn(f *os.File) (c Conn, err os.Error) {
// TODO: Implement this
return nil, os.NewSyscallError("FileConn", syscall.EWINDOWS)
}
func FileListener(f *os.File) (l Listener, err os.Error) {
// TODO: Implement this
return nil, os.NewSyscallError("FileListener", syscall.EWINDOWS)
}
func FilePacketConn(f *os.File) (c PacketConn, err os.Error) {
// TODO: Implement this
return nil, os.NewSyscallError("FilePacketConn", syscall.EWINDOWS)
}
|
// Copyright (c) 2018 Blackfynn, Inc. All Rights Reserved.
package com.blackfynn.upload.acceptance
import java.security.MessageDigest
import akka.http.scaladsl.model.HttpRequest
import akka.http.scaladsl.model.StatusCodes._
import akka.http.scaladsl.testkit.ScalatestRouteTest
import akka.stream.scaladsl.Source
import cats.implicits._
import com.amazonaws.services.dynamodbv2.model.ResourceNotFoundException
import com.pennsieve.service.utilities.ContextLogger
import com.blackfynn.upload.HashPorts.GetChunkHashes
import com.blackfynn.upload.StubPorts._
import com.blackfynn.upload.StubRoutes._
import com.blackfynn.upload.TestAuthentication.{ addJWT, generateClaim, makeToken }
import com.blackfynn.upload.TestData._
import com.blackfynn.upload.UploadPorts
import com.blackfynn.upload.UploadPorts.GetPreview
import com.blackfynn.upload.model.{ ChunkHash, ChunkHashId, Eventual, FileHash, PackagePreview }
import io.circe.parser.decode
import org.scalatest.{ Matchers, WordSpec }
class HashForFileSpec extends WordSpec with Matchers with ScalatestRouteTest {
implicit val log: ContextLogger = new ContextLogger()
"Getting a hash for file" should {
"return the hash for a upload with a single chunk" in {
val ports = createHashPorts(successfulGetChunkHash)
getHashRequest() ~> createRoutes(ports) ~> check {
decode[FileHash](entityAs[String]) shouldBe Right(FileHash(FirstByteStringHash))
}
}
"return the hash for a upload with a single chunk using a user claim" in {
val ports = createHashPorts(successfulGetChunkHash)
getHashRequest(userClaim = true) ~> createRoutes(ports) ~> check {
decode[FileHash](entityAs[String]) shouldBe Right(FileHash(FirstByteStringHash))
}
}
"return hashes for a upload with multiple chunks" in {
val hashes = (0 until 2).map(createChunkHash).toList
val successfulGetChunkHashes: GetChunkHashes =
(requestedHashes, _) => {
val onlyRequestedHashes = hashes.take(requestedHashes.length).map(Right(_))
Source(onlyRequestedHashes)
}
val ports =
createHashPorts(successfulGetChunkHashes, multipleChunksPreview)
val digest = MessageDigest.getInstance("SHA-256")
hashes.foreach(ch => digest.update(ch.hash.getBytes))
getHashRequest() ~> createRoutes(ports) ~> check {
decode[FileHash](entityAs[String]) shouldBe Right(FileHash(digest.digest()))
}
}
"return bad request for invalid import id" in {
val getHashInvalidImportId = addJWT(
Get(s"/hash/id/invalid?fileName=$someZipName&userId=1"),
token = makeToken(createClaim = generateClaim(userClaim = false))
)
getHashInvalidImportId ~> createRoutes(stubUploadPorts) ~> check(status shouldBe BadRequest)
}
"return bad request when using a service claim without a userId" in {
val getHashInvalidImportId = addJWT(
Get(s"/hash/id/$defaultImportId?fileName=$someZipName"),
token = makeToken(createClaim = generateClaim(userClaim = false))
)
getHashInvalidImportId ~> createRoutes(stubUploadPorts) ~> check(status shouldBe BadRequest)
}
"return internal server error for failed attempt to get hash" in {
val ports =
createHashPorts(
(_, _) => Source.single(createChunkHash(0)).map(_ => throw new Exception("shoot"))
)
getHashRequest() ~> createRoutes(ports) ~> check {
status shouldBe InternalServerError
}
}
"return not found when not all hashes can be found" in {
val ports =
createHashPorts(successfulGetChunkHash, multipleChunksPreview)
getHashRequest() ~> createRoutes(ports) ~> check(status shouldBe NotFound)
}
}
val successfulGetChunkHash: GetChunkHashes =
(chunkHashIds, _) => {
if (chunkHashIds.head.chunkNumber == 0 && chunkHashIds.length == 1)
Source.single(Right(createChunkHash(0)))
else {
Source(
Right(createChunkHash(0)) :: (1 until chunkHashIds.length)
.map(_ => Left(new ResourceNotFoundException("That hash didn't exist")))
.toList
)
}
}
val SecondByteStringHash: String =
"1b68dcaa02a2314eccbc153e65c351112bbeba25012d324cfc340f511cebb4bd"
private def createChunkHash(chunkNumber: Int) =
ChunkHash(
ChunkHashId(chunkNumber, defaultImportId, someZipName),
defaultImportId,
if (chunkNumber % 2 == 0) FirstByteStringHash else SecondByteStringHash
)
private val multipleChunksPreview =
zipPackagePreview
.copy(files = {
zipPackagePreview.files
.map { file =>
file.copy(chunkedUpload = file.chunkedUpload.get.copy(totalChunks = 2).some)
}
})
private def successfulGetPreview(preview: PackagePreview): GetPreview =
_ => Eventual.successful(preview)
private def createHashPorts(
getChunkHashes: GetChunkHashes,
preview: PackagePreview = zipPackagePreview
): UploadPorts =
createPorts(getChunkHashes = getChunkHashes, hashGetPreview = successfulGetPreview(preview))
def getHashRequest(userClaim: Boolean = false): HttpRequest =
addJWT(
Get(s"/hash/id/$defaultImportId?fileName=$someZipName&userId=1"),
token = makeToken(createClaim = generateClaim(userClaim = userClaim))
)
}
|
module Main where
import Criterion.Main
import qualified Crypto.CBC as CBC
import Crypto.Hash
import Control.Monad
import Data.ByteArray (constEq, convert)
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
-- Compares the original implementation in @tls@ with constant-time handling of
-- CBC padding. The code is simplified a little bit: instead of a complete
-- HMAC, we use only a digest of the message. There is no real authentication
-- but the difference with a complete implementation is a constant factor.
totalLen :: Int
totalLen = 16384
hashAlg :: SHA256
hashAlg = SHA256
digestSize :: Int
digestSize = hashDigestSize hashAlg
data CipherData = CipherData
{ cipherDataContent :: ByteString
, cipherDataMAC :: Maybe ByteString
, cipherDataPadding :: Maybe ByteString
} deriving (Show,Eq)
(&&!) :: Bool -> Bool -> Bool
True &&! True = True
True &&! False = False
False &&! True = False
False &&! False = False
partition3 :: ByteString -> (Int,Int,Int) -> Maybe (ByteString, ByteString, ByteString)
partition3 bytes (d1,d2,d3)
| any (< 0) l = Nothing
| sum l /= B.length bytes = Nothing
| otherwise = Just (p1,p2,p3)
where l = [d1,d2,d3]
(p1, r1) = B.splitAt d1 bytes
(p2, r2) = B.splitAt d2 r1
(p3, _) = B.splitAt d3 r2
getCipherData :: CipherData -> Maybe ByteString
getCipherData cdata = do
let macValid =
case cipherDataMAC cdata of
Nothing -> True
Just digest ->
let expected_digest = hashWith hashAlg $ cipherDataContent cdata
in expected_digest `constEq` digest
let paddingValid =
case cipherDataPadding cdata of
Nothing -> True
Just pad ->
let b = B.length pad - 1
in B.replicate (B.length pad) (fromIntegral b) `constEq` pad
guard (macValid &&! paddingValid)
return $ cipherDataContent cdata
generatePadded :: Bool -> Bool -> Int -> ByteString
generatePadded invalidPadding invalidDigest size =
B.concat [ bs, digest, B.replicate (fromIntegral b) b, B.singleton c ]
where
bs = B.replicate (totalLen - size) 0x11
b = fromIntegral size
digest | invalidDigest = B.replicate digestSize 0x22
| otherwise = convert (hashWith hashAlg bs)
c | invalidPadding = if b >= 0x80 then b - 1 else b + 1
| otherwise = b
benchOrig :: Bool -> Bool -> Int -> Benchmark
benchOrig invalidPadding invalidDigest padLen = bench (show padLen) $
nf run (generatePadded invalidPadding invalidDigest padLen)
where
get3i = partition3
run bs = do
let paddinglength = fromIntegral (B.last bs) + 1
let contentlen = B.length bs - paddinglength - digestSize
(content, mac, padding) <- get3i bs (contentlen, digestSize, paddinglength)
getCipherData CipherData
{ cipherDataContent = content
, cipherDataMAC = Just mac
, cipherDataPadding = Just padding
}
benchCT :: Bool -> Bool -> Int -> Benchmark
benchCT invalidPadding invalidDigest padLen = bench (show padLen) $
nf run (generatePadded invalidPadding invalidDigest padLen)
where
run bs = CBC.tls bs digestSize >>= \(paddingValid, paddingP) ->
let (begin, endmac) = B.splitAt (B.length bs - 256 - digestSize) bs
digestP = paddingP - digestSize
endLen = digestP - B.length begin
end = B.take 255 endmac -- digest and last padding byte never needed
computed = hashCT hashAlg begin end endLen
extracted = CBC.segment endmac endLen digestSize :: ByteString
digestValid = computed `constEq` extracted
in guard (digestValid &&! paddingValid) >> return (B.take digestP bs)
hashCT :: HashAlgorithmPrefix a => a -> ByteString -> ByteString -> Int -> Digest a
hashCT alg begin = hashFinalizePrefix (hashUpdate (hashInitWith alg) begin)
main :: IO ()
main = defaultMain
[ bgroup "CBC"
[ bgroup "original"
[ bgroup "valid" $ map (benchOrig False False) sizes
, bgroup "invalid-padding" $ map (benchOrig True False) sizes
, bgroup "invalid-digest" $ map (benchOrig False True) sizes
]
, bgroup "constant-time"
[ bgroup "valid" $ map (benchCT False False) sizes
, bgroup "invalid-padding" $ map (benchCT True False) sizes
, bgroup "invalid-digest" $ map (benchCT False True) sizes
]
]
]
where sizes = [0, 15, 31, 63, 127, 191, 255]
|
package org.aion.p2p.impl;
import org.aion.p2p.INode;
import org.aion.p2p.IP2pMgr;
import org.aion.p2p.impl.zero.msg.ReqActiveNodes;
import org.slf4j.Logger;
/** @author chris */
public final class TaskRequestActiveNodes implements Runnable {
private final IP2pMgr mgr;
private final Logger p2pLOG;
private static final ReqActiveNodes reqActiveNodesMsg = new ReqActiveNodes();
public TaskRequestActiveNodes(final IP2pMgr _mgr, final Logger p2pLOG) {
this.mgr = _mgr;
this.p2pLOG = p2pLOG;
}
@Override
public void run() {
INode node = mgr.getRandom();
if (node != null) {
if (p2pLOG.isTraceEnabled()) {
p2pLOG.trace("TaskRequestActiveNodes: {}", node.toString());
}
this.mgr.send(node.getIdHash(), node.getIdShort(), reqActiveNodesMsg);
}
}
}
|
// @ts-nocheck
/* eslint-disable */
// Styles
import './VChipGroup.sass'
// Extensions
import { BaseSlideGroup } from '../VSlideGroup/VSlideGroup'
// Mixins
import Colorable from '../../mixins/colorable'
// Utilities
import mixins from '../../util/mixins'
/* @vue/component */
export default mixins(
BaseSlideGroup,
Colorable
).extend({
name: 'v-chip-group',
provide () {
return {
chipGroup: this,
}
},
props: {
column: Boolean,
},
computed: {
classes () {
return {
...BaseSlideGroup.options.computed.classes.call(this),
'v-chip-group': true,
'v-chip-group--column': this.column,
}
},
},
watch: {
column (val) {
if (val) this.scrollOffset = 0
this.$nextTick(this.onResize)
},
},
methods: {
genData () {
return this.setTextColor(this.color, {
...BaseSlideGroup.options.methods.genData.call(this),
})
},
},
})
|
// Copyright 2021 Fredrick Allan Grott. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
import 'package:flutter/material.dart';
import 'package:flutter_platform_widgets/flutter_platform_widgets.dart';
import 'package:navbar_adaptive/src/presentation/widgets/app_adaptive_appbar.dart';
import 'package:navbar_adaptive/src/presentation/widgets/app_adaptive_scaffold.dart';
class DefaultScaffoldDemo extends StatefulWidget {
const DefaultScaffoldDemo({Key? key}) : super(key: key);
@override
_DefaultScaffoldDemoState createState() => _DefaultScaffoldDemoState();
}
class _DefaultScaffoldDemoState extends State<DefaultScaffoldDemo> {
int _destinationCount = 5;
bool _fabInRail = false;
bool _includeBaseDestinationsInMenu = true;
@override
Widget build(BuildContext context) {
return AdaptiveNavigationScaffold(
selectedIndex: 0,
destinations: _allDestinations.sublist(0, _destinationCount,),
appBar: AdaptiveAppBar(
title: PlatformText(
'Default Demo'),
),
body: _body(),
floatingActionButton: FloatingActionButton(
child: const Icon(Icons.add),
onPressed: () {},
),
fabInRail: _fabInRail,
includeBaseDestinationsInMenu: _includeBaseDestinationsInMenu,
);
}
Widget _body() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('''
This is the default behavior of the AdaptiveNavigationScaffold.
It switches between bottom navigation, navigation rail, and a permanent drawer.
Resize the window to switch between the navigation types.
'''),
const SizedBox(height: 40),
Slider(
min: 2,
max: _allDestinations.length.toDouble(),
divisions: _allDestinations.length - 2,
value: _destinationCount.toDouble(),
label: _destinationCount.toString(),
onChanged: (value) {
setState(() {
_destinationCount = value.round();
});
},
),
const Text('Destination Count'),
const SizedBox(height: 40),
Switch(
value: _fabInRail,
onChanged: (value) {
setState(() {
_fabInRail = value;
});
},
),
const Text('fabInRail'),
const SizedBox(height: 40),
Switch(
value: _includeBaseDestinationsInMenu,
onChanged: (value) {
setState(() {
_includeBaseDestinationsInMenu = value;
});
},
),
const Text('includeBaseDestinationsInMenu'),
const SizedBox(height: 40),
ElevatedButton(
child: const Text('BACK'),
onPressed: () {
Navigator.of(context).pushReplacementNamed('/');
},
),
],
),
);
}
}
const _allDestinations = [
AdaptiveScaffoldDestination(title: 'ALARM', icon: Icons.alarm,),
AdaptiveScaffoldDestination(title: 'BOOK', icon: Icons.book,),
AdaptiveScaffoldDestination(title: 'CAKE', icon: Icons.cake,),
AdaptiveScaffoldDestination(title: 'DIRECTIONS', icon: Icons.directions,),
AdaptiveScaffoldDestination(title: 'EMAIL', icon: Icons.email,),
AdaptiveScaffoldDestination(title: 'FAVORITE', icon: Icons.favorite,),
AdaptiveScaffoldDestination(title: 'GROUP', icon: Icons.group,),
AdaptiveScaffoldDestination(title: 'HEADSET', icon: Icons.headset,),
AdaptiveScaffoldDestination(title: 'INFO', icon: Icons.info,),
];
|
package p
func f() {
for {
x
}
switch x {
case 1:
y
case 2:
z
}
switch x.(type) {
case T:
y
case T1:
z
}
}
|
// =======================================================
// Author: Davain Pablo Edwards
// Email: [email protected]
// Web:
// =======================================================
using Microsoft.Extensions.Options;
using System;
using Microsoft.EntityFrameworkCore;
using RESTfulAPI.Core.AppSettingsLayer;
namespace RESTfulAPI.Core.DataLayer
{
public class RESTfulAPI_DbContext : DbContext
{
/// <summary>
///
/// </summary>
/// <param name="appSettings"></param>
/// <param name="entityMapper"></param>
public RESTfulAPI_DbContext(IOptions<DatabaseSettings> appSettings, IEntityMapper entityMapper)
{
ConnectionString = appSettings.Value.ConnectionString;
EntityMapper = entityMapper;
}
public String ConnectionString { get; } // MySql
public IEntityMapper EntityMapper { get; }
/// <summary>
///
/// </summary>
/// <param name="optionsBuilder"></param>
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql(ConnectionString);
//optionsBuilder.UseSqlServer(ConnectionString);
base.OnConfiguring(optionsBuilder);
}
/// <summary>
///
/// </summary>
/// <param name="modelBuilder"></param>
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
EntityMapper.MapEntities(modelBuilder);
base.OnModelCreating(modelBuilder);
}
}
}
|
/*
* Copyright (C) 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.copybara.doc;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.copybara.doc.annotations.Example;
import com.google.copybara.doc.annotations.Library;
import net.starlark.java.annot.StarlarkMethod;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Optional;
import java.util.TreeSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.annotation.Nullable;
public class Generator {
private Generator() {
}
public static void main(String[] args) throws IOException {
new Generator().generate(Paths.get(args[0]), Paths.get(args[1]));
}
private static void mdTitle(StringBuilder sb, int level, String name) {
sb.append("\n").append(Strings.repeat("#", level)).append(' ').append(name).append("\n\n");
}
private void generate(Path classListFile, Path outputFile)
throws IOException {
List<String> classes = Files.readAllLines(classListFile, StandardCharsets.UTF_8);
List<DocModule> modules = new ArrayList<>();
DocModule docModule = new DocModule("Globals", "Global functions available in Copybara");
modules.add(docModule);
for (String clsName : classes) {
try {
Class<?> cls = Generator.class.getClassLoader().loadClass(clsName);
getAnnotation(cls, Library.class)
.ifPresent(library -> docModule.functions.addAll(processLibrary(cls)));
} catch (ClassNotFoundException e) {
throw new IllegalStateException("Cannot generate documentation for " + clsName, e);
}
}
StringBuilder sb = new StringBuilder("## Table of Contents\n\n");
for (DocModule module : modules) {
sb.append(" - [");
sb.append(module.name);
sb.append("](#");
sb.append(module.name.toLowerCase());
sb.append(")\n");
}
sb.append("\n");
for (DocModule module : modules) {
sb.append(module.toMarkdown(2));
}
Files.write(outputFile, sb.toString().getBytes(StandardCharsets.UTF_8));
}
private ImmutableList<DocFunction> processLibrary(Class<?> cls) {
ImmutableList.Builder<DocFunction> result = ImmutableList.builder();
for (Method method : cls.getMethods()) {
getAnnotation(method, StarlarkMethod.class)
.ifPresent(sMethod -> result.add(processStarlarkMethod(cls, method, sMethod)));
}
return result.build();
}
private DocFunction processStarlarkMethod(Class<?> cls, Method method, StarlarkMethod sMethod) {
// TODO(malcon): Implement starlark method.
return new DocFunction(sMethod.name(), sMethod.doc(), "TBD", ImmutableList.of(),
ImmutableList.of(), ImmutableList.of());
}
@SuppressWarnings("unchecked")
private <T extends Annotation> Optional<T> getAnnotation(AnnotatedElement cls, Class<T> annCls) {
for (Annotation ann : cls.getAnnotations()) {
if (ann.annotationType().equals(annCls)) {
return Optional.of((T) ann);
}
}
return Optional.empty();
}
private void tableHeader(StringBuilder sb, String... fields) {
tableRow(sb, fields);
tableRow(sb, Stream.of(fields)
.map(e -> Strings.repeat("-", e.length()))
.toArray(String[]::new));
}
private void tableRow(StringBuilder sb, String... fields) {
sb.append(Arrays.stream(fields).map(s -> s.replace("\n", "<br>"))
.collect(Collectors.joining(" | ")))
.append("\n");
}
private abstract static class DocBase implements Comparable<DocBase> {
protected final String name;
protected final String description;
DocBase(String name, String description) {
this.name = checkNotNull(name);
this.description = checkNotNull(description);
}
@Override
public int compareTo(DocBase o) {
return name.compareTo(o.name);
}
public String getName() {
return name;
}
}
private static final class DocField extends DocBase {
DocField(String name, String description) {
super(name, description);
}
}
private final class DocFunction extends DocBase {
private final TreeSet<DocFlag> flags = new TreeSet<>();
@Nullable
private final String returnType;
private final ImmutableList<DocParam> params;
private final ImmutableList<DocExample> examples;
DocFunction(String name, String description, @Nullable String returnType,
Iterable<DocParam> params, Iterable<DocFlag> flags, Iterable<DocExample> examples) {
super(name, description);
this.returnType = returnType;
this.params = ImmutableList.copyOf(params);
this.examples = ImmutableList.copyOf(examples);
Iterables.addAll(this.flags, flags);
}
}
private final class DocModule extends DocBase {
private final TreeSet<DocField> fields = new TreeSet<>();
private final TreeSet<DocFunction> functions = new TreeSet<>();
private final TreeSet<DocFlag> flags = new TreeSet<>();
DocModule(String name, String description) {
super(name, description);
}
CharSequence toMarkdown(int level) {
StringBuilder sb = new StringBuilder();
mdTitle(sb, level, name);
sb.append(description).append("\n\n");
if (!fields.isEmpty()) {
// TODO(malcon): Skip showing in ToC for now by showing it as a more deep element.
mdTitle(sb, level + 2, "Fields:");
tableHeader(sb, "Name", "Description");
for (DocField field : fields) {
tableRow(sb, field.name, field.description);
}
sb.append("\n");
}
printFlags(sb, flags);
for (DocFunction func : functions) {
sb.append("<a id=\"").append(func.name).append("\" aria-hidden=\"true\"></a>");
mdTitle(sb, level + 1, func.name);
sb.append(func.description);
sb.append("\n\n");
sb.append("`");
if (func.returnType != null) {
sb.append(func.returnType).append(" ");
}
sb.append(func.name).append("(");
Joiner.on(", ").appendTo(sb, Lists.transform(func.params,
p -> p.name + (p.defaultValue == null ? "" : "=" + p.defaultValue)));
sb.append(")`\n\n");
if (!Iterables.isEmpty(func.params)) {
mdTitle(sb, level + 2, "Parameters:");
tableHeader(sb, "Parameter", "Description");
for (DocParam param : func.params) {
tableRow(
sb,
param.name,
String.format(
"`%s`<br><p>%s</p>",
Joiner.on("` or `").join(param.allowedTypes), param.description));
}
sb.append("\n");
}
if (!func.examples.isEmpty()) {
mdTitle(sb, level + 2, func.examples.size() == 1 ? "Example:" : "Examples:");
for (DocExample example : func.examples) {
printExample(sb, level + 3, example.example);
}
sb.append("\n");
}
printFlags(sb, func.flags);
}
return sb;
}
private void printExample(StringBuilder sb, int level, Example example) {
mdTitle(sb, level, example.title() + ":");
sb.append(example.before()).append("\n\n");
sb.append("```python\n").append(example.code()).append("\n```\n\n");
if (!example.after().equals("")) {
sb.append(example.after()).append("\n\n");
}
}
private void printFlags(StringBuilder sb, Collection<DocFlag> flags) {
if (!flags.isEmpty()) {
sb.append("\n\n**Command line flags:**\n\n");
tableHeader(sb, "Name", "Type", "Description");
for (DocFlag field : flags) {
tableRow(sb, nowrap(field.name), String.format("*%s*", field.type), field.description);
}
sb.append("\n");
}
}
/**
* Don't wrap this text. Also use '`' to show it as code.
*/
private String nowrap(String text) {
return String.format("<span style=\"white-space: nowrap;\">`%s`</span>", text);
}
}
private final class DocParam {
private final String name;
@Nullable
private final String defaultValue;
private final List<String> allowedTypes;
private final String description;
DocParam(
String name, @Nullable String defaultValue, List<String> allowedTypes, String description) {
this.name = name;
this.defaultValue = defaultValue;
this.allowedTypes = allowedTypes;
this.description = description;
}
}
private final class DocFlag extends DocBase {
public final String type;
DocFlag(String name, String type, String description) {
super(name, description);
this.type = type;
}
}
private final class DocExample {
private final Example example;
DocExample(Example example) {
this.example = example;
}
}
}
|
package bar
/**
* Second class in second module description [foo.FirstClass]
* @author John Doe
* @version 0.1.3
* @param name Name description text text text.
*/
class SecondClass(val name: String) {
val firstProperty = "propertystring"
/**
* Second property in second module description [foo.FirstSubclass]
*/
var secondProperty: String = ""
set(value) {
println("Second property not set")
}
init {
println("InitializerBlock")
}
}
|
using MediatR;
using System;
namespace CQRS_MediatR.Domain.Events
{
public class EmailAtualizadoComSucesso : IRequest
{
public string NomePessoa { get; set; }
public string NovoEmail { get; set; }
public DateTime DataHora { get; set; } = DateTime.Now;
}
}
|
# frozen_string_literal: true
module PagesCore
module Admin
module NewsPageController
extend ActiveSupport::Concern
included do
before_action :require_news_pages, only: [:news]
before_action :find_news_pages, only: %i[news new_news]
before_action :find_year_and_month, only: %i[news]
end
def news
@archive_finder = archive_finder(@news_pages, @locale)
unless @year
redirect_to(news_admin_pages_path(@locale,
(@archive_finder.latest_year ||
Time.zone.now.year)))
return
end
@pages = @archive_finder.by_year_and_maybe_month(@year, @month)
.paginate(per_page: 50, page: params[:page])
end
def new_news
new
render action: :new
end
private
def archive_finder(parents, locale)
Page.where(parent_page_id: parents)
.visible
.order("published_at DESC")
.in_locale(locale)
.archive_finder
end
def find_news_pages
@news_pages = Page.news_pages
.in_locale(@locale)
.reorder("parent_page_id ASC, position ASC")
return if @news_pages.any?
redirect_to(admin_pages_url(@locale))
end
def find_year_and_month
@year = params[:year]&.to_i
@month = params[:month]&.to_i
end
# Redirect away if no news pages has been configured
def require_news_pages
return if Page.news_pages.any?
redirect_to(admin_pages_url(@locale))
end
def latest_year
archive_finder.latest_year_and_month.first || Time.zone.now.year
end
end
end
end
|
class Dessert
attr_accessor :name,:calories
# protected :name,:calories
def initialize(name, calories)
@name = name
@calories = calories
end
def healthy?
@calories < 200 && self.delicious?
end
def delicious?
true
end
end
class JellyBean < Dessert
def initialize(flavor)
@flavor = flavor
@calories = 5
@name = flavor + " jelly bean"
end
def delicious?
return false if @flavor == 'licorice'
return true
end
end
|
<?php
namespace App\Http\Controllers\Guest;
use App\Http\Controllers\Controller;
use App\Models\Post;
use App\Http\Resources\PostResource;
use App\Http\Resources\PostCollection;
use App\Http\Requests\PostFormRequest;
use App\Models\Comment;
class PostController extends Controller
{
public function index()
{
return new PostCollection(Post::content()
->with(['categories:id,name,slug'])
->type(Post::TYPE_POST)
->published()
->latest('published_date')
->paginate(20));
}
public function show(Post $post)
{
return new PostResource($post->load([
'comments' => fn($query) => $query->where('is_approved', Comment::APPROVED)->latest()
]));
}
}
|
import { useAtom } from '@dbeining/react-atom';
import { Button } from '@equinor/eds-core-react';
import { SignWithComment } from './SignWithComment/SignWithComment';
import { useScopeChangeContext } from '../../../../hooks/context/useScopeChangeContext';
import { actionWithCommentAtom, resetSigningAtom } from '../../Atoms/signingAtom';
import { ReassignBar } from '../../ReassignBar/ReassignBar';
import styled from 'styled-components';
export const CriteriaActionOverlay = (): JSX.Element | null => {
const state = useAtom(actionWithCommentAtom);
const requestId = useScopeChangeContext(({ request }) => request.id);
if (!state) {
return null;
}
return (
<>
{state.action === 'Reassign' ? (
<ButtonContainer>
<ReassignBar
criteriaId={state.criteriaId}
requestId={requestId}
stepId={state.stepId}
/>
<Button variant="outlined" onClick={resetSigningAtom}>
Cancel
</Button>
</ButtonContainer>
) : (
<SignWithComment
action={state.action}
buttonText={state.buttonText}
criteriaId={state.criteriaId}
stepId={state.stepId}
/>
)}
</>
);
};
const ButtonContainer = styled.div`
display: flex;
gap: 2em;
width: 100%;
`;
|
## What is Cheque Management?
Cheque Management is an application Built using frappe framework and depends on ERPNext application.
Among other things, Cheque Management will help you to:
* Track all your Receivable and payable Cheques.
* Register all Cheque life cycle steps and track it.
> Tip: This Cheque Cycle works only for local currency Cheques so do not use it for any foreign currency Cheques.
### Topics
{index}
|
# Miscellaneous
## Entities
|Name|Description|
|---|---|
|[BrazilianElectronicReportingParameters](BrazilianElectronicReportingParameters.cdm.json)||
|[EFDocAuthorityState_BR](EFDocAuthorityState_BR.cdm.json)||
|[EFDocAuthority_BR](EFDocAuthority_BR.cdm.json)||
|[EFDocContingencyMode_BR](EFDocContingencyMode_BR.cdm.json)||
|[EFDocCorrectionLetter_BR](EFDocCorrectionLetter_BR.cdm.json)||
|[EFDocEmailHistory_BR](EFDocEmailHistory_BR.cdm.json)||
|[EFDocFormatClassInfo_BR](EFDocFormatClassInfo_BR.cdm.json)||
|[EFDocHist_BR](EFDocHist_BR.cdm.json)||
|[EFDocReceivedXmlApprovedDivergences_BR](EFDocReceivedXmlApprovedDivergences_BR.cdm.json)||
|[EFDocumentEmailAccount_BR](EFDocumentEmailAccount_BR.cdm.json)||
|[EFDocumentReceivedDanfe_BR](EFDocumentReceivedDanfe_BR.cdm.json)||
|[EFDocumentReceivedXMLData_BR](EFDocumentReceivedXMLData_BR.cdm.json)||
|[EFDocWebServiceParameters_BR](EFDocWebServiceParameters_BR.cdm.json)||
|[EFDReturnCode_BR](EFDReturnCode_BR.cdm.json)||
|[ExternalFiscalDocumentLine_BR](ExternalFiscalDocumentLine_BR.cdm.json)||
|[ExternalFiscalDocument_BR](ExternalFiscalDocument_BR.cdm.json)||
|[FBAdditionalInformationCodeLink_BR](FBAdditionalInformationCodeLink_BR.cdm.json)||
|[FBAdditionalInformationCode_BR](FBAdditionalInformationCode_BR.cdm.json)||
|[FBAdministrativeProcessLine_BR](FBAdministrativeProcessLine_BR.cdm.json)||
|[FBAdministrativeProcess_BR](FBAdministrativeProcess_BR.cdm.json)||
|[FBBookingPeriodInventTrans_BR](FBBookingPeriodInventTrans_BR.cdm.json)||
|[FBBookingPeriodPresumedIncDocuments_BR](FBBookingPeriodPresumedIncDocuments_BR.cdm.json)||
|[FBCFOPCreditBaseSource_BR](FBCFOPCreditBaseSource_BR.cdm.json)||
|[FBCIAPAssetTrans_FiscalDoc_BR](FBCIAPAssetTrans_FiscalDoc_BR.cdm.json)||
|[FBCIAPAssetTrans_OtherCredits_BR](FBCIAPAssetTrans_OtherCredits_BR.cdm.json)||
|[FBContribAssetAssessment_BR](FBContribAssetAssessment_BR.cdm.json)||
|[FBContribAssetTable_BR](FBContribAssetTable_BR.cdm.json)||
|[FBContribAssetTransReferencedProcess_BR](FBContribAssetTransReferencedProcess_BR.cdm.json)||
|[FBContribCreditControlDetail_BR](FBContribCreditControlDetail_BR.cdm.json)||
|[FBContribCreditTypeTaxTrans_BR](FBContribCreditTypeTaxTrans_BR.cdm.json)||
|[FBContribCreditType_BR](FBContribCreditType_BR.cdm.json)||
|[FBEconomicActivityCodeLine_BR](FBEconomicActivityCodeLine_BR.cdm.json)||
|[FBEconomicActivityCode_BR](FBEconomicActivityCode_BR.cdm.json)||
|[FBFiscalDocAdjustmentCodeICMSLedger_BR](FBFiscalDocAdjustmentCodeICMSLedger_BR.cdm.json)||
|[FBFiscalPrinterDailyReport_BR](FBFiscalPrinterDailyReport_BR.cdm.json)||
|[FBGeneralAdjustmentCodeLedger_BR](FBGeneralAdjustmentCodeLedger_BR.cdm.json)||
|[FBICMSSTInventoryBalance_BR](FBICMSSTInventoryBalance_BR.cdm.json)||
|[FBInventoryBalanceOutDocuments_BR](FBInventoryBalanceOutDocuments_BR.cdm.json)||
|[FBNonFiscalOperationTaxTrans_BR](FBNonFiscalOperationTaxTrans_BR.cdm.json)||
|[FBNonFiscalOperation_BR](FBNonFiscalOperation_BR.cdm.json)||
|[FbNonFiscalOpReferencedProcess_BR](FbNonFiscalOpReferencedProcess_BR.cdm.json)||
|[FBReasonCodeForRestitutionComplement_BR](FBReasonCodeForRestitutionComplement_BR.cdm.json)||
|[FBSpedEcfDerexClassificationCode_BR](FBSpedEcfDerexClassificationCode_BR.cdm.json)||
|[FBSpedEcfForeignBankAccount_BR](FBSpedEcfForeignBankAccount_BR.cdm.json)||
|[FBSpedEcfJournalName_BR](FBSpedEcfJournalName_BR.cdm.json)||
|[FBSpedEcfSetupParameters_BR](FBSpedEcfSetupParameters_BR.cdm.json)||
|[FBSpedReinfEventFiscalDocument_BR](FBSpedReinfEventFiscalDocument_BR.cdm.json)||
|[FBSpedReinfEvent_BR](FBSpedReinfEvent_BR.cdm.json)||
|[FBSpedReinfSetupParameters_BR](FBSpedReinfSetupParameters_BR.cdm.json)||
|[FBTaxAssessmentINSSCPRBTaxTrans_BR](FBTaxAssessmentINSSCPRBTaxTrans_BR.cdm.json)||
|[FBTaxAssessmentINSSCPRB_BR](FBTaxAssessmentINSSCPRB_BR.cdm.json)||
|[FBTaxAssessmentPaymentParameters_BR](FBTaxAssessmentPaymentParameters_BR.cdm.json)||
|[FBTaxClassificationCode_BR](FBTaxClassificationCode_BR.cdm.json)||
|[FBTaxStatementLocation_BR](FBTaxStatementLocation_BR.cdm.json)||
|[FBTaxStatementTaxType_BR](FBTaxStatementTaxType_BR.cdm.json)||
|[FBTaxTransPovertyFund_BR](FBTaxTransPovertyFund_BR.cdm.json)||
|[FBTaxTransTaxAssessmentPayment_BR](FBTaxTransTaxAssessmentPayment_BR.cdm.json)||
|[FBTaxWithholdTransCreditDetail_BR](FBTaxWithholdTransCreditDetail_BR.cdm.json)||
|[FBTaxWithholdTrans_BR](FBTaxWithholdTrans_BR.cdm.json)||
|[FBVendToPaymMode_BR](FBVendToPaymMode_BR.cdm.json)||
|[FiscalDocSourceTextReferenceProcess_BR](FiscalDocSourceTextReferenceProcess_BR.cdm.json)||
|[FiscalDocumentAdditionalAmount_BR](FiscalDocumentAdditionalAmount_BR.cdm.json)||
|[FiscalDocumentLineSource_BR](FiscalDocumentLineSource_BR.cdm.json)||
|[FiscalDocumentReferencedProcess_BR](FiscalDocumentReferencedProcess_BR.cdm.json)||
|[FiscalDocumentTaxTransOutgoingICMSDif_BR](FiscalDocumentTaxTransOutgoingICMSDif_BR.cdm.json)||
|[FiscalDocumentTaxTransPovertyFund_BR](FiscalDocumentTaxTransPovertyFund_BR.cdm.json)||
|[FiscalDocumentTaxTransPresumed_BR](FiscalDocumentTaxTransPresumed_BR.cdm.json)||
|[FiscalEstablishmentIEPerState_BR](FiscalEstablishmentIEPerState_BR.cdm.json)||
|[FiscalEstablishmentInventSite_BR](FiscalEstablishmentInventSite_BR.cdm.json)||
|[FiscalEstablishmentVendInvoiceJour_BR](FiscalEstablishmentVendInvoiceJour_BR.cdm.json)||
|[FiscalReferenceParm_BR](FiscalReferenceParm_BR.cdm.json)||
|
#! /bin/bash
###########################################
#
###########################################
# constants
baseDir=$(cd `dirname "$0"`;pwd)
appHome=$baseDir/..
registry=
imagename=chatopera/feishu
# functions
# main
[ -z "${BASH_SOURCE[0]}" -o "${BASH_SOURCE[0]}" = "$0" ] || return
cd $appHome
GIT_COMMIT_SHORT=`git rev-parse --short HEAD`
docker build \
--no-cache=true \
--force-rm=true --tag $imagename:$GIT_COMMIT_SHORT .
if [ $? -eq 0 ]; then
set -x
docker tag $imagename:$GIT_COMMIT_SHORT $imagename:develop
fi
|
### Text Generation
naive Text generation using Recurrent Neural Network (RNN) in Tensorflow and Keras |
/*
* Copyright (c) 2017 大前良介 (OHMAE Ryosuke)
*
* This software is released under the MIT License.
* http://opensource.org/licenses/MIT
*/
package net.mm2d.dmsexplorer.util
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.animation.Animation
import android.view.animation.AnimationUtils
import net.mm2d.dmsexplorer.R
import java.util.concurrent.TimeUnit
/**
* @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected])
*/
class FullscreenHelper(
private val rootView: View,
private val topView: View? = null,
private val bottomView: View? = null
) {
private val handler: Handler = Handler(Looper.getMainLooper())
private val enterFromTop: Animation
private val enterFromBottom: Animation
private val exitToTop: Animation
private val exitToBottom: Animation
private val hideNavigationTask = Runnable { this.hideNavigation() }
private var posted: Boolean = false
private var isInPictureInPictureMode: Boolean = false
init {
val context = rootView.context
enterFromTop = AnimationUtils.loadAnimation(context, R.anim.enter_from_top)
enterFromBottom = AnimationUtils.loadAnimation(context, R.anim.enter_from_bottom)
exitToTop = AnimationUtils.loadAnimation(context, R.anim.exit_to_top)
exitToBottom = AnimationUtils.loadAnimation(context, R.anim.exit_to_bottom)
rootView.setOnSystemUiVisibilityChangeListener { visibility ->
if (!posted && !isInPictureInPictureMode && visibility and View.SYSTEM_UI_FLAG_HIDE_NAVIGATION == 0) {
showNavigation()
}
}
}
private fun postHideNavigation(interval: Long) {
handler.removeCallbacks(hideNavigationTask)
handler.postDelayed(hideNavigationTask, interval)
posted = true
}
fun showNavigation(interval: Long = NAVIGATION_INTERVAL): Boolean {
if (isInPictureInPictureMode) {
return false
}
var execute = false
topView?.let {
if (it.visibility != View.VISIBLE) {
it.clearAnimation()
it.startAnimation(enterFromTop)
it.visibility = View.VISIBLE
execute = true
}
}
bottomView?.let {
if (it.visibility != View.VISIBLE) {
it.clearAnimation()
it.startAnimation(enterFromBottom)
it.visibility = View.VISIBLE
execute = true
}
}
rootView.systemUiVisibility = SYSTEM_UI_VISIBLE
postHideNavigation(interval)
return execute
}
private fun hideNavigation() {
posted = false
topView?.let {
if (it.visibility != View.GONE) {
it.clearAnimation()
it.startAnimation(exitToTop)
it.visibility = View.GONE
}
}
bottomView?.let {
if (it.visibility != View.GONE) {
it.clearAnimation()
it.startAnimation(exitToBottom)
it.visibility = View.GONE
}
}
rootView.systemUiVisibility = SYSTEM_UI_INVISIBLE
handler.removeCallbacks(hideNavigationTask)
}
fun hideNavigationImmediately() {
posted = false
topView?.let {
it.clearAnimation()
it.visibility = View.GONE
}
bottomView?.let {
it.clearAnimation()
it.visibility = View.GONE
}
rootView.systemUiVisibility = SYSTEM_UI_INVISIBLE
handler.removeCallbacks(hideNavigationTask)
}
fun onPictureInPictureModeChanged(pip: Boolean) {
isInPictureInPictureMode = pip
if (pip) {
handler.removeCallbacks(hideNavigationTask)
topView?.let {
it.clearAnimation()
it.visibility = View.GONE
}
bottomView?.let {
it.clearAnimation()
it.visibility = View.GONE
}
} else {
postHideNavigation(NAVIGATION_INTERVAL)
}
}
fun terminate() {
handler.removeCallbacks(hideNavigationTask)
}
companion object {
private val NAVIGATION_INTERVAL = TimeUnit.SECONDS.toMillis(3)
private const val SYSTEM_UI_VISIBLE: Int = (View.SYSTEM_UI_FLAG_LOW_PROFILE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)
private const val SYSTEM_UI_INVISIBLE: Int = (View.SYSTEM_UI_FLAG_FULLSCREEN
or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
or View.SYSTEM_UI_FLAG_IMMERSIVE
or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION)
}
}
|
// @flow
import FontAwesomeIcon from '@fortawesome/react-fontawesome';
import github from '@fortawesome/fontawesome-free-brands/faGithub';
import withProps from 'recompose/withProps';
import KeyboardArrowRight from '@material-ui/icons/KeyboardArrowRight';
import DeveloperMode from '@material-ui/icons/DeveloperMode';
import Devices from '@material-ui/icons/Devices';
import { navigateTo } from 'gatsby-link';
export default [
{
label: 'Getting Started',
onClick: () => navigateTo('/getting-started'),
icon: DeveloperMode,
},
{
label: 'Layout Controller Demo',
onClick: () => navigateTo('/layout-controller'),
icon: Devices,
},
{
href: 'https://github.com/OrigenStudio/material-ui-layout',
label: 'Code',
icon: withProps({ icon: github, size: 'lg' })(FontAwesomeIcon),
},
{
href: 'https://origen.studio',
label: 'Origen',
icon: KeyboardArrowRight,
},
];
|
{-|
Module : Database.Relational.StandardUniverse
Description : A universe on which some standard features will be defined.
Copyright : (c) Alexander Vieth, 2015
Licence : BSD3
Maintainer : [email protected]
Stability : experimental
Portability : non-portable (GHC only)
-}
{-# LANGUAGE AutoDeriveTypeable #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE ConstraintKinds #-}
module Database.Relational.StandardUniverse (
StandardUniverse(..)
) where
import Database.Relational.Universe
-- | The standard universe is meant to assist in code reuse.
-- Interpretation of relational terms in the standard universe should conform
-- to ANSI SQL, and therefore some RDBMS drivers should be able to use it.
data StandardUniverse = StandardUniverse
class StandardUniverseConstraint t
instance RelationalUniverse StandardUniverse where
type RelationalUniverseConstraint StandardUniverse = StandardUniverseConstraint
|
//go:build !windows
package function
import (
"fmt"
"os"
"strconv"
)
func Chmod(file string, raw string) error {
stat, err := os.Stat(file)
if err != nil {
return err
}
mode := stat.Mode()
perm, err := fm.Parse(mode.Perm(), raw)
if err != nil {
return err
}
return os.Chmod(file, (mode>>9)<<9|perm)
}
func chown(file string, uid, gid string) (err error) {
var u, g = int64(-1), int64(-1)
if uid != "" {
if u, err = strconv.ParseInt(uid, 10, 64); err != nil {
return err
}
}
if gid != "" {
if g, err = strconv.ParseInt(gid, 10, 64); err != nil {
return err
}
}
if u == -1 && g == -1 {
// this should be have by optional that make sure uid and gid at one is provided
return fmt.Errorf("user id %s and group id %s is not available", uid, gid)
}
return os.Chown(file, int(u), int(g))
}
// provide for test file only
func GetFDModePerm(file string) (os.FileMode, error) {
stat, err := os.Stat(file)
if err != nil {
return 0, err
} else {
return stat.Mode().Perm(), nil
}
}
func GetFDStat(file string) (stat os.FileInfo, err error) { return os.Stat(file) }
|
require 'rails_helper'
RSpec.describe User, :type => :model do
before do
Fabricate(:user)
end
it { should have_many :galleries }
it { should have_many(:photos).through(:galleries) }
it { should have_many :ads }
it { should have_many :artist_tags }
it { should have_many(:tags).through(:artist_tags) }
it { should accept_nested_attributes_for(:artist_tags) }
it { should validate_presence_of :email }
it { should validate_presence_of :password }
it { should validate_uniqueness_of :email }
end
|
using System.ComponentModel.DataAnnotations;
using Microsoft.EntityFrameworkCore.Query;
using MUDhub.Core.Abstracts.Models.Rooms;
namespace MUDhub.Server.ApiModels.Muds.Rooms
{
public class CreateRoomRequest
{
[Required]
public string Name { get; set; } = string.Empty;
public string Description { get; set; } = string.Empty;
public string EnterMessage { get; set; } = string.Empty;
public string ImageKey { get; set; } = string.Empty;
[Required]
public int X { get; set; } = 0;
[Required]
public int Y { get; set; } = 0;
[Required]
public string AreaId { get; set; }
public bool IsDefaultRoom { get; set; } = false;
public static RoomArgs ConvertFromRequest(CreateRoomRequest request)
{
if (request is null)
{
throw new System.ArgumentNullException(nameof(request));
}
return new RoomArgs()
{
Name = request.Name,
IsDefaultRoom = request.IsDefaultRoom,
EnterMessage = request.EnterMessage,
ImageKey = request.ImageKey,
X = request.X,
Y = request.Y,
Description = request.Description
};
}
}
}
|
package com.thebestdevelopers.find_my_beer.controller.pubControllerParam;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
public class createPubParam implements Serializable {
private String pubName;
public createPubParam() {
}
@JsonCreator
public createPubParam(@JsonProperty("pubName") String pubName){
this.pubName = pubName;
}
public String getPubName() {
return this.pubName;
}
public void setPubName(String pubName) {
this.pubName = pubName;
}
//
// public String getPhoto() {
// return this.photo;
// }
//
// public void setPhoto(String photo) {
// this.photo = photo;
// }
}
|
<form role="search" method="GET" class="search row align-items-center mb-3 mr-1">
<div class="input-group icon-search col-xl-6 my-2 my-md-0">
<span><i class="fas fa-search"></i></span>
<input type="search" name="q" value="{{$q}}" class="form-control" placeholder="Ingrese No. de Pedido a buscar">
</div>
<div class="form-group col-xl-4 my-2 my-md-0">
<div class="d-flex align-items-center">
<label class="mr-3 mb-0 d-none d-md-block">Fecha:</label>
<input type="month" name="f" class="form-control" value="{{$f}}">
</div>
</div>
<div class="input-group col-xl-1 my-2 my-md-0">
<button type="submit" class="btn btn-sm btn-default">Buscar</button>
</div>
</form>
|
/*
* @Description: In User Settings Edit
* @Author: your name
* @Date: 2019-09-25 10:42:47
* @LastEditTime: 2019-10-23 15:09:39
* @LastEditors: Please set LastEditors
*/
import { expect } from 'chai'
import { shallowMount } from '@vue/test-utils'
import Card from '../../../bs4/components/card/src/main.vue'
describe('Card', function () {
it('default', function () {
const wrapper = shallowMount(Card, {
slots: {
default: 'default'
}
})
expect(wrapper.classes()).to.have.members(['card'])
const body = wrapper.find('.card-body')
expect(body.exists()).to.be.true
expect(body.text()).to.equal('default')
})
it('top-img', function () {
const wrapper = shallowMount(Card, {
propsData: {
topImg: {
src: 'src',
alt: 'alt'
}
}
})
const topImg = wrapper.find('.card-img-top')
const attributes = topImg.attributes()
expect(attributes.src).to.equal('src')
expect(attributes.alt).to.equal('alt')
})
it('slots', function () {
const list = [
{
name: 'header',
selector: '.card-header',
html: 'header'
},
{
name: 'footer',
selector: '.card-footer',
html: 'footer'
},
{
name: 'other',
selector: '',
html: 'other'
}
]
list.forEach((v) => {
let options = { slots: {} }
options.slots[v.name] = v.html
const wrapper = shallowMount(Card, options)
expect((v.selector ? wrapper.find(v.selector) : wrapper).text()).to.equal(v.html)
})
})
})
|
<?php
declare(strict_types=1);
namespace App\Market\Domain\Exceptions;
use App\Shared\Exceptions\AppException;
class CreatePurchaseException extends AppException
{
protected string $errorMessage = 'Não foi possível fazer a compra.';
} |
const {vueComponentFilePath, vueTestFilePath} = require('./generators/file-path-generator');
const {generateFileContent, generateTestFileContent} = require('./generators/file-content-generator');
module.exports = {
generateComponentFile: (path, filename, typescript) => {
if (!path || !filename || typeof path !== 'string' || typeof filename !== 'string') {
throw new Error('Please provide a path and filename as valid and non empty stings.');
}
if (typeof typescript !== 'boolean') {
throw new Error('Please provide a boolean to specify the file format.');
}
return {
path: vueComponentFilePath(path, filename),
content: generateFileContent(typescript, filename),
};
},
generateTestFile: (path, filename, typescript) => {
if (!path || !filename || typeof path !== 'string' || typeof filename !== 'string') {
throw new Error('Please provide a path and filename as valid and non empty stings.');
}
if (typeof typescript !== 'boolean') {
throw new Error('Please provide a boolean to specify the file format.');
}
return {
path: vueTestFilePath(path, filename, typescript),
content: generateTestFileContent(typescript, filename),
}
}
} |
# Dryad2dataverse changelog
Perfection on the first attempt is rare.
## v.0.1.4 - 22 Sept 2021
**requirements.txt**
* Updated version requirements for `urllib3` and `requests` to plug dependabot alert hole.
**dryadd.py**
* Updated associated `dryadd.py` binaries to use newer versions of `requests` and `urllib3`
## v.0.1.3 - 10 August 2021
**setup.py**
* Enhanced information
**dryadd.py**
* Script repair for better functioning on Windows platforms
## v.0.1.2 - 4 May 2021
* fixed error in `setup.py`
* added binaries of `dryadd` for Windows and Mac
## v0.1.1 - 30 April 2021
**dryad2dataverse**
* improved versioning system
**dryad2dataverse.serializer**
* Fixed bug where keywords were only serialized when grants were present
**dryad2dataverse.transfer**
* Added better defaults for `transfer.set_correct_date`
**dryad2dataverse.monitor**
* Added meaningless change to `monitor.update` for internal consistency
**scripts/dryadd.py**
* Show version option added
* `transfer.set_correct_date()` added to set citation to match Dryad citation.
---
## v0.1.0 - 08 April 2021
* Initial release
|
package com.tuya.smart.android.demo.camera
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.util.Log
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import com.tuya.smart.android.camera.sdk.TuyaIPCSdk
import com.tuya.smart.android.demo.camera.databinding.ActivityCameraCloudVideoBinding
import com.tuya.smart.android.demo.camera.utils.Constants
import com.tuya.smart.android.demo.camera.utils.MessageUtil
import com.tuya.smart.android.demo.camera.utils.ToastUtil
import com.tuya.smart.camera.camerasdk.typlayer.callback.AbsP2pCameraListener
import com.tuya.smart.camera.camerasdk.typlayer.callback.IRegistorIOTCListener
import com.tuya.smart.camera.camerasdk.typlayer.callback.OperationCallBack
import com.tuya.smart.camera.camerasdk.typlayer.callback.OperationDelegateCallBack
import com.tuya.smart.camera.ipccamerasdk.msgvideo.ITYCloudVideo
import com.tuya.smart.camera.ipccamerasdk.p2p.ICameraP2P
import org.json.JSONObject
/**
* Cloud Video Message
* @author houqing <a href="mailto:[email protected]"/>
* @since 2021/7/27 5:50 PM
*/
class CameraCloudVideoActivity : AppCompatActivity() {
private val OPERATE_SUCCESS = 1
private val OPERATE_FAIL = 0
private val MSG_CLOUD_VIDEO_DEVICE = 1000
private var mCloudVideo: ITYCloudVideo? = null
private var playUrl: String? = null
private var encryptKey: String? = null
private var playDuration = 0
private var cachePath: String? = null
private var mDevId: String? = null
private var previewMute = ICameraP2P.MUTE
private lateinit var viewBinding: ActivityCameraCloudVideoBinding
private val mHandler: Handler = object : Handler() {
override fun handleMessage(msg: Message) {
when (msg.what) {
MSG_CLOUD_VIDEO_DEVICE -> startplay()
Constants.MSG_MUTE -> handleMute(msg)
}
super.handleMessage(msg)
}
}
private fun startplay() {
mCloudVideo?.playVideo(playUrl, 0, encryptKey, object : OperationCallBack {
override fun onSuccess(i: Int, i1: Int, s: String?, o: Any) {
Log.d("mcloudCamera", "onsuccess")
}
override fun onFailure(i: Int, i1: Int, i2: Int, o: Any) {}
}, object : OperationCallBack {
override fun onSuccess(i: Int, i1: Int, s: String?, o: Any) {
Log.d("mcloudCamera", "finish onsuccess")
}
override fun onFailure(i: Int, i1: Int, i2: Int, o: Any) {}
})
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewBinding = ActivityCameraCloudVideoBinding.inflate(layoutInflater)
setContentView(viewBinding.root)
initData()
initView()
initCloudCamera()
}
override fun onDestroy() {
super.onDestroy()
mCloudVideo?.stopVideo(null)
mCloudVideo?.removeOnDelegateP2PCameraListener()
mCloudVideo?.deinitCloudVideo()
}
private fun initData() {
playUrl = intent.getStringExtra("playUrl")
encryptKey = intent.getStringExtra("encryptKey")
playDuration = intent.getIntExtra("playDuration", 0)
mDevId = intent.getStringExtra("devId")
cachePath = application.cacheDir.path
}
private fun initCloudCamera() {
mCloudVideo = TuyaIPCSdk.getMessage()?.run { this.createVideoMessagePlayer() }
mCloudVideo?.let {
it.registerP2PCameraListener(object : AbsP2pCameraListener() {
override fun receiveFrameDataForMediaCodec(
i: Int,
bytes: ByteArray,
i1: Int,
i2: Int,
bytes1: ByteArray,
b: Boolean,
i3: Int
) {
super.receiveFrameDataForMediaCodec(i, bytes, i1, i2, bytes1, b, i3)
}
})
val listener: Any? = viewBinding.cameraCloudVideoView.createdView()
if (listener != null) {
it.generateCloudCameraView(listener as IRegistorIOTCListener)
}
it.createCloudDevice(cachePath, mDevId, object : OperationDelegateCallBack {
override fun onSuccess(sessionId: Int, requestId: Int, data: String?) {
mHandler.sendMessage(
MessageUtil.getMessage(
MSG_CLOUD_VIDEO_DEVICE,
OPERATE_SUCCESS
)
)
}
override fun onFailure(sessionId: Int, requestId: Int, errCode: Int) {}
})
}
}
private fun initView() {
viewBinding.cameraCloudVideoView.createVideoView(mDevId)
viewBinding.btnPauseVideoMsg.setOnClickListener {
mCloudVideo?.pauseVideo(null)
}
viewBinding.btnResumeVideoMsg.setOnClickListener {
mCloudVideo?.resumeVideo(null)
}
viewBinding.cameraMute.setOnClickListener { muteClick() }
viewBinding.cameraMute.isSelected = true
}
private fun muteClick() {
mCloudVideo?.let {
val mute = if (previewMute == ICameraP2P.MUTE) ICameraP2P.UNMUTE else ICameraP2P.MUTE
it.setCloudVideoMute(mute, object : OperationDelegateCallBack {
override fun onSuccess(sessionId: Int, requestId: Int, data: String?) {
val jsonObject = com.alibaba.fastjson.JSONObject.parseObject(data)
val value = jsonObject["mute"]
previewMute = Integer.valueOf(value.toString())
mHandler.sendMessage(
MessageUtil.getMessage(
Constants.MSG_MUTE,
Constants.ARG1_OPERATE_SUCCESS
)
)
}
override fun onFailure(sessionId: Int, requestId: Int, errCode: Int) {
mHandler.sendMessage(
MessageUtil.getMessage(
Constants.MSG_MUTE,
Constants.ARG1_OPERATE_FAIL
)
)
}
})
}
}
private fun handleMute(msg: Message) {
if (msg.arg1 == Constants.ARG1_OPERATE_SUCCESS) {
viewBinding.cameraMute.isSelected = previewMute == ICameraP2P.MUTE
} else {
ToastUtil.shortToast(
this@CameraCloudVideoActivity,
getString(R.string.operation_failed)
)
}
}
} |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using kc3.d.tz.common;
public class TestSceneLoad : MonoBehaviour{
// Start is called before the first frame update
[SerializeField] FadeManager fadeManager;
public void SceneLoad() {
fadeManager.FadeInAndSceneLoad();
}
}
|
<?php
/**
* [NULLED BY DARKGOTH 2014]
*/
defined('PHPFOX') or exit('NO DICE!');
/**
* Handles archives such as zip and tar.gz.
*
* Example to compress a ZIP archive:
* <code>
* Phpfox::getLib('archive', 'zip')->compress('foo', 'bar');
* </code>
*
* @copyright [PHPFOX_COPYRIGHT]
* @author Raymond Benc
* @package Phpfox
* @version $Id: archive.class.php 1666 2010-07-07 08:17:00Z Raymond_Benc $
*/
class Phpfox_Archive
{
/**
* Holds the object of the extension class depending on what sort of archive
* we are working with.
*
* @var object
*/
private $_oObject = null;
/**
* Constructor
*
*/
public function __construct($sExt = null)
{
if ($sExt)
{
switch ($sExt)
{
case 'zip':
$sObject = 'phpfox.archive.extension.zip';
break;
case 'tar.gz':
$sObject = 'phpfox.archive.extension.tar';
break;
case 'xml':
$sObject = 'phpfox.archive.extension.xml';
break;
default:
if (substr($sExt, -4) == '.zip')
{
$sObject = 'phpfox.archive.extension.zip';
}
}
(($sPlugin = Phpfox_Plugin::get('archive__construct')) ? eval($sPlugin) : false);
$this->_oObject = Phpfox::getLib($sObject);
}
}
/**
* Return the object of the extension class.
*
* @return object Object provided by the extension class we loaded earlier.
*/
public function &getInstance()
{
return $this->_oObject;
}
}
?> |
import Head from 'next/head'
import Link from 'next/link'
export default function Results() {
return (
<>
<Link href="/">
<a>Back to start</a>
</Link>
<h1>Results</h1>
</>
)
} |
module.exports = {
apps: [{
name: 'localtunnel-server',
script: './bin/server',
node_args: '-r esm',
args: '--port 1234 --secure true',
instances: 1,
exec_mode: "fork",
wait_ready: false,
watch: false,
}]
} |
use std::io::{BufWriter, Seek, SeekFrom, Write};
use sctk::seat;
use sctk::seat::keyboard::{self, Event as KeyboardEvent, KeyState, RepeatKind};
use sctk::shm::MemPool;
use sctk::window::{Event as WindowEvent, FallbackFrame};
use sctk::reexports::client::protocol::wl_shm;
use sctk::reexports::client::protocol::wl_surface::WlSurface;
use smithay_clipboard::Clipboard;
sctk::default_environment!(ClipboardExample, desktop);
/// Our dispatch data for simple clipboard access and processing frame events.
struct DispatchData {
/// Pending event from SCTK to update window.
pub pending_frame_event: Option<WindowEvent>,
/// Clipboard handler.
pub clipboard: Clipboard,
}
impl DispatchData {
fn new(clipboard: Clipboard) -> Self {
Self { pending_frame_event: None, clipboard }
}
}
fn main() {
// Setup default desktop environment
let (env, display, queue) = sctk::new_default_environment!(ClipboardExample, desktop)
.expect("unable to connect to a Wayland compositor.");
// Create event loop
let mut event_loop = sctk::reexports::calloop::EventLoop::<DispatchData>::try_new().unwrap();
// Initial window dimentions
let mut dimentions = (320u32, 240u32);
// Create surface
let surface = env.create_surface().detach();
// Create window
let mut window = env
.create_window::<FallbackFrame, _>(
surface,
None,
dimentions,
move |event, mut dispatch_data| {
// Get our dispath data
let dispatch_data = dispatch_data.get::<DispatchData>().unwrap();
// Keep last event in priority order : Close > Configure > Refresh
let should_replace_event = match (&event, &dispatch_data.pending_frame_event) {
(_, &None)
| (_, &Some(WindowEvent::Refresh))
| (&WindowEvent::Configure { .. }, &Some(WindowEvent::Configure { .. }))
| (&WindowEvent::Close, _) => true,
_ => false,
};
if should_replace_event {
dispatch_data.pending_frame_event = Some(event);
}
},
)
.expect("failed to create a window.");
// Set title and app id
window.set_title(String::from("smithay-clipboard example. Press C/P to copy/paste"));
window.set_app_id(String::from("smithay-clipboard-example"));
// Create memory pool
let mut pools = env.create_double_pool(|_| {}).expect("failed to create a memory pool.");
// Structure to track seats
let mut seats = Vec::new();
// Process existing seats
for seat in env.get_all_seats() {
let seat_data = match seat::with_seat_data(&seat, |seat_data| seat_data.clone()) {
Some(seat_data) => seat_data,
_ => continue,
};
if seat_data.has_keyboard && !seat_data.defunct {
// Suply event_loop's handle to handle key repeat
let event_loop_handle = event_loop.handle();
// Map keyboard for exising seats
let keyboard_mapping_result = keyboard::map_keyboard_repeat(
event_loop_handle,
&seat,
None,
RepeatKind::System,
move |event, _, mut dispatch_data| {
let dispatch_data = dispatch_data.get::<DispatchData>().unwrap();
process_keyboard_event(event, dispatch_data);
},
);
// Insert repeat rate handling source
match keyboard_mapping_result {
Ok((keyboard, repeat_source)) => {
seats.push((seat.detach(), Some((keyboard, repeat_source))));
}
Err(err) => {
eprintln!("Failed to map keyboard on seat {:?} : {:?}", seat_data.name, err);
seats.push((seat.detach(), None));
}
}
} else {
// Handle seats without keyboard, since they can gain keyboard later
seats.push((seat.detach(), None));
}
}
// Implement event listener for seats to handle capability change, etc
let event_loop_handle = event_loop.handle();
let _listener = env.listen_for_seats(move |seat, seat_data, _| {
// find the seat in the vec of seats or insert it
let idx = seats.iter().position(|(st, _)| st == &seat.detach());
let idx = idx.unwrap_or_else(|| {
seats.push((seat.detach(), None));
seats.len() - 1
});
let (_, mapped_keyboard) = &mut seats[idx];
if seat_data.has_keyboard && !seat_data.defunct {
// Map keyboard if it's not mapped already
if mapped_keyboard.is_none() {
let keyboard_mapping_result = keyboard::map_keyboard_repeat(
event_loop_handle.clone(),
&seat,
None,
RepeatKind::System,
move |event, _, mut dispatch_data| {
let dispatch_data = dispatch_data.get::<DispatchData>().unwrap();
process_keyboard_event(event, dispatch_data);
},
);
// Insert repeat rate source
match keyboard_mapping_result {
Ok((keyboard, repeat_source)) => {
*mapped_keyboard = Some((keyboard, repeat_source));
}
Err(err) => {
eprintln!("Failed to map keyboard on seat {} : {:?}", seat_data.name, err);
}
}
}
} else if let Some((keyboard, repeat_source)) = mapped_keyboard.take() {
if keyboard.as_ref().version() >= 3 {
keyboard.release();
}
event_loop_handle.remove(repeat_source);
}
});
if !env.get_shell().unwrap().needs_configure() {
if let Some(pool) = pools.pool() {
draw(pool, window.surface().clone(), dimentions).expect("failed to draw.")
}
// Refresh our frame
window.refresh();
}
sctk::WaylandSource::new(queue).quick_insert(event_loop.handle()).unwrap();
let clipboard = unsafe { Clipboard::new(display.get_display_ptr() as *mut _) };
let mut dispatch_data = DispatchData::new(clipboard);
loop {
if let Some(frame_event) = dispatch_data.pending_frame_event.take() {
match frame_event {
WindowEvent::Close => break,
WindowEvent::Refresh => {
window.refresh();
window.surface().commit();
}
WindowEvent::Configure { new_size, .. } => {
if let Some((w, h)) = new_size {
window.resize(w, h);
dimentions = (w, h)
}
window.refresh();
if let Some(pool) = pools.pool() {
draw(pool, window.surface().clone(), dimentions).expect("failed to draw.")
}
}
}
}
display.flush().unwrap();
event_loop.dispatch(None, &mut dispatch_data).unwrap();
}
}
fn process_keyboard_event(event: KeyboardEvent, dispatch_data: &mut DispatchData) {
let text = match event {
KeyboardEvent::Key { state, utf8: Some(text), .. } if state == KeyState::Pressed => text,
KeyboardEvent::Repeat { utf8: Some(text), .. } => text,
_ => return,
};
match text.as_str() {
// Paste primary.
"P" => {
let contents = dispatch_data
.clipboard
.load_primary()
.unwrap_or_else(|_| String::from("Failed to load primary selection"));
println!("Paste from primary clipboard: {}", contents);
}
// Paste.
"p" => {
let contents = dispatch_data
.clipboard
.load()
.unwrap_or_else(|_| String::from("Failed to load selection"));
println!("Paste: {}", contents);
}
// Copy primary.
"C" => {
let text = String::from("Copy primary");
dispatch_data.clipboard.store_primary(text.clone());
println!("Copied string into primary selection buffer: {}", text);
}
// Copy.
"c" => {
let text = String::from("Copy");
dispatch_data.clipboard.store(text.clone());
println!("Copied string: {}", text);
}
_ => (),
}
}
fn draw(
pool: &mut MemPool,
surface: WlSurface,
dimensions: (u32, u32),
) -> Result<(), std::io::Error> {
pool.resize((4 * dimensions.0 * dimensions.1) as usize).expect("failed to resize memory pool");
{
pool.seek(SeekFrom::Start(0))?;
let mut writer = BufWriter::new(&mut *pool);
for _ in 0..dimensions.0 * dimensions.1 {
// ARGB color written in LE, so it's #FF1C1C1C
writer.write_all(&[0x1c, 0x1c, 0x1c, 0xff])?;
}
writer.flush()?;
}
let new_buffer = pool.buffer(
0,
dimensions.0 as i32,
dimensions.1 as i32,
4 * dimensions.0 as i32,
wl_shm::Format::Argb8888,
);
surface.attach(Some(&new_buffer), 0, 0);
surface.commit();
Ok(())
}
|
import * as React from 'react';
import { KeyboardAvoidingView, Text, View } from 'react-native';
import { Input, Button } from 'react-native-elements';
import { useForm, Controller } from 'react-hook-form';
import { StatusBar } from 'expo-status-bar';
import { Store } from '../../state/storeProvider';
import { iamClient } from '../../service/defaultServices.js';
import { formStyles } from '../styles';
import { getClientDetails } from '../../helper/clientHelper';
export default ({ navigation }) => {
const {
handleSubmit,
control,
formState: { errors },
} = useForm({
defaultValues: {
email: '',
password: '',
},
});
const { state, dispatch } = React.useContext(Store);
const { authState, errorMessage, callInProgress } = state['auth'];
const onSubmit = async (data) => {
try {
const { email, password } = data;
const clientDetails = await getClientDetails();
const requestData = { email, password };
const responseData = await iamClient.signUp(
requestData,
clientDetails,
dispatch
);
console.log('screen:response:' + JSON.stringify(response));
if (response && !response.inError) {
navigation.navigate('ValidateEmail', { isResend: false });
}
} catch (err) {
console.log(err);
}
};
return (
<KeyboardAvoidingView behavior="height" style={formStyles.container}>
<StatusBar style="light" />
{/* <Image source={logo} style={formStyles.logo} /> */}
<View style={formStyles.inputContainer}>
<Controller
control={control}
render={({ field: { onChange, value } }) => (
<Input
placeholder="Email"
style={formStyles.input}
onChangeText={(value) => onChange(value)}
value={value}
/>
)}
name="email"
rules={{
required: 'Please enter your email',
pattern: {
value:
/^[a-zA-Z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/,
message: 'Invalid email address',
},
}}
/>
{errors.email && (
<Text style={formStyles.errorText}>{errors.email.message}</Text>
)}
<Controller
control={control}
render={({ field: { onChange, value } }) => (
<Input
placeholder="Password"
secureTextEntry
style={formStyles.input}
onChangeText={(value) => onChange(value)}
value={value}
/>
)}
name="password"
rules={{ required: 'password is required' }}
/>
{errors.password && (
<Text style={formStyles.errorText}>{errors.password.message}</Text>
)}
</View>
<Button
containerStyle={formStyles.button}
onPress={handleSubmit(onSubmit)}
title="Sign Up"
loading={callInProgress}
/>
{errorMessage && <Text style={formStyles.errorText}>{errorMessage}</Text>}
</KeyboardAvoidingView>
);
};
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// backgroundColor: '#fff',
// alignItems: 'center',
// justifyContent: 'center',
// padding: 10,
// },
// logo: {
// width: 200,
// height: 200,
// marginBottom: 20,
// },
// inputContainer: {
// width: 300,
// alignItems: 'center',
// },
// button: {
// width: 200,
// marginTop: 10,
// },
// buttonText: {
// fontSize: 20,
// color: '#fff',
// },
// errorText: {
// color: 'red',
// margin: 20,
// marginLeft: 0,
// },
// });
|
package osutil
import (
"fmt"
"github.com/rackspace/gophercloud"
"os"
)
var (
nilOptions = gophercloud.AuthOptions{}
// ErrNoAuthUrl errors occur when the value of the OS_AUTH_URL environment variable cannot be determined.
ErrNoAuthUrl = fmt.Errorf("Environment variable OS_AUTH_URL needs to be set.")
// ErrNoUsername errors occur when the value of the OS_USERNAME environment variable cannot be determined.
ErrNoUsername = fmt.Errorf("Environment variable OS_USERNAME needs to be set.")
// ErrNoPassword errors occur when the value of the OS_PASSWORD environment variable cannot be determined.
ErrNoPassword = fmt.Errorf("Environment variable OS_PASSWORD or OS_API_KEY needs to be set.")
)
// AuthOptions fills out a gophercloud.AuthOptions structure with the settings found on the various OpenStack
// OS_* environment variables. The following variables provide sources of truth: OS_AUTH_URL, OS_USERNAME,
// OS_PASSWORD, OS_TENANT_ID, and OS_TENANT_NAME. Of these, OS_USERNAME, OS_PASSWORD, and OS_AUTH_URL must
// have settings, or an error will result. OS_TENANT_ID and OS_TENANT_NAME are optional.
//
// The value of OS_AUTH_URL will be returned directly to the caller, for subsequent use in
// gophercloud.Authenticate()'s Provider parameter. This function will not interpret the value of OS_AUTH_URL,
// so as a convenient extention, you may set OS_AUTH_URL to, e.g., "rackspace-uk", or any other Gophercloud-recognized
// provider shortcuts. For broad compatibility, especially with local installations, you should probably
// avoid the temptation to do this.
func AuthOptions() (string, gophercloud.AuthOptions, error) {
provider := os.Getenv("OS_AUTH_URL")
username := os.Getenv("OS_USERNAME")
password := os.Getenv("OS_PASSWORD")
tenantId := os.Getenv("OS_TENANT_ID")
tenantName := os.Getenv("OS_TENANT_NAME")
if provider == "" {
return "", nilOptions, ErrNoAuthUrl
}
if username == "" {
return "", nilOptions, ErrNoUsername
}
if password == "" {
return "", nilOptions, ErrNoPassword
}
ao := gophercloud.AuthOptions{
Username: username,
Password: password,
TenantId: tenantId,
TenantName: tenantName,
}
return provider, ao, nil
}
|
package com.discord.simpleast.code
import com.discord.simpleast.assertNodeContents
import com.discord.simpleast.core.node.Node
import com.discord.simpleast.core.node.StyleNode
import com.discord.simpleast.core.parser.Parser
import com.discord.simpleast.core.simple.SimpleMarkdownRules
import com.discord.simpleast.core.utils.TreeMatcher
import org.junit.Before
import org.junit.Test
class JavaScriptRulesTest {
private class TestState
private lateinit var parser: Parser<TestRenderContext, Node<TestRenderContext>, TestState>
private lateinit var treeMatcher: TreeMatcher
@Before
fun setup() {
val codeStyleProviders = CodeStyleProviders<TestRenderContext>()
parser = Parser()
parser
.addRule(CodeRules.createCodeRule(
codeStyleProviders.defaultStyleProvider,
CodeRules.createCodeLanguageMap(codeStyleProviders))
)
.addRules(SimpleMarkdownRules.createSimpleMarkdownRules())
treeMatcher = TreeMatcher()
treeMatcher.registerDefaultMatchers()
}
@Test
fun comments() {
val ast = parser.parse("""
```js
/** Multiline
Comment
*/
foo.bar(); // Inlined
// Line comment
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>(
"""
/** Multiline
Comment
*/
""".trimIndent(),
"// Inlined",
"// Line comment")
}
@Test
fun strings() {
val ast = parser.parse("""
```js
x = 'Hello';
y = "world";
log(`Hi`);
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>(
"'Hello'",
"\"world\"",
"`Hi`")
}
@Test
fun stringsMultiline() {
val ast = parser.parse("""
```js
text = `
hello
world
`;
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>(
"""
`
hello
world
`
""".trimIndent(),
)
}
@Test
fun functions() {
val ast = parser.parse("""
```js
function test(T) {
// Implementation
}
fn = function () {};
function* generator() {}
static test() {}
async fetch() {}
get tokens() {}
set constants() {}
```
""".trimIndent(), TestState())
ast.assertNodeContents<JavaScript.FunctionNode<*>>(
"function test(T)",
"function ()",
"function* generator()",
"static test()",
"async fetch()",
"get tokens()",
"set constants()")
}
@Test
fun commentedFunction() {
val ast = parser.parse("""
```js
/*
function test(T) {
throw new Error();
}
*/
// function O() {}
log(x /* test var */);
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>(
"""
/*
function test(T) {
throw new Error();
}
*/
""".trimIndent(),
"// function O() {}",
"/* test var */")
}
@Test
fun keywords() {
val ast = parser.parse("""
```js
while (true) {}
for (;;) {}
if (false) {}
class {}
try {
} catch (err) {
throw
} finally {
return;
}
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>(
"while", "true",
"for", "if", "false",
"class", "try", "catch",
"throw", "finally", "return")
}
@Test
fun numbers() {
val ast = parser.parse("""
```js
x = 0;
x += 69;
max(x, 420);
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>(
"0", "69", "420"
)
}
@Test
fun fields() {
val ast = parser.parse("""
```js
var foo = x;
let bar = y;
const baz = z;
```
""".trimIndent(), TestState())
ast.assertNodeContents<JavaScript.FieldNode<*>>(
"var foo",
"let bar",
"const baz")
}
@Test
fun classDef() {
val ast = parser.parse("""
```js
class Bug {}
```
""".trimIndent(), TestState())
ast.assertNodeContents<CodeNode.DefinitionNode<*>>(
"class Bug")
}
@Test
fun regex() {
val ast = parser.parse("""
```js
/(.*)/g
/[\$\{\}]/
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>("/(.*)/g", """/[\$\{\}]/""")
}
@Test
fun generics() {
val ast = parser.parse("""
```js
<pending>
```
""".trimIndent(), TestState())
ast.assertNodeContents<StyleNode.TextStyledNode<*>>("<pending>")
}
@Test
fun objectProperties() {
val ast = parser.parse("""
```js
{ foo: bar }
```
""".trimIndent(), TestState())
ast.assertNodeContents<JavaScript.ObjectPropertyNode<*>>("{ foo:")
}
}
|
package pregnaware.naming.entities
import java.time.LocalDate
case class WrappedBabyName(
nameId: Int, userId: Int,
suggestedBy: Int, suggestedByName: String, suggestedDate: LocalDate,
name: String, isBoy: Boolean)
|
/*
* If not stated otherwise in this file or this component's license file the
* following copyright and licenses apply:
*
* Copyright 2018 RDK Management
*
* 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.
*/
/**
* @file aampoutputprotection.h
* @brief Comcast Output protection management for Aamp
*/
#ifndef aampoutputprotection_h
#define aampoutputprotection_h
#include <pthread.h>
#ifdef IARM_MGR
// IARM
#include "manager.hpp"
#include "host.hpp"
#include "videoResolution.hpp"
#include "videoOutputPort.hpp"
#include "videoOutputPortType.hpp"
#include <libIARM.h>
#include <libIBus.h>
#include "libIBusDaemon.h"
#include "dsMgr.h"
#include "dsDisplay.h"
#include <iarmUtil.h>
#else
#include <stdint.h>
typedef int dsHdcpProtocolVersion_t;
#define dsHDCP_VERSION_MAX 30
#define dsHDCP_VERSION_2X 22
#define dsHDCP_VERSION_1X 14
#endif // IARM_MGR
#include <stdio.h>
#include <gst/gst.h>
#ifndef USE_OPENCDM
#ifdef USE_PLAYREADY
#include <drmbuild_oem.h>
#include <drmcommon.h>
#include <drmmanager.h>
#include <drmmathsafe.h>
#include <drmtypes.h>
#include <drmerr.h>
#endif
#endif
#undef __in
#undef __out
using namespace std;
#define UHD_WITDH 3840
#define UHD_HEIGHT 2160
/**
* @class ReferenceCount
* @brief Provides reference based memory management
*/
class ReferenceCount
{
public:
ReferenceCount() : m_refCount(0), m_refCountMutex() {
pthread_mutex_init(&m_refCountMutex, NULL);
}
virtual ~ReferenceCount() {
pthread_mutex_destroy(&m_refCountMutex);
}
uint32_t AddRef() const {
pthread_mutex_lock(&m_refCountMutex);
m_refCount++;
pthread_mutex_unlock(&m_refCountMutex);
return m_refCount;
}
void Release() const {
pthread_mutex_lock(&m_refCountMutex);
m_refCount--;
pthread_mutex_unlock(&m_refCountMutex);
if(m_refCount == 0) {
delete (ReferenceCount *)this;
}
}
private:
mutable pthread_mutex_t m_refCountMutex;
mutable int m_refCount;
};
/**
* @class AampOutputProtection
* @brief Class to enforce HDCP authentication
*/
class AampOutputProtection : public ReferenceCount
{
private:
#ifndef USE_OPENCDM
#ifdef USE_PLAYREADY
// Protection levels from CDM
struct MinOPLevelsplayReady
{
DRM_WORD compressedDigitalVideo;
DRM_WORD uncompressedDigitalVideo;
DRM_WORD analogVideo;
DRM_WORD compressedDigitalAudio;
DRM_WORD uncompressedDigitalAudio;
};
#endif
#endif
pthread_mutex_t m_opProtectMutex;
#ifndef USE_OPENCDM
#ifdef USE_PLAYREADY
MinOPLevelsplayReady m_minOPLevels;
#endif
#endif
int m_sourceWidth;
int m_sourceHeight;
int m_displayWidth;
int m_displayHeight;
bool m_isHDCPEnabled;
dsHdcpProtocolVersion_t m_hdcpCurrentProtocol;
GstElement* m_gstElement;
void SetHDMIStatus();
void SetResolution(int width, int height);
public:
AampOutputProtection();
virtual ~AampOutputProtection();
AampOutputProtection(const AampOutputProtection&) = delete;
AampOutputProtection& operator=(const AampOutputProtection&) = delete;
#ifndef USE_OPENCDM
/**
* @brief Get PlayRedy OP levels
* @retval m_minOPLevels
*/
#ifdef USE_PLAYREADY
MinOPLevelsplayReady* getPlayReadyLevels() { return & m_minOPLevels; }
static DRM_RESULT DRM_CALL PR_OP_Callback(const DRM_VOID *f_pvOutputLevelsData,
DRM_POLICY_CALLBACK_TYPE f_dwCallbackType,
const DRM_VOID *data);
#endif
#endif
#ifdef IARM_MGR
// IARM Callbacks
static void HDMIEventHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len);
static void ResolutionHandler(const char *owner, IARM_EventId_t eventId, void *data, size_t len);
#endif //IARM_MGR
// State functions
/**
* @brief Check if HDCP is 2.2
* @retval true if 2.2 false otherwise
*/
bool isHDCPConnection2_2() { return m_hdcpCurrentProtocol == dsHDCP_VERSION_2X; }
bool IsSourceUHD();
/**
* @brief gets display resolution
* @param[out] int width : Display Width
* @param[out] int height : Display height
*/
void GetDisplayResolution(int &width, int &height);
/**
* @brief Set GstElement
* @param element
*/
void setGstElement(GstElement *element) { m_gstElement = element; }
// Singleton for object creation
static AampOutputProtection * GetAampOutputProcectionInstance();
static bool IsAampOutputProcectionInstanceActive();
};
#endif // aampoutputprotection_h
|
---
title: "알기 쉬운 약리학"
date: 2021-08-15 04:43:37
categories: [국내도서, 전공도서-대학교재]
image: https://bimage.interpark.com/goods_image/3/3/4/7/315323347s.jpg
description: ● ● ▶ 이 책은 약리학을 다룬 이론서입니다.
---
## **정보**
- **ISBN : 9791189487560**
- **출판사 : 메디컬사이언스**
- **출판일 : 20190816**
- **저자 : Hitner, Henry**
------
## **요약**
● ● ▶ 이 책은 약리학을 다룬 이론서입니다.
------
------
알기 쉬운 약리학
------
## **리뷰**
5.0 강-리 잘받았어요 2021.03.03 <br/>5.0 이-리 유익해염 2020.09.20 <br/>5.0 이-아 좋아요 2020.09.17 <br/> |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using OLEDB.Test.ModuleCore;
using XmlCoreTest.Common;
using Xunit;
namespace System.Xml.Tests
{
public class TCNewLineOnAttributes
{
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom & WriterType.AllButIndenting)]
public void NewLineOnAttributes_1(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.NewLineOnAttributes = true;
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineOnAttributes, false, "Mismatch in NewLineOnAttributes");
w.WriteStartElement("root");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root attr1=\"value1\" attr2=\"value2\" />"));
}
[Theory]
[XmlWriterInlineData(WriterType.AllButCustom)]
public void NewLineOnAttributes_2(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.Indent = true;
wSettings.NewLineOnAttributes = true;
XmlWriter w = utils.CreateWriter(wSettings);
CError.Compare(w.Settings.NewLineOnAttributes, true, "Mismatch in NewLineOnAttributes");
w.WriteStartElement("root");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareString("<root" + wSettings.NewLineChars + " attr1=\"value1\"" + wSettings.NewLineChars + " attr2=\"value2\" />"));
}
[Theory]
[XmlWriterInlineData]
public void NewLineOnAttributes_3(XmlWriterUtils utils)
{
XmlWriterSettings wSettings = new XmlWriterSettings();
wSettings.OmitXmlDeclaration = true;
wSettings.Indent = true;
wSettings.NewLineOnAttributes = true;
XmlWriter w = utils.CreateWriter(wSettings);
w.WriteStartElement("level1");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteStartElement("level2");
w.WriteAttributeString("attr1", "value1");
w.WriteAttributeString("attr2", "value2");
w.WriteEndElement();
w.WriteEndElement();
w.Dispose();
Assert.True(utils.CompareBaseline("NewLineOnAttributes3.txt"));
}
}
}
|
package sagan.renderer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
/**
* Application that renders lightweight markup languages
* and Spring guides content into HTML
*/
@SpringBootApplication
@EnableConfigurationProperties(RendererProperties.class)
public class RendererApplication {
public static void main(String[] args) {
SpringApplication.run(RendererApplication.class, args);
}
}
|
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_EXTENSIONS_API_TAB_GROUPS_TAB_GROUPS_API_H_
#define CHROME_BROWSER_EXTENSIONS_API_TAB_GROUPS_TAB_GROUPS_API_H_
#include <string>
#include "extensions/browser/extension_function.h"
namespace tab_groups {
class TabGroupId;
}
namespace extensions {
class TabGroupsGetFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("tabGroups.get", TAB_GROUPS_GET)
TabGroupsGetFunction() = default;
TabGroupsGetFunction(const TabGroupsGetFunction&) = delete;
TabGroupsGetFunction& operator=(const TabGroupsGetFunction&) = delete;
// ExtensionFunction:
ResponseAction Run() override;
protected:
~TabGroupsGetFunction() override = default;
};
class TabGroupsQueryFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("tabGroups.query", TAB_GROUPS_QUERY)
TabGroupsQueryFunction() = default;
TabGroupsQueryFunction(const TabGroupsQueryFunction&) = delete;
TabGroupsQueryFunction& operator=(const TabGroupsQueryFunction&) = delete;
// ExtensionFunction:
ResponseAction Run() override;
protected:
~TabGroupsQueryFunction() override = default;
};
class TabGroupsUpdateFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("tabGroups.update", TAB_GROUPS_UPDATE)
TabGroupsUpdateFunction() = default;
TabGroupsUpdateFunction(const TabGroupsUpdateFunction&) = delete;
TabGroupsUpdateFunction& operator=(const TabGroupsUpdateFunction&) = delete;
// ExtensionFunction:
ResponseAction Run() override;
protected:
~TabGroupsUpdateFunction() override = default;
};
class TabGroupsMoveFunction : public ExtensionFunction {
public:
DECLARE_EXTENSION_FUNCTION("tabGroups.move", TAB_GROUPS_MOVE)
TabGroupsMoveFunction() = default;
TabGroupsMoveFunction(const TabGroupsMoveFunction&) = delete;
TabGroupsMoveFunction& operator=(const TabGroupsMoveFunction&) = delete;
// ExtensionFunction:
ResponseAction Run() override;
protected:
~TabGroupsMoveFunction() override = default;
private:
// Moves the group with ID |group_id| to the |new_index| in the window with ID
// |window_id|. If |window_id| is not specified, moves the group within its
// current window. |group| is populated with the group's TabGroupId, and
// |error| is populated if the group cannot be found or moved.
bool MoveGroup(int group_id,
int new_index,
int* window_id,
tab_groups::TabGroupId* group,
std::string* error);
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_TAB_GROUPS_TAB_GROUPS_API_H_
|
// constructor function for the Cat class
const net = require('net');
const IdGenerator = require('shortid');
var frameType = require('./Frame');
const { Transform } = require('stream');
var TCPPHY = function (port, host) {
this.upper_layer = null;
this.lower_layer = null;
this.port = port;
this.host = host;
this.buffer_collector = Buffer.alloc(0);
var self = this;
this.bufferSplitter = new Transform({
readableObjectMode: true,
transform(chunk, encoding, callback) {
if (self.buffer_collector) {
self.buffer_collector = Buffer.concat([self.buffer_collector, chunk]);
} else {
self.buffer_collector = Buffer.from(chunk);
}
if (self.buffer_collector.length >= 16) {
var _bufferHeader = Buffer.alloc(16);
self.buffer_collector.copy(_bufferHeader, 0, 0, 15);
var header = frameType.decodeHeader(_bufferHeader);
if (header) {
if (self.buffer_collector.length >= header.DataSize + 16) {
var sliced_buffer = self.buffer_collector.slice(0, header.DataSize + 16);
var rest = Buffer.alloc(self.buffer_collector.length - (header.DataSize + 16));
self.buffer_collector.copy(rest, 0, header.DataSize + 16, self.buffer_collector.length);
self.buffer_collector = rest;
this.push([sliced_buffer]);
}
}
}
callback();
}
});
this.server = net.createServer(
function (socket) {
console.log((new Date()) + ' - A client connected to server...' + JSON.stringify(socket.address()));
socket.id = IdGenerator.generate();
socket.pipe(self.bufferSplitter)
.on('data', function (data) {
if(self.started){
self.handleReceived(data, socket);
}
});
}
);
this.server.on('error', (err) => {
throw err;
});
this.started = false;
}
TCPPHY.prototype.start = function () {
var self = this;
self.server.listen(self.port, self.host, function () {
console.log("Server listening on port: " + self.port);
});
this.started = true;
};
TCPPHY.prototype.stop = function () {
this.server.close();
this.started = false;
};
TCPPHY.prototype.setUpperLayer = function (upper_layer) {
this.upper_layer = upper_layer;
};
TCPPHY.prototype.setUpperLayer = function (upper_layer) {
this.upper_layer = upper_layer;
};
TCPPHY.prototype.getUpperLayer = function () {
return this.upper_layer;
};
TCPPHY.prototype.setLowerLayer = function (lower_layer) {
this.lower_layer = lower_layer;
};
TCPPHY.prototype.getLowerLayer = function () {
return this.lower_layer;
};
TCPPHY.prototype.transmit = function (buffer, socket) {
socket.write(buffer);
};
TCPPHY.prototype.handleReceived = function (buffers, socket) {
if (this.getUpperLayer()) {
this.getUpperLayer().handleReceived(buffers[0], socket);
}
};
// Now we export the module
module.exports = TCPPHY; |
# set_db_env_vars.inc.sh: Functions used by the set_db_env_vars script
set_db_env_vars () {
local config_file="${1}"
# Read in and export all name=value pairs where the name starts with PG
# unless we already have an env var with that value
# (NOTE: all whitespaces are removed from each line)
while read -r DBVAR
do
if ! $(env | grep -qFle "${DBVAR%%=*}"); then
eval "export ${DBVAR}"
fi
done < <(grep -Ee '^PG' "${config_file}" | sed 's/ //g')
}
|
package org.demo.archknife
import androidx.lifecycle.ViewModel
import archknife.annotation.ProvideViewModel
import javax.inject.Inject
@ProvideViewModel
class MainActivityViewModel
@Inject constructor(testObject: TestObject) : ViewModel() {
init {
testObject.doSomething()
}
} |
import React from 'react'
import { Switch, Route, Redirect } from 'react-router-dom'
import FormPage from './FormPage'
import FormPostConfirmation from './FormPostConfirmation'
import Page2 from './Page2'
import Page3 from './Page3'
import Page4 from './Page4'
const Routes = () => (
<Switch>
<Route exact path="/" component={FormPage} />
<Route exact path="/post" component={FormPostConfirmation} />
<Route exact path="/page2" component={Page2} />
<Route exact path="/page3" component={Page3} />
<Route exact path="/page4" component={Page4} />
{/* catch any invalid URLs */}
<Redirect to="/" />
</Switch>
)
export default Routes
|
// SPDX-License-Identifier: MIT
// Copyright (c) 2018-2020 The Pybricks Authors
#include <pbdrv/config.h>
#include "pbinit.h"
#define MICROPY_HW_BOARD_NAME "LEGO MINDSTORMS EV3 Intelligent Brick"
#define MICROPY_HW_MCU_NAME "Texas Instruments AM1808"
#define PYBRICKS_HUB_EV3BRICK (1)
// Pybricks modules
#define PYBRICKS_PY_COMMON (1)
#define PYBRICKS_PY_COMMON_IMU (0)
#define PYBRICKS_PY_COMMON_KEYPAD (1)
#define PYBRICKS_PY_COMMON_LIGHT_MATRIX (0)
#define PYBRICKS_PY_COMMON_MOTORS (1)
#define PYBRICKS_PY_EV3DEVICES (1)
#define PYBRICKS_PY_EXPERIMENTAL (1)
#define PYBRICKS_PY_GEOMETRY (1)
#define PYBRICKS_PY_HUBS (1)
#define PYBRICKS_PY_IODEVICES (1)
#define PYBRICKS_PY_MEDIA (0)
#define PYBRICKS_PY_MEDIA_EV3DEV (1)
#define PYBRICKS_PY_NXTDEVICES (1)
#define PYBRICKS_PY_PARAMETERS (1)
#define PYBRICKS_PY_PARAMETERS_BUTTON (1)
#define PYBRICKS_PY_PARAMETERS_ICON (0)
#define PYBRICKS_PY_PUPDEVICES (0)
#define PYBRICKS_PY_ROBOTICS (1)
#define PYBRICKS_PY_TOOLS (1)
#define PYBRICKS_PY_USIGNAL (1)
#define MICROPY_PORT_INIT_FUNC pybricks_init()
#define MICROPY_PORT_DEINIT_FUNC pybricks_deinit()
#define MICROPY_MPHALPORT_H "ev3dev_mphal.h"
#define MICROPY_PY_SYS_PATH_DEFAULT (":~/.pybricks-micropython/lib:/usr/lib/pybricks-micropython")
extern const struct _mp_obj_module_t pb_package_pybricks;
#define _PYBRICKS_PACKAGE_PYBRICKS \
{ MP_OBJ_NEW_QSTR(MP_QSTR__pybricks), (mp_obj_t)&pb_package_pybricks },
extern const struct _mp_obj_module_t pb_module_bluetooth;
extern const struct _mp_obj_module_t pb_module_media_ev3dev;
extern const struct _mp_obj_module_t pb_module_usignal;
#define PYBRICKS_PORT_BUILTIN_MODULES \
_PYBRICKS_PACKAGE_PYBRICKS \
{ MP_ROM_QSTR(MP_QSTR_bluetooth_c), MP_ROM_PTR(&pb_module_bluetooth) }, \
{ MP_ROM_QSTR(MP_QSTR_media_ev3dev_c), MP_ROM_PTR(&pb_module_media_ev3dev) }, \
{ MP_ROM_QSTR(MP_QSTR_usignal), MP_ROM_PTR(&pb_module_usignal) },
|
# ART
ART is a retained mode vector drawing API designed for multiple output modes.
There's also a built-in SVG parser. It uses Node style CommonJS modules.
The first line in your program should select rendering mode by requiring either:
- __art/modes/canvas__ - HTML5 Canvas
- __art/modes/svg__ - SVG for modern browsers and vector tools
- __art/modes/vml__ - VML for Internet Explorer or Office
- __art/modes/script__ - Code generation for ART modules
- __art/modes/dom__ - SVG or VML depending on environment
- __art/modes/fast__ - Canvas, SVG or VML depending on environment
These modules exposes four core rendering classes:
- __Surface__ - Required rectangular rendering area. Container for the rest.
- __Group__ - Container for Shapes, Text or other Groups.
- __Shape__ - Fill and/or stroke an arbitrary vector path.
- __Text__ - Fill and/or stroke text content rendered using native fonts.
There are also helper classes to work with vector paths, 3x3 transformation
matrices, colors, morphing, common shapes etc.
#Demos
[See ./demos](./demos)
|
package org.oso.core.services
import org.oso.core.entities.Emergency
import org.oso.core.entities.HelpProvider
interface EmergencyStatusService {
fun addStatus(emergency: Emergency, helpProvider: HelpProvider, status: String)
} |
package com.github.android.quick.core
/**
* Created by XuCanHui on 2021/1/23.
*/
class BaseActivity {
} |
/**
* support libraries
*/
object Support {
// material
const val material = "com.google.android.material:material:${Versions.material}"
// constraint layout
const val constraintLayout = "androidx.constraintlayout:constraintlayout:${Versions.constraintLayout}"
// appCompat
const val appCompat = "androidx.appcompat:appcompat:${Versions.appCompat}"
}
|
require 'cgi'
module Seahorse
module Client
module Plugins
class RestfulBindings < Plugin
# @api private
class Handler < Client::Handler
def call(context)
build_request(context)
@handler.call(context).on(200..299) do |response|
parse_response(response)
end
end
private
def build_request(context)
populate_method(context)
populate_headers(context)
populate_body(context)
end
def populate_method(context)
context.http_request.http_method = context.operation.http_method
end
def populate_headers(context)
context.operation.input.header_members.each do |member_name, member|
value = context.params[member_name]
unless value.nil?
build_header(member, context.http_request.headers, value)
end
end
end
def populate_body(context)
input = context.operation.input
if input.raw_payload?
payload = context.params[input.payload]
context.http_request.body = payload unless payload.nil?
end
end
def build_header(rule, headers, value)
if map_shape?(rule)
build_header_map(rule, headers, value)
else
headers[rule.serialized_name] = serialize_header_value(rule, value)
end
end
def build_header_map(shape, headers, hash)
hash.each_pair do |suffix, value|
headers["#{shape.serialized_name}#{suffix}"] =
serialize_header_value(shape.members, value)
end
end
def serialize_header_value(shape, value)
case shape
when Model::Shapes::UnixTimestampShape then value.to_i.to_s
when Model::Shapes::Rfc822TimestampShape then value.utc.rfc822
when Model::Shapes::Iso8601TimestampShape then value.utc.iso8601
else value.to_s
end
end
def parse_response(response)
output = response.context.operation.output
response.data ||= Aws::Structure.new(output.members.keys)
extract_status_code(response)
extract_headers(response)
extract_body(response)
end
def extract_status_code(response)
if member = response.context.operation.output.status_code_member
status_code = response.context.http_response.status_code
response.data[member.member_name] = status_code
end
end
def extract_headers(response)
headers = response.context.http_response.headers
rules = response.context.operation.output.header_members
rules.each do |member_name, member|
response.data[member_name] = header_value(member, headers)
end
end
def header_value(shape, headers)
if map_shape?(shape)
header_map(shape, headers)
else
parse_header_value(shape, headers[shape.serialized_name])
end
end
def header_map(shape, headers)
hash = {}
headers.each do |header, value|
if match = header.match(/^#{shape.serialized_name}(.+)/)
hash[match[1]] = parse_header_value(shape.members, value)
end
end
hash
end
def parse_header_value(shape, value)
if value
case shape
when Model::Shapes::UnixTimestampShape then Time.at(value.to_i)
when Model::Shapes::TimestampShape then Time.parse(value)
when Model::Shapes::IntegerShape then value.to_i
when Model::Shapes::FloatShape then value.to_f
when Model::Shapes::BooleanShape then value == 'true'
else value
end
end
end
def extract_body(response)
output = response.context.operation.output
if output.raw_payload?
response.data[output.payload] = response.context.http_response.body
end
end
def map_shape?(shape)
shape.is_a?(Model::Shapes::MapShape)
end
end
handle(Handler, priority: 90)
end
end
end
end
|
import AnswerHub, {Question} from "./AnswerHub";
import fs = require("fs");
import fetch from "node-fetch";
const MINIMUM_CONFIDENCE = 0; // TODO set this
const LAST_QUESTION_FILE = `${__dirname}/../data/last_question_timestamp.txt`;
const CONFIG_FILE = `${__dirname}/../config.json`;
/** How often to check the forums (in seconds) */
const CHECK_INTERVAL = 5;
const ANSWER_URL = "http://localhost:41170/autoguru/answer-stub";
const config = JSON.parse(fs.readFileSync(CONFIG_FILE).toString());
const answerHub = new AnswerHub(
"https://discussion.developer.riotgames.com/",
config.answerhub_credentials.username,
config.answerhub_credentials.password
);
const answerQuestion = async (question: Question) => {
const response = await fetch(ANSWER_URL, {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({question: question.body})
});
if (response.status !== 200) {
console.error(`Received ${response.status} code from question anwering server`);
return;
}
const body = await response.json();
if (body.confidence > MINIMUM_CONFIDENCE) {
await answerHub.answerQuestion(question.id, body.content);
}
};
setInterval(async () => {
let lastQuestionTime: number = 0;
if (fs.existsSync(LAST_QUESTION_FILE)) {
lastQuestionTime = +fs.readFileSync(LAST_QUESTION_FILE).toString();
}
try {
const questions = await answerHub.getQuestions(0, "newest");
for (const question of questions.list) {
try {
if (question.creationDate > lastQuestionTime) {
console.log("Found a question that needs to be answered");
await answerQuestion(question);
}
} catch (ex) {
console.error(`Error occurred while responding to question ${question.id}: ${ex}`);
}
if (lastQuestionTime < question.creationDate) {
lastQuestionTime = question.creationDate;
}
}
} catch (ex) {
console.error(`Error checking questions: ${ex}`);
}
fs.writeFileSync(LAST_QUESTION_FILE, lastQuestionTime);
}, CHECK_INTERVAL * 1000);
|
using AutoMapper;
using DIGNDB.App.SmitteStop.Domain.Db;
using DIGNDB.App.SmitteStop.Domain.Dto;
namespace DIGNDB.App.SmitteStop.API.Mappers
{
public class ApplicationStatisticsMapper : Profile
{
public ApplicationStatisticsMapper()
{
CreateMap<ApplicationStatistics, AppStatisticsDto>()
.ForMember(x => x.NumberOfPositiveTestsResultsLast7Days,
opts => opts.MapFrom(x => x.PositiveResultsLast7Days))
.ForMember(x => x.NumberOfPositiveTestsResultsTotal,
opts => opts.MapFrom(x => x.PositiveTestsResultsTotal))
.ForMember(x => x.SmittestopDownloadsTotal,
opts => opts.MapFrom(x => x.TotalSmittestopDownloads));
}
}
} |
// ctan_ex.c : ctan() example
// --------------------------------------------------------------------
#include <complex.h> // double complex ctan( double complex z );
// float complex ctanf( float complex z );
// long double complex ctanl( long double complex z );
#include <stdio.h>
int main()
{
double complex z = -0.53 + 0.62 * I;
double complex c, d;
c = ctan( z );
d = csin( z ) / ccos( z );
printf("The ctan() function returns %.2f %+.2f × I.\n",
creal(c), cimag(c) );
printf("Using the csin() and ccos() functions yields %.2f %+.2f × I.\n",
creal(d), cimag(d) );
return 0;
}
|
import {
DOMOutputSpec,
DOMSerializer,
Node as PmNode,
} from 'prosemirror-model';
import { EditorView, NodeView } from 'prosemirror-view';
import React from 'react';
import ReactNodeView, {
ForwardRef,
getPosHandler,
getPosHandlerNode,
} from '../../../nodeviews/ReactNodeView';
import { PortalProviderAPI } from '../../../ui/PortalProvider';
import WithPluginState from '../../../ui/WithPluginState';
import { pluginKey as widthPluginKey } from '../../width';
import { pluginConfig as getPluginConfig } from '../create-plugin-config';
import { getPluginState, pluginKey } from '../pm-plugins/plugin-factory';
import { pluginKey as tableResizingPluginKey } from '../pm-plugins/table-resizing/index';
import { generateColgroup } from '../pm-plugins/table-resizing/utils';
import TableComponent from './TableComponent';
import { Props, TableOptions } from './types';
const tableAttributes = (node: PmNode) => {
return {
'data-number-column': node.attrs.isNumberColumnEnabled,
'data-layout': node.attrs.layout,
'data-autosize': node.attrs.__autoSize,
};
};
const toDOM = (node: PmNode, props: Props) => {
let colgroup: DOMOutputSpec = '';
if (props.allowColumnResizing) {
// @ts-ignore
colgroup = ['colgroup', {}].concat(generateColgroup(node));
}
return [
'table',
tableAttributes(node),
colgroup,
['tbody', 0],
] as DOMOutputSpec;
};
export default class TableView extends ReactNodeView<Props> {
private table: HTMLElement | undefined;
getPos: getPosHandlerNode;
constructor(props: Props) {
super(props.node, props.view, props.getPos, props.portalProviderAPI, props);
this.getPos = props.getPos;
}
getContentDOM() {
const rendered = DOMSerializer.renderSpec(
document,
toDOM(this.node, this.reactComponentProps as Props),
);
if (rendered.dom) {
this.table = rendered.dom as HTMLElement;
}
return rendered;
}
setDomAttrs(node: PmNode) {
if (!this.table) {
return;
}
const attrs = tableAttributes(node);
(Object.keys(attrs) as Array<keyof typeof attrs>).forEach((attr) => {
this.table!.setAttribute(attr, attrs[attr]);
});
}
render(props: Props, forwardRef: ForwardRef) {
return (
<WithPluginState
plugins={{
containerWidth: widthPluginKey,
pluginState: pluginKey,
tableResizingPluginState: tableResizingPluginKey,
}}
editorView={props.view}
render={(pluginStates) => (
<TableComponent
{...props}
{...pluginStates}
node={this.node}
width={pluginStates.containerWidth.width}
contentDOM={forwardRef}
/>
)}
/>
);
}
ignoreMutation() {
return true;
}
}
export const createTableView = (
node: PmNode,
view: EditorView,
getPos: getPosHandler,
portalProviderAPI: PortalProviderAPI,
options: TableOptions,
): NodeView => {
const { pluginConfig } = getPluginState(view.state);
const { allowColumnResizing } = getPluginConfig(pluginConfig);
return new TableView({
node,
view,
allowColumnResizing,
portalProviderAPI,
getPos: getPos as getPosHandlerNode,
options,
}).init();
};
|
#!/bin/bash
psql -U postgres -h localhost --set ON_ERROR_STOP=on businesses < businesses_backup.sql
|
import { SelectInputOption } from "../../../../../../../shared/components/inputs/select-input/interfaces";
export interface AddStudentFormValues {
firstName: string;
lastName: string;
email: string;
phone: string;
cpfCnpj: string;
}
|
#! /usr/bin/bash
# only for local test, not used for github action
nvim +'Vader! test/test_command.vader'
nvim +'Vader! test/test_keymap.vader'
nvim +'Vader! test/test_function.vader'
nvim +'Vader! test/test_floaterm_size.vader'
|
package com.mburakcakir.taketicket.ui.entry.login
import android.os.Bundle
import android.text.Editable
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import com.mburakcakir.taketicket.databinding.FragmentLoginBinding
import com.mburakcakir.taketicket.ui.entry.CustomTextWatcher
import com.mburakcakir.taketicket.util.enums.EntryState
import com.mburakcakir.taketicket.util.enums.EntryType
import com.mburakcakir.taketicket.util.navigate
import com.mburakcakir.taketicket.util.toast
class LoginFragment : Fragment() {
private lateinit var loginViewModel: LoginViewModel
private var _binding: FragmentLoginBinding? = null
private val binding get() = _binding!!
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentLoginBinding.inflate(inflater, container, false)
return binding.root
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
init()
}
fun init() {
loginViewModel = ViewModelProvider(this).get(LoginViewModel::class.java)
loginViewModel.setEntryType(EntryType.LOGIN)
binding.loginViewModel = loginViewModel
binding.lifecycleOwner = viewLifecycleOwner
binding.btnRegister.setOnClickListener {
this.navigate(LoginFragmentDirections.actionLoginFragmentToRegisterFragment())
}
binding.edtUsername.afterTextChanged {
loginViewModel.isDataChanged(
EntryState.USERNAME,
binding.edtUsername.text.toString()
)
}
binding.edtPassword.afterTextChanged {
loginViewModel.isDataChanged(
EntryState.PASSWORD,
binding.edtPassword.text.toString()
)
}
loginViewModel.result.observe(viewLifecycleOwner, {
when {
!it.success.isNullOrEmpty() -> {
this.navigate(LoginFragmentDirections.actionLoginFragmentToHomeFragment())
it.success
}
!it.loading.isNullOrEmpty() -> it.loading
!it.warning.isNullOrEmpty() -> it.warning
else -> it.error
}?.let { message ->
requireContext() toast message
}
})
}
private fun EditText.afterTextChanged(afterTextChanged: (String) -> Unit) {
addTextChangedListener(object : CustomTextWatcher() {
override fun afterTextChanged(editable: Editable?) {
afterTextChanged.invoke(editable.toString())
}
})
}
} |
/*
* Licensed under the Apache License, Version 2.0 (the "License"); you
* may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.sdap.mudrod.ontology;
import java.util.Iterator;
/**
* Base class for working with ontologies. Methods indicate ability
* to load, merge e.g. merge relevant ontology subgraphs into a new
* subgraph which can be used within Mudrod, subclass retreival,
* synonym expansion, etc.
*
* @author lewismc
*/
public interface Ontology {
/**
* Load an array URIs which resolve to ontology resources.
*
* @param urls a {@link java.lang.String} containing ontology URIs.
*/
public void load(String[] urls);
/**
* Load a collection of default ontology resources.
*/
public void load() ;
/**
* merge relevant ontology subgraphs into a new subgraph which can
* be used within Mudrod
*
* @param o an ontology to merge with the current ontology held
* within Mudrod.
*/
public void merge(Ontology o);
/**
* Retreive all subclasses for a particular entity provided within the
* search term e.g.subclass-based query expansion.
*
* @param entitySearchTerm an input search term
* @return an {@link java.util.Iterator} object containing subClass entries.
*/
public Iterator<String> subclasses(String entitySearchTerm);
/**
* Retreive all synonyms for a particular entity provided within the
* search term e.g.synonym-based query expansion.
*
* @param queryKeyPhrase a phrase to undertake synonym expansion on.
* @return an {@link java.util.Iterator} object containing synonym entries.
*/
public Iterator<String> synonyms(String queryKeyPhrase);
}
|
/**
* Created by liuxuwen on 18-11-17.
*/
import { Directive, ElementRef,HostListener,Input } from '@angular/core';
@Directive({
selector: '[inputNumber]'
})
export class InputNumberDirective {
@Input('inputNumber') max_number: number;
constructor(private el: ElementRef) {
}
@HostListener('keyup') onkeyup() {
if(!Number(this.el.nativeElement.value) ||
(Number(this.el.nativeElement.value) > this.max_number)) {
this.el.nativeElement.value = this.max_number;
}
}
@HostListener('paste') onPaste() {
return false;
}
@HostListener('keypress') onkeypress() {
return true;
}
@HostListener('keydown') onkeydown() {
return true;
}
} |
# Read about factories at https://github.com/thoughtbot/factory_girl
FactoryGirl.define do
factory :reading do
temp 68
original_temp { temp }
outdoor_temp 40
association :user
association :twine
trait :day_time do
sequence(:created_at) { |n| Time.new(2014,03,01,15,40,n % 60,'-04:00') }
end
trait :night_time do
sequence(:created_at) { |n| Time.new(2014,03,01,23,40,n % 60,'-04:00') }
end
trait :violation do
outdoor_temp 30
temp 30
end
end
end
|
import { Dispatch } from 'redux';
import * as superagent from 'superagent';
import { IColorPayload, IgetColorListAction } from '../reducers-types/color-list-types';
export const GET_COLOR_LIST = 'GET_COLOR_LIST';
export const getColorList: (payload: IColorPayload) => IgetColorListAction = (
payload: IColorPayload,
): IgetColorListAction => ({ type: GET_COLOR_LIST, payload });
export const fetchColorList = () => {
return (dispatch: Dispatch<IgetColorListAction>): void =>
superagent.get('/api/color-list').end((err, res) => {
return dispatch(getColorList(err || !res || !res.body ? {} : res.body));
});
};
|
# 题目描述
给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
你可以假设数组是非空的,并且给定的数组总是存在众数。
示例 1:
```
输入: [3,2,3]
输出: 3
```
示例 2:
```
输入: [2,2,1,1,1,2,2]
输出: 2
```
# 题解
题解1:统计每个数出现的次数,返回最多的即可.
题解2:
定义一个计数器count=0,一个当前值resValue=0.
```
依次遍历数组
当count=0的时候,resValue修改为当前数组的值.
如果下一个值不等于当前值,那么count-1;
如果下一个值等于当前值,那么count+1;
```
简而言之也就是看看哪一个最多,不占用存储空间,遍历一遍即可.好办法 |
import { IProjectSupportingChannel } from './project-supporting-channel';
export interface IProject {
id: string;
projectName: string;
siteName: string;
siteId: string;
rawChannelName: string;
rawChannelId: string;
finalChannelName: string;
finalChannelId: string;
supportingChannels?: IProjectSupportingChannel[];
}
|
#!/bin/sh
mkdir Release
cd Release
cmake -DCMAKE_BUILD_TYPE=Release -B. -H..
cd ..
mkdir Debug
cd Debug
cmake -DCMAKE_BUILD_TYPE=Debug -B. -H..
cd ..
|
---
layout: page
title: About Me
subtitle: because why not?
---
I'm Aiswarya.
### My story
I love learning. I'm currently learning [Go](https://golang.org/).
|
((_pid, _app) => {
if(System.isMobile) {
_app.data('swinfo', System.serviceWorker ? `${System.serviceWorker.scope}で有効` : '無効');
} else {
_app.data('swinfo', 'モバイルではありません');
}
_app.event({
mobile() {
location.href = 'mobile.html'
},
desktop() {
location.href = 'index.html'
}
});
})(pid, app);
|
import 'dart:ui';
import 'package:meta/meta.dart';
import '../components/component.dart';
import '../components/mixins/collidable.dart';
import '../components/mixins/draggable.dart';
import '../components/mixins/has_collidables.dart';
import '../components/mixins/hoverable.dart';
import '../components/mixins/tappable.dart';
import '../extensions/vector2.dart';
import 'camera/camera.dart';
import 'camera/camera_wrapper.dart';
import 'mixins/game.dart';
/// This is a more complete and opinionated implementation of [Game].
///
/// [FlameGame] can be extended to add your game logic, or you can keep the
/// logic in child [Component]s.
///
/// This is the recommended base class to use for most games made with Flame.
/// It is based on the Flame Component System (also known as FCS).
class FlameGame extends Component with Game {
FlameGame() {
_cameraWrapper = CameraWrapper(Camera(), children);
}
/// The camera translates the coordinate space after the viewport is applied.
Camera get camera => _cameraWrapper.camera;
// When the Game becomes a Component (#906), this could be added directly
// into the component tree.
late final CameraWrapper _cameraWrapper;
/// This is overwritten to consider the viewport transformation.
///
/// Which means that this is the logical size of the game screen area as
/// exposed to the canvas after viewport transformations and camera zooming.
///
/// This does not match the Flutter widget size; for that see [canvasSize].
@override
Vector2 get size => camera.gameSize;
/// This is the original Flutter widget size, without any transformation.
Vector2 get canvasSize => camera.canvasSize;
/// This method is called for every component before it is added to the
/// component tree.
/// It does preparation on a component before any update or render method is
/// called on it.
///
/// You can use this to set up your mixins or pre-calculate things for
/// example.
/// By default, this calls the first [onGameResize] for every component, so
/// don't forget to call `super.prepareComponent` when overriding.
@mustCallSuper
void prepareComponent(Component c) {
assert(
hasLayout,
'"prepare/add" called before the game is ready. '
'Did you try to access it on the Game constructor? '
'Use the "onLoad" ot "onParentMethod" method instead.',
);
if (c is Collidable) {
assert(
this is HasCollidables,
'You can only use the Hitbox/Collidable feature with games that has '
'the HasCollidables mixin',
);
}
if (c is Tappable) {
assert(
this is HasTappableComponents,
'Tappable Components can only be added to a FlameGame with '
'HasTappableComponents',
);
}
if (c is Draggable) {
assert(
this is HasDraggableComponents,
'Draggable Components can only be added to a FlameGame with '
'HasDraggableComponents',
);
}
if (c is Hoverable) {
assert(
this is HasHoverableComponents,
'Hoverable Components can only be added to a FlameGame with '
'HasHoverableComponents',
);
}
// First time resize
c.onGameResize(size);
}
/// This implementation of render renders each component, making sure the
/// canvas is reset for each one.
///
/// You can override it further to add more custom behavior.
/// Beware of that if you are rendering components without using this method;
/// you must be careful to save and restore the canvas to avoid components
/// interfering with each others rendering.
@override
@mustCallSuper
void render(Canvas canvas) {
_cameraWrapper.render(canvas);
}
/// This updates every component in the tree.
///
/// It also adds the components added via [add] since the previous tick, and
/// removes those that are marked for removal via the [remove] and
/// [Component.removeFromParent] methods.
/// You can override it to add more custom behavior.
@override
@mustCallSuper
void update(double dt) {
super.update(dt);
_cameraWrapper.update(dt);
}
/// This passes the new size along to every component in the tree via their
/// [Component.onGameResize] method, enabling each one to make their decision
/// of how to handle the resize event.
///
/// It also updates the [size] field of the class to be used by later added
/// components and other methods.
/// You can override it further to add more custom behavior, but you should
/// seriously consider calling the super implementation as well.
/// This implementation also uses the current [camera] in order to transform
/// the coordinate system appropriately.
@override
@mustCallSuper
void onGameResize(Vector2 canvasSize) {
camera.handleResize(canvasSize);
super.onGameResize(canvasSize);
}
/// Changes the priority of [component] and reorders the games component list.
///
/// Returns true if changing the component's priority modified one of the
/// components that existed directly on the game and false if it
/// either was a child of another component, if it didn't exist at all or if
/// it was a component added directly on the game but its priority didn't
/// change.
bool changePriority(
Component component,
int priority, {
bool reorderRoot = true,
}) {
if (component.priority == priority) {
return false;
}
component.changePriorityWithoutResorting(priority);
if (reorderRoot) {
final parent = component.parent;
if (parent != null) {
parent.reorderChildren();
} else if (contains(component)) {
children.rebalanceAll();
}
}
return true;
}
/// Since changing priorities is quite an expensive operation you should use
/// this method if you want to change multiple priorities at once so that the
/// tree doesn't have to be reordered multiple times.
void changePriorities(Map<Component, int> priorities) {
var hasRootComponents = false;
final parents = <Component>{};
priorities.forEach((component, priority) {
final wasUpdated = changePriority(
component,
priority,
reorderRoot: false,
);
if (wasUpdated) {
final parent = component.parent;
if (parent != null) {
parents.add(parent);
} else {
hasRootComponents |= contains(component);
}
}
});
if (hasRootComponents) {
children.rebalanceAll();
}
parents.forEach((parent) => parent.reorderChildren());
}
/// Whether a point is within the boundaries of the visible part of the game.
@override
bool containsPoint(Vector2 p) {
return p.x > 0 && p.y > 0 && p.x < size.x && p.y < size.y;
}
/// Returns the current time in seconds with microseconds precision.
///
/// This is compatible with the `dt` value used in the [update] method.
double currentTime() {
return DateTime.now().microsecondsSinceEpoch.toDouble() /
Duration.microsecondsPerSecond;
}
@override
Vector2 projectVector(Vector2 vector) {
return camera.combinedProjector.projectVector(vector);
}
@override
Vector2 unprojectVector(Vector2 vector) {
return camera.combinedProjector.unprojectVector(vector);
}
@override
Vector2 scaleVector(Vector2 vector) {
return camera.combinedProjector.scaleVector(vector);
}
@override
Vector2 unscaleVector(Vector2 vector) {
return camera.combinedProjector.unscaleVector(vector);
}
}
|
import 'package:cricketeer/custom_widgets/player_page.dart';
import 'package:flutter/material.dart';
import 'package:cricketeer/utilities/team.dart';
class Players extends StatelessWidget {
static const routeName = 'Players';
Players({@required this.country});
final country;
final _pageController =
PageController(initialPage: 0, viewportFraction: 0.85);
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
body: PageView.builder(
controller: _pageController,
itemCount: team[country].length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return PlayerPage(
img: team[country][index]['img'],
pname: team[country][index]['pname'],
);
},
),
),
);
}
}
|
## Hands-On Time
---
# Using Services To Enable Communication Between Pods
## Exposing Ports
---
```bash
cat svc/go-demo-2-rs.yml
kubectl create -f svc/go-demo-2-rs.yml
kubectl get -f svc/go-demo-2-rs.yml
kubectl expose rs go-demo-2 --name=go-demo-2-svc --target-port=28017 \
--type=NodePort
```
<!-- .slide: data-background="img/seq_svc_ch05.png" data-background-size="contain" -->
<!-- .slide: data-background="img/comp_svc_ch05.png" data-background-size="contain" -->
## Exposing Ports
---
```bash
kubectl describe svc go-demo-2-svc
PORT=$(kubectl get svc go-demo-2-svc \
-o jsonpath="{.spec.ports[0].nodePort}")
IP=$(minikube ip)
open "http://$IP:$PORT"
```
<!-- .slide: data-background="img/svc-expose-rs.png" data-background-size="contain" -->
## Exposing Ports
---
```bash
kubectl delete svc go-demo-2-svc
```
## Declarative Syntax
---
```bash
cat svc/go-demo-2-svc.yml
kubectl create -f svc/go-demo-2-svc.yml
kubectl get -f svc/go-demo-2-svc.yml
open "http://$IP:30001"
```
<!-- .slide: data-background="img/svc-hard-coded-port.png" data-background-size="contain" -->
## Declarative Syntax
---
```bash
kubectl delete -f svc/go-demo-2-svc.yml
kubectl delete -f svc/go-demo-2-rs.yml
```
## Communication Through Services
---
```bash
cat svc/go-demo-2-db-rs.yml
kubectl create -f svc/go-demo-2-db-rs.yml
cat svc/go-demo-2-db-svc.yml
kubectl create -f svc/go-demo-2-db-svc.yml
cat svc/go-demo-2-api-rs.yml
kubectl create -f svc/go-demo-2-api-rs.yml
cat svc/go-demo-2-api-svc.yml
kubectl create -f svc/go-demo-2-api-svc.yml
```
## Communication Through Services
---
```bash
kubectl get all
PORT=$(kubectl get svc go-demo-2-api \
-o jsonpath="{.spec.ports[0].nodePort}")
curl -i "http://$IP:$PORT/demo/hello"
kubectl delete -f svc/go-demo-2-db-rs.yml
kubectl delete -f svc/go-demo-2-db-svc.yml
kubectl delete -f svc/go-demo-2-api-rs.yml
kubectl delete -f svc/go-demo-2-api-svc.yml
```
## Defining Multiple Objects In The Same YAML file
---
```bash
cat svc/go-demo-2.yml
kubectl create -f svc/go-demo-2.yml
kubectl get -f svc/go-demo-2.yml
PORT=$(kubectl get svc go-demo-2-api \
-o jsonpath="{.spec.ports[0].nodePort}")
curl -i "http://$IP:$PORT/demo/hello"
POD_NAME=$(kubectl get pod --no-headers \
-o=custom-columns=NAME:.metadata.name \
-l type=api,service=go-demo-2 | tail -1)
kubectl exec $POD_NAME env
kubectl describe svc go-demo-2-db
cat ./svc/go-demo-2-api-rs.yml
```
<!-- .slide: data-background="img/flow_svc_ch05.png" data-background-size="contain" -->
## Services?
---
* Communication between Pods<!-- .element: class="fragment" -->
* Communication from outside the cluster<!-- .element: class="fragment" -->
<!-- .slide: data-background="img/svc-components.png" data-background-size="contain" -->
## What Now?
---
```bash
kubectl delete -f svc/go-demo-2.yml
```
|
import React, { useState } from "react";
import { PRCommentCard, ButtonRow } from "./PullRequestComponents";
import MessageInput from "./MessageInput";
import { RadioGroup, Radio } from "../src/components/RadioGroup";
import { useDispatch, useSelector } from "react-redux";
import { CodeStreamState } from "../store";
import { CSMe } from "../protocols/agent/api.protocol.models";
import { HostApi } from "..";
import { Button } from "../src/components/Button";
import Tooltip from "./Tooltip";
import { api } from "../store/providerPullRequests/actions";
import { replaceHtml } from "../utils";
export const PullRequestFinishReview = (props: {
pr: {
providerId: string;
viewerDidAuthor: boolean;
pendingReview: {
id: string;
author: {
login: string;
avatarUrl: string;
};
comments?: {
totalCount: number;
};
};
};
mode: "dropdown" | "timeline";
fetch: Function;
setIsLoadingMessage: Function;
setFinishReviewOpen?: Function;
}) => {
const dispatch = useDispatch();
const [reviewText, setReviewText] = useState("");
const [submittingReview, setSubmittingReview] = useState(false);
const [reviewType, setReviewType] = useState<"COMMENT" | "APPROVE" | "REQUEST_CHANGES">(
"COMMENT"
);
const [isPreviewing, setIsPreviewing] = useState(false);
const { pr, mode, fetch, setIsLoadingMessage, setFinishReviewOpen } = props;
const supportsFinishReviewTypes = !pr.providerId.includes("gitlab");
const submitReview = async e => {
setIsLoadingMessage("Submitting Review...");
setSubmittingReview(true);
HostApi.instance.track("PR Review Finished", {
Host: pr.providerId,
"Review Type": reviewType
});
await dispatch(
api("submitReview", {
eventType: reviewType,
text: replaceHtml(reviewText)
})
);
setFinishReviewOpen && setFinishReviewOpen(false);
return fetch();
};
const cancelReview = async (e, id) => {
setIsLoadingMessage("Canceling Review...");
await dispatch(
api("deletePullRequestReview", {
pullRequestReviewId: id
})
);
setFinishReviewOpen && setFinishReviewOpen(false);
fetch();
};
const pendingCommentCount =
pr && pr.pendingReview && pr.pendingReview.comments ? pr.pendingReview.comments.totalCount : 0;
return (
<PRCommentCard className={`add-comment finish-review-${mode}`}>
<div
style={{
margin: "5px 0 15px 0",
border: isPreviewing ? "none" : "1px solid var(--base-border-color)"
}}
>
<MessageInput
autoFocus
multiCompose
text={reviewText}
placeholder="Leave a comment"
onChange={setReviewText}
onSubmit={submitReview}
setIsPreviewing={value => setIsPreviewing(value)}
/>
<div style={{ clear: "both" }}></div>
</div>
{!isPreviewing && supportsFinishReviewTypes && (
<RadioGroup
name="approval"
selectedValue={reviewType}
onChange={value => setReviewType(value)}
>
<Radio value={"COMMENT"}>
Comment
<div className="subtle">Submit general feedback without explicit approval.</div>
</Radio>
<Radio disabled={pr.viewerDidAuthor} value={"APPROVE"}>
<Tooltip
title={
pr.viewerDidAuthor
? "Pull request authors can't approve their own pull request"
: ""
}
placement="top"
>
<span>
Approve
<div className="subtle">Submit feedback and approve merging these changes. </div>
</span>
</Tooltip>
</Radio>
<Radio disabled={pr.viewerDidAuthor} value={"REQUEST_CHANGES"}>
<Tooltip
title={
pr.viewerDidAuthor
? "Pull request authors can't request changes on their own pull request"
: ""
}
placement="top"
>
<span>
{" "}
Request Changes
<div className="subtle">Submit feedback that must be addressed before merging.</div>
</span>
</Tooltip>
</Radio>
</RadioGroup>
)}
{!isPreviewing && (
<ButtonRow>
<Button
disabled={!pendingCommentCount && !supportsFinishReviewTypes}
isLoading={submittingReview}
onClick={submitReview}
>
Submit<span className="wide-text"> review</span>
</Button>
{pendingCommentCount > 0 && (
<Button variant="secondary" onClick={e => cancelReview(e, pr.pendingReview.id)}>
Cancel review
</Button>
)}
<div className="subtle" style={{ margin: "10px 0 0 10px" }}>
{pendingCommentCount} pending comment{pendingCommentCount == 1 ? "" : "s"}
</div>
</ButtonRow>
)}
</PRCommentCard>
);
};
|
require File.expand_path(File.dirname(__FILE__) + '/spec_helper')
require File.expand_path(File.dirname(__FILE__) + '/../lib/pedump')
require File.expand_path(File.dirname(__FILE__) + '/../lib/pedump/cli')
require 'digest/md5'
class CLIReturn < Struct.new(:status, :output)
def md5
Digest::MD5.hexdigest(self.output.to_s)
end
end
def cli args
output = capture_stdout do
PEdump::CLI.new(args.split).run
end
CLIReturn.new(0, output)
rescue SystemExit
CLIReturn.new($!.status, "")
end
describe "--extract resource" do
it "should set errorlevel to 1 if resource is not found" do
cli("samples/calc.exe --extract resource:0x12345").status.should == 1
end
it "should extract resource by hex offset" do
cli("samples/calc.exe --extract resource:0x98478").md5.should == "84e38f8bb6e3c6f35380f3373050c013"
end
it "should extract resource by decimal offset" do
cli("samples/calc.exe --extract resource:623736").md5.should == "84e38f8bb6e3c6f35380f3373050c013"
end
it "should extract resource by type & name" do
cli(
"samples/calc.exe --extract resource:BITMAP/IDT_BTN_STR_STATISTICS"
).md5.should == "baafb42dcb9d9e817b168b51de013312"
end
it "should extract resource by type & ordinal" do
cli("samples/calc.exe --extract resource:VERSION/#1").md5.should == "64ded21a538a442dcf90e280acb28496"
end
end
describe "--extract section" do
it "should set errorlevel to 1 if section is not found" do
cli("samples/calc.exe --extract section:foo").status.should == 1
end
it "should extract section by name" do
cli("samples/calc.exe --extract section:.text").md5.should == "b7347dffd3d096f0b02ef8e1fe586b97"
end
it "should extract section by RVA" do
cli("samples/calc.exe --extract section:rva/0x1000").md5.should == "b7347dffd3d096f0b02ef8e1fe586b97"
end
it "should extract section by RAW_PTR" do
cli("samples/calc.exe --extract section:raw/0x400").md5.should == "b7347dffd3d096f0b02ef8e1fe586b97"
end
end
describe "--extract datadir" do
it "should set errorlevel to 1 if datadir is not found" do
cli("samples/calc.exe --extract datadir:foo").status.should == 1
end
it "should extract empty datadir" do
cli("samples/calc.exe --extract datadir:EXPORT").output.should == ""
cli("samples/calc.exe --extract datadir:EXPORT").status.should == 0
end
it "should extract datadir by RVA" do
cli("samples/calc.exe --extract datadir:IMPORT").md5.should == "de0ef456633e7a605a3b5d34921edf0d"
end
end
|
package com.semicolon.domain.enums
enum class NotificationType {
CHALLENGE, CHALLENGE_SUCCESS, CHALLENGE_EXPIRATION, EXERCIZE, NOTICE
} |
import freemarker.template.Configuration
import spark.Route
import spark.Spark.*
import java.io.File
import java.io.StringWriter
import java.util.*
fun main(args: Array<String>) {
port(8080)
externalStaticFileLocation("static")
get("/", "*", Route { request, response ->
try {
val configuration = Configuration()
configuration.setDirectoryForTemplateLoading(File("templates"))
val temp = configuration.getTemplate("index.ftlh")
val writer = StringWriter()
val data = HashMap<String, Object>()
temp.process(data, writer)
return@Route writer.toString()
} catch (e: Exception) {
e.printStackTrace()
return@Route e.message
}
})
} |
package com.shopapp.ui.account.router
import com.nhaarman.mockito_kotlin.mock
import com.shopapp.TestShopApplication
import com.shopapp.gateway.entity.Policy
import com.shopapp.ui.account.*
import com.shopapp.ui.address.account.AddressListActivity
import com.shopapp.ui.const.RequestCode
import com.shopapp.ui.home.HomeActivity
import com.shopapp.ui.order.list.OrderListActivity
import com.shopapp.ui.policy.PolicyActivity
import org.junit.Assert.assertEquals
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.Shadows
import org.robolectric.annotation.Config
import org.robolectric.shadows.support.v4.SupportFragmentTestUtil
@RunWith(RobolectricTestRunner::class)
@Config(manifest = Config.NONE, application = TestShopApplication::class)
class AccountRouterTest {
private lateinit var fragment: AccountFragment
private lateinit var router: AccountRouter
@Before
fun setUp() {
fragment = AccountFragment()
router = AccountRouter()
SupportFragmentTestUtil.startFragment(fragment, HomeActivity::class.java)
}
@Test
fun shouldShowSignInActivity() {
router.showSignInForResult(fragment, RequestCode.SIGN_IN)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(SignInActivity::class.java, shadowIntent.intentClass)
}
@Test
fun shouldShowSignUp() {
val terms: Policy = mock()
val privacy: Policy = mock()
router.showSignUpForResult(fragment, privacy, terms, RequestCode.SIGN_UP)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(SignUpActivity::class.java, shadowIntent.intentClass)
assertEquals(terms, startedIntent.extras.getParcelable(SignUpActivity.TERMS_OF_SERVICE))
assertEquals(privacy, startedIntent.extras.getParcelable(SignUpActivity.PRIVACY_POLICY))
}
@Test
fun shouldShowOrder() {
router.showOrderList(fragment.context)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(OrderListActivity::class.java, shadowIntent.intentClass)
}
@Test
fun shouldShowPersonalInfo() {
router.showPersonalInfoForResult(fragment, RequestCode.PERSONAL_INFO)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(PersonalInfoActivity::class.java, shadowIntent.intentClass)
}
@Test
fun shouldShowAddressList() {
router.showAddressList(fragment.context)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(AddressListActivity::class.java, shadowIntent.intentClass)
}
@Test
fun shouldShowAccountSettings() {
router.showSettings(fragment.context)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(AccountSettingsActivity::class.java, shadowIntent.intentClass)
}
@Test
fun shouldShowPrivacy() {
val privacy: Policy = mock()
router.showPolicy(fragment.context, privacy)
val startedIntent = Shadows.shadowOf(fragment.activity).nextStartedActivity
val shadowIntent = Shadows.shadowOf(startedIntent)
assertEquals(PolicyActivity::class.java, shadowIntent.intentClass)
assertEquals(privacy, startedIntent.extras.getParcelable(PolicyActivity.EXTRA_POLICY))
}
} |
# Contributing
## Ways to Contribute
Some ways that you can contribute, in order of increasing involvement:
* Read [the documentation](https://pages.charlesreid1.com/boring-mind-machine)!
If you find a problem or can't understand something, open an issue (see below).
* Use boring mind machine! You can test it out and come up with new ideas
and ways of using boring mind machine.
* [Open an issue](https://github.com/boring-mind-machine/boring-mind-machine/issues/new)
in the boring mind machine repository on Github. The issue can be a bug,
a question, an idea, or anything else.
* [Fork boring mind machine on
Github!](htts://github.com/boring-mind-machine/boring-mind-machine)
|
import { DataFrame, DataObject } from '../../data';
import { ObjectProcessingNodeOptions } from '../ObjectProcessingNode';
import { ProcessingNode } from '../ProcessingNode';
/**
* @category Flow shape
*/
export class ObjectFilterNode<InOut extends DataFrame> extends ProcessingNode<InOut, InOut> {
protected options: ObjectProcessingNodeOptions;
constructor(filterFn: (object: DataObject, frame?: DataFrame) => boolean, options?: ObjectProcessingNodeOptions) {
super(options);
this.options.objectFilter = this.options.objectFilter || filterFn;
}
public process(frame: InOut): Promise<InOut> {
return new Promise<InOut>((resolve) => {
frame
.getObjects()
.filter((object) => !this.options.objectFilter(object, frame))
.forEach(frame.removeObject);
resolve(frame);
});
}
}
|
// Copyright © 2018 650 Industries. All rights reserved.
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
/**
EXSplashScreenHUDButton is a preconfigured button that notifies the user when the splash screen has been visible for too long
Its goal is to direct the user to documentation that might help them resolve their issue
*/
@interface EXSplashScreenHUDButton : UIButton
@end
NS_ASSUME_NONNULL_END
|
//Chapter 18 Vektor Drill
//#include "std_lib_facilities.h"
#include <iostream>
#include <stdexcept>
#include <vector>
using namespace std;
vector<int> gv {1, 2, 4, 8, 16, 32, 64, 128, 256, 512};
void f(vector<int> v)
{
vector<int> lv(10);
lv = v;
for (auto& a : lv)
cout << a << '\t';
cout << '\n';
vector<int> lv2 = v;
for (auto& a : lv2)
cout << a << '\t';
cout << '\n';
}
int faktorialis(int n) { return n > 1 ? n*faktorialis(n-1) : 1; }
int main()
try {
f(gv);
vector<int> vv(10);
for (int i=0; i<vv.size(); ++i)
vv[i] = faktorialis(i + 1);
f(vv);
}
catch(std::exception& e) {
std::cerr << "Exception: " << e.what() << '\n';
return 1;
}
catch(...) {
std::cerr << "Unknown exception\n";
return 2;
} |
---
title: 액션바 (ActionBar)
apiRef: https://docs.nativescript.org/api-reference/classes/_ui_action_bar_.actionbar
contributors: [rigor789, eddyverbruggen]
---
액션바 컴포넌트는 안드로이드 액션바와 iOS NavigationBar의 네이티브-스크립트 추상화 입니다.
---
#### 제목 사용
```html
<ActionBar title="MyApp" />
```
#### 커스텀 제목 view
```html
<ActionBar>
<StackLayout orientation="horizontal">
<Image src="res://icon" width="40" height="40" verticalAlignment="center" />
<Label text="NativeScript" fontSize="24" verticalAlignment="center" />
</StackLayout>
</ActionBar>
```
#### 안드로이드에서 앱 아이콘 설정
```html
<ActionBar title="My App" android.icon="res://icon" android.iconVisibility="always" />
```
#### 가장자리 경계(border) 없애기
iOS와 안드로이드에서 작은 보더가 액션바 바닥에 그려집니다.
추가로 iOS에서 액션바의 배경색은 iOS가 적용하는 필터때문에 지정한 값과 약간 달라집니다.
이 필터와 보더를 제거하려면 `flat` 을 `true` 로 설정하세요
```html
<ActionBar title="My App" flat="true" />
```
## Props
| 이름 | 타입 | 설명 |
|------|------|-------------|
| `title` | `String` | 액션바에 나타나는 제목.
| `android.icon` | `String` | 안드로이드에서 보여지는 아이콘.
| `android.iconVisibility` | `String` | 아이콘이 보여질지 지정.
| `flat` | `boolean` | 보더와 iOS 컬러 필터를 제거. 기본값은 `false`.
|
namespace iRLeagueApiCore.Server.Models.ResultsParsing
{
public struct ParseLivery
{
public int car_id { get; set; }
public int pattern { get; set; }
public string color1 { get; set; }
public string color2 { get; set; }
public string color3 { get; set; }
public int number_font { get; set; }
public string number_color1 { get; set; }
public string number_color2 { get; set; }
public string number_color3 { get; set; }
public int number_slant { get; set; }
public int sponsor1 { get; set; }
public int sponsor2 { get; set; }
public string car_number { get; set; }
public string wheel_color { get; set; }
public int rim_type { get; set; }
}
}
|
# frozen_string_literal: true
class Foo
def initialize(param)
@param = param
end
def set_param(value)
@param = value
end
def get_param
@param
end
def format_param
"Your parameter is : #{get_param}"
end
def miscellaneous_method
# :nocov:
raise "Don't call me!"
# :nocov:
end
end
|
#include "pch.h"
#include "tdd_surface_instance.h"
#include "tdd_render.h"
using namespace std;
namespace TDD
{
std::optional<Location> SurfaceInstance::OnKeyDown(wchar_t c)
{
switch (c)
{
case input_esc:
render->EndSurfaceEditMode();
break;
}
return {};
}
std::optional<Location> SurfaceInstance::OnChar(wchar_t c)
{
return {};
}
void SurfaceInstance::OnKeyUp(wchar_t c)
{
}
} |
import 'package:flutter/material.dart';
import 'typography.dart';
import 'themedata.dart';
class IndieduTheme {
// Theme data
static ThemeData kIndieduLightThemeData() => kLightThemeData();
static ThemeData kIndieduDarkThemeData() => kDarkThemeData();
// Text theme
static TextTheme kIndieduLightTextTheme() => kLightText;
static TextTheme kIndieduDarkTextTheme() => kDarkText;
}
final indiedu = IndieduTheme.kIndieduLightThemeData();
|
## Response Text
The response itself can be written with standard text without any special
formatting. However, if wishing to convey an action a robotic version of Clara
would take use the `*` symbol such as `*smiles*`. For now, this helps the user
further engage with conversations. However, in the future a physical version of
Clara could take these prewritten actions and perform them. To future proof your
bot, this can be very helpful. Support for standardized speech markup is in the
works for changing the tone and conveyance of responses.
## .convo
To be added...
## .json
To be added...
|
Subsets and Splits