text
stringlengths 27
775k
|
|---|
<?php
/**
* @var $categories \common\models\db\CategoryPoster
*/
use yii\helpers\Url;
?>
<section class="afisha-menu">
<div class="container">
<ul>
<?php foreach ($categories as $category): ?>
<li><a href="<?= Url::to([
'/poster/default/single_category',
'slug' => $category->slug,
]) ?>"><?= $category->title; ?></a></li>
<?php endforeach; ?>
</ul>
</div>
</section>
|
class ManualSectionIndexableFormatter
def initialize(section, manual)
@section = section
@manual = manual
end
def type
"manual_section"
end
def id
link
end
def indexable_attributes
{
title: "#{manual.title}: #{section.title}",
description: section.summary,
link: link,
indexable_content: section.body,
organisations: [manual.organisation_slug],
manual: manual.slug,
}
end
private
attr_reader :section, :manual
def link
section.slug
end
end
|
export default class Ray {
constructor(p1, a, maxLen) {
this.p1 = p1;
this.a = a;
this.maxLen = maxLen;
// If no obstacles in way, this is end point
this.maxP2 = createVector(
cos(a) * this.maxLen + this.p1.x,
sin(a) * this.maxLen + this.p1.y,
);
this.p2 = this.maxP2.copy();
}
// detectCollision(walls) {
// // TODO: find endpoints and return or set new p2
// return false;
// }
updateP2() {
this.p2.x = cos(this.a) * this.maxLen + this.p1.x;
this.p2.y = sin(this.a) * this.maxLen + this.p1.y;
}
draw() {
line(this.p1.x, this.p1.y, this.p2.x, this.p2.y);
}
}
|
package ru.luckycactus.steamroulette.presentation.features.game_details.adapter
import ru.luckycactus.steamroulette.databinding.ItemGameDetailsLinksBinding
import ru.luckycactus.steamroulette.presentation.features.game_details.GameDetailsViewModel
import ru.luckycactus.steamroulette.presentation.features.game_details.model.GameDetailsUiModel
class GameLinksViewHolder(
binding: ItemGameDetailsLinksBinding,
gameDetailsViewModel: GameDetailsViewModel
) : GameDetailsViewHolder<GameDetailsUiModel.Links>(binding.root) {
init {
binding.btnStore.setOnClickListener { gameDetailsViewModel.onStoreClick() }
binding.btnHub.setOnClickListener { gameDetailsViewModel.onHubClick() }
}
override fun bind(item: GameDetailsUiModel.Links) {
//nothing
}
}
|
/*
* GridGain Community Edition Licensing
* Copyright 2019 GridGain Systems, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License") modified with Commons Clause
* Restriction; 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.
*
* Commons Clause Restriction
*
* The Software is provided to you by the Licensor under the License, as defined below, subject to
* the following condition.
*
* Without limiting other conditions in the License, the grant of rights under the License will not
* include, and the License does not grant to you, the right to Sell the Software.
* For purposes of the foregoing, โSellโ means practicing any or all of the rights granted to you
* under the License to provide to third parties, for a fee or other consideration (including without
* limitation fees for hosting or consulting/ support services related to the Software), a product or
* service whose value derives, entirely or substantially, from the functionality of the Software.
* Any license notice or attribution required by the License must also include this Commons Clause
* License Condition notice.
*
* For purposes of the clause above, the โLicensorโ is Copyright 2019 GridGain Systems, Inc.,
* the โLicenseโ is the Apache License, Version 2.0, and the Software is the GridGain Community
* Edition software provided with this notice.
*/
package org.apache.ignite.internal.processors.cache.query.continuous;
import java.io.Serializable;
import java.util.Collections;
import javax.cache.configuration.Factory;
import javax.cache.event.CacheEntryEvent;
import javax.cache.event.CacheEntryEventFilter;
import javax.cache.event.CacheEntryUpdatedListener;
import org.apache.ignite.Ignite;
import org.apache.ignite.IgniteCache;
import org.apache.ignite.IgniteException;
import org.apache.ignite.cache.query.ContinuousQuery;
import org.apache.ignite.cluster.ClusterNode;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.lang.IgnitePredicate;
import org.apache.ignite.testframework.GridStringLogger;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** */
@SuppressWarnings("unused")
@RunWith(JUnit4.class)
public class GridCacheContinuousQueryNodesFilteringTest extends GridCommonAbstractTest implements Serializable {
/** */
private static final String ENTRY_FILTER_CLS_NAME = "org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilter";
/**
* Tests that node not matched by filter really does not try to participate in the query.
*
* @throws Exception if failed.
*/
@Test
public void testNodeWithoutAttributeExclusion() throws Exception {
try (Ignite node1 = startNodeWithCache()) {
try (Ignite node2 = startGrid("node2", getConfiguration("node2", false, null))) {
assertEquals(2, node2.cluster().nodes().size());
}
}
}
/**
* Test that node matched by filter and having filter instantiation problems fails for sure.
*
* @throws Exception if failed.
*/
@Test
public void testNodeWithAttributeFailure() throws Exception {
try (Ignite node1 = startNodeWithCache()) {
GridStringLogger log = new GridStringLogger();
try (Ignite node2 = startGrid("node2", getConfiguration("node2", true, log))) {
fail();
}
catch (IgniteException ignored) {
assertTrue(log.toString().contains("Class not found for continuous query remote filter " +
"[name=org.apache.ignite.tests.p2p.CacheDeploymentEntryEventFilter]"));
}
}
}
/**
* Start first, attribute-bearing, node, create new cache and launch continuous query on it.
*
* @return Node.
* @throws Exception if failed.
*/
private Ignite startNodeWithCache() throws Exception {
Ignite node1 = startGrid("node1", getConfiguration("node1", true, null));
CacheConfiguration<Integer, Integer> ccfg = new CacheConfiguration<>(DEFAULT_CACHE_NAME);
ccfg.setName("attrsTestCache");
ccfg.setNodeFilter(new IgnitePredicate<ClusterNode>() {
/** {@inheritDoc} */
@Override public boolean apply(ClusterNode node) {
return "data".equals(node.attribute("node-type"));
}
});
IgniteCache<Integer, Integer> cache = node1.createCache(ccfg);
ContinuousQuery<Integer, Integer> qry = new ContinuousQuery<>();
qry.setRemoteFilterFactory(new RemoteFilterFactory());
qry.setLocalListener(new CacheEntryUpdatedListener<Integer, Integer>() {
/** {@inheritDoc} */
@Override public void onUpdated(Iterable<CacheEntryEvent<? extends Integer, ? extends Integer>> evts) {
// No-op.
}
});
RemoteFilterFactory.clsLdr = getExternalClassLoader();
cache.query(qry);
// Switch class loader before starting the second node.
RemoteFilterFactory.clsLdr = getClass().getClassLoader();
return node1;
}
/**
* @param name Node name.
* @param setAttr Flag indicating whether node user attribute should be set.
* @param log Logger.
* @return Node configuration w/specified name.
* @throws Exception If failed.
*/
private IgniteConfiguration getConfiguration(String name, boolean setAttr, GridStringLogger log) throws Exception {
IgniteConfiguration cfg = optimize(getConfiguration(name));
if (setAttr)
cfg.setUserAttributes(Collections.singletonMap("node-type", "data"));
cfg.setGridLogger(log);
return cfg;
}
/**
*
*/
private static class RemoteFilterFactory implements Factory<CacheEntryEventFilter<Integer, Integer>> {
/** */
private static ClassLoader clsLdr;
/** {@inheritDoc} */
@SuppressWarnings("unchecked")
@Override public CacheEntryEventFilter<Integer, Integer> create() {
try {
Class<?> filterCls = clsLdr.loadClass(ENTRY_FILTER_CLS_NAME);
assert CacheEntryEventFilter.class.isAssignableFrom(filterCls);
return ((Class<CacheEntryEventFilter>)filterCls).newInstance();
}
catch (ClassNotFoundException e) {
throw new IgniteException("Class not found for continuous query remote filter [name=" +
e.getMessage() + "]");
}
catch (Exception e) { // We really don't expect anything else fancy here.
throw new AssertionError("Unexpected exception", e);
}
}
}
}
|
---
layout: watch
title: TLP1 - 22/02/2021 - M20210222_030849_TLP_1T.jpg
date: 2021-02-22 03:08:49
permalink: /2021/02/22/watch/M20210222_030849_TLP_1
capture: TLP1/2021/202102/20210221/M20210222_030849_TLP_1T.jpg
---
|
package definiti.tests.end2end.controls.expression
import definiti.common.ast.Root
import definiti.common.program.Ko
import definiti.common.tests.LocationPath
import definiti.tests.ConfigurationBuilder
import definiti.tests.end2end.EndToEndSpec
import definiti.tests.utils.CommonTypes._
import definiti.tests.validation.controls.expression.ConditionControl
class ConditionControlSpec extends EndToEndSpec {
import ConditionControlSpec._
"TestsValidation" should "validate a control with boolean condition" in {
val output = processFile("controls.expression.condition.nominal", configuration)
output shouldBe ok[Root]
}
it should "invalidate a control with a non-boolean condition" in {
val output = processFile("controls.expression.condition.invalidCondition", configuration)
output should beResult(Ko[Root](
ConditionControl.invalidBoolean(number, invalidConditionLocation(3, 9, 24))
))
}
}
object ConditionControlSpec {
val configuration = ConfigurationBuilder().withOnlyControls(ConditionControl).build()
val controlDirectory = s"expression/${ConditionControl.name}"
val invalidConditionLocation = LocationPath.control(controlDirectory, "invalidCondition")
}
|
package com.android.elk.common
typealias Email = String
typealias Username = String
typealias Password = String
|
import React from 'react';
const Details = (props) => {
return (
<div>
<header>
{props.toolbar}
</header>
<main className="details">
{props.main}
</main>
{props.footer}
</div>
);
}
export default Details;
|
import toml
from ttblackjack import CONFIG_FP
def test_config():
config1 = toml.load(CONFIG_FP)
config2 = {
"decks": 2,
"sleep": 1.0,
"rounds": 0,
"yes": True,
"viewer": "cli",
"debug": False,
"players": [
{"name": "player 1", "algorithm": "basic 1"},
{"name": "player 2", "algorithm": "basic 2"},
{"name": "player 3", "algorithm": "x-ray"},
{"name": "USER", "algorithm": "user"},
{"name": "dealer", "algorithm": "dealer"},
]
}
assert True # Implement later
|
# Regenerates GATK golden files for comparison upon GATK version changes
DESIRED_GATK_VERSION=$(~/gatk/gatk --version | grep GATK | sed -E 's/.*v([0-9.]*).*/\1/')
# Checks if the file was already generated with the same tool and GATK version
file_has_desired_gatk_version () {
FILE_NAME=$1
TOOL_NAME=$2
if [ -f $FILE_NAME ]; then
GATK_HEADER_PATTERN="##GATKCommandLine=<ID=$TOOL_NAME"
FILE_GATK_HEADER_LINE=$(grep -m 1 "$GATK_HEADER_PATTERN" $FILE_NAME)
FILE_GATK_VERSION=$(sed -E 's/.*Version="([0-9.]*).*/\1/' <<< $FILE_GATK_HEADER_LINE)
if [ "$DESIRED_GATK_VERSION" == "$FILE_GATK_VERSION" ]; then
echo "$FILE_NAME was generated with $TOOL_NAME GATK version $DESIRED_GATK_VERSION"
return 0
else
if [ -z "$FILE_GATK_HEADER_LINE" ]; then
echo "$FILE_NAME was not generated with $TOOL_NAME"
return 1
else
echo "$FILE_NAME was generated with $TOOL_NAME GATK version $FILE_GATK_VERSION"
return 1
fi
fi
else
echo "$FILE_NAME does not exist"
return 1
fi
}
# DNASeq
TOOL=HaplotypeCaller
OUTPUT=dnaseq/CEUTrio.HiSeq.WGS.b37.NA12878.20.21.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input ~/gatk/src/test/resources/large/CEUTrio.HiSeq.WGS.b37.NA12878.20.21.bam \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--max-reads-per-alignment-start 0 \
--output $OUTPUT
fi
OUTPUT=dnaseq/NA12878_21_10002403.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input NA12878_21_10002403.bam \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=dnaseq/NA12878_21_10002403.g.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input NA12878_21_10002403.bam \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--emit-ref-confidence GVCF \
--intervals 21_10002393_10002413.bed \
--output $OUTPUT
fi
OUTPUT=dnaseq/NA12878_21_10002403.bp.g.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input NA12878_21_10002403.bam \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--emit-ref-confidence BP_RESOLUTION \
--intervals 21_10002393_10002413.bed \
--output $OUTPUT
fi
OUTPUT=dnaseq/aligned.reads.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input aligned.reads/bwa_mem_paired_end.bam \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--output $OUTPUT
fi
# MutSeq
TOOL=Mutect2
OUTPUT=mutseq/golden_1.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/normal_1.bam \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/tumor_1.bam \
--exclude-intervals mutseq/mask1.bed \
--normal-sample "synthetic.challenge.set1.normal" \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=mutseq/golden_2.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/normal_2.bam \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/tumor_2.bam \
--exclude-intervals mutseq/mask2.bed \
--normal-sample "synthetic.challenge.set2.normal" \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=mutseq/golden_3.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/normal_3.bam \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/tumor_3.bam \
--exclude-intervals mutseq/mask3.bed \
--normal-sample "G15512.prenormal.sorted" \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=mutseq/golden_4.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk $TOOL \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/normal_4.bam \
--input ~/gatk/src/test/resources/large/mutect/dream_synthetic_bams/tumor_4.bam \
--exclude-intervals mutseq/mask4.bed \
--normal-sample "synthetic.challenge.set4.normal" \
--reference ~/gatk/src/test/resources/large/human_g1k_v37.20.21.fasta \
--output $OUTPUT
fi
# Joint genotyping
TOOL=GenotypeGVCFs
COMBINED_OUTPUT=joint/combined.g.vcf
OUTPUT=joint/genotyped.chr20_419.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk CombineGVCFs \
--variant joint/HG002.chr20_419.g.vcf \
--variant joint/HG003.chr20_419.g.vcf \
--variant joint/HG004.chr20_419.g.vcf \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $COMBINED_OUTPUT
~/gatk/gatk $TOOL \
--allow-old-rms-mapping-quality-annotation-data \
--variant $COMBINED_OUTPUT \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=joint/genotyped.chr20_17960111.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk CombineGVCFs \
--variant joint/HG00096.chr20_17960111.g.vcf \
--variant joint/HG00268.chr20_17960111.g.vcf \
--variant joint/NA19625.chr20_17960111.g.vcf \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $COMBINED_OUTPUT
~/gatk/gatk $TOOL \
--allow-old-rms-mapping-quality-annotation-data \
--variant $COMBINED_OUTPUT \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=joint/genotyped.chr20_17983267.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk CombineGVCFs \
--variant joint/HG00096.chr20_17983267.g.vcf \
--variant joint/HG00268.chr20_17983267.g.vcf \
--variant joint/NA19625.chr20_17983267.g.vcf \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $COMBINED_OUTPUT
~/gatk/gatk $TOOL \
--allow-old-rms-mapping-quality-annotation-data \
--variant $COMBINED_OUTPUT \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=joint/genotyped.chr20_18034651_18034655.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk CombineGVCFs \
--variant joint/HG00096.chr20_18034651_18034655.g.vcf \
--variant joint/HG00268.chr20_18034651_18034655.g.vcf \
--variant joint/NA19625.chr20_18034651_18034655.g.vcf \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $COMBINED_OUTPUT
~/gatk/gatk $TOOL \
--allow-old-rms-mapping-quality-annotation-data \
--variant $COMBINED_OUTPUT \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $OUTPUT
fi
OUTPUT=joint/genotyped.chr21_575.vcf
if ! file_has_desired_gatk_version $OUTPUT $TOOL; then
~/gatk/gatk CombineGVCFs \
--variant joint/HG002.chr21_575.g.vcf \
--variant joint/HG003.chr21_575.g.vcf \
--variant joint/HG004.chr21_575.g.vcf \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $COMBINED_OUTPUT
~/gatk/gatk $TOOL \
--allow-old-rms-mapping-quality-annotation-data \
--variant $COMBINED_OUTPUT \
--reference ~/gatk/src/test/resources/large/Homo_sapiens_assembly38.20.21.fasta \
--output $OUTPUT
fi
if [ -f $COMBINED_OUTPUT ]; then
rm $COMBINED_OUTPUT
fi
|
require File.dirname(__FILE__) + '/../test'
module BuildMaster
describe Git do
it 'should take a directory as the working directory' do
current_dir = Cotta.parent_dir(__FILE__)
git = Git.new(current_dir)
git.work_dir.should == current_dir
end
it 'should change directory and run command' do
current_dir = Cotta.parent_dir(__FILE__)
Dir.chdir('/') do
git = Git.new(current_dir)
git.status.should_not be_empty
end
end
it 'should issue proper commands' do
system = InMemorySystem.new
cotta = Cotta.new(system)
work = cotta.dir('/tmp/work')
system.output_for_command('git pull', 'pull output')
system.output_for_command('git add .', 'add output')
system.output_for_command("git add #{work.file('file.txt')}", 'add output')
system.output_for_command("git commit -m \"comment\"", 'commit output')
system.output_for_command("git tag tag", 'tag output')
system.output_for_command("git push origin master", "push output")
git = Git.new(work)
git.pull
git.add
git.add(work.file('file.txt'))
git.commit('comment')
git.tag('tag')
git.push
end
end
end
|
#!/bin/bash
for foto in *.png; do
#echo "ORIGINAL: $foto ; NOVO: $foto.NEW.png";
convert -resize 30x30 "$foto" "$foto.NEW.png";
done
|
package proctor
// Version is the main version number that is being run at the moment.
var Version = "No version set"
// VersionPrerelease is a pre-release marker for the version. If this is ""
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var VersionPrerelease = ""
// BuildStamp is the build timestamp
var BuildStamp = "No BuildStamp Provided"
// GitHash is the git hash ;)
var GitHash = "No Git Commit Provided"
|
module Api
module V1
class UsersController < ApplicationController
before_action :authenticate_request!, only: [:show, :create, :update_permissions]
before_action :user_type!, only: [:current_user_data]
before_action :set_user, only: [:show, :update]
def index
paginate json: User.ransack(params[:q]).result
end
def create
user = User.new(user_params)
if user.save
auth_token = JsonWebToken.encode({user_id: user.id})
render json: {status: 'User created successfully', auth_token: auth_token}, status: :created
else
render json: { errors: user.errors.full_messages }, status: :bad_request
end
end
def show
render json: @user
end
def update
@user.update(user_params)
render json: @user
end
def update_permissions
user = User.find(params[:user_id])
user.update_attribute(:permission_ids, params[:permission_ids])
render json: user
end
def current_user_data
render json: @current_user
end
def login
user = User.find_by(email: params[:email].to_s.downcase)
if user && user.authenticate(params[:password])
auth_token = JsonWebToken.encode({user_id: user.id})
email = user.email
render json: {auth_token: auth_token}, status: :ok
else
render json: {error: 'Invalid username / password'}, status: :unauthorized
end
end
def permissions
user = User.find(params[:user_id])
user_permissions = user.user_permissions.map do |user_permission|
{
id: user_permission.id,
name: user_permission.permission.name,
description: user_permission.permission.description,
permission_id: user_permission.permission.id
}
end
render json: user_permissions
end
private
def set_user
@user = User.find(params[:id])
end
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :permission_ids, :dishes_ids => [])
end
end
end
end
|
import React from 'react'
import {Switch,Route} from 'react-router-dom'
import App from './components/app'
// import Courses from './pages/coursePage'
// import {CourseDetail} from './components/courses/'
// import {LoginRoute, PrivateRoute} from './privateRoute';
// import PrivateInstructorRoute from './privateInstructorRoute';
// import {Paths} from './components/path/path';
// import AddPath from './components/path/createPath'
// import Login from './components/login'
// import Page404 from './components/404'
const Root=()=>(
<Switch>
{/* <PrivateInstructorRoute path="/courses/:id" component={CourseDetail} /> */}
{/* <PrivateRoute path="/courses" exact component={Courses} />
<PrivateRoute path="/path" component={Paths} />
<LoginRoute path="/login" component={Login} />
<Route path="/addpath" exact component={AddPath} /> */}
<Route path="/" exact component={App} />
</Switch>
)
export default Root
|
/*-
* #%L
* Arcade Connectors
* %%
* Copyright (C) 2018 - 2021 ArcadeData
* %%
* 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.
* #L%
*/
package com.arcadeanalytics.data
import org.assertj.core.api.Assertions.assertThat
import org.assertj.core.util.Lists
import org.assertj.guava.api.Assertions.assertThat
import org.assertj.guava.api.Assertions.entry
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
import java.time.LocalDate
import java.time.format.DateTimeFormatter
import java.util.regex.Pattern
class SpriteShould {
private lateinit var sprite: Sprite
@BeforeEach
internal fun setUp() {
sprite = Sprite()
}
@Test
internal fun `add values of different types`() {
sprite.add("field1", "value1")
.add("field2", 10)
.add("field3", false)
assertThat(sprite.entries()).contains(
entry("field1", "value1"),
entry("field2", 10),
entry("field3", false)
)
}
@Test
internal fun `flat collection value`() {
val values = mutableListOf<String>("value1", "value2", "value3")
sprite.add("field1", values)
.add("field2", 10)
.add("field3", false)
assertThat(sprite.rawValuesOf<String>("field1")).isNotEmpty
.hasSize(3)
assertThat(sprite.entries()).contains(
entry("field1", "value1"),
entry("field1", "value2"),
entry("field1", "value3"),
entry("field2", 10),
entry("field3", false)
)
}
@Test
internal fun `return single value as string`() {
sprite.add("field1", "value1")
.add("field2", 10)
.add("field3", false)
assertThat(sprite.valueOf("field1")).isEqualTo("value1")
assertThat(sprite.valueOf("field2")).isEqualTo("10")
assertThat(sprite.valueOf("field3")).isEqualTo("false")
}
@Test
internal fun `return multi value as string`() {
sprite.add("field1", 10)
.add("field1", 20)
.add("field1", 30)
assertThat(sprite.valuesOf("field1")).contains("10", "20", "30")
}
@Test
internal fun `return multi value as int type`() {
sprite.add("field1", 10)
.add("field1", 20)
.add("field1", 30)
assertThat(sprite.rawValuesOf<Int>("field1")).contains(10, 20, 30)
}
@Test
internal fun `return single value typed`() {
sprite.add("field1", "value1")
.add("field2", 10)
.add("field3", false)
assertThat(sprite.rawValueOf<String>("field1")).isEqualTo("value1")
assertThat(sprite.rawValueOf<Int>("field2")).isEqualTo(10)
assertThat(sprite.rawValueOf<Boolean>("field3")).isEqualTo(false)
}
@Test
internal fun `copy single value field`() {
sprite.add("field", "value")
.copy("field", "copyOfField")
assertThat(sprite.entries()).contains(
entry("field", "value"),
entry("copyOfField", "value")
)
}
@Test
internal fun `copy multi values field`() {
sprite.add("field", "value1")
.add("field", "value2")
.add("field", "value3")
.add("field", "value4")
.copy("field", "copyOfField")
assertThat(sprite.entries()).isNotEmpty
assertThat(sprite.entries()).contains(
entry("field", "value1"),
entry("field", "value2"),
entry("field", "value3"),
entry("field", "value4"),
entry("copyOfField", "value1"),
entry("copyOfField", "value2"),
entry("copyOfField", "value3"),
entry("copyOfField", "value4")
)
}
@Test
internal fun `not adds empty values`() {
sprite.addAll("field", Lists.emptyList())
assertThat(sprite.data).isEmpty()
sprite.add("field", "")
assertThat(sprite.data).isEmpty()
}
@Test
internal fun `rename field`() {
sprite.add("field", "value1")
.add("field", "value2")
.add("field", "value3")
.add("field", "value4")
.rename("field", "renamed")
assertThat(sprite.data).contains(
entry("renamed", "value1"),
entry("renamed", "value2"),
entry("renamed", "value3"),
entry("renamed", "value4")
)
}
@Test
internal fun `rename with lambda`() {
sprite.add("a_field", "value1")
.rename(Pattern.compile("a_.*")) { v: String -> v.removePrefix("a_") }
assertThat(sprite.data)
.contains(entry("field", "value1"))
.hasSize(1)
}
@Test
internal fun `join field values`() {
sprite.add("field", "value1")
.add("field", "value2")
.add("field", "value3")
.add("field", "value4")
.joinValuesOf("field", "\n", "VALUES\n", "\nEND")
assertThat(sprite.isSingleValue("field")).isTrue()
assertThat(sprite.valueOf("field"))
.isEqualTo(
"""VALUES
|value1
|value2
|value3
|value4
|END""".trimMargin()
)
}
@Test
internal fun `split field value`() {
sprite.add("field", "value1 value2 value3 value4")
.splitValues("field", " ")
assertThat(sprite.isMultiValue("field")).isTrue()
assertThat(sprite.valuesOf("field"))
.contains("value1", "value2", "value3", "value4")
}
@Test
internal fun `be idempotent on renaming not present field`() {
sprite.rename("notPresent", "renamed")
assertThat(sprite.isEmpty()).isTrue()
}
@Test
internal fun `retrieve field names`() {
sprite.add("field", "value")
.add("field2", "value2")
.add("field3", "value3")
assertThat(sprite.fields())
.contains("field", "field2", "field3")
}
@Test
internal fun `retrieve field names with regexp`() {
sprite.add("field1", "value")
.add("field2", "value2")
.add("field3", "value3")
.add("a_field", "value")
assertThat(sprite.fields(Pattern.compile("field.*")))
.contains("field1", "field2", "field3")
assertThat(sprite.fields(Regex("field.*")))
.contains("field1", "field2", "field3")
assertThat(sprite.fields(Regex("a_.*")))
.contains("a_field")
}
@Test
internal fun `retrieve field string values with regexp`() {
sprite.add("field1", "value")
.add("field2", "value2")
.add("field3", "value3")
.add("a_field", "value")
assertThat(sprite.valuesOf(Pattern.compile("field.*")))
.contains("value", "value2", "value3")
assertThat(sprite.valuesOf(Regex("field.*")))
.contains("value", "value2", "value3")
assertThat(sprite.valuesOf(Regex("a_.*")))
.contains("value")
}
@Test
internal fun `say if value exists`() {
sprite.add("field", "value")
assertThat(sprite.hasValue("value")).isTrue()
assertThat(sprite.hasValue("field", "value")).isTrue()
assertThat(sprite.hasNotValue("notPresent")).isTrue()
assertThat(sprite.hasNotValue("field", "NotPresent")).isTrue()
}
@Test
internal fun `remove field`() {
sprite.add("field", "value")
sprite.remove("field")
assertThat(sprite.data).isEmpty()
}
@Test
internal fun `remove fields`() {
sprite.add("field", "value")
.add("field", "value2")
.add("field2", "value2")
sprite.remove(listOf("field", "field2"))
assertThat(sprite.data).isEmpty()
}
@Test
internal fun `remove fields with pattern`() {
sprite.add("field", "value")
.add("field", "value2")
.add("field2", "value2")
sprite.remove(Pattern.compile("field.*"))
assertThat(sprite.data).isEmpty()
}
@Test
internal fun `load from map`() {
val now = LocalDate.now()
val input = mapOf(
"field1" to "value1",
"field2" to "value2",
"field3" to now
)
sprite.load(input)
assertThat(sprite.hasField("field1")).isTrue()
assertThat(sprite.hasField("field2")).isTrue()
assertThat(sprite.hasField("field3")).isTrue()
assertThat(sprite.valueOf("field3")).isEqualTo(now.toString())
}
@Test
internal fun `apply lambda to all field values`() {
sprite.add("field", "value")
.add("field", "value2")
sprite.apply("field", String::toUpperCase)
assertThat(sprite.data).isNotEmpty()
assertThat(sprite.valuesOf("field")).contains("VALUE", "VALUE2")
}
@Test
internal fun `apply lambda to all fields matching a pattern`() {
sprite.add("firstField", "value")
.add("secondField", "value2")
sprite.apply(Pattern.compile(".*Field"), String::toUpperCase)
assertThat(sprite.data).isNotEmpty()
assertThat(sprite.valuesOf("firstField")).contains("VALUE")
assertThat(sprite.valuesOf("secondField")).contains("VALUE2")
}
@Test
internal fun `apply lambda to all field values and store on another field`() {
sprite.add("field", "value")
.add("field", "value2")
sprite.apply("field", String::toUpperCase, "to")
assertThat(sprite.data).isNotEmpty()
assertThat(sprite.valuesOf("field")).contains("value", "value2")
assertThat(sprite.valuesOf("to")).contains("VALUE", "VALUE2")
}
@Test
internal fun `return map with single value`() {
val now = LocalDate.now()
val map = sprite.add("field", "value")
.add("field", "value2")
.add("field", "value3")
.add("dateField", now)
.asMap()
assertThat(map?.get("field")).isEqualTo("value")
assertThat(map?.get("dateField")).isEqualTo(now)
}
@Test
internal fun `return map with single value as string`() {
val now = LocalDate.now()
val map = sprite.add("field", "value")
.add("field", "value2")
.add("field", "value3")
.add("dateField", now)
.asStringMap()
assertThat(map.get("field")).isEqualTo("value")
assertThat(map.get("dateField")).isEqualTo(now.toString())
}
@Test
internal fun `transform sprite to mutable map of collections`() {
val map = sprite.add("field", "value")
.add("field", "value2")
.add("field", "value3")
.add("single", "singleValue")
.asMultimap()
assertThat(map?.get("field"))
.hasSize(3)
.contains("value", "value2", "value3")
assertThat(map?.get("single"))
.hasSize(1)
.containsOnly("singleValue")
}
@Test
internal fun `answer about field's size`() {
sprite.add("field", "value")
.add("field", "value2")
.add("field", "value3")
.add("dateField", LocalDate.now())
// field
assertThat(sprite.isMultiValue("field")).isTrue()
assertThat(sprite.isSingleValue("field")).isFalse()
assertThat(sprite.sizeOf("field")).isEqualTo(3)
// dateField
assertThat(sprite.isMultiValue("dateField")).isFalse()
assertThat(sprite.isSingleValue("dateField")).isTrue()
assertThat(sprite.sizeOf("dateField")).isEqualTo(1)
}
@Test
internal fun `consider two sprites equals`() {
sprite.add("f", "v")
val other = Sprite().add("f", "v")
assertThat(sprite).isEqualTo(other)
}
@Test
internal fun `view date as string`() {
sprite.add("text", "the text")
.add("text", "another text")
.add("date", LocalDate.parse("20180901", DateTimeFormatter.ofPattern("yyyyMMdd")))
.add("age", 10)
assertThat(sprite.toString())
.isEqualTo("{date=[2018-09-01], text=[the text, another text], age=[10]}")
}
@Test
internal fun `show an ETL example`() {
val data = Sprite()
.add("age", 90)
.add("name", "rob")
.add("text", "first phrase")
.add("text", "second phrase")
.add("text", "third phrase")
.add("text", "fourth phrase")
.rename("age", "weight")
.apply("weight") { v: Float -> v * 2.2 }
.apply("name", String::toUpperCase)
.joinValuesOf("text")
assertThat(data.hasField("age"))
.isFalse()
assertThat(data.rawValueOf<Float>("weight"))
.isEqualTo(198.0f)
assertThat(data.valueOf("name"))
.isEqualTo("ROB")
assertThat(data.valueOf("text"))
.isEqualTo("first phrase, second phrase, third phrase, fourth phrase")
}
}
|
apply(from = "enterprise.gradle.kts")
include(":app")
rootProject.name = "app"
|
(ns day_01
(:require [utils :refer [open-resource]]))
(def input-file "day_01.txt")
(def data (->> input-file open-resource (map #(Integer/parseInt %))))
(defn part-01 [input]
(let [pairs #(partition 2 1 %)
differences (fn [[f s]] (- f s))]
(->> input pairs (map differences) (filter neg?) count)))
(defn part-02 [input]
(let [threes #(partition 3 1 %)
pairs #(partition 2 1 %)
sums #(reduce + %)
differences (fn [pair] (- (first pair) (second pair)))]
(->> input threes (map sums) pairs (map differences) (filter neg?) count)))
(defn -main [& _]
(println "Day 01:")
(println "\t-> Part 1: " (part-01 data))
(println "\t-> Part 2: " (part-02 data)))
|
import toDate from '../toDate/index'
import requiredArgs from '../_lib/requiredArgs/index'
/**
* @name startOfSecond
* @category Second Helpers
* @summary Return the start of a second for the given date.
*
* @description
* Return the start of a second for the given date.
* The result will be in the local timezone.
*
* @param {Date|Number} date - the original date
* @returns {Date} the start of a second
* @throws {TypeError} 1 argument required
*
* @example
* // The start of a second for 1 December 2014 22:15:45.400:
* const result = startOfSecond(new Date(2014, 11, 1, 22, 15, 45, 400))
* //=> Mon Dec 01 2014 22:15:45.000
*/
export default function startOfSecond(dirtyDate: Date | number): Date {
requiredArgs(1, arguments)
const date = toDate(dirtyDate)
date.setMilliseconds(0)
return date
}
|
import 'package:linkfy_text/src/enum.dart';
String urlRegExp = r'(?:(?:https?|ftp):\/\/)?[\w/\-?=%.]+\.[\w/\-&?=%.]+';
String hashtagRegExp = r'(#+[a-zA-Z0-9(_)]{1,})';
String emailRegExp =
r"([a-zA-Z0-9.a-zA-Z0-9.!#$%&'*+-/=?^_`{|}~]+@[a-zA-Z0-9]+\.[a-zA-Z]+)";
/// construct regexp. pattern from provided link linkTypes
RegExp constructRegExpFromLinkType(List<LinkType> linkTypes) {
// default case where we always want to match url strings
if (linkTypes.length == 1 && linkTypes.first == LinkType.url)
return RegExp(urlRegExp);
StringBuffer _regexBuffer = StringBuffer();
for (var i = 0; i < linkTypes.length; i++) {
final _type = linkTypes[i];
final _isLast = i == linkTypes.length - 1;
switch (_type) {
case LinkType.url:
_isLast
? _regexBuffer.write("($urlRegExp)")
: _regexBuffer.write("($urlRegExp)|");
break;
case LinkType.hashTag:
_isLast
? _regexBuffer.write("($hashtagRegExp)")
: _regexBuffer.write("($hashtagRegExp)|");
break;
case LinkType.email:
_isLast
? _regexBuffer.write("($emailRegExp)")
: _regexBuffer.write("($emailRegExp)|");
break;
default:
}
}
return RegExp(_regexBuffer.toString());
}
LinkType getMatchedType(RegExpMatch match) {
late LinkType _type;
if (RegExp(urlRegExp).hasMatch(match.input)) {
_type = LinkType.url;
} else if (RegExp(hashtagRegExp).hasMatch(match.input)) {
_type = LinkType.hashTag;
} else if (RegExp(hashtagRegExp).hasMatch(match.input)) {
_type = LinkType.email;
}
return _type;
}
|
#set -x
# extract minor version (eg. 10.9 vs. 10.10 vs. 10.11)
MINOR_VER=$([[ "$(sw_vers -productVersion)" =~ [0-9]+\.([0-9]+) ]] && echo ${BASH_REMATCH[1]})
if [[ $MINOR_VER -ge 11 ]]; then
echo 10.11+
else
echo 10.10-
fi
|
๏ปฟusing Kingmaker.Blueprints;
using Kingmaker.Blueprints.Facts;
using Kingmaker.Blueprints.JsonSystem;
using Kingmaker.Items;
using Kingmaker.Items.Slots;
using Kingmaker.PubSubSystem;
using Kingmaker.UnitLogic;
namespace TabletopTweaks.Core.NewComponents {
[AllowedOn(typeof(BlueprintUnitFact), false)]
[AllowMultipleComponents]
[TypeId("3bc123b6862c42d987955e4350a7fd94")]
public class RecalculateOnEquipmentChange :
UnitFactComponentDelegate,
IUnitActiveEquipmentSetHandler,
IUnitSubscriber,
ISubscriber,
IUnitEquipmentHandler {
public void HandleEquipmentSlotUpdated(ItemSlot slot, ItemEntity previousItem) {
if (slot.Owner != this.Owner)
return;
this.Fact.Reapply();
}
public void HandleUnitChangeActiveEquipmentSet(UnitDescriptor unit) {
this.Fact.Reapply();
}
}
}
|
<?php
namespace Spatie\EventSourcing\Enums;
class MetaData
{
const AGGREGATE_ROOT_UUID = 'aggregate-root-uuid';
const AGGREGATE_ROOT_VERSION = 'aggregate-root-version';
}
|
package kim.jeonghyeon.simplearchitecture.plugin.config
import kim.jeonghyeon.simplearchitecture.plugin.extension.simpleArchExtension
import org.gradle.api.Project
import org.gradle.kotlin.dsl.apply
import org.gradle.kotlin.dsl.withType
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
fun Project.applyCommonConfig() {
if (!simpleArchExtension.commonConfig) {
return
}
System.setProperty(// Enabling kotlin compiler plugin
"kotlin.compiler.execution.strategy",
"in-process"
)
project.tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
}
|
*----------------------------------------------------------------------*
subroutine prop_evaluate(ndens,rank,label_den,trplt,
& env_type,op_info,str_info,orb_info)
*----------------------------------------------------------------------*
*
* for a given list of densities (all have rank "rank") evaluate
* all properties available in the environment
*
*----------------------------------------------------------------------*
implicit none
include 'opdim.h'
include 'ioparam.h'
include 'def_graph.h'
include 'def_strinf.h'
include 'def_orbinf.h'
include 'mdef_operator_info.h'
integer, intent(in) ::
& ndens, rank
logical, intent(in) ::
& trplt
character(*), intent(in) ::
& label_den(ndens)
character(*), intent(in) ::
& env_type
type(operator_info) ::
& op_info
type(strinf) ::
& str_info
type(orbinf) ::
& orb_info
integer ::
& cmo_type, idens, idxden
character ::
& label*8
type(filinf) ::
& ffcmo, ffdao, ffprop
integer, external ::
& idx_mel_list
! get MO-AO trafo from environment
call file_init(ffcmo,'CMO',ftyp_da_unf,lblk_da)
cmo_type = -1
call import_cmo(ffcmo,cmo_type,env_type,orb_info)
do idens = 1, ndens
idxden = idx_mel_list(label_den(idens),op_info)
if (idxden.le.0)
& call quit(1,'prop_evaluate',
& 'label not found: '//trim(label_den(idens)))
! back-transform densities
if (rank.eq.1) then
call file_init(ffdao,'DAO',ftyp_da_unf,lblk_da)
call btran_one(ffdao,ffcmo,trplt,
& op_info%mel_arr(idxden)%mel,orb_info,str_info)
else
call quit(1,'prop_evaluate','only rank==1 supported')
end if
! calculate trace with one-electron integrals
! provided by environment
call oneprop_ao(ffdao,op_info%mel_arr(idxden)%mel,
& env_type,orb_info)
end do
call file_delete(ffcmo)
return
end
|
<?php
/**
* Administration panel
*
* @package Cotonti
* @version 0.1.0
* @author Neocrome, Cotonti Team
* @copyright Copyright (c) Cotonti Team 2008-2009
* @license BSD
*/
(defined('SED_CODE') && defined('SED_ADMIN')) or die('Wrong URL.');
list($usr['auth_read'], $usr['auth_write'], $usr['isadmin']) = sed_auth('admin', 'any');
sed_block($usr['auth_read']);
$enabled[0] = $L['Disabled'];
$enabled[1] = $L['Enabled'];
$id = sed_import('id', 'G', 'TXT');
$po = sed_import('po', 'G', 'TXT');
$c = sed_import('c', 'G', 'TXT');
$p = sed_import('p', 'G', 'TXT');
$l = sed_import('l', 'G', 'TXT');
$o = sed_import('o', 'P', 'TXT');
$w = sed_import('w', 'P', 'TXT');
$u = sed_import('u', 'P', 'TXT');
$s = sed_import('s', 'G', 'ALP', 24);
/* === Hook for the plugins === */
$extp = sed_getextplugins('admin.main');
if(is_array($extp))
{
foreach($extp as $k => $pl)
{
include_once($cfg['plugins_dir'].'/'.$pl['pl_code'].'/'.$pl['pl_file'].'.php');
}
}
$sys['inc'] = (empty($m)) ? 'admin.home' : "admin.$m";
$sys['inc'] = (empty($s)) ? $sys['inc'] : $sys['inc'].".$s";
$sys['inc'] = $cfg['system_dir'].'/core/admin/'.$sys['inc'].'.inc.php';
if(!file_exists($sys['inc']))
{
sed_die();
}
$allow_img['0']['0'] = "<img src=\"images/admin/deny.gif\" alt=\"\" />";
$allow_img['1']['0'] = "<img src=\"images/admin/allow.gif\" alt=\"\" />";
$allow_img['0']['1'] = "<img src=\"images/admin/deny_locked.gif\" alt=\"\" />";
$allow_img['1']['1'] = "<img src=\"images/admin/allow_locked.gif\" alt=\"\" />";
$t = new XTemplate(sed_skinfile('admin.inc', false, true));
$lincif_conf = sed_auth('admin', 'a', 'A');
$lincif_page = sed_auth('page', 'any', 'A');
$lincif_user = sed_auth('users', 'a', 'A');
$t -> assign(array(
"ADMINMENU_URL" => sed_url('admin'),
"ADMINMENU_CONF_URL" => sed_url('admin', "m=config"),
"ADMINMENU_PAGE_URL" => sed_url('admin', "m=page"),
"ADMINMENU_FORUMS_URL" => sed_url('admin', "m=forums"),
"ADMINMENU_USERS_URL" => sed_url('admin', "m=users"),
"ADMINMENU_PLUG_URL" => sed_url('admin', "m=plug"),
"ADMINMENU_TOOLS_URL" => sed_url('admin', "m=tools"),
"ADMINMENU_TRASHCAN_URL" => sed_url('admin', "m=trashcan"),
"ADMINMENU_OTHER_URL" => sed_url('admin', "m=other")
));
$t -> parse("ADMINMENU");
$adminmenu = $t -> text("ADMINMENU");
require_once($sys['inc']);
$adminhelp = (empty($adminhelp)) ? $L['None'] : $adminhelp;
$title_tags[] = array('{ADMIN}');
$title_tags[] = array('%1$s');
$title_data = array($L['Administration']);
$out['subtitle'] = sed_title('{ADMIN}', $title_tags, $title_data);
require_once($cfg['system_dir'].'/header.php');
$t = new XTemplate(sed_skinfile('admin', false, true));
$t->assign(array(
"ADMIN_TITLE" => sed_build_adminsection($adminpath),
"ADMIN_SUBTITLE" => $adminsubtitle,
"ADMIN_MENU" => $adminmenu,
"ADMIN_MAIN" => $adminmain,
"ADMIN_HELP" => $adminhelp,
));
/* === Hook for the plugins === */
$extp = sed_getextplugins('admin.tags');
if(is_array($extp))
{
foreach($extp as $k => $pl)
{
include_once($cfg['plugins_dir'].'/'.$pl['pl_code'].'/'.$pl['pl_file'].'.php');
}
}
/* ===== */
$t->parse("MAIN");
$t->out("MAIN");
require_once($cfg['system_dir'].'/footer.php');
?>
|
const getWinston = async (bytes, target) => {
bytes = bytes ||ย 0;
target = target ||ย '';
const response = await fetch(`https://arweave.net/price/${bytes}/${target}`);
return response.ok ? response.text() : null;
};
const createState = (state) => {
return new Proxy(state, {
set(obj, property, value) {
obj[property] = value;
const target = obj['target'].toString();
const amount = parseInt(obj['amount']);
const unit = parseInt(obj['unit']);
const size = amount * unit;
getWinston(size, target).then(data => {
if (!data) {
return false;
}
const winston = new Big(data);
const ar = new Big(0.000000000001);
obj['winston'] = winston;
obj['ar'] = (winston * ar).toFixed(12);
render();
return true;
});
}
});
};
const state = createState({
amount: 0,
unit: 1,
target: '',
winston: 0,
ar: 0
});
document.querySelectorAll('[data-model]').forEach(listener => {
const name = listener.dataset.model;
for(const e of ['keyup', 'click', 'change']) {
listener.addEventListener(e, event => {
state[name] = listener.value;
});
}
});
const render = () => {
Array.from(document.querySelectorAll('[data-binding]'))
.map(e => e.dataset.binding)
.forEach(binding => {
document.querySelector(`[data-binding='${binding}']`).innerText = state[binding];
});
};
render();
document.getElementById('amount').click();
|
// Copyright 2020 Sarbagya Dhaubanjar. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
/// Formats month to literal form
String formattedMonth(int month) {
switch (month) {
case 1:
return 'January';
case 2:
return 'February';
case 3:
return 'March';
case 4:
return 'April';
case 5:
return 'May';
case 6:
return 'June';
case 7:
return 'July';
case 8:
return 'August';
case 9:
return 'September';
case 10:
return 'October';
case 11:
return 'November';
case 12:
return 'December';
default:
return '';
}
}
|
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
/// <summary>
/// Serializable helper for System.Windows.Media.Color
/// </summary>
[Serializable]
public struct Colour
{
public byte A;
public byte R;
public byte G;
public byte B;
public Colour(byte a, byte r, byte g, byte b)
{
A = a;
R = r;
G = g;
B = b;
}
public Colour(Color color) : this(color.A, color.R, color.G, color.B)
{
}
public static implicit operator Colour(Color color)
{
return new Colour(color);
}
public static implicit operator Color(Colour colour)
{
return Color.FromArgb(colour.A, colour.R, colour.G, colour.B);
}
}
|
#!/bin/bash
#ๅฝๅๆฅๆ
today=`date "+%Y%m%d"`
# ่ฎพ็ฝฎๅๆถ่ทฏๅพ
trashPath=$HOME/.Trash
# ๅๅปบๅๆถๆไปถๅคน
if [ ! -d "$trashPath" ]; then
mkdir $trashPath
fi
# ๆธ
้คๅฝไปคไธญ็ๆๆๅผๅ
ณ้้กน
args=${@##-*}
# ็งปๅจๆไปถๅนถๅคไปฝ๏ผๅฆๆๅฟ
่ฆ๏ผไฟฎๆน้่ฏฏไฟกๆฏๅนถ่พๅบ
msg=`mv --backup=t $args $trashPath 2>&1`
if [ ! "$msg" = "" ]; then
echo ${msg//mv/.rm.sh} # ๅฐ้่ฏฏไฟกๆฏไธญ็โmvโๆฟๆขๆ".rm.sh"
fi
# ่ฎพ็ฝฎๆ ๅฟๆไปถ่ทฏๅพ
flagFile=$trashPath/.flag
# ======================================
# ๆฏๅคฉ็ฌฌไธๆฌกไฝฟ็จ่ฟไธชๅฝไปคๅ๏ผๆธ
็ไธๆฎตๆถ้ดไปฅๅๅๆถ็ๆไปถ
# ------------------------------
# ๅฎไนๆธ
็ๆงๆไปถ็ๅฝๆฐ
function clearOldFile()
{
echo "delete old file, please wait ..."
find $trashPath -maxdepth 1 -ctime +7 |xargs /bin/rm -rf
echo $today > $flagFile # ่พๅบไปๅคฉ็ๆฅๆๅฐๆ ๅฟๆไปถ
}
if [ -f "$flagFile" ]; then
lastDate=`cat $flagFile` # ่ฏปๅๆ ๅฟๆไปถไธญ็ๆฅๆ
if [ "$lastDate" -ne "$today" ]; then # ๅฆๆไธๆฏไปๅคฉ็ๆฅๆๅฐฑๆธ
็
clearOldFile
fi
else # ๆ ๅฟๆไปถไธๅญๅจไน่ฆๆธ
็
clearOldFile
fi
|
# Ayehu
AY IncidentConfigurationCreateIncident
Method: Post
OperationID: IncidentConfiguration_CreateIncident
EndPoint:
/API/IncidentConfiguration/createIncident
|
CREATE DATABASE threads ENCODING 'UTF8' LC_COLLATE 'en_US.UTF-8' LC_CTYPE 'en_US.UTF-8';
GRANT All PRIVILEGES ON database threads TO doug;
|
<?php
namespace App\Enum;
class TableStatuses
{
public const BUSY = 'busy';
public const FREE = 'free';
public const SERVED = 'served';
}
|
<?php
include_once('config.php');
if(isset($_POST["update"])){
$id = $_GET['id'];
$nama = $_POST['nama'];
$user = $_POST['username'];
$pass = $_POST['password'];
$query= "UPDATE tb_user SET username='$user', password='$pass', nama='$nama' WHERE id='$id' ";
mysqli_query($koneksi, $query);
header('location:user');
}
else {
header('location:user');
}
?>
|
import { Controller, HttpResponse, Validation } from '@/presentation/protocols'
import { AddChildren } from '@/domain/usecases'
import { Gender } from '@/domain/models'
import { badRequest, serverError, created } from '@/presentation/helpers'
export class AddChildrenController implements Controller {
constructor (
private readonly validation: Validation,
private readonly addChildren: AddChildren
) { }
async handle (httpRequest: AddChildrenController.Request): Promise<HttpResponse> {
try {
const request = {
accountId: httpRequest.accountId,
name: httpRequest.name,
birth: httpRequest.birth,
gender: httpRequest.gender
}
const error = this.validation.validate(request)
if (error) {
return badRequest(error)
}
const id = await this.addChildren.add(request)
return created({ id })
} catch (error) {
return serverError(error)
}
}
}
export namespace AddChildrenController {
export type Request = {
accountId: string
name: string
birth: number
gender: Gender
}
}
|
#!/usr/bin/perl
#This perl script can be used to create a Qt QRC file for all the files in a given folder
# To generate a QRC file for all the icons in the /icons folder,
# first, cd into the Core folder
# second, call "perl ../icons/createQRC.pl ../icons > Tinkercell.qrc"
# compile again so that the new qrc file is used
$dir = $ARGV[0];
opendir(DIR,$dir );
@FILES= readdir(DIR);
if ($dir !~ /\/$/)
{
$dir = $dir."/";
}
print "<RCC>\n";
print " <qresource prefix=\"/images\">\n";
foreach my $file(@FILES)
{
if ($file =~ /[A-Za-z0-9]\.[A-Za-z0-9]/ && $file !~ /~/ && $file !~ /\.pl/)
{
print " <file alias=\"$file\">$dir$file</file>\n";
}
}
print " </qresource>\n";
print "</RCC>\n";
|
# Club de Investigaciรณn en Ciencia de Datos
Pรกgina Web del Club de Investigaciรณn en Ciencia de Datos.
|
import 'package:flutter/material.dart';
import 'package:video_viewer/data/repositories/video.dart';
import 'package:video_viewer/ui/widgets/transitions.dart';
class VideoCoreThumbnail extends StatelessWidget {
const VideoCoreThumbnail({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
final query = VideoQuery();
final video = query.video(context, listen: true);
final style = query.videoStyle(context);
return CustomOpacityTransition(
visible: video.isShowingThumbnail,
child: GestureDetector(
onTap: video.controller.play,
child: Container(
color: Colors.transparent,
child: style.thumbnail,
),
),
);
}
}
|
package admin
import (
"context"
"net/http"
"github.com/ops-cn/common/schema"
)
// ILogin ็ปๅฝไธๅก้ป่พๆฅๅฃ
type ILogin interface {
// ่ทๅๅพๅฝข้ช่ฏ็ ไฟกๆฏ
GetCaptcha(ctx context.Context, length int) (*schema.LoginCaptcha, error)
// ็ๆๅนถๅๅบๅพๅฝข้ช่ฏ็
ResCaptcha(ctx context.Context, w http.ResponseWriter, captchaID string, width, height int) error
// ็ปๅฝ้ช่ฏ
Verify(ctx context.Context, userName, password string) (*schema.User, error)
// ็ๆไปค็
GenerateToken(ctx context.Context, userID string) (*schema.LoginTokenInfo, error)
// ้ๆฏไปค็
DestroyToken(ctx context.Context, tokenString string) error
// ่ทๅ็จๆท็ปๅฝไฟกๆฏ
GetLoginInfo(ctx context.Context, userID string) (*schema.UserLoginInfo, error)
// ๆฅ่ฏข็จๆท็ๆ้่ๅๆ
QueryUserMenuTree(ctx context.Context, userID string) (schema.MenuTrees, error)
// ๆดๆฐ็จๆท็ปๅฝๅฏ็
UpdatePassword(ctx context.Context, userID string, params schema.UpdatePasswordParam) error
}
|
## DRUM MACHINE APP
this project is part of freecodecamp projects challenges
https://learn.freecodecamp.org/front-end-libraries/front-end-libraries-projects/build-a-drum-machine/
### Steps to run
#### 1- for provide local audio is necesary
Web Server for Chrome extension
https://chrome.google.com/webstore/detail/web-server-for-chrome/ofhbbkphhbklhfoeikjpcbhemlocgigb/related
#### 2- setup Web Server and choice folder, and paste all sounds under src/sounds path to selected folder.
#### 3- run npm start
## tegnologies
### ReactJS
* components
* props
* FLUX
### Redux
* stores
* actions
* actions creators
* reducers
### React-Redux
-Provider
-connect
-handling redux store
-connecting states properties to components props
-connecting actions creators and dispatchers to components props
### material-ui
## Preview

|
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../blocs/counter_bloc.dart';
class ProviderPage extends StatelessWidget {
const ProviderPage();
@override
Widget build(BuildContext context) {
return Provider<CounterBloc>(
create: (_) => CounterBloc(),
dispose: (_, bloc) => bloc.dispose(),
child: Scaffold(
appBar: AppBar(
title: const Text('Provider()'),
),
body: const _CounterText(),
floatingActionButton: _floatingButton(),
),
);
}
Widget _floatingButton() {
// Using Consumer here rather than Selector does not affect the performance
// badly because CounterBloc is not ChangeNotifier, meaning that changes of
// values in CounterBloc does not trigger rebuilds.
return Consumer<CounterBloc>(
builder: (_, bloc, child) {
return FloatingActionButton(
onPressed: bloc.increment,
child: child,
);
},
child: const Icon(Icons.add),
);
}
}
class _CounterText extends StatelessWidget {
const _CounterText();
@override
Widget build(BuildContext context) {
// Using context.read<CounterBloc>() inside build() causes an exception.
// Either of Provider.of(), context.watch() or context.select() has to be
// used instead.
final bloc = Provider.of<CounterBloc>(context, listen: false);
return StreamBuilder<int>(
stream: bloc.value,
initialData: 0,
builder: (_, snapshot) {
return Center(
child: Text(snapshot.data.toString()),
);
},
);
}
}
|
/*
Package storage provides type definitions for use with the Chrome Storage protocol
https://chromedevtools.github.io/devtools-protocol/tot/Storage/
*/
package storage
/*
UsageForType is usage for a storage type.
https://chromedevtools.github.io/devtools-protocol/tot/Storage/#type-UsageForType
*/
type UsageForType struct {
// Name of storage type.
Type TypeEnum `json:"storageType"`
// Storage usage (bytes).
Usage int `json:"usage"`
}
|
#!/bin/bash
farm=${1:-farmNotSet}
argFile=${2:-reaper.conf}
echo $0
echo farm $farm
echo argFile $argFile
export PYTHONPATH=~/ncscli
export PATH=$PATH:~/ncscli/ncscli
sdt=$(date -u --iso-8601=seconds)
sdtTag=$(date --date=$sdt +"%Y-%m-%d_%H%M%S")
cd ~/ncscli/examples/neoload
dataDirPath=data/$farm
#mkdir -p $dataDirPath
errLogPath=$dataDirPath/checkAgentsInfinite.log
echo $errLogPath
touch $errLogPath
echo ">>>$0" >> $errLogPath
echo $sdtTag >> $errLogPath
while true
do
#logrotate --state $dataDirPath/logrotate.state $dataDirPath/logrotate.conf
./checkAgents.py @$argFile --terminateBad True \
--dataDirPath $dataDirPath 2>> $errLogPath
echo ">>>$0 end of loop" >> $errLogPath
sleep 120
done
|
#!/usr/bin/perl
# postprocess data for spec_index: squash multiple occurrences of parameters
# @(#) $Id: 344fb98b28f19144666c0c8de994f015d47e3215 $
# 2016-05-05: append "COMMIT;"
# 2016-04-16, Dr. Georg Fischer
#------------------------------------------------------------------
# Usage: c.f. makefile
# perl -i*.bak unify_parms.pl etc/sql/spec_index_insert.sql
#-------------------------------------------------------------------------------
use strict;
while (<>) {
my $line = $_;
if (m{\A\t\,\'(\&[^\']+)\'}) {
my $parms_column = $1;
my $rest = $2;
my @parms = split(/\&/, $parms_column);
my %hash = ();
foreach my $parm(@parms) {
my ($name, $value) = split(/\=/, $parm);
if (0) {
} elsif (! defined($hash{$name})) {
$hash{$name} = $value;
} elsif (length($hash{$name}) == 0) {
$hash{$name} = $value;
}
} # foreach $parm
$parms_column = "";
foreach my $key(sort(keys(%hash))) {
if (length($key) > 0) {
$parms_column .= "\&$key=$hash{$key}";
}
} # foreach $key
print "\t,\'$parms_column\');\r\n";
} else {
print "$line";
}
} # while <>
print <<GFis;
--
COMMIT;
GFis
__DATA__
# Example before processing by this Perl program
INSERT INTO spec_index (subdir, name, lang, title, comment, params) VALUES (
'test','fragment01','de','fragment01',
'Abfrage mit Fragment im Link '
,'&name=% &name= &name= ');
COMMIT;
INSERT INTO spec_index (subdir, name, lang, title, comment, params) VALUES (
'test','grouping','de','grouping',
'Test der wiederholten รberschriften beim Gruppenwechsel '
,'');
COMMIT;
INSERT INTO spec_index (subdir, name, lang, title, comment, params) VALUES (
'test','highlight','de','highlight',
'Liste der Spezifikationen mit Hervorhebung eines Schlagworts '
,'&keyword=color &keyword= &keyword= &keyword= ');
COMMIT;
INSERT INTO spec_index (subdir, name, lang, title, comment, params) VALUES (
'test','image01','de','image01',
'Abfrage einer Tabelle mit Bildern '
,'');
COMMIT;
|
package service
import (
"net"
pb "github.com/huajiao-tv/gokeeper/pb/go"
"github.com/huajiao-tv/gokeeper/server/setting"
"github.com/huajiao-tv/gokeeper/server/sync"
"github.com/johntech-o/gorpc"
"google.golang.org/grpc"
)
//@todo ๅฎๅserverๅๅงๅ้จๅๅ
ๅฎน,ไผๅไปฃ็
var (
grpcListener net.Listener //grpcไธญ้
็ฝฎๅๆๅกๅ็ฐ็็ซฏๅฃๆๆถๅ
ฑ็จ
)
//ๅฏๅจsync server๏ผ้ป่ฎคๅผๅฏgorpcๅ่ฎฎ็server
func StartSyncServer(withGrpc bool) {
go startPSync()
if withGrpc {
go startGSync()
}
}
//ๅฏๅจpepper gorpcๅ่ฎฎ็server
func startPSync() {
s := gorpc.NewServer(setting.GoRpcListen)
err := s.Register(new(sync.Server))
if err != nil {
panic("psync register error:" + err.Error())
}
s.Serve()
panic("start gorpc service error")
}
//ๅฏๅจgoogle grpcๅ่ฎฎ็server @todo ๅฎๅserver
func startGSync() {
s := grpc.NewServer([]grpc.ServerOption{}...)
pb.RegisterSyncServer(s, &sync.GSyncServer{})
registerDiscovery(s)
err := s.Serve(setting.GrpcListener)
if err != nil {
panic("start grpc service error:" + err.Error())
}
}
|
#include "stdafx.h"
#include "ObjectAnimator.h"
#include "motion.h"
bool st_AnimParam::Update(float dt){
t+=dt;
if (t>max_t){
if (bLoop){ t=min_t; return true; }
else { t=max_t; return false;}
}
return true;
}
void st_AnimParam::Set(COMotion* M, bool _loop){
t=0;
bLoop = _loop;
min_t=(float)M->FrameStart()/M->FPS();
max_t=(float)M->FrameEnd()/M->FPS();
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CObjectAnimator::CObjectAnimator()
{
}
CObjectAnimator::~CObjectAnimator()
{
for(MotionPairIt m_it=m_Motions.begin(); m_it!=m_Motions.end(); m_it++){
free(m_it->first);
_DELETE(m_it->second);
}
m_Motions.clear ();
}
void CObjectAnimator::SetActiveMotion(COMotion* mot, bool bLoop){
m_ActiveMotion =mot;
if (m_ActiveMotion) m_MParam.Set(m_ActiveMotion, bLoop);
vPosition.set (0,0,0);
mRotate.identity ();
}
void CObjectAnimator::LoadMotions(const char* fname){
FILE_NAME full_path;
if (!Engine.FS.Exist( full_path, Path.Current, fname ))
if (!Engine.FS.Exist( full_path, Path.Meshes, fname ))
Device.Fatal("Can't find motion file '%s'.",fname);
CFileStream F (full_path);
DWORD dwMCnt = F.Rdword(); VERIFY(dwMCnt);
for (DWORD i=0; i<dwMCnt; i++){
COMotion* M = new COMotion();
M->Load (F);
m_Motions[strdup(M->Name())]=M;
}
}
void CObjectAnimator::Load(CInifile* ini, const char * section)
{
LPCSTR temp = ini->ReadSTRING(section,"motions");
LoadMotions (temp);
SetActiveMotion (0,false);
}
void CObjectAnimator::OnMove()
{
if (IsMotionActive()){
Fvector R;
m_ActiveMotion->Evaluate(m_MParam.Frame(),vPosition,R);
if (!m_MParam.Update(Device.fTimeDelta)) StopMotion();
mRotate.setHPB (R.x,R.y,R.z);
}
}
COMotion* CObjectAnimator::PlayMotion(LPCSTR name, bool bLoop)
{
MotionPairIt I = m_Motions.find(LPSTR(name));
if (I!=m_Motions.end()) SetActiveMotion(I->second, bLoop);
else {
Msg("OBJ ANIM::Cycle '%s' not found.",name);
return NULL;
}
return I->second;
}
void CObjectAnimator::StopMotion(){
SetActiveMotion (0);
}
void CObjectAnimator::ManualUpdate(COMotion* M, float t){
Fvector R;
m_ActiveMotion->Evaluate(t,vPosition,R);
mRotate.setHPB (R.x,R.y,R.z);
}
/*
#include "stdafx.h"
#include "ObjectAnimator.h"
#include "motion.h"
//---------------------------------------------------------------------
class fMNameEQ {
const char* name;
public:
fMNameEQ(char *N) : name(N) {};
IC int operator() (CEMotion* M) { return strcmp(M->Name(),name); }
};
//---------------------------------------------------------------------
bool st_AnimParam::Update(float dt){
t+=dt;
if (t>max_t){
if (bLoop){ t=min_t; return true; }
else { t=max_t; return false;}
}
return true;
}
void st_AnimParam::Set(CEMotion* M, bool _loop){
t=0;
bLoop = _loop;
min_t=(float)M->FrameStart()/M->FPS();
max_t=(float)M->FrameEnd()/M->FPS();
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CObjectAnimator::CObjectAnimator()
{
}
CObjectAnimator::~CObjectAnimator()
{
for(MotionIt m_it=m_Motions.begin(); m_it!=m_Motions.end(); m_it++)
_DELETE(*m_it);
m_Motions.clear ();
}
void CObjectAnimator::SetActiveMotion(CEMotion* mot, bool bLoop){
m_ActiveMotion =mot;
if (m_ActiveMotion) m_MParam.Set(m_ActiveMotion, bLoop);
vPosition.set (0,0,0);
mRotate.identity ();
}
void CObjectAnimator::LoadMotions(const char* fname){
FILE_NAME full_path;
if (!Engine.FS.Exist( full_path, LEVEL_PATH, fname ))
if (!Engine.FS.Exist( full_path, MESHES_PATH, fname )){
Msg("Can't find motion file '%s'.",fname);
THROW;
}
CFileStream F (full_path);
DWORD dwMCnt = F.Rdword(); VERIFY(dwMCnt);
for (int i=0; i<dwMCnt; i++){
CEMotion* M = new CEMotion();
M->Load (F);
m_Motions.push_back(M);
}
}
void CObjectAnimator::Load(CInifile* ini, const char * section)
{
LPCSTR temp = ini->ReadSTRING(section,"motions");
LoadMotions (temp);
SetActiveMotion (0,false);
}
void CObjectAnimator::OnMove()
{
if (IsMotionActive()){
Fvector R;
m_ActiveMotion->Evaluate(0,m_MParam.Frame(),vPosition,R);
if (!m_MParam.Update(Device.fTimeDelta)) StopMotion();
mRotate.setHPB (R.x,R.y,R.z);
}
}
CEMotion* CObjectAnimator::FindMotionByName(LPCSTR name){
for (MotionIt m_it=m_Motions.begin(); m_it!=m_Motions.end(); m_it++)
if (strcmp((*m_it)->Name(), name)==0) return *m_it;
return 0;
}
CEMotion* CObjectAnimator::PlayMotion(LPCSTR name, bool bLoop)
{
CEMotion* M = FindMotionByName(name);
if (M) SetActiveMotion(M, bLoop);
else {
Msg("OBJ ANIM::Cycle '%s' not found.",name);
return NULL;
}
return M;
}
void CObjectAnimator::StopMotion(){
SetActiveMotion (0);
}
void CObjectAnimator::ManualUpdate(CEMotion* M, float t){
Fvector R;
m_ActiveMotion->Evaluate(0,t,vPosition,R);
mRotate.setHPB (R.x,R.y,R.z);
}
*/
|
<?php
/**
* This file is part of the LdapTools package.
*
* (c) Chad Sikorra <Chad.Sikorra@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace LdapTools\Security\Ace;
use LdapTools\Security\Flags;
use LdapTools\Security\FlagsSddlTrait;
/**
* Represents ACE flags.
*
* @author Chad Sikorra <Chad.Sikorra@gmail.com>
*/
class AceFlags extends Flags
{
use FlagsSddlTrait;
/**
* Valid ACE type-specific control flags.
*/
const FLAG = [
'OBJECT_INHERIT' => 0x01,
'CONTAINER_INHERIT' => 0x02,
'NO_PROPAGATE_INHERIT' => 0x04,
'INHERIT_ONLY' => 0x08,
'INHERITED' => 0x10,
'SUCCESSFUL_ACCESS' => 0x40,
'FAILED_ACCESS' => 0x80,
];
/**
* The short name for the flag used in SDDL.
*/
const SHORT_NAME = [
'OI' => 0x01,
'CI' => 0x02,
'NP' => 0x04,
'IO' => 0x08,
'ID' => 0x10,
'SA' => 0x40,
'FA' => 0x80,
];
/**
* Check or set whether the ACE does not control access to the object to which it is attached. When this is true,
* the ACE only controls access on those objects which inherit it.
*
* @param null $action
* @return $this|bool
*/
public function inheritOnly($action = null)
{
return $this->hasOrSet(self::FLAG['INHERIT_ONLY'], $action);
}
/**
* Check or set whether inheritance of this ACE should be propagated.
*
* @param null|bool $action
* @return $this|bool
*/
public function propagateInheritance($action = null)
{
// The bit means the opposite, so flip it depending on the context (same for the return).
$action = is_null($action) ? $action : !((bool) $action);
$result = $this->hasOrSet(self::FLAG['NO_PROPAGATE_INHERIT'], $action);
return is_null($action) ? !$result : $result;
}
/**
* Check or set whether containers should inherit this ACE.
*
* @param null|bool $action
* @return $this|bool
*/
public function containerInherit($action = null)
{
return $this->hasOrSet(self::FLAG['CONTAINER_INHERIT'], $action);
}
/**
* Check or set whether objects should inherit this ACE.
*
* @param null|bool $action
* @return $this|bool
*/
public function objectInherit($action = null)
{
return $this->hasOrSet(self::FLAG['OBJECT_INHERIT'], $action);
}
/**
* Whether or not the ACE should generate audit messages for failed access attempts (only valid in the SACL).
*
* @param null|bool $action
* @return $this|bool
*/
public function auditFailedAccess($action = null)
{
return $this->hasOrSet(self::FLAG['FAILED_ACCESS'], $action);
}
/**
* Whether or not the ACE should generate audit messages for successful access attempts (only valid in the SACL).
*
* @param null|bool $action
* @return $this|bool
*/
public function auditSuccessfulAccess($action = null)
{
return $this->hasOrSet(self::FLAG['SUCCESSFUL_ACCESS'], $action);
}
/**
* Check whether or not the ACE is inherited.
*
* @return bool
*/
public function isInherited()
{
return $this->has(self::FLAG['INHERITED']);
}
}
|
package org.moe.runtime
abstract class MoeNativeObject[A] (
private var value: A,
private var associatedType: Option[MoeType] = None
) extends MoeObject(associatedType) {
def getNativeValue: A = value
protected def setNativeValue(v: A) = value = v
def copy: MoeNativeObject[A]
}
|
#### Parser Content
```Java
{
Name = crowdstrike-config-change
Vendor = CrowdStrike
Product = Falcon
Lms = Direct
DataType = "config-change"
TimeFormat = "epoch"
Conditions = [ """"event_simpleName":"Firewall""" ]
Fields = [
"""exabeam_host=([^=]{1,2000}@\s{0,100})?(gcs-topic|({host}[\w\-.]{1,2000}))""",
""""hostname":"({host}[\w\-.]{1,2000})"""",
""""timestamp":"({time}\d{1,100})""",
""""event_simpleName":"({activity}[^"]{1,2000})""",
""""aid":"({aid}[^"]{1,2000})""",
""""FirewallRule":"({object}[^"]{1,2000})""",
""""UserName":"(({user_email}[^@"]{1,2000}@[^"]{1,2000})|({user}[^@"]{1,2000}))"""",
"""src-account-name":"({account_name}[^"]{1,2000})""",
""""FirewallOption":"({object}[^"]{1,2000})""""
]
DupFields = ["activity->event_code"]
}
```
|
import React from 'react';
import './Note.scss';
import { deleteNote } from './notesStore';
import { ReactComponent as CloseIcon } from '../../icons/Close.svg';
import { useDispatch } from 'react-redux';
export const Note: React.FC<{ content: string; noteId: number }> = ({
content,
noteId,
}) => {
const dispatch = useDispatch();
return (
<p className="note-container">
<button
className="close-btn-container"
onClick={() => dispatch(deleteNote(noteId))}
>
<CloseIcon />
</button>
{content}
</p>
);
};
|
๏ปฟusing UnityEngine;
public class PauseScreenComponent : MonoBehaviour
{
public void OnExitMenuClick()
{
OsFps.Instance.MenuStack.Pop();
}
public void OnOptionsClick()
{
OsFps.Instance.EnterOptionsScreen();
}
public void OnLeaveServerClick()
{
OsFps.Instance.MenuStack.Pop();
OsFps.Instance.Client.LeaveServer();
}
}
|
package uk.gov.nationalarchives.signcookies
import java.time.Instant
trait TimeUtils {
def now(): Instant
}
|
import mongoose from "mongoose";
import { CardItemSchema } from "../cardItem/cardItemModel";
const Schema = mongoose.Schema;
export const CardItemsSchema = new Schema({
header: {
type: String,
required: true
},
cardItems: [CardItemSchema]
});
export default mongoose.model("CardItems", CardItemsSchema);
|
# Bayesian Logistic Regression with Laplace Approximation
See the `ftr_notebook.ipynb` for example usage.


|
//'use strict';
/*
*
* TASK 1
*
* ะกะพะทะดะฐะนัะต ััะฝะบัะธั ะบะพัะพัะฐั ะฑัะดะตั ะทะฐะฟะพะผะธะฝะฐัั ะฟะตัะตะดะฐะฝะฝัะต
* ะตะน ะฐัะณัะผะตะฝัั, ะธ ะฟัะธะฑะฐะฒะปััั ะธั
ะฒ ัััะพะบั
* ะธ ะพัะพะฑัะฐะถะฐัั ะฒ ะบะพะฝัะพะปะต ะฒัั ัััะพะบั
*
*
* */
function solution1() {
let str = "";
let args = [];
return function(arg) {
args.push(arg);
return (str += arg + " ");
};
}
let stringBuffer = solution1();
stringBuffer('ะะฐะผัะบะฐะฝะธั'); // ะะฐะผัะบะฐะฝะธั
stringBuffer('ะัะฟะพะปัะทะพะฒะฐัั ะฝัะถะฝะพ'); // ะะฐะผัะบะฐะฝะธั ะัะฟะพะปัะทะพะฒะฐัั ะฝัะถะฝะพ
console.log(stringBuffer('ะัะธะฒะตั')); // ะะฐะผัะบะฐะฝะธั ะัะฟะพะปัะทะพะฒะฐัั ะฝัะถะฝะพ ะัะธะฒะตั
// ะฒัะทัะฒะฐะตะผ ะผะฝะพะณะพ ัะฐะท
/*
*
* TASK 2
* ะะฐะฟะธัะธัะต ััะฝะบัะธั ะบะพัะพัะฐั ะฟัะธะฝะธะผะฐะตั ะฒ ะบะฐัะตััะฒะต ะฐัะณัะผะตะฝัะฐ ัััะพะบั
* ะธะท ัะบะพะฑะพัะตะบ ะธ ะฟะพััะธัะฐะนัะต, * ััะพ ะฒัะต ัะบะพะฑะพัะบะธ ะทะฐะบััะฒะฐัััั ะบะพััะตะบัะฝะพ
*
* */
let openBra = ["(", "[", "{"]; //ะฝะฐะฑะพั ะพัะบััะฒะฐััะธั
ัั ัะบะพะฑะพะบ
let closeBra = [")", "]", "}"]; //ะฝะฐะฑะพั ะทะฐะบััะฒะฐััะธั
ัั ัะบะพะฑะพะบ (ะธะฝะดะตะบัั ะดะพะปะถะฝั ัะพะพัะฒะตัััะฒะพะฒะฐัั)
function validBraces(str) {
console.log(str);
let opened = [];
for (let i = 0; i < str.length; i++) {
if (openBra.indexOf(str[i]) > -1) {// ะฟัะพะฒะตัะบะฐ ะตััั ะปะธ ะฒ ะผะฐััะธะฒะต ะพัะบััััั
ัะบะพะฑะพะบ
opened.push(str[i]); // ะตัะปะธ ะตััั ะดะพะฑะฐะฒะปัะตะผ ะฒ ะผะฐััะธะฒ ะพัะบััััะต ัะบะพะฑะบะธ
}
if (closeBra.indexOf(str[i]) > -1) {// ะฟัะพะฒะตัะบะฐ ะตััั ะปะธ ะฒ ะผะฐััะธะฒะต ะทะฐะบััััั
ัะบะพะฑะพะบ
if (openBra.indexOf(opened[opened.length - 1]) - closeBra.indexOf(str[i]) !==0) {
return false;// ะตัะปะธ ะธะฝะดะตะบั ะฟะพัะปะตะดะฝะตะน ะพัะบัััะพะน ัะบะพะฑะบะธ ะผะธะฝัั ะธะฝะดะตะบั ะทะฐะบัััะพะน ะฝะต 0 ัะพะณะดะฐ false
} else {
opened.pop();//ะตัะปะธ 0 ะทะฝะฐัะธั ัะบะพะฑะบะฐ ะบะฐะบะฐั ะพัะบััะปะฐ ัะฐะบะฐั ะธ ะทะฐะบััะปะฐ ัะดะฐะปัะตะผ ะฟะพัะปะตะดะฝัั ะพัะบััััั
}
}
}
return (opened.length == 0 ? true : false) // ะตัะปะธ ะฒ ะบะพะฝัะต ะผะฐััะธะฒ ะฟััั ะทะฝะฐัะธั ะฒัะต ะพัะบััััะต ัะบะพะฑะบะธ ะทะฐะบััะปะธัั
}
console.log(validBraces('(){}[]')); //=> returns true
console.log(validBraces('(}')); //=> returns false
console.log(validBraces('[(])')); // => returns false
console.log(validBraces('([{}])')); //=> returns true
console.log(validBraces('{([()(()){}])}')); //=> returns true
/*
*
* TASK 3
* ะะฐะฟะธัะธัะต ััะฝะบัะธั ะบะพัะพัะฐั ะฑัะดะตั ะฟัะธะฝะธะผะฐัั 1 ะฐัะณัะผะตะฝัะฐ - ััะฝะบัะธั
*
* ะััะตัะฐะบัะพัะธัะต ะบะพะด ัะฐะบะธะผ ะพะฑัะฐะทะพะผ, ััะพะฑั ัะพะพะฑัะตะฝะธะต 'THE LAST LAST comment',
* ะพัะพะฑัะฐะทะธะปะพัั ะฒ ะบะพะฝัะพะปะต ะฟะพัะปะตะดะฝะธะผ
*
* */
function makeCallback(fn) {
for (let i = 1; i <= 10; i++) {
setTimeout(function() {
console.log(i);
if (i == 10){
fn();
}
}, i * 1000);
}
}
makeCallback(function() {
console.log('THE LAST LAST comment');
});
// @SUPER
/*
*
* ะะฐะฟะธัะธัะต ััะฝะบัะธั ะบะพัะพัะฐั ะฑัะดะตั ะฟัะธะฝะธะผะฐัั ะพะดะฝะพ ัะธัะปะพ ะธ ะฒัะฒะพะดะธัั ััะผะผั
* ะฒัะตั
ะฝะฐัััะฐะปัะฝัั
ัะธัะตะป
* sum(5) //5+4+3+2+1
*
* ะััะธัะปะตะฝะธั ะดะพะปะถะฝั ะบะตัะธัะพะฒะฐัััั, ะตัะปะธ ะฒ ััะฝะบัะธั ะฟะพะฟะฐะดะฐะตั ะทะฐะบะตัะธัะพะฒะฐะฝะฝะพะต
* ะทะฝะฐัะตะฝะธะต, ะฒ ะบะพะฝัะพะปะต ะดะพะปะถะฝะพ ะพัะพะฑัะฐะทะธัััั
* ะะฝะฐัะตะฝะธะต ะฒะทััะพ ะธะท ะบััะฐ
*
* */
// function fnc(n) {
// let summ = 0;
// for (let i = 0; i <= n; i++) {
// summ += i;
// }
// return { [n]: summ };
// }
function sum(n) {
let summ = 0;
for (let i = 0; i <= n; i++) {
summ += i;
}
if (sum[n] == undefined) {
sum[n] = summ;
console.log(`${sum[n]} ะะพะฒะพะต ะทะฝะฐัะตะฝะธะต`);
} else {
console.log(`${sum[n]} ะะท ะบะตัะฐ`);
}
}
sum(5); // 15 ะะฝะฐัะตะฝะธะต ะบะตัะธัะพะฒะฐะฝะพ
sum(5); // 15 ะะฝะฐัะตะฝะธะต ะฒะทััะพ ะธะท ะบััะฐ
sum(6); // 21 ะะตัะธัะพะฒะฐะฝะพ
sum(6); // 21 ะะฝะฐัะตะฝะธะต ะฒะทััะพ ะธะท ะบััะฐ
// console.log(sum1(7));
|
#include "charitydialog.h"
#include "ui_charitydialog.h"
#include "clientmodel.h"
#include "notificator.h"
#include "version.h"
#include "wallet.h"
#include "walletdb.h"
#include "main.h"
#include "init.h"
#include <QMessageBox>
charityDialog::charityDialog(QWidget *parent) :
QDialog(parent),
ui(new Ui::charityDialog)
{
ui->setupUi(this);
}
charityDialog::~charityDialog()
{
delete ui;
}
void charityDialog::setModel(ClientModel *model)
{
}
void charityDialog::on_buttonBox_accepted()
{
QMessageBox msgBox;
CBitcoinAddress address = ui->charityAddressEdit->text().toStdString();
QString str = ui->charityPercentEdit->text();
bool fIntConversion;
unsigned int nCharityPercent = str.toInt(&fIntConversion, 10);
if (!address.IsValid())
{
msgBox.setText("Invalid CypertsCoin address");
msgBox.exec();
return;
}
if (nCharityPercent < 1)
{
msgBox.setText("Invalid parameter, expected valid percentage");
msgBox.exec();
return;
}
if (pwalletMain->IsLocked())
{
msgBox.setText("Error: Please enter the wallet passphrase with walletpassphrase first.");
msgBox.exec();
return;
}
//Turn off if we set to zero.
//Future: After we allow multiple addresses, only turn of this address
if(nCharityPercent == 0)
{
pwalletMain->fStakeForCharity = false;
pwalletMain->StakeForCharityAddress = "";
pwalletMain->nStakeForCharityPercent = 0;
msgBox.setText("0 Percent Selected, void");
msgBox.exec();
return;
}
//For now max percentage is 50.
if (nCharityPercent > 50 )
nCharityPercent = 50;
pwalletMain->StakeForCharityAddress = address;
pwalletMain->nStakeForCharityPercent = nCharityPercent;
pwalletMain->fStakeForCharity = true;
msgBox.setText("Split Stake Set");
msgBox.exec();
}
void charityDialog::on_buttonBox_rejected()
{
close();
}
void charityDialog::on_pushButton_clicked()
{
QMessageBox msgBox;
pwalletMain->fStakeForCharity = false;
pwalletMain->StakeForCharityAddress = "";
pwalletMain->nStakeForCharityPercent = 0;
msgBox.setText("Split Stake Disabled");
msgBox.exec();
}
|
use crate::hardware::Cpu;
use crate::memory::Memory;
const INTERRUPTS_VBLANK: u8 = 1 << 0;
const INTERRUPTS_LCDSTAT: u8 = 1 << 1;
const INTERRUPTS_TIMER: u8 = 1 << 2;
const INTERRUPTS_SERIAL: u8 = 1 << 3;
const INTERRUPTS_JOYPAD: u8 = 1 << 4;
pub fn interrupt_check(cpu: &mut Cpu, mem: &mut Memory) -> bool {
if mem.read(0xFFFF) & mem.read(0xFF0F) > 0 {
if cpu.mie {
let mask: u8 = mem.read(0xFFFF) & mem.read(0xFF0F);
if mask & INTERRUPTS_VBLANK > 0 {
mem.write(0xFF0F, mem.read(0xFF0F) & !INTERRUPTS_VBLANK);
vblank(cpu, mem);
//println!("vblank");
return true;
}
if mask & INTERRUPTS_LCDSTAT > 0 {
mem.write(0xFF0F, mem.read(0xFF0F) & !INTERRUPTS_LCDSTAT);
lcd_stat(cpu, mem);
//println!("stat");
return true;
}
if mask & INTERRUPTS_TIMER > 0 {
mem.write(0xFF0F, mem.read(0xFF0F) & !INTERRUPTS_TIMER);
timer(cpu, mem);
//println!("timer");
return true;
}
if mask & INTERRUPTS_SERIAL > 0 {
mem.write(0xFF0F, mem.read(0xFF0F) & !INTERRUPTS_SERIAL);
serial(cpu, mem);
//println!("serial");
return true;
}
if mask & INTERRUPTS_JOYPAD > 0 {
mem.write(0xFF0F, mem.read(0xFF0F) & !INTERRUPTS_JOYPAD);
joypad(cpu, mem);
//println!("joypad");
return true;
}
}
true
} else {
false
}
}
pub fn vblank(cpu: &mut Cpu, mem: &mut Memory) {
cpu.mie = false;
cpu.write_u16_to_stack(cpu.pc, mem);
cpu.pc = 0x40; // +12 ticks
}
pub fn lcd_stat(cpu: &mut Cpu, mem: &mut Memory) {
cpu.mie = false;
cpu.write_u16_to_stack(cpu.pc, mem);
cpu.pc = 0x48; // +12 ticks
}
pub fn timer(cpu: &mut Cpu, mem: &mut Memory) {
cpu.mie = false;
cpu.write_u16_to_stack(cpu.pc, mem);
cpu.pc = 0x50; // +12 ticks
}
pub fn serial(cpu: &mut Cpu, mem: &mut Memory) {
cpu.mie = false;
cpu.write_u16_to_stack(cpu.pc, mem);
cpu.pc = 0x58; // +12 ticks
}
pub fn joypad(cpu: &mut Cpu, mem: &mut Memory) {
cpu.mie = false;
cpu.write_u16_to_stack(cpu.pc, mem);
cpu.pc = 0x60; // +12 ticks
}
|
Topics that should be covered
-------------------------
* History of Software
* Challenges of Project Management
* History of OSS
* Prehistoric open source: BSD, MIT Emacs, X Windows, etc.
* GNU, Stallman, etc.
* Linux
* Today...
* Well-known projects
* Linux
* Distros
* Languages (Ruby, ... which other ones are relevant enough)
* Android
* Other models
* Proprietary software
* Standards-driven software (C++, etc.)
* Hybrid models (Java, etc.)
* Roles in an OSS project
* Visionary/owner
* Main developers
* Contributers
* Testing
* Documentation
* Users
* (what else)
* Challenges
* Audience too narrow
* Competing commercial interests/agendas
* Owner loses interest or focus
* Code forks and schisms
* Emacs; (any other famous stories)
|
import {
Component,
OnInit,
ChangeDetectionStrategy,
Input,
AfterViewInit
} from "@angular/core";
@Component({
selector: "ng-marquee",
templateUrl: "./ng-marquee.component.html",
styleUrls: ["./ng-marquee.component.css"],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class NgMarqueeComponent implements OnInit {
@Input() duration: string | number;
@Input() marqueeId: string;
animationElem: HTMLDivElement;
constructor() {}
updateDuration() {
if (!this.duration) {
return;
}
this.animationElem.style.animationDuration = `${this.duration}s`;
}
ngOnInit() {}
ngAfterViewInit() {
this.animationElem = document.querySelector(
`.ng-marquee-wrapper#${this.marqueeId} > div`
) as HTMLDivElement;
this.updateDuration();
}
}
|
import {
Controller,
Get,
Post,
Body,
Delete,
UploadedFile,
UseInterceptors,
Query,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { BannerService } from './banner.service';
@Controller('banner')
export class BannerController {
constructor(private readonly bannerService: BannerService) {}
@Post()
@UseInterceptors(FileInterceptor('file'))
async create(@UploadedFile() file, @Body() body) {
return this.bannerService.create(file, body);
}
@Get()
findAll() {
return this.bannerService.findAll();
}
@Delete()
remove(@Query('id') id: string) {
return this.bannerService.remove(+id);
}
@Get('delete')
remmoveAll() {
return this.bannerService.removeAll();
}
}
|
at_style=At typ systรฉmu,1,linux-Linux,solaris-Solaris,freebsd-FreeBSD,irix-Irix,macos-MacOS X,openserver-OpenServer
at_dir=At adresรกล รบkolลฏ,0
allow_file=Povolit soubor At uลพivatelลฏ,3,Nic
deny_file=Zakรกzat soubor At uลพivatelรฉ,3,Nic
|
๏ปฟ/*! @file */
/*
Copyright (C) 2018-2021, Sakura Editor Organization
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
*/
#include "StdAfx.h"
#include "CCodeBase.h"
#include "charset/CCodeFactory.h"
#include "convert/convert_util2.h"
#include "charset/codechecker.h"
#include "CEol.h"
#include "env/CommonSetting.h"
/*!
ๆๅญใณใผใใฎ16้ฒ่กจ็คบ
ในใใผใฟในใใผ่กจ็คบ็จใซๆๅญใ16้ฒ่กจ่จใซๅคๆใใ
@param [in] cSrc ๅคๆใใๆๅญ
@param [in] sStatusbar ๅ
ฑ้่จญๅฎ ในใใผใฟในใใผ
@param [in,opt] bUseFallback cSrcใ็นๅฎใณใผใใง่กจ็พใงใใชใๅ ดๅใซใใฉใผใซใใใฏใใใใฉใใ
*/
std::wstring CCodeBase::CodeToHex(const CNativeW& cSrc, const CommonSetting_Statusbar& sStatusbar, bool bUseFallback /* = true */)
{
std::wstring buff(32, L'\0');
if (const auto ret = UnicodeToHex(cSrc.GetStringPtr(), cSrc.GetStringLength(), buff.data(), &sStatusbar);
ret != RESULT_COMPLETE && bUseFallback) {
// ใใพใใณใผใใๅใใชใใฃใ(Unicodeใง่กจ็คบ)
return CCodeFactory::CreateCodeBase(CODE_UNICODE)->CodeToHex(cSrc, sStatusbar, false);
}
return buff;
}
// ่กจ็คบ็จ16้ฒ่กจ็คบ UNICODE โ Hex ๅคๆ 2008/6/9 Uchi
EConvertResult CCodeBase::UnicodeToHex(const wchar_t* cSrc, const int iSLen, WCHAR* pDst, const CommonSetting_Statusbar* psStatusbar)
{
if (IsUTF16High(cSrc[0]) && iSLen >= 2 && IsUTF16Low(cSrc[1])) {
// ใตใญใฒใผใใใข
if (psStatusbar->m_bDispSPCodepoint) {
auto_sprintf( pDst, L"U+%05X", 0x10000 + ((cSrc[0] & 0x3FF)<<10) + (cSrc[1] & 0x3FF));
}
else {
auto_sprintf( pDst, L"%04X%04X", cSrc[0], cSrc[1]);
}
}
else {
auto_sprintf( pDst, L"U+%04X", cSrc[0] );
}
return RESULT_COMPLETE;
}
/*!
MIME ใใณใผใใผ
@param[out] pcMem ใใณใผใๆธใฟใฎๆๅญๅใๆ ผ็ด
*/
bool CCodeBase::MIMEHeaderDecode( const char* pSrc, const int nSrcLen, CMemory* pcMem, const ECodeType eCodetype )
{
ECodeType ecodetype;
int nskip_bytes;
// ใฝใผในใๅๅพ
pcMem->AllocBuffer( nSrcLen );
char* pdst = reinterpret_cast<char*>( pcMem->GetRawPtr() );
if( pdst == NULL ){
pcMem->SetRawData( "", 0 );
return false;
}
CMemory cmembuf;
int i = 0;
int j = 0;
while( i < nSrcLen ){
if( pSrc[i] != '=' ){
pdst[j] = pSrc[i];
++i;
++j;
continue;
}
nskip_bytes = _DecodeMimeHeader( &pSrc[i], nSrcLen-i, &cmembuf, &ecodetype );
if( nskip_bytes < 1 ){
pdst[j] = pSrc[i];
++i;
++j;
}else{
if( ecodetype == eCodetype ){
// eChartype ใ ecodetype ใจไธ่ดใใฆใใๅ ดๅใซใ ใใ
// ๅคๆ็ตๆใใณใใผ
memcpy( &pdst[j], cmembuf.GetRawPtr(), cmembuf.GetRawLength() );
i += nskip_bytes;
j += cmembuf.GetRawLength();
}else{
memcpy( &pdst[j], &pSrc[i], nskip_bytes );
i += nskip_bytes;
j += nskip_bytes;
}
}
}
pcMem->_SetRawLength( j );
return true;
}
/*!
BOMใใผใฟๅๅพ
ByteOrderMarkใซๅฏพใใ็นๅฎใณใผใใซใใใใคใใช่กจ็พใๅๅพใใใ
ใใซใใใคใใชUnicodeๆๅญใปใใใฎใใคใ้ ใ่ญๅฅใใใฎใซไฝฟใใ
*/
[[nodiscard]] BinarySequence CCodeBase::GetBomDefinition()
{
const CNativeW cBom( L"\xFEFF" );
bool bComplete = false;
auto converted = UnicodeToCode( cBom, &bComplete );
if( !bComplete ){
converted.clear();
}
return converted;
}
/*!
BOMใใผใฟๅๅพ
ByteOrderMarkใซๅฏพใใ็นๅฎใณใผใใซใใใใคใใช่กจ็พใๅๅพใใใ
ใใซใใใคใใชUnicodeๆๅญใปใใใฎใใคใ้ ใ่ญๅฅใใใฎใซไฝฟใใ
*/
void CCodeBase::GetBom( CMemory* pcmemBom )
{
if( pcmemBom != nullptr ){
if( const auto bom = GetBomDefinition(); 0 < bom.length() ){
pcmemBom->SetRawData( bom.data(), bom.length() );
}else{
pcmemBom->Reset();
}
}
}
/*!
ๆน่กใใผใฟๅๅพ
ๅ็จฎ่ก็ต็ซฏๅญใซๅฏพใใ็นๅฎใณใผใใซใใใใคใใช่กจ็พใฎใปใใใๅๅพใใใ
็นๅฎใณใผใใงๅฉ็จใงใใชใ่ก็ต็ซฏๅญใซใคใใฆใฏ็ฉบใฎใใคใใช่กจ็พใ่ฟใใ
*/
[[nodiscard]] std::map<EEolType, BinarySequence> CCodeBase::GetEolDefinitions()
{
constexpr struct {
EEolType type;
std::wstring_view str;
}
aEolTable[] = {
{ EEolType::cr_and_lf, L"\x0d\x0a", },
{ EEolType::line_feed, L"\x0a", },
{ EEolType::carriage_return, L"\x0d", },
{ EEolType::next_line, L"\x85", },
{ EEolType::line_separator, L"\u2028", },
{ EEolType::paragraph_separator, L"\u2029", },
};
std::map<EEolType, BinarySequence> map;
for( auto& eolData : aEolTable ){
bool bComplete = false;
const auto& str = eolData.str;
auto converted = UnicodeToCode( CNativeW( str.data(), str.length() ), &bComplete );
if( !bComplete ){
converted.clear();
}
map.try_emplace( eolData.type, std::move(converted) );
}
return map;
}
/*!
ๆน่กใใผใฟๅๅพ
ๆๅฎใใ่ก็ต็ซฏๅญใซๅฏพใใ็นๅฎใณใผใใซใใใใคใใช่กจ็พใๅๅพใใใ
ใณใผใใใคใณใใจใใคใใชใทใผใฑใณในใ1ๅฏพ1ใซๅฏพๅฟไปใใใใๆๅญใณใผใใฎๆน่กใๆคๅบใใใฎใซไฝฟใใ
*/
void CCodeBase::GetEol( CMemory* pcmemEol, EEolType eEolType )
{
if( pcmemEol != nullptr ){
const auto map = GetEolDefinitions();
if( auto it = map.find( eEolType ); it != map.end() ){
const auto& bin = it->second;
pcmemEol->SetRawData( bin.data(), bin.length() );
}else{
pcmemEol->Reset();
}
}
}
|
module Dev
class Vault
RELEASE = '1'.freeze
VERSION = '0.5.2'.freeze
end
end
|
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from .models import RemRole, RemUser, RemOrganization
from .utils import DateInput
# from phonenumber_field.formfields import PhoneNumberField
ACTIVE = 1
INACTIVE = 0
Status = [
(ACTIVE, 'Active'),
(INACTIVE, 'Inactive'),
]
MALE = 'male'
FEMALE = 'female'
OTHERS = 'others'
GenderChoices = [
(MALE, 'Male'),
(FEMALE, 'Female'),
(FEMALE, 'Others'),
]
class NewPassword(forms.ModelForm):
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Password",
"class": "form-control"
}
)
)
password1 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Confirm Password",
"class": "form-control"
}
)
)
def clean(self):
password_ = self.cleaned_data.get('password')
password__ = self.cleaned_data.get('password1')
if password_ != password__:
raise ValidationError(
{
"password": "Password and confirm password do not match",
"password1": "Password and confirm password do not match"
}
)
return self.cleaned_data
class Meta:
model = User
fields = ('password', 'password1',)
class ForgotPassword(forms.ModelForm):
email = forms.EmailField(
widget=forms.EmailInput(
attrs={
"placeholder": "Email",
"class": "form-control"
}
)
)
def clean(self):
email = self.cleaned_data.get('email')
if not User.objects.filter(email=email).exists():
raise ValidationError({"email": "Email does not exists"})
return self.cleaned_data
class Meta:
model = User
fields = ('email',)
class LoginForm(forms.Form):
username = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Username",
"class": "form-control"
}
))
password = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Password",
"class": "form-control"
}
))
remember_me = forms.BooleanField(required=False)
class Meta:
model = User
fields = ('username', 'password', 'remember_me')
class SignUpForm(UserCreationForm):
username = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Username",
"class": "form-control",
"autocomplete": "off",
}
))
first_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "First Name",
"autocomplete": "off",
"class": "form-control"
}
))
last_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Last Name",
"autocomplete": "off",
"class": "form-control"
}
))
email = forms.EmailField(
widget=forms.EmailInput(
attrs={
"placeholder": "Email",
"autocomplete": "off",
"class": "form-control"
}
))
phone = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Phone Number",
"autocomplete": "off",
"class": "form-control"
}
)
)
organization = forms.ModelChoiceField(
queryset=RemOrganization.objects.all().filter(status=ACTIVE),
empty_label='Not Listed',
required=False,
widget=forms.Select(
attrs={
'class': 'form-control',
'style': 'border-color: none;',
"autocomplete": "off",
'id': 'id_organization',
}
)
)
role = forms.ModelChoiceField(
queryset=RemRole.objects.all().filter(status=ACTIVE),
empty_label='Not Listed',
required=False,
widget=forms.Select(
attrs={
'class': 'form-control',
'style': 'border-color: none;',
"autocomplete": "off",
'id': 'id_role'
}
)
)
password1 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Password",
"autocomplete": "off",
"class": "form-control"
}
))
password2 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Confirm Password",
"autocomplete": "off",
"class": "form-control"
}
))
def clean(self):
email = self.cleaned_data.get('email')
if User.objects.filter(email=email).exists():
raise ValidationError({"email": "Email exists"})
username = self.cleaned_data.get('username')
if User.objects.filter(username=username).exists():
raise ValidationError({"username": "Username exists"})
password = self.cleaned_data.get('password1')
password1 = self.cleaned_data.get('password2')
if password != password1:
raise ValidationError(
{
"password1": "Password and confirm password do not match",
"password2": "Password and confirm password do not match"
}
)
return self.cleaned_data
class Meta:
model = User
fields = (
'username', 'first_name', 'last_name', 'email', 'phone', 'organization', 'role', 'password1', 'password2')
class FullSignUpForm(forms.ModelForm):
user_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Username",
"class": "form-control"
}
)
)
first_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "First Name",
"class": "form-control"
}
)
)
last_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Last Name",
"class": "form-control"
}
)
)
gender = forms.CharField(
max_length=6,
widget=forms.Select(
choices=GenderChoices,
attrs={
'class': 'form-control',
'style': 'border-color: none;',
}
),
)
date_of_birth = forms.DateField(widget=DateInput())
# phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format:
# '+999999999'. Up to 15 digits allowed.")
phone = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Phone Number",
"class": "form-control"
}
)
)
email = forms.EmailField(
widget=forms.EmailInput(
attrs={
"placeholder": "Email",
"class": "form-control"
}
)
)
organization_name = forms.ModelChoiceField(
queryset=RemOrganization.objects.all().filter(status=ACTIVE),
empty_label='Not Listed',
widget=forms.Select(
attrs={
'class': 'form-control',
'style': 'border-color: none;',
'id': 'id_organization',
}
)
)
# selected_org = ''
# if organization_name != "---------":
# selected_org = organization_name
role = forms.ModelChoiceField(
queryset=RemRole.objects.none(),
# empty_label='(Not Listed)',.filter(organization = selected_org)
empty_label='Not Listed',
widget=forms.Select(
attrs={
'class': 'form-control',
'style': 'border-color: none;',
'id': 'id_role'
}
)
)
address = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Address",
"class": "form-control"
}
)
)
country = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Country",
"class": "form-control"
}
)
)
city = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "City",
"class": "form-control"
}
)
)
password1 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Password",
"class": "form-control"
}
)
)
password2 = forms.CharField(
widget=forms.PasswordInput(
attrs={
"placeholder": "Password check",
"class": "form-control"
}
)
)
class Meta:
model = RemUser
fields = (
'user_name',
'first_name',
'last_name',
'gender',
'date_of_birth',
'phone',
'email',
'organization_name',
'role',
'address',
'country',
'city',
'password1',
'password2'
)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Init empty did queryset
self.fields['role'].queryset = RemRole.objects.none()
# Get did queryset for the selected fid
if 'organization_name' in self.data:
try:
org_id = int(self.data.get('organization_name'))
self.fields['role'].queryset = RemRole.objects.filter(
organization=org_id)
except (ValueError, TypeError):
# invalid input from the client; ignore and use empty queryset
pass
class RegisterOrganization(forms.ModelForm):
organization_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Organization Name",
"class": "form-control"
}
)
)
description = forms.CharField(
widget=forms.Textarea(
attrs={
"placeholder": "Description",
"class": "form-control"
}
)
)
phone = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Phone Number",
"class": "form-control"
}
)
)
e_mail = forms.EmailField(
widget=forms.EmailInput(
attrs={
"placeholder": "Email",
"class": "form-control"
}
)
)
website = forms.URLField(
widget=forms.URLInput(
attrs={
"placeholder": "Website",
"class": "form-control"
}
)
)
address = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Address",
"class": "form-control"
}
)
)
country = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Country",
"class": "form-control"
}
)
)
city = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "City",
"class": "form-control"
}
)
)
class Meta:
model = RemOrganization
fields = (
'organization_name',
'description',
'phone',
'e_mail',
'website',
'address',
'country',
'city',
)
'''
role_name = models.CharField(max_length=200)
organization = models.ForeignKey(RemOrganization, on_delete=models.CASCADE, null=True)
status = models.IntegerField(choices=Status, default=ACTIVE,)
created_by = models.BigIntegerField()
created_date = models.DateTimeField(blank=False, null=False)
updated_by = models.BigIntegerField()
updated_date = models.DateTimeField(blank=False, null=False)
'''
class RegisterRole(forms.ModelForm):
role_name = forms.CharField(
widget=forms.TextInput(
attrs={
"placeholder": "Role",
"class": "form-control"
}
)
)
# organization_ = forms.ModelChoiceField(
# queryset=RemOrganization.objects.all(),
# empty_label='Not Listed',
# widget=forms.Select(
# attrs={
# 'class': 'form-control',
# 'style': 'border-color: none;',
# }
# )
# )
class Meta:
model = RemRole
fields = (
'role_name',
# 'organization_',
)
|
# tcpts
Shutdown computer on request on given port. Default is 80.
## Help
```console
TCP to shutdown 0.1.0
Shutdown a computer if a specified port is requested
USAGE:
tcpts [OPTIONS] [port]
FLAGS:
-h, --help Prints help information
-V, --version Prints version information
OPTIONS:
-d, --delay <delay> Specify the delay between request and shutdown in seconds [default: 0]
ARGS:
<port> Specify the port to listen on [default: 80]
```
## How to use it
Run the binary and then send a request to the specified localhost port (default: 80) to shut down
your PC. On macOS, you will need to run it as super user.
## Installation
### GNU/Linux
* `wget https://github.com/Pythack/tcpts/releases/latest/download/tcpts-x86_64-unknown-linux-gnu.tar.gz`
* `tar -xzvf tcpts-x86_64-unknown-linux-gnu.tar.gz`
* `sudo mv tcpts-x86_64-unknown-linux-gnu/tcpts /bin`
### MacOS
If you have an M1 cpu, your architecture is ARM. If you have an Intel cpu, your architecture is x86_64
#### ARM
* `wget https://github.com/Pythack/tcpts/releases/latest/download/tcpts-aarch64-apple-darwin.zip`
* `unzip tcpts-aarch64-apple-darwin.zip`
* `sudo mv tcpts-aarch64-apple-darwin/tcpts /bin`
#### x86_64
* `wget https://github.com/Pythack/tcpts/releases/latest/download/tcpts-x86_64-apple-darwin.zip`
* `unzip tcpts-x86_64-apple-darwin.zip`
* `sudo mv tcpts-x86_64-apple-darwin/tcpts /bin`
## Building
* As permscan is written in rust, you will need rust to build it. The
[latest](https://www.rust-lang.org/tools/install) version is recommended.
* To build :
* `git clone https://github.com/Pythack/permscan`
* `cd permscan`
* `cargo build --release`
## License
This project is licensed under both :
* The Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or <http://www.apache.org/licenses/LICENSE-2.0>)
* The MIT license ([LICENSE-MIT](LICENSE-MIT) or
<http://opensource.org/licenses/MIT>)
|
<?php
namespace App\Http\Controllers;
use App\Kememberan;
use Illuminate\Http\Request;
class ApiKememberanController extends Controller
{
public function index()
{
$data = Kememberan::get();
return response()->json([
'status' => 'success',
'message' => 'list data kememberan',
'data' => $data
], 200);
}
public function show($id)
{
$data = Kememberan::find($id);
if(!$data)
{
return response()->json([
'status' => 'error',
'message' => 'id kememberan tidak ada'
], 404);
}
return response()->json([
'status' => 'success',
'message' => 'detail kememberan',
'data' => $data
], 200);
}
}
|
<?php
namespace Litepie\Contact\Repositories\Eloquent;
use Litepie\Contact\Interfaces\ContactRepositoryInterface;
use Litepie\Repository\Eloquent\BaseRepository;
class ContactRepository extends BaseRepository implements ContactRepositoryInterface
{
/**
* @var array
*/
protected $fieldSearchable = [
'name' => 'like'
];
public function boot()
{
}
/**
* Specify Model class name.
*
* @return string
*/
public function model()
{
return config('litepie.contact.contact.model');
}
}
|
predictionfile=outputs/simple_tagger_output.txt
outfname=outputs/simple_tagger_summary.txt
tgtfile=data/processed/multicopy.test.src.txt
# tune threshold to get equivalent summary length. # agg-ppl: 1867.28 words
python prediction_to_text.py -data $predictionfile \
-output $outfname \
-tgt $tgtfile \
-threshold 0.2 \
-divider "" \
-style sentences \
-prune 40000
python get-summary-stats.py
|
import 'package:flutter/material.dart';
import 'package:foldable_sidebar/foldable_sidebar.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:provider/provider.dart';
import 'package:realpet/components/state_management.dart';
import 'package:realpet/pages/login_page.dart';
import 'package:realpet/pages/product_page.dart';
import 'package:realpet/pages/register_page.dart';
import 'package:realpet/pages/results_page.dart';
import 'package:realpet/pages/user_page.dart';
import 'pages/storefront.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MultiProvider(
providers: [
ListenableProvider<DrawerModel>(
create: (_) => DrawerModel(drawerStatus: FSBStatus.FSB_CLOSE)),
ListenableProvider<BottomSearchModel>(
create: (_) => BottomSearchModel()),
ListenableProvider<ResultsContainerModel>(
create: (_) => ResultsContainerModel()),
],
child: GetMaterialApp(
title: 'Real Pet Catalog App',
theme: ThemeData.dark().copyWith(
scaffoldBackgroundColor: Colors.transparent,
sliderTheme: SliderThemeData(
overlayColor: Colors.black,
inactiveTrackColor: Colors.red,
activeTrackColor: Colors.white,
overlayShape: const RoundSliderOverlayShape(overlayRadius: 30),
trackHeight: 10,
valueIndicatorTextStyle: GoogleFonts.comfortaa(),
inactiveTickMarkColor: Colors.black,
thumbColor: Colors.yellow,
),
),
initialRoute: '/login',
getPages: [
GetPage(
name: '/',
page: () => StoreFront(),
),
GetPage(
name: '/login',
page: () => LoginPage(),
transition: Transition.leftToRight),
GetPage(
name: '/register',
page: () => RegisterPage(),
transition: Transition.rightToLeft,
),
GetPage(
name: '/product',
page: () => ProductPage(),
transition: Transition.size),
GetPage(
name: '/results',
page: () => ResultsPage(),
transition: Transition.fade),
GetPage(
name: '/user',
page: () => UserPage(),
transition: Transition.fade),
],
),
);
}
}
|
# coding: utf-8
require File.dirname(__FILE__) + '/spec_helper'
require 'htmldiff'
class TestDiff
extend HTMLDiff
end
describe "htmldiff" do
it "should diff text" do
diff = TestDiff.diff('a word is here', 'a nother word is there')
diff.should == "a<ins class=\"diffins\"> nother</ins> word is <del class=\"diffmod\">here</del><ins class=\"diffmod\">there</ins>"
end
it "should insert a letter and a space" do
diff = TestDiff.diff('a c', 'a b c')
diff.should == "a <ins class=\"diffins\">b </ins>c"
end
it "should remove a letter and a space" do
diff = TestDiff.diff('a b c', 'a c')
diff.should == "a <del class=\"diffdel\">b </del>c"
end
it "should change a letter" do
diff = TestDiff.diff('a b c', 'a d c')
diff.should == "a <del class=\"diffmod\">b</del><ins class=\"diffmod\">d</ins> c"
end
it "should support Chinese" do
diff = TestDiff.diff('่ฟไธชๆฏไธญๆๅ
ๅฎน, Ruby is the bast', '่ฟๆฏไธญๅฝ่ฏญๅ
ๅฎน๏ผRuby is the best language.')
diff.should == "่ฟ<del class=\"diffdel\">ไธช</del>ๆฏไธญ<del class=\"diffmod\">ๆ</del><ins class=\"diffmod\">ๅฝ่ฏญ</ins>ๅ
<del class=\"diffmod\">ๅฎน, Ruby</del><ins class=\"diffmod\">ๅฎน๏ผRuby</ins> is the <del class=\"diffmod\">bast</del><ins class=\"diffmod\">best language.</ins>"
end
it "should support img tags insertion" do
oldv = 'a b c'
newv = 'a b <img src="some_url" /> c'
diff = TestDiff.diff(oldv, newv)
diff.should == "a b <ins class=\"diffins\"><img src=\"some_url\" /> </ins>c"
end
it "should support img tags deletion" do
oldv = 'a b c'
newv = 'a b <img src="some_url" /> c'
diff = TestDiff.diff(newv, oldv)
diff.should == "a b <del class=\"diffdel\"><img src=\"some_url\" /> </del>c"
end
end
|
/*
Copyright (C) 2016 Red Hat, 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 registration
import (
"fmt"
"testing"
"github.com/docker/machine/libmachine/drivers"
"github.com/docker/machine/libmachine/provision"
"github.com/minishift/minishift/pkg/minikube/tests"
)
var (
param = &RegistrationParameters{
Username: "foo",
Password: "foo",
}
expectedCMDRegistration = fmt.Sprintf("sudo -E subscription-manager register --auto-attach --username %s --password '%s' ",
param.Username, param.Password)
expectedCMDUnregistration = "sudo -E subscription-manager unregister"
)
func setup(t *testing.T) (registrator Registrator) {
s, _ := tests.NewSSHServer()
s.CommandToOutput = make(map[string]string)
s.CommandToOutput["sudo -E subscription-manager version"] = `server type: This system is currently not registered.`
port, err := s.Start()
if err != nil {
t.Fatalf("Error starting ssh server: %s", err)
}
d := &tests.MockDriver{
Port: port,
BaseDriver: drivers.BaseDriver{
IPAddress: "127.0.0.1",
SSHKeyPath: "",
},
}
commander := provision.GenericSSHCommander{Driver: d}
registrator = NewRedHatRegistrator(commander)
return registrator
}
func TestRedHatRegistratorCompatibleWithDistribution(t *testing.T) {
registrator := setup(t)
info := &provision.OsRelease{
Name: "Red Hat Enterprise Linux Server",
ID: "rhel",
VersionID: "7.3",
}
if !registrator.CompatibleWithDistribution(info) {
t.Fatal("Registration capability should be in the Distribution")
}
}
func TestRedHatRegistratorNotCompatibleWithDistribution(t *testing.T) {
registrator := setup(t)
info := &provision.OsRelease{
Name: "CentOS",
ID: "centos",
VersionID: "7.3",
}
if registrator.CompatibleWithDistribution(info) {
t.Fatal("Registration capability shouldn't be in the Distribution")
}
}
func TestRedHatRegistratorRegister(t *testing.T) {
s, _ := tests.NewSSHServer()
s.CommandToOutput = make(map[string]string)
port, err := s.Start()
if err != nil {
t.Fatalf("Error starting ssh server: %s", err)
}
d := &tests.MockDriver{
Port: port,
BaseDriver: drivers.BaseDriver{
IPAddress: "127.0.0.1",
SSHKeyPath: "",
},
}
commander := provision.GenericSSHCommander{Driver: d}
registrator := NewRedHatRegistrator(commander)
s.CommandToOutput["sudo -E subscription-manager version"] = `server type: This system is currently not registered.`
if err := registrator.Register(param); err != nil {
t.Fatal("Distribution should able to register")
} else {
if _, ok := s.Commands[expectedCMDRegistration]; !ok {
t.Fatalf("Expected command: %s", expectedCMDRegistration)
}
}
}
func TestRedHatRegistratorUnregister(t *testing.T) {
s, _ := tests.NewSSHServer()
s.CommandToOutput = make(map[string]string)
port, err := s.Start()
if err != nil {
t.Fatalf("Error starting ssh server: %s", err)
}
d := &tests.MockDriver{
Port: port,
BaseDriver: drivers.BaseDriver{
IPAddress: "127.0.0.1",
SSHKeyPath: "",
},
}
commander := provision.GenericSSHCommander{Driver: d}
registrator := NewRedHatRegistrator(commander)
s.CommandToOutput["sudo -E subscription-manager version"] = `server type: RedHat Subscription Management`
if err := registrator.Unregister(param); err != nil {
t.Fatal("Distribution should be able to unregister")
} else {
if _, ok := s.Commands[expectedCMDUnregistration]; !ok {
t.Fatalf("Expected command: %s", expectedCMDUnregistration)
}
}
}
|
๏ปฟusing System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking.NetworkSystem;
using Julo.Logging;
using Julo.Network;
namespace Julo.TurnBased
{
public abstract class TurnBasedClient : GameClient
{
public static new TurnBasedClient instance = null;
ClientPlayers<TBPlayer> clientPlayers;
TBPlayer playingPlayer = null;
// only local
TurnBasedServer tbServer;
// local case
public override void OnStartLocalClient(GameServer server)
{
base.OnStartLocalClient(server);
instance = this;
this.tbServer = (TurnBasedServer)server;
if(mode == Mode.OfflineMode)
{
var players = new Dictionary<uint, TBPlayer>();
// TODO!!!
foreach(var p in DualNetworkManager.instance.OfflinePlayers())
{
var pp = (OfflinePlayer)p;
var tbp = pp.GetComponent<TBPlayer>();
players.Add(p.GetId(), tbp);
}
clientPlayers = new FixedClientPlayers<TBPlayer>(players);
}
else
{
clientPlayers = new CacheClientPlayers<TBPlayer>();
}
}
// remote case
public override void OnStartRemoteClient(StartGameMessage initialMessages)
{
base.OnStartRemoteClient(initialMessages);
instance = this;
clientPlayers = new CacheClientPlayers<TBPlayer>();
}
void IsMyTurn(TBPlayer player)
{
if(playingPlayer != null)
{
Log.Error("A player is already playing here!");
return;
}
playingPlayer = player;
playingPlayer.SetPlaying(true);
if(player.IsLocal())
StartCoroutine(PlayTurn());
}
// only in client that owns the current player
IEnumerator PlayTurn()
{
OnStartTurn(playingPlayer);
do
{
yield return new WaitForEndOfFrame();
} while(TurnIsOn());
OnEndTurn(playingPlayer);
SendToServer(Julo.TurnBased.MsgType.EndTurn, new EmptyMessage());
}
////// Message handlers
void OnStartTurnMessage(TurnMessage turnMsg)
{
var netId = turnMsg.playerNetId;
var player = clientPlayers.GetPlayerByNetId(netId);
IsMyTurn(player);
}
void OnEndTurnMessage()
{
if(playingPlayer == null)
{
Log.Warn("Already cleaned up");
return;
}
playingPlayer.SetPlaying(false);
playingPlayer = null;
}
public override void OnMessage(WrappedMessage message)
{
short msgType = message.messageType;
if(msgType == Julo.TurnBased.MsgType.StartTurn)
{
var turnMsg = message.ReadExtraMessage<TurnMessage>();
OnStartTurnMessage(turnMsg);
}
else if(msgType == Julo.TurnBased.MsgType.EndTurn)
{
OnEndTurnMessage();
}
else
{
base.OnMessage(message);
}
}
protected abstract void OnStartTurn(TBPlayer player);
protected abstract bool TurnIsOn();
protected abstract void OnEndTurn(TBPlayer player);
} // class TurnBasedClient
} // namespace Julo.TurnBased
|
alter table ref_hm_pcode_objecttype
add
constraint ref_hm_pcode_objecttype_fk1
foreign key (hm_pcode)
references ref_hm_pcode(hm_pcode);
alter table ref_hm_pcode_objecttype
add
constraint ref_hm_pcode_objecttype_fk2
foreign key (objecttype_id)
references hdb_objecttype(objecttype_id);
|
@extends('themes.admin-theme')
@section('content')
<div class="row">
<div class="col-md-12">
<div class="card">
<div class="card-header card-header-primary card-header-icon">
<div class="card-icon">
<i class="material-icons">person</i>
</div>
<h4 class="card-title">Data User</h4>
</div>
<hr>
<div class="card-body">
<div class="toolbar">
<button class="btn btn-info" onclick="show();">Tambah Data Baru</button>
</div>
<hr>
<div class="material-datatables">
@include('user.table.tbl-user')
</div>
</div>
<!-- end content-->
</div>
<!-- end card -->
</div>
<!-- end col-md-12 -->
</div>
@endsection
@section('modal')
@include('user.modal.modal-user')
@stop
@section('js')
@include('user.js.js-user')
@stop
|
import java.util.*;
public class ParrotSalute {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.print("How big is your group?: ");
int groupSize = keyboard.nextInt();
while (groupSize <= 0 || groupSize >= 11){
System.out.print("Hmm that doesn't seem right. How big is your group: ");
groupSize = keyboard.nextInt();
}
String salute = "";
for(int i = 0; i < groupSize; i++){
salute = salute + "Hi";
if (i < (groupSize-1)){
salute = salute + "-";
}
}
System.out.println(salute);
keyboard.close();
}
}
|
import React, { useState } from 'react';
import { SurveyTemplate, AgeBox } from '@/components/domain/survey';
import { Title } from '@/lib/styles/styledComponents';
import styled from 'styled-components';
import { MIN_AGE, MAX_AGE } from '@/components/domain/survey/AgeBox';
import ChooseTwoBox from '@/components/domain/survey/ChooseTwoBox';
import { useMeetingNavigate } from '@/hooks/common/useMeetingNavigate';
import Path from '@/router/Path';
import { useNavigate } from 'react-router-dom';
import { GENDER_ITEMS } from '@/types/constants/constant';
export type GenderOptions = 'FEMAIL' | 'MALE';
const GenderAverageAgeSurvey = () => {
const navigate = useNavigate();
const meetingNavigate = useMeetingNavigate();
const [genderOption, setGenderOption] = useState<GenderOptions>('FEMAIL');
const [ageOption, setAgeOption] = useState(Math.floor((MIN_AGE + MAX_AGE) / 2));
const onChangeOption = (e: React.ChangeEvent<HTMLInputElement>) => {
const { id } = e.target;
setGenderOption(id as GenderOptions);
};
return (
<SurveyTemplate
disableNext={!ageOption && !genderOption}
currStep={2}
totalStep={14}
handlePrevClick={() => navigate(Path.TypeOfMeetingSurvey)}
handleNextClick={() => meetingNavigate(Path.OurUniversitiesSurvey)}
>
<StyledTitle>
<strong>2:2 ๋ฏธํ
</strong>์ ์ ํํ์
จ์ด์.
<br />
๋ช๊ฐ์ง ์ง๋ฌธ๋ง ๋๋ตํ์๋ฉด
<br />
๋ฐ๋ก ๋งค์นญํด๋๋ฆด๊ฒ์!
</StyledTitle>
<ChooseTwoBox items={GENDER_ITEMS} selectedOption={genderOption} onChangeOption={onChangeOption}>
์ฑ๋ณ์ ์ ํํด์ฃผ์ธ์.
</ChooseTwoBox>
<AgeBox setAgeOption={setAgeOption}>์ฐธ์ฌ์์ ํ๊ท ๋์ด๋ฅผ ์๋ ค์ฃผ์ธ์.</AgeBox>
</SurveyTemplate>
);
};
const StyledTitle = styled(Title)`
font-weight: 400;
`;
export default GenderAverageAgeSurvey;
|
package io.burkard.cdk.services.codepipeline
@SuppressWarnings(Array("org.wartremover.warts.DefaultArguments", "org.wartremover.warts.Null", "DisableSyntax.null"))
object AlexaSkillDeployAction {
def apply(
clientId: String,
skillId: String,
input: software.amazon.awscdk.services.codepipeline.Artifact,
refreshToken: software.amazon.awscdk.SecretValue,
clientSecret: software.amazon.awscdk.SecretValue,
parameterOverridesArtifact: Option[software.amazon.awscdk.services.codepipeline.Artifact] = None,
variablesNamespace: Option[String] = None,
runOrder: Option[Number] = None,
actionName: Option[String] = None
): software.amazon.awscdk.services.codepipeline.actions.AlexaSkillDeployAction =
software.amazon.awscdk.services.codepipeline.actions.AlexaSkillDeployAction.Builder
.create()
.clientId(clientId)
.skillId(skillId)
.input(input)
.refreshToken(refreshToken)
.clientSecret(clientSecret)
.parameterOverridesArtifact(parameterOverridesArtifact.orNull)
.variablesNamespace(variablesNamespace.orNull)
.runOrder(runOrder.orNull)
.actionName(actionName.orNull)
.build()
}
|
# frozen_string_literal: true
module Renderer
# Read a file and render the markdown
class MarkdownFileRenderer
include Util::Logging
include Parser::FrontmatterMetadataFinder
attr_reader :path, :image_provider, :vtt_file
def initialize(path:, image_provider: nil, vtt_file: nil)
@path = path
@image_provider = image_provider
@vtt_file = vtt_file
end
def render
logger.debug 'MarkdownFileRenderer::render'
remove_h1(doc)
apply_vtt_timestamps(doc)
fix_team_bio_markup(rw_renderer.render(doc))
end
def rw_renderer
@rw_renderer ||= Renderer::RWMarkdownRenderer.new(
options: %i[TABLE_PREFER_STYLE_ATTRIBUTES],
extensions: %i[table strikethrough autolink],
image_provider: image_provider,
root_path: root_directory
)
end
def raw_content
@raw_content ||= File.read(path)
end
def preproccessed_markdown
@preproccessed_markdown ||= begin
removing_pagesetting_notation = raw_content.gsub(/\$\[=[=sp]=\]/, '')
without_metadata(removing_pagesetting_notation.each_line)
end
end
def doc
@doc ||= CommonMarker.render_doc(
preproccessed_markdown,
%i[SMART STRIKETHROUGH_DOUBLE_TILDE],
%i[table strikethrough autolink]
)
end
def remove_h1(document)
document.walk do |node|
node.delete if node.type == :header && node.header_level.to_i == 1
end
document
end
def apply_vtt_timestamps(document)
return unless vtt_file.present?
timestamper = MarkdownTimestamper.new(document, vtt_file)
timestamper.apply!
end
def fix_team_bio_markup(html)
# It'd be nice to do this pre-render, but that involves allowing unsafe rendering of HTML
html.gsub(/<p>\$\[#tb\]<\/p>/, '<div>').gsub(/<p>\$\[tb#\]<\/p>/, '</div>')
end
def root_directory
@root_directory ||= Pathname.new(path).dirname
end
end
end
|
// ignore_for_file: unused_local_variable
import 'dart:convert';
import 'package:amatrider/features/home/data/data.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:logger/logger.dart';
import '../fixtures/fixture_reader.dart';
void main() {
test(
'test that `BankAccountDTO` model can parse json list response',
() async {
var result = jsonDecode(fixture('bank_account/bank_account.json'));
final _res = GenericObjectDTO.fromJson(
result as Map<String, dynamic>,
(json) => BankAccountDTO.fromJson(json as Map<String, dynamic>),
);
final domain = _res.domain((e) => e?.domain);
Logger().i(domain?.accountName);
Logger().w(domain);
},
);
}
|
# Developer notes
## Storybook deployment
Run `yarn build-storybook` to build the static storybook in the `docs/` directory and then commit + push to GitHub.
## Publish package
Run `npx np` and follow the interactive prompts to publish a new version.
|
<?php
/**
* Created by PhpStorm.
* User: engineer
* Date: 1/9/19
* Time: 11:48 PM
*/
class User_Authentication_model extends CI_Model
{
public function fetch()
{
$this->db->order_by('ID', 'DESC');
$this->db->where('STATUS', TRUE);
return $this->db->get('USERS');
}
function fetch_single_row_data_to_edit($row)
{
$this->db->where('ID', $row);
$data = $this->db->get('USERS');
return $data;
}
}
?>
|
import { ERROR, LOADED, LOADING } from "../api/status";
import React, { PureComponent } from "react";
import ContactMap from "./ContactMap";
import NoMatch from "./NoMatch";
import PropTypes from "prop-types";
class Detail extends PureComponent {
constructor(props) {
super(props);
}
render() {
const { status, contact } = this.props;
let view;
if (status === LOADING) {
view = <p>Loadingโฆ</p>;
} else if (status === ERROR) {
view = <p>Error</p>;
} else if (status === LOADED && contact) {
view = (
<div className="contact">
<h3 className="contact__name">{contact.name}</h3>
<ContactMap contact={contact} />
<p className="contact__field contact__field--phone">
<a className="contact__link" href={`tel:${contact.phone_number}`}>
{contact.phone_number}
</a>
</p>
<p className="contact__field contact__field--address">
{contact.address}
</p>
</div>
);
} else {
view = <NoMatch />;
}
return view;
}
}
Detail.propTypes = {
contact: PropTypes.shape({
name: PropTypes.string.isRequired,
phone_number: PropTypes.string.isRequired,
address: PropTypes.string.isRequired
})
};
export default Detail;
|
---
layout: post
title: "Vue.js Router , Axios"
date: 2022-04-08 13:51
image: '/assets/img/'
description: 'Vue.js'
tags:
- Vue.js
categories:
- Vue.js
twitter_text: ''
comments: true
---
ํ๋ก์ ํธ ๋ฐ ์ด์ฌ์ค๋น ๋๋ฌธ์ ๋ธ๋ก๊ทธ ๊ด๋ฆฌ์ ์ํํ๋ค..
์์ง ์๋ฒฝํ๊ฒ ํด๊ฒฐ๋๊ฑด ์๋์ง๋ง ์ด๋์ ๋ ์ฌ์ ๊ฐ ์๊ฒผ๊ธฐ์ ๋ค์ ๋ธ๋ก๊ทธ๋ฅผ ์์ฑํ๋ ค๊ณ ํ๋ค.
Vue.js ์์ ๊ฐ์ฅ ํต์ฌ(?) ์ด๋ผ๊ณ ํ ์ ์๋ Router , Axios ์ ๋ํด ์์๋ณด์.
### Router ###
SPA(Single Page Application) ์์ ๊ฐ์ฅ ๋จผ์ ์ฒ๋ฆฌํ๋ ๊ฒ์ผ๋ก, __๋ฏธ๋ฆฌ ํด๋น ํ์ด์ง๋ฅผ ๋ฐ์๋๊ณ ํ์ด์ง ์ด๋์ ํ๋ฉด์ ๊ฐฑ์ ํด์ฃผ๋ ์ญํ __ ์ ํ๋ค.
์ด๋ ๊ฒ ํ ์, ํ๋ฉด์ ํ์ด ๋งค๋๋ฝ๊ฒ ์งํ๋์ด ์ฌ์ฉ์๊ฐ ์ฌ์ฉํ๋ ์
์ฅ์์๋ ๋งค์ฐ ํธํ๋ค.
### ์ฌ์ฉ๋ฐฉ๋ฒ ###
Vue.js ์์๋ VueRouter ๋ผ๋ ๊ณต์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ง์ํ๋ค.
{% highlight javascript %}
<router-link to = "URL"> -- ํ์ด์ง ์ด๋ Tag
<router-view> -- ํ์ด์ง ํ์ Tag
{% endhighlight %}
๋ค์์ Router ์ ๋ํ ์์์ด๋ค.
{% highlight javascript %}
routes:[
{path: '/TEST', compoment : TestComponent},
{path: '/1234', component : NumberComponent}
]
{% endhighlight %}
### Axios ###
Axios ๋ __Vues.js ์์ HTTP ํต์ ๋ผ์ด๋ธ๋ฌ๋ฆฌ__ ๋ฅผ ๋งํ๋ค. ์ด์ ์๋ vue resource ๋ผ๋ ๋ผ์ด๋ธ๋ฌ๋ผ๋ฅผ ์ฌ์ฉํ์ผ๋,
ํ์ฌ๋ ์ฌ์ฉํ์ง ์๊ณ Axios ๋ฅผ ๊ถ๊ณ ํ๊ณ ์๋ค๊ณ ํ๋ค.
Axios์ ๊ธฐ๋ฅ์ผ๋ก๋ XMLHttpRequests ์์ฑ , Intercept, ๋ฐ์ดํฐ๋ณํ , json ๋ฐ์ดํฐ ๋ณํ๋ฑ์ด ์๋ค.
ํต์ ๋ฐฉ๋ฒ์ผ๋ก๋ GET,POST PATCH , DELETE ๊ฐ ์๋ค.
{% highlight javascript %}
axios.get()
axios.post()
axios.patch()
axios.delete()
{% endhighlight %}
### Async ๋ฌธ๋ฒ ###
async ๋ฌธ๋ฒ์ ์ฌ์ฉํด ๋น๋๊ธฐ ํต์ ์์ฒญ์ ์ฒ๋ฆฌํ๋ฉฐ try..catch๋ฅผ ์ฌ์ฉํด ์ค๋ฅ ๋๋ฒ๊น
๋ ๊ฐ๋ฅํ๋ค.
ํ์ง๋ง , ES8์ ์ถ๊ฐ๋ ๋ฌธ๋ฒ์ด๋ผ ์ค๋๋ ๋ธ๋ผ์ฐ์ ๋ ์ง์ํ์ง ์๋๋ค.
|
{-# LANGUAGE OverloadedStrings #-}
module Network.SCP.Types where
import Control.Applicative ((<|>))
import Data.Attoparsec.ByteString (anyWord8)
import Data.Attoparsec.ByteString.Char8
import Data.ByteString (ByteString)
import qualified Data.ByteString as B
import qualified Data.ByteString.Char8 as C
import Prelude hiding (takeWhile)
import Data.Word (Word8)
data Command =
Copy Word8 Word8 Word8 Word8 Int ByteString
-- ^ Copy a file. Permissions (4 bytes), file size in bytes, filename.
| Push Word8 Word8 Word8 Word8 ByteString
-- ^ Enter directory. Permissions, directory name.
| Pop
-- ^ Exit directory.
| Abort ByteString
-- ^ This is not really a command, it is an error message received from the
-- client. For instance when the client sends a non-existing file and
-- discovers the fact only after having started the upload process.
deriving Show
-- e.g. C0755 567 run.sh
commandParser :: Parser Command
commandParser = copyParser <|> pushParser <|> popParser <|> errorParser
copyParser :: Parser Command
copyParser = do
_ <- char 'C'
(a, b, c, d) <- permissionsParser
_ <- char ' '
size <- decimal
_ <- char ' '
filename <- takeWhile (/= '\n')
-- I think a dot '.' is valid when scp -t is used with a target filename.
if '/' `C.elem` filename
then fail "Invalid filename"
else do
_ <- char '\n'
return $ Copy a b c d size filename
pushParser :: Parser Command
pushParser = do
_ <- char 'D'
(a, b, c, d) <- permissionsParser
_ <- string " 0 "
dir <- takeWhile (/= '\n')
_ <- char '\n'
return $ Push a b c d dir
popParser :: Parser Command
popParser = Pop <$ string "E\n"
errorParser :: Parser Command
errorParser = do
_ <- anyWord8
msg <- takeWhile (/= '\n')
_ <- char '\n'
return $ Abort msg
permissionsParser :: Parser (Word8, Word8, Word8, Word8)
permissionsParser = do
a <- read . (:[]) <$> digit
b <- read . (:[]) <$> digit
c <- read . (:[]) <$> digit
d <- read . (:[]) <$> digit
return (a, b, c, d)
-- TODO use cereal
unparse :: Command -> ByteString
unparse command = case command of
(Copy a b c d size filename) ->
C.pack ['C', head $ show a, head $ show b, head $ show c, head $ show d]
`B.append` " " `B.append` C.pack (show size) `B.append` " "
`B.append` filename
(Push a b c d filename) ->
C.pack ['D', head $ show a, head $ show b, head $ show c, head $ show d]
`B.append` " 0 " `B.append` filename
Pop -> "E"
Abort msg -> 1 `B.cons` msg `B.append` "\n"
|
<?php declare(strict_types=1);
namespace JTL\Filter\Pagination;
/**
* Class ItemFactory
* @package JTL\Filter\Pagination
*/
class ItemFactory
{
/**
* @return Item
*/
public function create(): Item
{
return new Item();
}
}
|
<?php
namespace App\Http\Controllers\Backend;
use App\Models\Menu;
use App\Repository\CommentRepository;
use App\Repository\MemberRepository;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use GrahamCampbell\Markdown\Facades\Markdown;
class HomeController extends CommonController
{
protected $commentRepository;
protected $memberRepository;
function __construct(CommentRepository $commentRepository,MemberRepository $memberRepository)
{
parent::__construct();
$this->commentRepository=$commentRepository;
$this->memberRepository=$memberRepository;
}
public function index()
{
//่ทๅๆๆฐ่ฏ่ฎบ
$comments=$this->commentRepository->scopeQuery(function ($query){
return $query->where('state',1)->orderBy('created_at','desc')->limit(10);
})->get();
//่ทๅๆๆฐๆณจๅ็จๆท
$members=$this->memberRepository->scopeQuery(function ($query){
return $query->where('state',1)->orderBy('created_at','desc')->limit(5);
})->get();
return view('backend.home.index',compact('comments','members'));
}
//ๆธ
้ค็ผๅญ
public function clearCache(){
if (\Cache::clear()){
alert()->success('็ผๅญๆธ
้คๆๅ๏ผ');
}else{
alert()->error('็ผๅญๆธ
้คๅคฑ่ดฅ๏ผ');
}
return redirect()->route('login');
}
}
|
/*
Agregamos la instruccion strict para acceder
a las nuevas funciones de javascript:
*/
'use strict'
/*
Conexion a la base de datos:
1. Creamos un objeto con los
parametros de la libreria mongoose:
*/
var mongoose = require('mongoose');
/*
Agregamos app.js y el puerto de escucha:
*/
var app = require('./app');
var port = 3800;
/*
Conexion a la base de datos:
2.Para conectarnos a mongo debemos utilizar
un metodo de promesas:
*/
mongoose.Promise = global.Promise;
/*
Conexion a la base de datos:
3. Conectamos con el servidor:
*/
mongoose.connect('mongodb://localhost:27017/riskpsico')
.then(() => {
console.log("Bienvenido, la conexion a la base de datos ha sido establecida");
//Creaciรณn del servidor:
app.listen(port,() => {
console.log("Servidor corriendo en: http://localhost:3800");
})
})
.catch(err =>console.log(err));
|
package org.cocos2d.actions.ease;
import org.cocos2d.actions.interval.CCIntervalAction;
public class CCEaseSineIn extends CCEaseAction {
public static CCEaseSineIn action(CCIntervalAction action) {
return new CCEaseSineIn(action);
}
protected CCEaseSineIn(CCIntervalAction action) {
super(action);
}
@Override
public CCEaseSineIn copy() {
return new CCEaseSineIn(other.copy());
}
@Override
public void update(float t) {
other.update(-1 * (float)Math.cos(t * (float) Math.PI / 2) + 1);
}
@Override
public CCIntervalAction reverse() {
return new CCEaseSineOut(other.reverse());
}
}
|
import React, { useEffect, useState, SetStateAction, Dispatch } from "react";
import { PasswordGenerator } from "./PasswordGenerator";
export const Password = () => {
const [password, setPassword] = useState("");
const [useNumber, setUseNumber] = useState(false);
const [useSign, setUseSign] = useState(false);
useEffect(() => {
refreshPassword(setPassword, useNumber, useSign);
}, [useNumber, useSign]);
return (
<div>
<h2>{password}</h2>
<label>
<input type="checkbox" onClick={() => setUseNumber(!useNumber)} />
Use Number
</label>
<label>
<input type="checkbox" onClick={() => setUseSign(!useSign)} />
Use Sign
</label>
<div>
<button
onClick={() => refreshPassword(setPassword, useNumber, useSign)}
>
Refresh
</button>
</div>
</div>
);
};
const refreshPassword = (
setPassword: Dispatch<SetStateAction<string>>,
useNumber: boolean,
useSign: boolean
) => {
const g = new PasswordGenerator(useNumber, useSign);
setPassword(g.generate());
};
|
import { Action, ActionReducerMap, combineReducers, createFeatureSelector } from '@ngrx/store';
import * as fromLibrarians from './librarian.reducer';
import * as fromPagination from './pagination/librarians-pagination.reducer';
export interface LibrariansModuleState {
librarians: fromLibrarians.LibrariansState,
pagination: fromPagination.LibrariansPaginationState
};
const reducerMap: ActionReducerMap<LibrariansModuleState> = {
librarians: fromLibrarians.librariansReducer,
pagination: fromPagination.librariansPaginationReducer
};
const reducer = combineReducers(reducerMap);
export function librarianModuleReducer(state: LibrariansModuleState, action: Action) {
return reducer(state, action);
}
export const librariansModuleState = createFeatureSelector('librarians');
|
import * as express from "express";
import controller from "./controller";
export default express
.Router()
.post("/login", controller.login)
.post("/register", controller.register)
.get("/refreshtoken", controller.refreshToken)
.get(
"/msal",
process.env.MSAL_ACTIVE === "true"
? controller.msal
: controller.notImplemented
)
.get(
"/msal-redirect",
process.env.MSAL_ACTIVE === "true"
? controller.msalRedirect
: controller.notImplemented
);
|
/**
* Management of the release downloads.
* @module releases
*/
const ReleaseManager = require('./ReleaseManager');
module.exports = {
ReleaseManager: ReleaseManager
}
|
import logging
from . import AbstractTranslationProvider
from google.cloud import translate
logger = logging.getLogger(__name__)
class GoogleTranslate(AbstractTranslationProvider):
def translate(self, strings, target_language, source_language="en"):
client = translate.Client()
response = client.translate(
strings, source_language=source_language, target_language=target_language
)
return list(map(lambda x: x["translatedText"], response))
|
test = """
F10
N3
F7
R90
F11
"""
function parse_program(prog::AbstractString)::Vector
return split(prog, "\n"; keepempty = false) .|> Instruction
end
struct Instruction{code}
v::Int
Instruction(cmd::AbstractString) = new{cmd[1]}(parse(Int, cmd[2:end]))
end
Base.show(io::IO, i::Instruction{code}) where code = print(io, "$(code)$(i.v)")
const E = [ 1, 0]
const N = [ 0, -1]
const W = [-1, 0]
const S = [ 0, 1]
struct State{mode}
pos
target
end
State{:ship}() = State{:ship}([0, 0], E)
State{:wp }() = State{:wp }([0, 0], 10E + N)
function run(program::AbstractVector; mode::Symbol)::Int
state = foldl(|>, program; init = State{mode}())
return state.pos .|> abs |> sum
end
(i::Instruction{'N'})(state::State) = move(state, N .* i.v)
(i::Instruction{'S'})(state::State) = move(state, S .* i.v)
(i::Instruction{'E'})(state::State) = move(state, E .* i.v)
(i::Instruction{'W'})(state::State) = move(state, W .* i.v)
(i::Instruction{'F'})(state::State) = forward(state, state.target .* i.v)
(i::Instruction{'L'})(state::State) = turn(state, i.v)
(i::Instruction{'R'})(state::State) = turn(state, -i.v)
move(state::State{:ship}, m) = forward(state, m)
move(state::State{:wp}, m) = State{:wp}(state.pos, state.target + m)
forward(state::S, m) where {S <: State} = S(state.pos + m, state.target)
turn(state::S, d) where {S <: State} = S(state.pos, rotate(state.target, d))
rotate(v, d::Number) = round.(Int, [cosd(d) sind(d); -sind(d) cosd(d)] * v)
q1(program::AbstractVector)::Int = run(program; mode = :ship)
q2(program::AbstractVector)::Int = run(program; mode = :wp)
let program = parse_program(test)
@assert q1(program) == 25
@assert q2(program) == 286
end
program = parse_program(read("day12.in", String))
println("Q1: ", q1(program))
println("Q2: ", q2(program))
|
namespace Machete.X12Schema.V5010
{
using X12;
public interface MOA :
X12Segment
{
Value<decimal> ReimbursementRate { get; }
Value<decimal> HCPCSPayableAmount { get; }
Value<string> ClaimPaymentRemarkCode1 { get; }
Value<string> ClaimPaymentRemarkCode2 { get; }
Value<string> ClaimPaymentRemarkCode3 { get; }
Value<string> ClaimPaymentRemarkCode4 { get; }
Value<string> ClaimPaymentRemarkCode5 { get; }
Value<decimal> EndStageRenalDisaesePaymentAmount { get; }
Value<decimal> NonPayableProfessionalComponentBilledAmount { get; }
}
}
|
import type { Client, CommandInteraction, ContextMenuInteraction } from 'discord.js';
import type { ChooksConfig } from './config';
import type { ChooksLogger } from '@chookscord/logger';
import type { FetchUtil } from '@chookscord/fetch';
export type ChooksDep = Record<string, unknown>;
export type EmptyDep = Record<string, never>;
/**
* The base context object that all contexts will inherit from.
*/
export interface ChooksContext {
client: Client<true>;
logger: ChooksLogger;
fetch: FetchUtil;
}
/**
* The context object passed to event listeners.
*/
export interface ChooksEventContext extends ChooksContext {
config: ChooksConfig;
}
/**
* The context object passed to slash commands.
*/
export interface ChooksCommandContext extends ChooksContext {
interaction: CommandInteraction;
}
/**
* The context object passed to context menu commands.
*/
export interface ChooksContextCommandContext extends ChooksContext {
interaction: ContextMenuInteraction;
}
|
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'managedmac', 'common'))
Puppet::Type.newtype(:macgroup) do
@doc = %q(A drop-in replacement for the built-in Puppet Type: Group
A custom Puppet type for configuring and managing OS X groups.
Similar to the built-in Puppet type, Macgroup can manage user membership and
other attributes of DSLocal group records.
However, unlike the built-in Puppet type, it also supports management of
nestedgroups records, aka "Groups-in-Group".
==== USAGE ====
macgroup { 'foo':
ensure => present,
realname => 'FooGroup',
comment => 'Installed by Puppet',
users => ['foo', 'bar', 'baz'],
nestedgroups => ["ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050", 'group_two'],
strict => true,
}
)
ensurable
newparam(:name) do
desc 'The resource name.
Corresponds to the RecordName/name attribute.
'
isnamevar
# Override #insync?
# - We only compare the first element of the array
def insync?(is)
i, s = [is, should].each do |a|
Array(a).first
end
i.eql? s
end
end
newproperty(:gid) do
desc 'The numeric ID for the Group.
Corresponds to the PrimaryGroupID/gid attribute.
If you create a new group and do not specify a GID, one will be selected
for you. However, this is not recommended as it cannot guarantee GID
specification across a collection of machines. For example, if the same
resource were applied to two different machines, the GID could not be
guaranteed to be the same on both, unless you were to configure this
parameter.
By the same token, if you do specify a GID parameter, you must ensure
that the GID will not collide with existing groups on the machine --
especially built-ins.
Default is :absent.
'
newvalues(%r{^\d+$})
def insync?(is)
i, s = [is, should].map do |a|
Array(a.to_i).first
end
i == s
end
# Normalize the :gid
munge do |value|
value.to_i
end
end
newproperty(:users, array_matching: :all) do
desc "The list of users you want added to the group.
Corresponds to the GroupMembership/users attribute.
Membership is managed wholesale, that is, it's purged prior to
modification unless you set strict => false.
Please see the documentation on :strict _before_ using this feature.
To specify users, you pass an Array of user names. The provider will warn
about an invalid user account, but it will apply the configuration
anyway. This is to prevent temporary OpenDirectory or network outages
from wreaking havoc with your Puppet config.
Note: an empty list is not the same as an absent one. An absent list
implies that the attribute is unmanaged, while an empty list _is_ managed
and will create and empty list... Use caution.
Default is :absent (no management)
"
# Validate a user account parameter
def validate_user(name)
result = ::ManagedMacCommon.dscl_find_by(:users, 'name', name)
unless result.respond_to? :first
raise Puppet::Error,
"An unknown error occured while searching: #{result}"
end
if result.empty?
Puppet::Util::Warnings.warnonce(
"Macgroup: User not found: \'#{name}\'",
)
end
name
end
# Override #insync?
# - We need to sort the Arrays before performing an equality test.
# - We also need to obey the :strict param and compare the Arrays appropriately
def insync?(is)
i, s = [is, should].map do |a|
if a == :absent
[]
else
a = Array(a)
a.compact!
a.sort!
end
end
return i.eql? s if resource[:strict] == :true
(i | s).eql? i
end
# Normalize the should parameter
munge do |value|
validate_user(value)
end
end
newproperty(:nestedgroups, array_matching: :all) do
desc %q{A list of groups you want nested inside the group.
Corresponds to the NestedGroups/nestedgroups attribute.
Note: this attribute lists membership according the record's GeneratedUID,
not the record's' name like the user list.
Membership is managed wholesale, that is, it's purged prior to
modification unless you set strict => false.
Please see the documentation on :strict _before_ using this feature.
To specify nested groups, you pass an Array of:
a) Group Names (ie. "admin", "staff", etc.)
b) GeneratedUIDs (ie. "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050", etc.)
c) A mix of both (ie. "ABCDEFAB-CDEF-ABCD-EFAB-CDEF00000050", "staff")
When you provide a list of group names, the Macgroup type will attempt to
resolve the record to its associated GeneratedUID. This is IMPORTANT to
keep in mind when referring to external node records (ie. LDAP or AD). If
it cannot resolve the record name to GeneratedUID, the Magroup type will
generate a warning and _skip_ configuration of the unresolvable record.
Like the user membership control, this "warn and continue" style of
resource management is sub-optimal, but provides greater resilience
during temporary outages.
For this reason, it is recommended that you list nestegroups according to
their respective GeneratedUIDs and NOT the record names as this will
provide the greatest stability (and less log noise).
Note: an empty list is not the same as an absent one. An absent list
implies that the attribute is unmanaged, while an empty list _is_ managed
and will create and empty list... Use caution.
Default is :absent (no management)
}
# Resolve a group name to uuid in OpenDirectory
# - given a valid name value, return the GeneratedUID for the group
def group_to_uuid(name)
result = ::ManagedMacCommon.dscl_find_by(:groups, 'name', name)
unless result.respond_to? :first
raise Puppet::Error,
"An unknown error occured while searching: #{result}"
end
if result.empty?
Puppet::Util::Warnings.warnonce(
"Macgroup: Group not found: \'#{name}\'",
)
return nil
end
cmd_args = [::ManagedMacCommon::DSCL, ::ManagedMacCommon::SEARCH_NODE,
'read', "/Groups/\'#{name}\'", 'GeneratedUID']
`#{cmd_args.join(' ')}`.chomp.split.last.strip
end
# Validate a Group's GeneratedUUID in OpenDirectory
# - given a valid uuid, find the corresponding record
# - generates a warning if the uuid cannot be resovled
# - always returns the GeneratedUID (input)
def uuid_to_group(uuid)
result = ::ManagedMacCommon.dscl_find_by(:groups, 'GeneratedUID', uuid)
unless result.respond_to? :first
raise Puppet::Error,
"An unknown error occurred while searching: #{result}"
end
if result.empty?
Puppet::Util::Warnings.warnonce(
"Macgroup: Group not found: \'#{uuid}\'",
)
end
uuid
end
# Override #insync?
# - We need to sort the Arrays before performing an equality test.
# - We also need to obey the :strict param and compare the Arrays appropriately
def insync?(is)
i, s = [is, should].map do |a|
if a == :absent
[]
else
a = Array(a)
a.compact!
a.sort!
end
end
return i.eql? s if resource[:strict] == :true
(i | s).eql? i
end
# Normalize the should parameter
munge do |value|
guid = '\A[0-9A-Z]{8}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{4}-[0-9A-Z]{12}\z'
if value =~ %r{#{guid}}
uuid_to_group(value)
else
group_to_uuid(value)
end
end
end
newparam(:strict) do
desc "How to handle membership in the users and nestedgroups arrays.
A Boolean value that informs the provider whether to merge the
specified members into the record, or replace them outright.
This parameter controls the behavior of BOTH the users and nestedgroups
arrays.
By default, the users and nestedgroups arrays will be PURGED and replaced
by whatever you specify in the resource (ie. strict => true).
Still, this isn't always what you want. Sometimes, you simply want to
ensure that the users/groups you specify in the resource are members, and
ignore any other records in the list(s).
To accomplish this, you can set the strict parameter to false.
Default is :true (purge)
"
newvalues(:true, :false)
defaultto :true
end
newproperty(:realname) do
desc "Optional string value that declares the group's RealName.
Corresponds to the RealName/realname attribute.
Default is :absent.
"
def insync?(is)
i, s = [is, should].each do |a|
Array(a).first
end
i.eql? s
end
validate do |value|
unless value.is_a? String
raise ArgumentError, "Expected String, got #{value.class}"
end
end
end
newproperty(:comment) do
desc "String that describes the group's purpose.
Corresponds to the Comment/comment attribute.
Default is :absent.
"
def insync?(is)
i, s = [is, should].each do |a|
Array(a).first
end
i.eql? s
end
validate do |value|
unless value.is_a? String
raise ArgumentError, "Expected String, got #{value.class}"
end
end
end
end
|
import Joi from '@hapi/joi';
const route = {
options: {
validate: {
payload: Joi.object({}),
},
},
handler: async (request, h) => {
// work
},
};
export default route;
|
package _936_stamping_the_sequence
func movesToStamp(stamp string, target string) []int {
letters, toErase := []byte(target), len(target)
contains := func(offset int) bool {
empty := true
for i := 0; i < len(stamp); i++ {
if l := letters[offset+i]; l != '.' && l != stamp[i] {
return false
} else if l != '.' {
empty = false
}
}
return !empty
}
erase := func(offset int) {
for i := 0; i < len(stamp); i++ {
if letters[offset+i] != '.' {
letters[offset+i] = '.'
toErase--
}
}
}
var result []int
for toErase != 0 {
erased := false
for i := 0; i < len(letters)-len(stamp)+1; i++ {
if contains(i) {
erase(i)
result = append(result, i)
erased = true
i += len(stamp)
if toErase == 0 {
break
}
}
}
if !erased {
return []int{}
}
}
for l, r := 0, len(result)-1; l < r; l, r = l+1, r-1 {
result[l], result[r] = result[r], result[l]
}
return result
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.