text
stringlengths 1
1.05M
|
|---|
gcc ./client.c -o client -levent -lcrypto -lssl -ldl -lsqlite3 -ljansson -std=c99 `pkg-config --cflags --libs glib-2.0 gtk+-2.0 gnet-2.0` -Wall -Wextra -pedantic
|
package utils
import (
"context"
"log"
"firebase.google.com/go/v4/auth"
"github.com/Dev-Qwerty/zod-backend/project_service/api/config"
)
// GetUserDetails fetch user details from firebase
func GetUserDetails(uid string) (*auth.UserInfo, error) {
u, err := config.Client.GetUser(context.TODO(), uid)
if err != nil {
log.Println("GetUserDetails: ", err)
return nil, err
}
return u.UserInfo, nil
}
func GetUserDetailsByEmail(email string) (string, error) {
u, err := config.Client.GetUserByEmail(context.TODO(), email)
if err != nil {
log.Println("GetUserDetailsByEmail: ", err)
return "", err
}
return u.DisplayName, nil
}
|
<gh_stars>0
// Copyright (c) 2020 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package ipn
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/tailscale/wireguard-go/wgcfg"
"tailscale.com/atomicfile"
"tailscale.com/control/controlclient"
)
// Prefs are the user modifiable settings of the Tailscale node agent.
type Prefs struct {
// RouteAll specifies whether to accept subnet and default routes
// advertised by other nodes on the Tailscale network.
RouteAll bool
// AllowSingleHosts specifies whether to install routes for each
// node IP on the tailscale network, in addition to a route for
// the whole network.
//
// TODO(danderson): why do we have this? It dumps a lot of stuff
// into the routing table, and a single network route _should_ be
// all that we need. But when I turn this off in my tailscaled,
// packets stop flowing. What's up with that?
AllowSingleHosts bool
// CorpDNS specifies whether to install the Tailscale network's
// DNS configuration, if it exists.
CorpDNS bool
// WantRunning indicates whether networking should be active on
// this node.
WantRunning bool
// UsePacketFilter indicates whether to enforce centralized ACLs
// on this node. If false, all traffic in and out of this node is
// allowed.
UsePacketFilter bool
// AdvertiseRoutes specifies CIDR prefixes to advertise into the
// Tailscale network as reachable through the current node.
AdvertiseRoutes []wgcfg.CIDR
// NotepadURLs is a debugging setting that opens OAuth URLs in
// notepad.exe on Windows, rather than loading them in a browser.
//
// TODO(danderson): remove?
NotepadURLs bool
// The Persist field is named 'Config' in the file for backward
// compatibility with earlier versions.
// TODO(apenwarr): We should move this out of here, it's not a pref.
// We can maybe do that once we're sure which module should persist
// it (backend or frontend?)
Persist *controlclient.Persist `json:"Config"`
}
// IsEmpty reports whether p is nil or pointing to a Prefs zero value.
func (p *Prefs) IsEmpty() bool { return p == nil || p.Equals(&Prefs{}) }
func (p *Prefs) Pretty() string {
var pp string
if p.Persist != nil {
pp = p.Persist.Pretty()
} else {
pp = "Persist=nil"
}
return fmt.Sprintf("Prefs{ra=%v mesh=%v dns=%v want=%v notepad=%v pf=%v routes=%v %v}",
p.RouteAll, p.AllowSingleHosts, p.CorpDNS, p.WantRunning,
p.NotepadURLs, p.UsePacketFilter, p.AdvertiseRoutes, pp)
}
func (p *Prefs) ToBytes() []byte {
data, err := json.MarshalIndent(p, "", "\t")
if err != nil {
log.Fatalf("Prefs marshal: %v\n", err)
}
return data
}
func (p *Prefs) Equals(p2 *Prefs) bool {
if p == nil && p2 == nil {
return true
}
if p == nil || p2 == nil {
return false
}
return p != nil && p2 != nil &&
p.RouteAll == p2.RouteAll &&
p.AllowSingleHosts == p2.AllowSingleHosts &&
p.CorpDNS == p2.CorpDNS &&
p.WantRunning == p2.WantRunning &&
p.NotepadURLs == p2.NotepadURLs &&
p.UsePacketFilter == p2.UsePacketFilter &&
compareIPNets(p.AdvertiseRoutes, p2.AdvertiseRoutes) &&
p.Persist.Equals(p2.Persist)
}
func compareIPNets(a, b []wgcfg.CIDR) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !a[i].IP.Equal(&b[i].IP) || a[i].Mask != b[i].Mask {
return false
}
}
return true
}
func NewPrefs() Prefs {
return Prefs{
// Provide default values for options which are normally
// true, but might be missing from the json data for any
// reason. The json can still override them to false.
RouteAll: true,
AllowSingleHosts: true,
CorpDNS: true,
WantRunning: true,
UsePacketFilter: true,
}
}
func PrefsFromBytes(b []byte, enforceDefaults bool) (Prefs, error) {
p := NewPrefs()
if len(b) == 0 {
return p, nil
}
persist := &controlclient.Persist{}
err := json.Unmarshal(b, persist)
if err == nil && (persist.Provider != "" || persist.LoginName != "") {
// old-style relaynode config; import it
p.Persist = persist
} else {
err = json.Unmarshal(b, &p)
if err != nil {
log.Printf("Prefs parse: %v: %v\n", err, b)
}
}
if enforceDefaults {
p.RouteAll = true
p.AllowSingleHosts = true
}
return p, err
}
func (p *Prefs) Copy() *Prefs {
p2, err := PrefsFromBytes(p.ToBytes(), false)
if err != nil {
log.Fatalf("Prefs was uncopyable: %v\n", err)
}
return &p2
}
func LoadPrefs(filename string, enforceDefaults bool) *Prefs {
log.Printf("Loading prefs %v\n", filename)
data, err := ioutil.ReadFile(filename)
p := NewPrefs()
if err != nil {
log.Printf("Read: %v: %v\n", filename, err)
goto fail
}
p, err = PrefsFromBytes(data, enforceDefaults)
if err != nil {
log.Printf("Parse: %v: %v\n", filename, err)
goto fail
}
goto post
fail:
log.Printf("failed to load config. Generating a new one.\n")
p = NewPrefs()
p.WantRunning = true
post:
// Update: we changed our minds :)
// Versabank would like to persist the setting across reboots, for now,
// because they don't fully trust the system and want to be able to
// leave it turned off when not in use. Eventually we need to make
// all motivation for this go away.
if false {
// Usability note: we always want WantRunning = true on startup.
// That way, if someone accidentally disables their VPN and doesn't
// know how, rebooting will fix it.
// We still persist WantRunning just in case we change our minds on
// this topic.
p.WantRunning = true
}
log.Printf("Loaded prefs %v %v\n", filename, p.Pretty())
return &p
}
func SavePrefs(filename string, p *Prefs) {
log.Printf("Saving prefs %v %v\n", filename, p.Pretty())
data := p.ToBytes()
os.MkdirAll(filepath.Dir(filename), 0700)
if err := atomicfile.WriteFile(filename, data, 0666); err != nil {
log.Printf("SavePrefs: %v\n", err)
}
}
|
#!/bin/bash
if [[ $target_platform =~ linux.* ]] || [[ $target_platform == win-32 ]] || [[ $target_platform == win-64 ]] || [[ $target_platform == osx-64 ]]; then
export DISABLE_AUTOBREW=1
$R CMD INSTALL --build .
else
mkdir -p $PREFIX/lib/R/library/optimbase
mv * $PREFIX/lib/R/library/optimbase
if [[ $target_platform == osx-64 ]]; then
pushd $PREFIX
for libdir in lib/R/lib lib/R/modules lib/R/library lib/R/bin/exec sysroot/usr/lib; do
pushd $libdir || exit 1
for SHARED_LIB in $(find . -type f -iname "*.dylib" -or -iname "*.so" -or -iname "R"); do
echo "fixing SHARED_LIB $SHARED_LIB"
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5.0-MRO/Resources/lib/libR.dylib "$PREFIX"/lib/R/lib/libR.dylib $SHARED_LIB || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libR.dylib "$PREFIX"/lib/R/lib/libR.dylib $SHARED_LIB || true
install_name_tool -change /usr/local/clang4/lib/libomp.dylib "$PREFIX"/lib/libomp.dylib $SHARED_LIB || true
install_name_tool -change /usr/local/gfortran/lib/libgfortran.3.dylib "$PREFIX"/lib/libgfortran.3.dylib $SHARED_LIB || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libquadmath.0.dylib "$PREFIX"/lib/libquadmath.0.dylib $SHARED_LIB || true
install_name_tool -change /usr/local/gfortran/lib/libquadmath.0.dylib "$PREFIX"/lib/libquadmath.0.dylib $SHARED_LIB || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libgfortran.3.dylib "$PREFIX"/lib/libgfortran.3.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libgcc_s.1.dylib "$PREFIX"/lib/libgcc_s.1.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libiconv.2.dylib "$PREFIX"/sysroot/usr/lib/libiconv.2.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libncurses.5.4.dylib "$PREFIX"/sysroot/usr/lib/libncurses.5.4.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libicucore.A.dylib "$PREFIX"/sysroot/usr/lib/libicucore.A.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libexpat.1.dylib "$PREFIX"/lib/libexpat.1.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libcurl.4.dylib "$PREFIX"/lib/libcurl.4.dylib $SHARED_LIB || true
install_name_tool -change /usr/lib/libc++.1.dylib "$PREFIX"/lib/libc++.1.dylib $SHARED_LIB || true
install_name_tool -change /Library/Frameworks/R.framework/Versions/3.5/Resources/lib/libc++.1.dylib "$PREFIX"/lib/libc++.1.dylib $SHARED_LIB || true
done
popd
done
popd
fi
fi
|
/**
* Created by tvaisanen on 12/22/17.
*/
define(["configuration/classNames"],
function (classNames) {
"use strict";
/**
* Form for creating node post request
*
* @exports templateRenderer
*/
var renderedTemplate = document.createElement('div');
renderedTemplate.className = 'rendered-template';
function renderHeader(title){
var header = document.createElement('h1');
header.style.background = 'blue';
//header.style.padding = '0';
header.style.margin = '0';
header.innerHTML = title;
return header;
}
function renderMetas(metas){
var div = document.createElement('div');
var metasList = document.createElement('ul');
/*var metasLabel = document.createElement('label');
metasLabel.innerHTML = "metas:";
metas.forEach(function(meta){
var spanMeta = document.createElement('li');
spanMeta.innerHTML = meta;
metasList.appendChild(spanMeta);
});
div.appendChild(metasLabel);
div.appendChild(metasList);*/
div.innerHTML = "metas: " + metas.join(", ");
return div;
}
function renderTemplate(parameters){
var div = document.createElement('div');
var table = document.createElement('table');
Object.keys(parameters).forEach(function(key){
var tr = document.createElement('tr');
var tdKey = document.createElement('td');
tdKey.innerHTML = key;
var tdValue = document.createElement('td');
tdValue.innerHTML = parameters[key];
tr.appendChild(tdKey);
tr.appendChild(tdValue);
table.appendChild(tr);
});
div.appendChild(table);
return div;
}
function render(nodeData) {
"use strict";
try {
renderedTemplate.style.border = "solid 1px red";
renderedTemplate.appendChild(renderHeader(nodeData.name));
renderedTemplate.appendChild(renderMetas(nodeData.metas));
renderedTemplate.appendChild(renderTemplate(nodeData.parameters));
//renderedTemplate.innerHTML += JSON.stringify(nodeData);
return renderedTemplate;
} catch (error) {
console.group('nodeForm.render()');
console.debug(error);
console.groupEnd();
}
}
return {
render: render
}
});
|
#!/usr/bin/env bash
# Exit immediately if a pipeline, which may consist of a single simple command,
# a list, or a compound command returns a non-zero status
set -e
readonly COMPONENT=${1?Component is not specified}
readonly RELEASE=${2?Release is not specified}
readonly SET=${3?Set is not specified}
readonly base_release_url=https://bgbilling.ru/download/$RELEASE
readonly base_set_url=$base_release_url/sets/$SET
readonly files_dat_url=$base_set_url/files.dat
readonly zip_file=$(wget --quiet $files_dat_url --output-document=- | grep '^name:'$COMPONENT'\s' | awk -F '\t|:' '{print $4}')
readonly zip_url=$base_set_url/$zip_file
wget --quiet $zip_url
echo $zip_file
|
<filename>src/client/main.ts
/// <reference path="../../typings/knockout/knockout.d.ts" />
/// <reference path="./partial_viewmodels/common.ts" />
/// <reference path="./utils.ts" />
/// <reference path="./config.ts" />
type MenuItem = PartialViewmodels.MenuItem;
class ApplicationViewmodel {
public mainMenu: KnockoutObservableArray<MenuItem>;
public activeView: KnockoutObservable<string>;
public isLoggedIn: KnockoutObservable<boolean>;
constructor() {
this.mainMenu = ko.observableArray<MenuItem>();
this.activeView = ko.observable<string>();
this.isLoggedIn = ko.observable<boolean>(false);
}
public changeView(nextView: string): void {
let item = this.getMenuItem(nextView) || {} as MenuItem;
if (item.requiresLogin && !this.isLoggedIn()) {
alert("Seeing " + item.name + " requires you to be logged in!");
return;
}
this.activeView("view!" + nextView);
}
private getMenuItem(itemName: string): MenuItem {
for (let item of this.mainMenu()) {
if (item.link === itemName) {
return item;
}
}
return null;
}
}
let appViewmodel = new ApplicationViewmodel();
interface IClassMap {
[name: string]: Function;
}
let getViewmodelForComponent = function (fullName: string): Function {
// Remove the view! or component! part
let shortName = fullName.substr(fullName.indexOf("!") + 1);
// Capitalize
shortName = shortName[0].toUpperCase() + shortName.substr(1);
shortName = shortName.replace(/_[a-z]/g, (replacement) => {
return replacement[1].toUpperCase();
});
let partialViewmodel = (<IClassMap><any>PartialViewmodels)[shortName];
if (partialViewmodel) {
return partialViewmodel;
}
// If there's no partial viewmodel available, create a params proxy
return function (params: Object): Object {
return params;
};
};
let registerComponents = function (): void {
let componentTemplates = document.querySelectorAll(".component");
for (let i = 0; i < componentTemplates.length; i++) {
let component = <HTMLElement>(componentTemplates.item(i));
ko.components.register(component.id, {
viewModel: getViewmodelForComponent(component.id),
template: component.innerHTML
});
}
};
let initializeBindings = function (): void {
let mainMenuItems = Config.instance.courseInfo.translations.mainMenu;
for (let itemName in mainMenuItems) {
let text = mainMenuItems[itemName].text;
let link = itemName;
let icon = mainMenuItems[itemName].icon;
let requiresLogin = mainMenuItems[itemName].requiresLogin;
let item = new PartialViewmodels.MenuItem(text, link,
icon, requiresLogin);
appViewmodel.mainMenu.push(item);
}
ko.applyBindings(appViewmodel);
};
let main = (): void => {
let initializeConfig = Config.initialize();
Config.instance.onToggleLogged(appViewmodel.isLoggedIn);
initializeConfig.then(() => appViewmodel.changeView("home"))
.done(initializeBindings);
registerComponents();
};
document.addEventListener("DOMContentLoaded", main);
|
// Copyright 2020 Wearless Tech Inc All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package globals
import (
cfg "github.com/chryscloud/go-microkit-plugins/config"
mclog "github.com/chryscloud/go-microkit-plugins/log"
)
// Conf global config
var Conf Config
// Log global wide logging
var Log mclog.Logger
type Config struct {
cfg.YamlConfig `yaml:",inline"`
GrpcPort string `yaml:"grpc_port"`
Redis *RedisSubconfig `yaml:"redis"`
Annotation *AnnotationSubconfig `yaml:"annotation"`
API *ApiSubconfig `yaml:"api"`
Buffer *BufferSubconfig `yaml:"buffer"`
}
// RedisSubconfig connnection settings
type RedisSubconfig struct {
Connection string `yaml:"connection"`
Database int `yaml:"database"`
Password string `yaml:"password"`
}
// AnnotationSubconfig - annotation consumer rates
type AnnotationSubconfig struct {
Endpoint string `yaml:"endpoint"` // chryscloud annotation endpoint
UnackedLimit int `yaml:"unacked_limit"` // maximum number of unacknowledged annotations
PollDurationMs int `yaml:"poll_duration_ms"` // time to wait until new poll of annotations (miliseconds)
MaxBatchSize int `yaml:"max_batch_size"` // maximum number of events processed in one batch
}
// VideoApiSubconfig - video api specifics
type ApiSubconfig struct {
Endpoint string `yaml:"endpoint"` // video storage on/off endpoint
}
// Buffer - in memory and on disk buffering
type BufferSubconfig struct {
InMemory int `yaml:"in_memory"` // number of decoded frames to store in memory per camera
InMemoryScale string `yaml:"in_memory_scale"` // scale in-memory video to desired size (e.g.: default = "-1:-1" , "400:-1", "300x200", "iw/2:ih/2")
OnDisk bool `yaml:"on_disk"` // store key-frame segmented mp4 files to disk
OnDiskCleanupOlderThan string `yaml:"on_disk_clean_older_than"` // clean up mp4 segments after X time
OnDiskFolder string `yaml:"on_disk_folder"` // location to store mp4 segments
OnDiskSchedule string `yaml:"on_disk_schedule"` // schedule cleanup every X duration
}
func init() {
l, err := mclog.NewZapLogger("info")
if err != nil {
panic("failed to initalize logging")
}
Log = l
}
|
<reponame>willviles/firelink<filename>src/helpers/revert-json.spec.ts
import 'jest';
import { readFile, unlink } from 'fs';
import { promisify } from 'util';
import { PackageJson } from '../injection-tokens';
import { fileExists } from './file-exists';
import { revertJson } from './revert-json';
import { writeFileJson } from './write-file-json';
describe('[RevertJson]: tests', () => {
it('Should revert package-temp.json', async () => {
const testJsonFileName = 'package-temp2.json';
const testJsonToSave = 'package-temp3.json';
writeFileJson(testJsonToSave, {
dependencies: { '@pesho/test': '0.0.1' },
fireDependencies: {},
fireConfig: {},
});
writeFileJson(testJsonFileName, {
dependencies: { '@pesho/test': '0.0.1' },
fireDependencies: {},
fireConfig: {},
});
const file: PackageJson = JSON.parse(
await promisify(readFile)(testJsonFileName, { encoding: 'utf-8' }),
);
expect(file.dependencies['@pesho/test']).toBe('0.0.1');
revertJson(testJsonToSave, testJsonFileName);
const modifiedJson: PackageJson = JSON.parse(
await promisify(readFile)(testJsonToSave, { encoding: 'utf-8' }),
);
expect(modifiedJson.dependencies['@pesho/test']).toBe('0.0.1');
await promisify(unlink)(testJsonToSave);
expect(await fileExists(testJsonToSave)).toBeFalsy();
});
});
|
package com.dvisagie.vote.users
import java.util.UUID
import akka.actor.{Actor, ReceiveTimeout}
import com.dvisagie.vote.injector.Provider
import com.dvisagie.vote.repositories.UserRepository
import scala.concurrent.duration._
class UserControllerActor(implicit provider: Provider) extends Actor {
import UserControllerActor._
context.setReceiveTimeout(5.seconds)
val userRepository: UserRepository = provider.userRepository
def receive: Receive = {
case createUserRequest: CreateUserRequest =>
sender() ! CreationRequestResponse("message received", createUserRequest.username)
context stop self
case id: UUID =>
sender() ! userRepository.getUserForId(id)
context stop self
case username: String =>
sender() ! userRepository.getUserForUsername(username)
context stop self
case ReceiveTimeout =>
context stop self
}
}
object UserControllerActor {
final case class CreateUserRequest(
username: String,
firstNames: String,
lastName: String,
email: String)
final case class CreationRequestResponse(
message: String,
username: String)
final case class UserResponse(
username: String,
firstNames: String,
lastNames: String)
}
|
#!/bin/bash
pushd $(dirname $0) 2>/dev/null
if [[ -n "${1}" ]]; then
echo ${1} ' build'
cargo build --${1:-release}
else
echo 'debug build'
cargo build
fi
rm -rf "sled.node" 2>/dev/null
[[ -f ${FILE:="../../target/${1:-debug}/libsled_nodex.dylib"} ]] && cp ${FILE} sled.node
[[ -f ${FILE:="../../target/${1:-debug}/libsled_nodex.so"} ]] && cp ${FILE} sled.node
node --napi-modules -e 'const sled = require("./sled.node"); console.log(sled)'
popd 2>/dev/null
|
<gh_stars>1-10
// (C) 2018 ETH Zurich, ITP, <NAME> and <NAME>
#ifndef CINTRIN_HPP_
#define CINTRIN_HPP_
//#include <x86intrin.h>
#include <immintrin.h>
#include <complex>
#include <vector>
#include <algorithm>
template <class M, class I>
inline void permute_qubits_and_matrix(I *delta_list, unsigned n, M & matrix){
using Pair = std::pair<std::size_t, std::size_t>;
std::vector<Pair> qubits(n);
for (unsigned i = 0; i < qubits.size(); ++i){
qubits[i].first = i;
qubits[i].second = delta_list[i];
}
std::sort(qubits.begin(), qubits.end(), [](Pair const& p1, Pair const& p2){ return p1.second < p2.second; });
M old = matrix;
for (std::size_t i = 0; i < (1ULL << qubits.size()); ++i){
for (std::size_t j = 0; j < (1ULL << qubits.size()); ++j){
std::size_t old_i=0, old_j=0;
for (unsigned k = 0; k < qubits.size(); ++k){
old_i |= ((i >> k)&1ULL) << qubits[k].first;
old_j |= ((j >> k)&1ULL) << qubits[k].first;
}
matrix[i][j] = old[old_i][old_j];
}
}
std::sort(delta_list, delta_list+n, std::greater<I>());
}
inline std::complex<double> fma(std::complex<double> const& c1, std::complex<double> const& c2, std::complex<double> const& a){
return c1*c2 + a;
}
inline __m256d fma(__m256d const& c1, __m256d const& c2, __m256d const& a){
auto const c1t = _mm256_permute_pd(c1, 5);
#ifndef HAVE_FMA
auto tmp = _mm256_addsub_pd(_mm256_mul_pd(c1t, _mm256_permute_pd(c2, 15)), a);
return _mm256_addsub_pd(_mm256_mul_pd(c1, _mm256_permute_pd(c2, 0)), tmp);
#else
return _mm256_fmaddsub_pd(c1, _mm256_permute_pd(c2, 0), _mm256_fmaddsub_pd(c1t, _mm256_permute_pd(c2, 15), a));
#endif
}
inline __m256d fma(__m256d const& c1, __m256d const& c2, __m256d const& c2tm, __m256d const& a){
auto const c1t = _mm256_permute_pd(c1, 5);
#ifndef HAVE_FMA
auto const tmp = _mm256_add_pd(_mm256_mul_pd(c1, c2), a);
return _mm256_add_pd(_mm256_mul_pd(c1t, c2tm), tmp);
#else
return _mm256_fmadd_pd(c1, c2, _mm256_fmadd_pd(c1t, c2tm, a));
#endif
}
template <class U>
inline __m256d load1(U *p){
/*auto const tmp = _mm_load_pd((double const*)p);
return _mm256_insertf128_pd(_mm256_castpd128_pd256(tmp), tmp, 0x1);*/
return _mm256_broadcast_pd((__m128d const*)p);
}
template <class U>
inline __m256d load(U const*p1, U const*p2){
return _mm256_insertf128_pd(_mm256_castpd128_pd256(_mm_load_pd((double const*)p1)), _mm_load_pd((double const*)p2), 0x1);
}
template <class U>
inline __m256d loadab(U *p1, U *p2){
return load(p1, p2);
//return _mm256_set_pd(std::imag(*p2), std::real(*p2), std::imag(*p1), std::real(*p1));
}
template <class U>
inline __m256d loada(U *p1, U *p2){
auto r1 = _mm_load1_pd((double*)p1);
auto r2 = _mm_load1_pd((double*)p2);
return _mm256_insertf128_pd(_mm256_castpd128_pd256(r1), r2, 0x1);
//return _mm256_set_pd(std::real(*p2), std::real(*p2), std::real(*p1), std::real(*p1));
}
template <class U>
inline __m256d loadbm(U *p1, U *p2){
auto const mpmp = _mm256_set_pd(1., -1., 1., -1.);
auto i1 = _mm_load1_pd(((double*)p1)+1);
auto i2 = _mm_load1_pd(((double*)p2)+1);
auto tmp = _mm256_insertf128_pd(_mm256_castpd128_pd256(i1), i2, 0x1);
return _mm256_mul_pd(tmp, mpmp);
//return _mm256_set_pd(std::imag(*p2), -std::imag(*p2), std::imag(*p1), -std::imag(*p1));
}
template <class U>
inline __m256d loadb(U *p1, U *p2){
auto i1 = _mm_load1_pd(((double*)p1)+1);
auto i2 = _mm_load1_pd(((double*)p2)+1);
return _mm256_insertf128_pd(_mm256_castpd128_pd256(i1), i2, 0x1);
}
template <class U>
inline void store(U* high, U* low, __m256d const& a){
_mm_store_pd(low, _mm256_castpd256_pd128(a));
_mm_store_pd(high, _mm256_extractf128_pd(a, 0x1));
}
// avx-512
#ifdef HAVE_AVX512
inline __m512d mul(__m512d const& c1, __m512d const& c2, __m512d const& c2tm){
/*auto ac_bd = _mm512_mul_pd(c1, c2);
auto multbmadmc = _mm512_mul_pd(c1, c2tm);
return _mm512_hsub_pd(ac_bd, multbmadmc);*/
auto c1t = _mm512_permute_pd(c1, 85);
return _mm512_add_pd(_mm512_mul_pd(c1, c2), _mm512_mul_pd(c1t, c2tm));
}
inline __m512d add(__m512d const& c1, __m512d const& c2){
return _mm512_add_pd(c1, c2);
}
inline __m512d fma(__m512d const& c1, __m512d const& c2, __m512d const& a){
auto const c1t = _mm512_permute_pd(c1, 85);
#ifndef HAVE_FMA
auto tmp = _mm512_addsub_pd(_mm512_mul_pd(c1t, _mm512_permute_pd(c2, 255)), a);
return _mm512_addsub_pd(_mm512_mul_pd(c1, _mm512_permute_pd(c2, 0)), tmp);
#else
return _mm512_fmaddsub_pd(c1, _mm512_permute_pd(c2, 0), _mm512_fmaddsub_pd(c1t, _mm512_permute_pd(c2, 255), a));
#endif
}
inline __m512d fma(__m512d const& c1, __m512d const& c2, __m512d const& c2tm, __m512d const& a){
auto const c1t = _mm512_permute_pd(c1, 85);
#ifndef HAVE_FMA
auto const tmp = _mm512_add_pd(_mm512_mul_pd(c1, c2), a);
return _mm512_add_pd(_mm512_mul_pd(c1t, c2tm), tmp);
#else
return _mm512_fmadd_pd(c1, c2, _mm512_fmadd_pd(c1t, c2tm, a));
#endif
}
template <class U>
inline __m512d load1x4(U *p){
return _mm512_broadcast_f64x4(load1(p));
}
template <class U>
inline __m512d loadab(U *p1, U *p2, U *p3, U* p4){
return _mm512_insertf64x4(_mm512_castpd256_pd512(loadab(p1, p2)), loadab(p3, p4), 0x1);
}
template <class U>
inline __m512d loada(U *p1, U *p2, U *p3, U *p4){
return _mm512_insertf64x4(_mm512_castpd256_pd512(loada(p1, p2)), loada(p3, p4), 0x1);
}
template <class U>
inline __m512d loadbm(U *p1, U *p2, U *p3, U *p4){
return _mm512_insertf64x4(_mm512_castpd256_pd512(loadbm(p1, p2)), loadbm(p3, p4), 0x1);
}
template <class U>
inline void store(U* hhigh, U* hlow, U* lhigh, U* llow, __m512d const& a){
auto al = _mm512_castpd512_pd256(a);
_mm_storeu_pd(llow, _mm256_castpd256_pd128(al));
_mm_storeu_pd(lhigh, _mm256_extractf128_pd(al, 0x1));
auto ah = _mm512_extractf64x4_pd(a, 0x1);
_mm_storeu_pd(hlow, _mm256_castpd256_pd128(ah));
_mm_storeu_pd(hhigh, _mm256_extractf128_pd(ah, 0x1));
}
template <class U>
inline __m512d load(U const*p1, U const*p2, U const*p3, U const*p4){
auto tmp = _mm256_insertf128_pd(_mm256_castpd128_pd256(_mm_loadu_pd((double const*)p1)), _mm_loadu_pd((double const*)p2), 0x1);
auto tmp2 = _mm256_insertf128_pd(_mm256_castpd128_pd256(_mm_loadu_pd((double const*)p3)), _mm_loadu_pd((double const*)p4), 0x1);
return _mm512_insertf64x4(_mm512_castpd256_pd512(tmp), tmp2, 0x1);
}
#endif
#endif
|
<gh_stars>1-10
import { combineReducers } from 'redux';
import { reducer as github } from './github';
export default combineReducers({
github,
});
|
function numsToStrings(arr) {
return arr.map(x => x.toString());
}
|
#!/bin/sh -e
# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# Monitors a web-based CSV queue for autotest requests, runs the test, and
# uploads the status and results.
# Example CSV contents (must be fully quoted):
# "Timestamp","Repository","Branch","Additional parameters"
# "2013/10/16 8:24:52 PM GMT","dnschneid/crouton","master",""
set -e
APPLICATION="${0##*/}"
SCRIPTDIR="`readlink -f "\`dirname "$0"\`/.."`"
LOGUPLOADINTERVAL=60
POLLINTERVAL=10
READYPINGINTERVAL=600
QUEUEURL=''
SCPBASEOPTIONS='-BCqr'
SCPOPTIONS=''
UPLOADROOT="$HOME"
USAGE="$APPLICATION [options] -q QUEUEURL
Runs a daemon that polls a CSV on the internet for tests to run, and uploads
status and results to some destination via scp.
Options:
-q QUEUEURL Queue URL to poll for new test requests. Must be specified.
-s SCPOPTIONS Special options to pass to SCP in addition to $SCPBASEOPTIONS
Default: ${SCPOPTIONS:-"(nothing)"}
-u UPLOADROOT Base SCP-compatible URL directory to upload to. Must exist.
Default: $UPLOADROOT"
# Common functions
. "$SCRIPTDIR/installer/functions"
# Process arguments
while getopts 'q:s:u:' f; do
case "$f" in
q) QUEUEURL="$OPTARG";;
s) SCPOPTIONS="$OPTARG";;
u) UPLOADROOT="$OPTARG";;
\?) error 2 "$USAGE";;
esac
done
shift "$((OPTIND-1))"
if [ -z "$QUEUEURL" -o "$#" != 0 ]; then
error 2 "$USAGE"
fi
# We need to run as root
if [ "$USER" != root -a "$UID" != 0 ]; then
error 2 "$APPLICATION must be run as root."
fi
statusmonitor() { (
local machinestatus="$LOCALROOT/status-$id"
if [ -n "$CURTESTROOT" ]; then
local sig='USR1'
local teststatus="${CURTESTROOT%/}/status-$id"
local uploadcmd="scp $SCPBASEOPTIONS $SCPOPTIONS \
'$machinestatus' '$CURTESTROOT' '$UPLOADROOT'"
echo -n '' > "$machinestatus"
echo -n '' > "$teststatus"
trap '' "$sig"
(
updatetime=0
while sleep 1; do
if [ "$updatetime" = 0 ]; then
trap '' "$sig"
eval "$uploadcmd"
trap "$uploadcmd" "$sig"
updatetime="$LOGUPLOADINTERVAL"
else
updatetime="$(($updatetime-1))"
fi
done
) &
uploader="$!"
settrap "kill '$uploader' 2>/dev/null;"
while read line; do
echo "$line" >> "$machinestatus"
echo "$line" >> "$teststatus"
kill -"$sig" "$uploader"
done
kill "$uploader"
wait "$uploader" || true
eval "$uploadcmd"
else
sed "s/^READY/READY ` \
dbus-send --system --type=method_call --print-reply \
--dest=org.chromium.UpdateEngine /org/chromium/UpdateEngine \
org.chromium.UpdateEngineInterface.GetStatus 2>/dev/null \
| awk -F'"' '/UPDATE_STATUS/ {print $2; exit}'`/" > "$machinestatus"
scp $SCPBASEOPTIONS $SCPOPTIONS "$machinestatus" "$UPLOADROOT"
fi
) }
# Get a consistent ID for the device in the form of board-channel_xxxxxxxx
if hash vpd 2>/dev/null; then
id="`awk '/_RELEASE_DESCRIPTION=/{print $NF "-" $(NF-1)}' /etc/lsb-release`"
id="${id%"-channel"}_`vpd -g serial_number | sha1sum | head -c 8`"
else
# Oh well. Random testing ID it is.
id="test-unknown_`hexdump -v -n4 -e '"" 1/1 "%02x"' /dev/urandom`"
fi
LOCALROOT="`mktemp -d --tmpdir='/tmp' 'crouton-autotest.XXX'`"
addtrap "rm -rf --one-file-system '$LOCALROOT'"
CURTESTROOT=''
CROUTONROOT="$LOCALROOT/crouton"
LASTFILE="$LOCALROOT/last"
echo "2 `date '+%s'`" > "$LASTFILE"
READYFILE="$LOCALROOT/ready"
echo 'READY' > "$READYFILE"
readypingtime=0
while sleep "$POLLINTERVAL"; do
read lastline last < "$LASTFILE"
# Grab the queue, skip to the next interesting line, convert field
# boundaries into pipe characters, and then parse the result.
(wget -qO- "$QUEUEURL" && echo) | tail -n"+$lastline" \
| sed 's/^"//; s/","/|/g; s/"$//' | {
while IFS='|' read date repo branch params _; do
if [ -z "$date" ]; then
continue
fi
lastline="$(($lastline+1))"
# Convert to UNIX time and skip if it's an old request
date="`date '+%s' --date="$date"`"
if [ "$date" -le "$last" ]; then
continue
fi
last="$date"
# Validate the other fields
branch="${branch%%/*}"
gituser="${repo%%/*}"
repo="${repo##*/}"
tarball="https://github.com/$gituser/$repo/archive/$branch.tar.gz"
# Test root should be consistent between machines
date="`date -u '+%Y-%m-%d_%H-%M-%S' --date="@$date"`"
paramsstr="${params:+"_"}`echo "$params" | tr ' [:punct:]' '_-'`"
tname="${date}_${gituser}_${repo}_$branch$paramsstr"
CURTESTROOT="$LOCALROOT/$tname"
logdir="$CURTESTROOT/$id"
mkdir -p "$logdir"
# Start logging to the server
{
echo "BEGIN TEST SUITE $tname"
ret=''
mkdir -p "$CROUTONROOT"
if wget -qO- "$tarball" \
| tar -C "$CROUTONROOT" -xz --strip-components=1; then
ret=0
sh -e "$CROUTONROOT/test/run.sh" -l "$logdir" $params \
|| ret=$?
fi
rm -rf --one-file-system "$CROUTONROOT"
if [ -z "$ret" ]; then
result="TEST SUITE $tname FAILED: unable to download branch"
elif [ "$ret" != 0 ]; then
result="TEST SUITE $tname FAILED: finished with exit code $ret"
else
result="TEST SUITE $tname PASSED: finished with exit code $ret"
fi
echo "$result"
(echo 'READY'; echo "$result") > "$READYFILE"
} 2>&1 | statusmonitor
CURTESTROOT=''
cat "$READYFILE" | statusmonitor
done
echo "$lastline $last" > "$LASTFILE"
}
# Update the 'ready' file once every $READYPINGTIME seconds
if [ "$readypingtime" -le 0 ]; then
cat "$READYFILE" | statusmonitor
readypingtime="$READYPINGINTERVAL"
else
readypingtime="$(($readypingtime-$POLLINTERVAL))"
fi
done
|
def celsius_to_fahrenheit(celsius):
fahrenheit = (celsius * 9/5) + 32
return fahrenheit
celsius_temp = float(input("Enter Celsius temperature: "))
fahrenheit_temp = celsius_to_fahrenheit(celsius_temp)
print(f"Fahrenheit temperature: {fahrenheit_temp}")
|
<filename>examples/counter/containers/App.ts
import {Component, Inject, OnDestroy} from 'angular2/core';
import {bindActionCreators} from 'redux';
import {Counter} from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
@Component({
selector: 'root',
directives: [Counter],
template: `
<counter [counter]="counter"
[increment]="increment"
[decrement]="decrement"
[incrementIfOdd]="incrementIfOdd"
[incrementAsync]="incrementAsync">
</counter>
`
})
export default class App implements OnDestroy {
protected unsubscribe: Function;
constructor( @Inject('ngRedux') ngRedux, @Inject('devTools') devTools) {
devTools.start(ngRedux);
this.unsubscribe = ngRedux.connect(this.mapStateToThis, this.mapDispatchToThis)(this);
}
ngOnDestroy() {
this.unsubscribe();
}
mapStateToThis(state) {
return {
counter: state.counter
};
}
mapDispatchToThis(dispatch) {
return bindActionCreators(CounterActions, dispatch);
}
}
|
function FolderHandler() {}
Object.assign(FolderHandler.prototype, {
load: function (url, callback) {
callback(null, null);
},
open: function (url, data) {
return data;
}
});
export { FolderHandler };
|
#!/bin/bash
# To make executable command:
# chmod +X assemble.sh
# sudo cp ./assemble.sh /usr/bin/assemble
# Once done, simply execute as:
# $ assemble [source file] [executable name]
arm-linux-gnueabi-as -o a.o $1
arm-linux-gnueabi-ld -o $2 a.o
rm a.o # comment out if you don't want the intermidiate binary deleted every build
|
//Run all tests.
require('./mouse');
require('./keyboard');
require('./screen');
require('./bitmap');
|
<filename>rover/core/servers/tobeintegrated/armFreqServer.py
from socket import AF_INET, socket, SOCK_STREAM
from threading import Thread
import subprocess
from time import sleep
import smbus
import time
# for RPI version 1, use "bus = smbus.SMBus(0)"
bus = smbus.SMBus(1)
def acceptConnections():
while True:
client, client_address = SERVER.accept()
print("%s:%s has connected." % client_address)
Thread(target=handle_client, args=(client, )).start()
def StringToBytes(val):
retVal = []
for c in val:
retVal.append(ord(c))
return retVal
def writeToBus(addr, deg, client):
#print(addr, type(int(addr)))
bus.write_i2c_block_data(int(addr), 0x00, StringToBytes(deg))
if deg[0] == '9':
block = bus.read_word_data(addr, 0)
client.send(block)
else:
client.send("Successful")
def handle_client(client):
global currentPoints
while True :
data = client.recv(4096)
value = data.split(',')
#print(value)
writeToBus(value[0], value[1], client)
clients = {}
HOST = ''
PORT = 9080
BUFSIZ = 4096
ADDR = (HOST, PORT)
SERVER = socket(AF_INET, SOCK_STREAM)
while True:
try:
SERVER.bind(ADDR)
break
except:
subprocess.call(' sudo lsof -t -i tcp:9090 | xargs kill -9', shell = True)
if __name__ == "__main__":
SERVER.listen(5)
print("Waiting for connection...")
ACCEPT_THREAD = Thread(target=acceptConnections)
ACCEPT_THREAD.start()
ACCEPT_THREAD.join()
SERVER.close()
|
import { logger, post } from '../utils';
export default function received(pushCode, deviceCode, token) {
const url = `/pushes/${pushCode}/received/`;
const device = `/api/v1/devices/${deviceCode}/`;
return post(url, { device }, token)
.then(response => logger('received', response.status));
}
|
import {GameInstance} from "./GameInstance";
/**
* Created by Hyperion on 04/06/2017.
*/
export class GameInfo {
/**
* If true means this data comes from lobby parent server
* else from dedi server or server instanced by lobby
*/
IsLobbyServer:boolean;
IsPassworded:boolean;
/**
* Total number of players for all instanced servers
* or for dedi server
*/
NumPlayers:number;
/**
* Total num matchs
* ALways 1 for dedi else 0-n for lobby
*/
NumMatches:number;
/**
* Games instances.
* Array of one instance for dedi
* else many for lobby
*/
GameInstances:GameInstance[];
}
|
import { Value } from 'slate';
export interface CompletionItem {
/**
* The label of this completion item. By default
* this is also the text that is inserted when selecting
* this completion.
*/
label: string;
/**
* The kind of this completion item. Based on the kind
* an icon is chosen by the editor.
*/
kind?: string;
/**
* A human-readable string with additional information
* about this item, like type or symbol information.
*/
detail?: string;
/**
* A human-readable string, can be Markdown, that represents a doc-comment.
*/
documentation?: string;
/**
* A string that should be used when comparing this item
* with other items. When `falsy` the `label` is used.
*/
sortText?: string;
/**
* A string that should be used when filtering a set of
* completion items. When `falsy` the `label` is used.
*/
filterText?: string;
/**
* A string or snippet that should be inserted in a document when selecting
* this completion. When `falsy` the `label` is used.
*/
insertText?: string;
/**
* Delete number of characters before the caret position,
* by default the letters from the beginning of the word.
*/
deleteBackwards?: number;
/**
* Number of steps to move after the insertion, can be negative.
*/
move?: number;
}
export interface CompletionItemGroup {
/**
* Label that will be displayed for all entries of this group.
*/
label: string;
/**
* List of suggestions of this group.
*/
items: CompletionItem[];
/**
* If true, match only by prefix (and not mid-word).
*/
prefixMatch?: boolean;
/**
* If true, do not filter items in this group based on the search.
*/
skipFilter?: boolean;
/**
* If true, do not sort items.
*/
skipSort?: boolean;
}
interface ExploreDatasource {
value: string;
label: string;
}
export interface HistoryItem {
ts: number;
query: string;
}
export abstract class LanguageProvider {
datasource: any;
request: (url) => Promise<any>;
start: () => Promise<any>;
}
export interface TypeaheadInput {
text: string;
prefix: string;
wrapperClasses: string[];
labelKey?: string;
value?: Value;
}
export interface TypeaheadOutput {
context?: string;
refresher?: Promise<{}>;
suggestions: CompletionItemGroup[];
}
export interface Range {
from: string;
to: string;
}
export interface Query {
query: string;
key?: string;
}
export interface QueryFix {
type: string;
label: string;
action?: QueryFixAction;
}
export interface QueryFixAction {
type: string;
query?: string;
preventSubmit?: boolean;
}
export interface QueryHint {
type: string;
label: string;
fix?: QueryFix;
}
export interface QueryTransaction {
id: string;
done: boolean;
error?: string;
hints?: QueryHint[];
latency: number;
options: any;
query: string;
result?: any; // Table model / Timeseries[] / Logs
resultType: ResultType;
rowIndex: number;
}
export interface TextMatch {
text: string;
start: number;
length: number;
end: number;
}
export interface ExploreState {
datasource: any;
datasourceError: any;
datasourceLoading: boolean | null;
datasourceMissing: boolean;
datasourceName?: string;
exploreDatasources: ExploreDatasource[];
graphRange: Range;
history: HistoryItem[];
/**
* Initial rows of queries to push down the tree.
* Modifications do not end up here, but in `this.queryExpressions`.
* The only way to reset a query is to change its `key`.
*/
queries: Query[];
/**
* Hints gathered for the query row.
*/
queryTransactions: QueryTransaction[];
range: Range;
showingGraph: boolean;
showingLogs: boolean;
showingTable: boolean;
supportsGraph: boolean | null;
supportsLogs: boolean | null;
supportsTable: boolean | null;
}
export interface ExploreUrlState {
datasource: string;
queries: Query[];
range: Range;
}
export type ResultType = 'Graph' | 'Logs' | 'Table';
|
<reponame>ywkim0606/gtsam<filename>gtsam/geometry/Similarity2.cpp
/* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: <NAME>, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file Similarity2.cpp
* @brief Implementation of Similarity2 transform
* @author <NAME>, <NAME>
*/
#include <gtsam/base/Manifold.h>
#include <gtsam/geometry/Pose2.h>
#include <gtsam/geometry/Rot3.h>
#include <gtsam/geometry/Similarity2.h>
#include <gtsam/slam/KarcherMeanFactor-inl.h>
namespace gtsam {
using std::vector;
namespace internal {
/// Subtract centroids from point pairs.
static Point2Pairs SubtractCentroids(const Point2Pairs& abPointPairs,
const Point2Pair& centroids) {
Point2Pairs d_abPointPairs;
for (const Point2Pair& abPair : abPointPairs) {
Point2 da = abPair.first - centroids.first;
Point2 db = abPair.second - centroids.second;
d_abPointPairs.emplace_back(da, db);
}
return d_abPointPairs;
}
/// Form inner products x and y and calculate scale.
static double CalculateScale(const Point2Pairs& d_abPointPairs,
const Rot2& aRb) {
double x = 0, y = 0;
Point2 da, db;
for (const Point2Pair& d_abPair : d_abPointPairs) {
std::tie(da, db) = d_abPair;
const Vector2 da_prime = aRb * db;
y += da.transpose() * da_prime;
x += da_prime.transpose() * da_prime;
}
const double s = y / x;
return s;
}
/// Form outer product H.
static Matrix2 CalculateH(const Point2Pairs& d_abPointPairs) {
Matrix2 H = Z_2x2;
for (const Point2Pair& d_abPair : d_abPointPairs) {
H += d_abPair.first * d_abPair.second.transpose();
}
return H;
}
/**
* @brief This method estimates the similarity transform from differences point
* pairs, given a known or estimated rotation and point centroids.
*
* @param d_abPointPairs
* @param aRb
* @param centroids
* @return Similarity2
*/
static Similarity2 Align(const Point2Pairs& d_abPointPairs, const Rot2& aRb,
const Point2Pair& centroids) {
const double s = CalculateScale(d_abPointPairs, aRb);
// dividing aTb by s is required because the registration cost function
// minimizes ||a - sRb - t||, whereas Sim(2) computes s(Rb + t)
const Point2 aTb = (centroids.first - s * (aRb * centroids.second)) / s;
return Similarity2(aRb, aTb, s);
}
/**
* @brief This method estimates the similarity transform from point pairs,
* given a known or estimated rotation.
* Refer to:
* http://www5.informatik.uni-erlangen.de/Forschung/Publikationen/2005/Zinsser05-PSR.pdf
* Chapter 3
*
* @param abPointPairs
* @param aRb
* @return Similarity2
*/
static Similarity2 AlignGivenR(const Point2Pairs& abPointPairs,
const Rot2& aRb) {
auto centroids = means(abPointPairs);
auto d_abPointPairs = internal::SubtractCentroids(abPointPairs, centroids);
return internal::Align(d_abPointPairs, aRb, centroids);
}
} // namespace internal
Similarity2::Similarity2() : t_(0, 0), s_(1) {}
Similarity2::Similarity2(double s) : t_(0, 0), s_(s) {}
Similarity2::Similarity2(const Rot2& R, const Point2& t, double s)
: R_(R), t_(t), s_(s) {}
Similarity2::Similarity2(const Matrix2& R, const Vector2& t, double s)
: R_(Rot2::ClosestTo(R)), t_(t), s_(s) {}
Similarity2::Similarity2(const Matrix3& T)
: R_(Rot2::ClosestTo(T.topLeftCorner<2, 2>())),
t_(T.topRightCorner<2, 1>()),
s_(1.0 / T(2, 2)) {}
bool Similarity2::equals(const Similarity2& other, double tol) const {
return R_.equals(other.R_, tol) &&
traits<Point2>::Equals(t_, other.t_, tol) && s_ < (other.s_ + tol) &&
s_ > (other.s_ - tol);
}
bool Similarity2::operator==(const Similarity2& other) const {
return R_.matrix() == other.R_.matrix() && t_ == other.t_ && s_ == other.s_;
}
void Similarity2::print(const std::string& s) const {
std::cout << std::endl;
std::cout << s;
rotation().print("\nR:\n");
std::cout << "t: " << translation().transpose() << " s: " << scale()
<< std::endl;
}
Similarity2 Similarity2::identity() { return Similarity2(); }
Similarity2 Similarity2::operator*(const Similarity2& S) const {
return Similarity2(R_ * S.R_, ((1.0 / S.s_) * t_) + R_ * S.t_, s_ * S.s_);
}
Similarity2 Similarity2::inverse() const {
const Rot2 Rt = R_.inverse();
const Point2 sRt = Rt * (-s_ * t_);
return Similarity2(Rt, sRt, 1.0 / s_);
}
Point2 Similarity2::transformFrom(const Point2& p) const {
const Point2 q = R_ * p + t_;
return s_ * q;
}
Pose2 Similarity2::transformFrom(const Pose2& T) const {
Rot2 R = R_.compose(T.rotation());
Point2 t = Point2(s_ * (R_ * T.translation() + t_));
return Pose2(R, t);
}
Point2 Similarity2::operator*(const Point2& p) const {
return transformFrom(p);
}
Similarity2 Similarity2::Align(const Point2Pairs& abPointPairs) {
// Refer to Chapter 3 of
// http://www5.informatik.uni-erlangen.de/Forschung/Publikationen/2005/Zinsser05-PSR.pdf
if (abPointPairs.size() < 2)
throw std::runtime_error("input should have at least 2 pairs of points");
auto centroids = means(abPointPairs);
auto d_abPointPairs = internal::SubtractCentroids(abPointPairs, centroids);
Matrix2 H = internal::CalculateH(d_abPointPairs);
// ClosestTo finds rotation matrix closest to H in Frobenius sense
Rot2 aRb = Rot2::ClosestTo(H);
return internal::Align(d_abPointPairs, aRb, centroids);
}
Similarity2 Similarity2::Align(const Pose2Pairs& abPosePairs) {
const size_t n = abPosePairs.size();
if (n < 2)
throw std::runtime_error("input should have at least 2 pairs of poses");
// calculate rotation
vector<Rot2> rotations;
Point2Pairs abPointPairs;
rotations.reserve(n);
abPointPairs.reserve(n);
// Below denotes the pose of the i'th object/camera/etc
// in frame "a" or frame "b".
Pose2 aTi, bTi;
for (const Pose2Pair& abPair : abPosePairs) {
std::tie(aTi, bTi) = abPair;
const Rot2 aRb = aTi.rotation().compose(bTi.rotation().inverse());
rotations.emplace_back(aRb);
abPointPairs.emplace_back(aTi.translation(), bTi.translation());
}
const Rot2 aRb_estimate = FindKarcherMean<Rot2>(rotations);
return internal::AlignGivenR(abPointPairs, aRb_estimate);
}
Vector4 Similarity2::Logmap(const Similarity2& S, //
OptionalJacobian<4, 4> Hm) {
const Vector2 u = S.t_;
const Vector1 w = Rot2::Logmap(S.R_);
const double s = log(S.s_);
Vector4 result;
result << u, w, s;
if (Hm) {
throw std::runtime_error("Similarity2::Logmap: derivative not implemented");
}
return result;
}
Similarity2 Similarity2::Expmap(const Vector4& v, //
OptionalJacobian<4, 4> Hm) {
const Vector2 t = v.head<2>();
const Rot2 R = Rot2::Expmap(v.segment<1>(2));
const double s = v[3];
if (Hm) {
throw std::runtime_error("Similarity2::Expmap: derivative not implemented");
}
return Similarity2(R, t, s);
}
Matrix4 Similarity2::AdjointMap() const {
throw std::runtime_error("Similarity2::AdjointMap not implemented");
}
std::ostream& operator<<(std::ostream& os, const Similarity2& p) {
os << "[" << p.rotation().theta() << " " << p.translation().transpose() << " "
<< p.scale() << "]\';";
return os;
}
Matrix3 Similarity2::matrix() const {
Matrix3 T;
T.topRows<2>() << R_.matrix(), t_;
T.bottomRows<1>() << 0, 0, 1.0 / s_;
return T;
}
} // namespace gtsam
|
use std::path::{Path, PathBuf};
use tokio::task::spawn_blocking;
use std::fs::File;
use std::io::{Read, Result as IoResult};
enum Endianness {
BigEndian,
LittleEndian,
}
struct YourType; // Replace with the actual type you are working with
impl YourType {
#[inline]
async fn from_file_with_offset_async<P>(
path: P,
initial_offset: usize,
endianness: Endianness,
) -> Result<Self, std::io::Error>
where
P: AsRef<Path> + Sync + Send,
{
let path = path.as_ref().to_path_buf();
let result = spawn_blocking(move || {
let mut file = File::open(path)?;
file.seek(std::io::SeekFrom::Start(initial_offset as u64))?;
// Read the file with the specified endianness
let data = match endianness {
Endianness::BigEndian => read_big_endian(&mut file)?,
Endianness::LittleEndian => read_little_endian(&mut file)?,
};
Ok(data) // Assuming `YourType` is the result type
}).await;
result
}
}
fn read_big_endian(file: &mut File) -> IoResult<YourType> {
// Implement reading in big endian format
unimplemented!()
}
fn read_little_endian(file: &mut File) -> IoResult<YourType> {
// Implement reading in little endian format
unimplemented!()
}
|
#!/usr/bin/ruby
class YadSystrayCmd
def initialize
self.instance_eval(File.read(ENV["maildeliv_conf"] || "#{ENV["HOME"]}/.yek/maildeliv/maildelivrc.rb")) # To use configuration file.
@memofile = (ENV["maildeliv_tempdir"] || @maildeliv_conf[:TempDir] || "#{ENV["HOME"]}/tmp/recv-mails") + ".summery"
@yadlist = (ENV["maildeliv_tempdir"] || @maildeliv_conf[:TempDir] || "#{ENV["HOME"]}/tmp/recv-mails") + ".yad"
if system("yad", "--list", "--width=650", "--height=500", '--top', '--title=Maildeliver Notification', '--column=From', '--column=Date', '--column=Subject', *File.foreach(@yadlist).map {|i| i.gsub('&', '&')}.map {|i| i.gsub('<', '<')} )
File.open(@memofile, "r+") do |f|
f.flock(File::LOCK_EX)
f.seek(0)
f.truncate(0)
end
end
end
end
YadSystrayCmd.new
|
#!/bin/bash
# Copyright 2013 Kyle Harper
# Licensed per the details in the LICENSE file in this package.
# Source shared, core, and namespace.
. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/../../__shared.inc.sh"
. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/../../../sbt/core.sh"
. "$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/../../../sbt/string.sh"
# Performance check
if [ "${1}" == 'performance' ] ; then iteration=1 ; START="$(date '+%s%N')" ; else echo '' ; fi
# Testing loop
while [ ${iteration} -le ${MAX_ITERATIONS} ] ; do
# -- 1 -- Use it as expected
new_test "Sending all arguments as required, to simulate a good test: "
[ "$(string__reverse 'hello')" == 'olleh' ] || fail 1
pass
# -- 2 -- Multiple lines should be fine
new_test "Sending a multi-line string and breaking into an array: "
declare -a lines
while IFS=$'\n' read -r line ; do lines+=("${line}") ; done < <(string__reverse $'hello\nthere\nmommy')
[ ${#lines[@]} -eq 3 ] || fail 1
[ "${lines[0]}" == 'olleh' ] || fail 2
[ "${lines[1]}" == 'ereht' ] || fail 3
[ "${lines[2]}" == 'ymmom' ] || fail 4
unset lines
pass
# -- 3 -- Storing by reference to ensure it works
new_test "Storing output by reference: "
rv=''
string__reverse -R 'rv' 'hello'
[ "${rv}" == 'olleh' ] || fail 1
rv=''
string__reverse $'hello\nthere\nmommy' -R 'rv'
declare -a lines
while IFS=$'\n' read -r line ; do lines+=("${line}") ; done <<< "${rv}"
[ ${#lines[@]} -eq 3 ] || fail 2
[ "${lines[0]}" == 'olleh' ] || fail 3
[ "${lines[1]}" == 'ereht' ] || fail 4
[ "${lines[2]}" == 'ymmom' ] || fail 5
unset lines
pass
# -- 4 -- Read from files, because we can.
new_test "Reading from a file instead of parameters: "
echo -e "hello\nthere\nmommy" >/tmp/string__reverse
rv=''
string__reverse -R 'rv' -f /tmp/string__reverse
declare -a lines
while IFS=$'\n' read -r line ; do lines+=("${line}") ; done <<< "${rv}"
[ ${#lines[@]} -eq 3 ] || fail 1
[ "${lines[0]}" == 'olleh' ] || fail 2
[ "${lines[1]}" == 'ereht' ] || fail 3
[ "${lines[2]}" == 'ymmom' ] || fail 4
unset lines
rm /tmp/string__reverse
pass
let iteration++
done
# Send final data
if [ "${1}" == 'performance' ] ; then
END="$(date '+%s%N')"
let "TOTAL = (${END} - ${START}) / 1000000"
printf " %'.0f tests in %'.0f ms (%s tests/sec)\n" "${test_number}" "${TOTAL}" "$(bc <<< "scale = 3; ${test_number} / (${TOTAL} / 1000)")" >&2
fi
|
export * from './change_detection';
export * from './core';
export * from './annotations';
export * from './directives';
export * from './forms';
export * from './di';
export * from './http';
export {Observable, EventEmitter} from 'angular2/src/facade/async';
export * from 'angular2/src/render/api';
export {DomRenderer, DOCUMENT_TOKEN} from 'angular2/src/render/dom/dom_renderer';
|
<reponame>OS2World/LIB-GRAPHICS-The_Mesa_3D_Graphics_Library
/*
* Copyright (c) 1991, 1992, 1993 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the name of
* Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF
* ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <GL/glut.h>
#include "loadppm.ch"
GLenum doubleBuffer;
GLint windW, windH;
char *fileName = 0;
PPMImage *image;
float point[3];
float zoom;
GLint x, y;
static void Init(void)
{
glClearColor(0.0, 0.0, 0.0, 0.0);
x = 0;
y = windH;
zoom = 1.8;
}
static void GLUTCALLBACK Reshape(int width, int height)
{
windW = (GLint)width;
windH = (GLint)height;
glViewport(0, 0, windW, windH);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, windW, 0, windH);
glMatrixMode(GL_MODELVIEW);
}
static void GLUTCALLBACK Key(unsigned char key, int x, int y)
{
switch (key) {
case 27:
exit(1);
case 'Z':
zoom += 0.2;
break;
case 'z':
zoom -= 0.2;
if (zoom < 0.2) {
zoom = 0.2;
}
break;
default:
return;
}
glutPostRedisplay();
}
static void GLUTCALLBACK Mouse(int button, int state, int mouseX, int mouseY)
{
if (state != GLUT_DOWN)
return;
x = (GLint)mouseX;
y = (GLint)mouseY;
printf("x=%i,y=%i\n",x,y);
glutPostRedisplay();
}
static void GLUTCALLBACK Draw(void)
{
glClear(GL_COLOR_BUFFER_BIT);
point[0] = (windW / 2) - (image->sizeX / 2);
point[1] = (windH / 2) - (image->sizeY / 2);
point[2] = 0;
glRasterPos3fv(point);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glPixelZoom(1.0, 1.0);
glDrawPixels(image->sizeX, image->sizeY, GL_RGB, GL_UNSIGNED_BYTE,
image->data);
point[0] = (float)x;
point[1] = (float)y;
point[2] = 0.0;
glRasterPos3fv(point);
glPixelZoom(zoom, zoom);
glCopyPixels((windW/2)-(image->sizeX/2),
(windH/2)-(image->sizeY/2),
image->sizeX, image->sizeY, GL_COLOR);
glFlush();
if (doubleBuffer) {
glutSwapBuffers();
}
}
static GLenum Args(int argc, char **argv)
{
GLint i;
doubleBuffer = GL_FALSE;
for (i = 1; i < argc; i++) {
if (strcmp(argv[i], "-sb") == 0) {
doubleBuffer = GL_FALSE;
} else if (strcmp(argv[i], "-db") == 0) {
doubleBuffer = GL_TRUE;
} else if (strcmp(argv[i], "-f") == 0) {
if (i+1 >= argc || argv[i+1][0] == '-') {
printf("-f (No file name).\n");
return GL_FALSE;
} else {
fileName = argv[++i];
}
} else {
printf("%s (Bad option).\n", argv[i]);
return GL_FALSE;
}
}
return GL_TRUE;
}
void maininit(int argc, char **argv)
{
GLenum type;
glutInit(&argc, argv);
if (Args(argc, argv) == GL_FALSE) {
exit(1);
}
if (fileName == 0) {
printf("No image file.\n");
fileName = "tile.ppm";
// exit(1);
}
image = LoadPPM(fileName);
windW = 300;
windH = 300;
glutInitWindowPosition(0, 0); glutInitWindowSize( windW, windH);
type = GLUT_RGB;
type |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE;
glutInitDisplayMode(type);
if (glutCreateWindow("Copy Test") == GL_FALSE) {
exit(1);
}
Init();
glutReshapeFunc(Reshape);
glutKeyboardFunc(Key);
glutMouseFunc(Mouse);
glutDisplayFunc(Draw);
glutMainLoop();
}
|
#!/bin/sh
[ -f /tmp/debug_apkg ] && echo "APKG_DEBUG: $0 $@" >> /tmp/debug_apkg
path=$1
log=/tmp/rclone.log
echo "INIT linking files from path: $path" >> $log
# create link to binary
ln -sf $path/rclone-*-linux-*/rclone /usr/bin/rclone
# create folder for the webpage
WEBPATH="/var/www/rclone/"
mkdir -p $WEBPATH
ln -sf $path/web/* $WEBPATH
|
<filename>public/vocables/js/tools/annotator.js<gh_stars>0
/** The MIT License
Copyright 2020 <NAME> / SousLesens <EMAIL>
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var Annotator = (function () {
var self = {}
self.selectedSources;
self.onLoaded = function () {
var html = "<button onclick='Annotator.showActionPanel()'>OK</button>"
$("#sourceDivControlPanelDiv").html(html)
}
self.onSourceSelect = function () {
}
self.showActionPanel = function () {
self.selectedSources = $("#sourcesTreeDiv").jstree(true).get_checked()
$("#actionDiv").html("")
$("#graphDiv").load("snippets/annotator.html")
$("#accordion").accordion("option", {active: 2});
}
self.annotate = function () {
$("#waitImg").css("display", "block");
MainController.UI.message("querying Spacy library (can take time...)")
var text = $("#Annotator_textArea").val();
var sourcesLabels = self.selectedSources;
var sources = [];
sourcesLabels.forEach(function (label) {
var source = Config.sources[label]
source.name = label;
sources.push(source)
})
var payload = {
annotateLive: 1,
text: text,
sources: JSON.stringify(sources)
}
$.ajax({
type: "POST",
url: Config.serverUrl,
data: payload,
dataType: "json",
/* beforeSend: function(request) {
request.setRequestHeader('Age', '10000');
},*/
success: function (data, textStatus, jqXHR) {
MainController.UI.message("")
$("#waitImg").css("display", "none");
var x = data
self.showAnnotationResult(data)
}
, error: function (err) {
MainController.UI.message(err)
$("#waitImg").css("display", "none");
}
})
}
self.showAnnotationResult = function (data) {
if (Object.keys(data.entities).length == 0 && data.missingNouns.length == 0) {
$("#Annotator_AnnotationResultDiv").html("")
return alert("no matching concepts")
}
var html = "<table class='center' >"
html += "<tr><td> </td>"
var sourcesLabels = self.selectedSources;
sourcesLabels.forEach(function (source) {
html += "<td>" + source + "</td>"
})
html += "</tr>"
for (var word in data.entities) {
html += "<tr><td>" + word + "</td>"
sourcesLabels.forEach(function (source) {
var value = "";
if (data.entities[word][source]) {
data.entities[word][source].forEach(function (entity) {
if (entity.source == source)
var id = ("AnnotatorEntity|" + source + "|" + entity.id)
// console.log(id)
value += "<span class='Annotator_entitySpan' data-source='" + source + "' data-label='" + word + "' data-id='" + entity.id + "' id='" + id + "'>" + "+" + "</span>"
})
}
html += "<td>" + value + "</td>"
})
html += "</tr>"
}
html += "</table>"
$("#Annotator_AnnotationResultDiv").html(html)
$(".Annotator_entitySpan").bind("click", Annotator.onNodeClick)
var html = ""
var uniqueMissingNouns={}
data.missingNouns.forEach(function (item) {
if(!uniqueMissingNouns[item]) {
uniqueMissingNouns[item]=1
html += "<span class='Annotator_orphanNouns' id='Annotator_noun|" + "orphan" + "|" + item + "'>" + item + "</span>"
}
})
$("#Annotator_orphanNounsDiv").html(html)
$(".Annotator_orphanNouns").bind("click", function (e) {
if(e.ctrlKey)
Clipboard.copy({type: "word", source: "none", label: $(this).html()}, $(this).attr("id"),e)
})
}
self.onNodeClick = function (e) {
var source = $(this).data("source")
var label = $(this).data("label")
var id = $(this).data("id")
if (e.ctrlKey) {
Clipboard.copy({type: "node", source: source, id: id, label: label}, $(this).attr("id"), e)
} else
self.getEntityInfo(e)
}
self.getEntityInfo = function (e) {
var id = e.target.id;
var array = id.split("|")
var source = array[1]
id = array[2]
MainController.UI.showNodeInfos(source, id,"Annotator_EntityDetailsDiv")
/* Sparql_generic.getNodeInfos(source, id, null, function (err, result) {
if (err)
return MainController.UI.message(err)
SourceEditor.showNodeInfos("Annotator_EntityDetailsDiv", "en", id, result);
})*/
Sparql_generic.getSingleNodeAllGenealogy(source, id, function (err, result) {
if (err)
return MainController.UI.message(err)
var html = "Genealogy : "
result.forEach(function (item) {
html += "<span class='Annotator_entityGenealogySpan' data-source='" + source + "' data-id='" + item.broader.value + "' data-label='" + item.broaderLabel.value + "' id='Annotator_entity|" + source + "|" + item.broader.value + "'>" + item.broaderLabel.value + "</span>"
})
$("#Annotator_EntityGenealogyDiv").html(html)
$(".Annotator_entityGenealogySpan").bind("click", Annotator.onNodeClick)
})
}
self.setTestText = function () {
var text = "Compaction drives characteristically exhibit elevated rock compressibilities, often 10 to 50 times greater than normal. Rock compressibility is called pore volume (PV), or pore, compressibility and is expressed in units of PV change per unit PV per unit pressure change. Rock compressibility is a function of pressure. Normal compressibilities range from 3 to 8 × 10–6 psi–1 at pressures greater than approximately 1,000 psia. In contrast, elevated rock compressibilities can reach as high as 150 × 10–6 psi–1 or higher at comparable pressures. [1]\n"
$("#Annotator_textArea").val(text);
}
return self;
}
()
)
|
#!/bin/sh
docker build -f Dockerfile.nmap -t nmap .
MYIP=`ip route get 8.8.8.8 | awk '{print $NF; exit}'`
echo "ip address of my host is $MYIP"
echo "scan my host network with nmap from inside the container (assuming 24bit subnet)"
docker run --rm nmap $MYIP/24
echo "scan gateway ip for default network bridge"
GWIP=`docker network inspect --format='{{(index .IPAM.Config 0).Gateway}}' bridge`
docker run --rm nmap $GWIP
echo "scan gateway ip for newly created network bridge"
NWNAME="bridge-network-for-testing-firewall"
docker network create $NWNAME
GWIP=`docker network inspect --format='{{(index .IPAM.Config 0).Gateway}}' $NWNAME`
docker run --rm --net=$NWNAME nmap $GWIP
docker network rm $NWNAME
|
package com.cgs.kerberos.server;
import java.io.IOException;
import java.net.Socket;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.cgs.kerberos.bean.FirstRequest;
import com.cgs.kerberos.bean.FirstResponse;
import com.cgs.kerberos.exception.KerberosException;
import com.cgs.kerberos.handle.TgtProcessor;
/**
* TGS 请求处理器
*
* @author xumh
*
*/
public class TGTHandler extends BaseHandler implements Runnable {
private static Logger logger = LoggerFactory.getLogger(TGTHandler.class);
private TgtProcessor tgtProcessor;
public void setTgtProcessor(TgtProcessor tgtProcessor) {
this.tgtProcessor = tgtProcessor;
}
public TGTHandler(Socket socket) {
super(socket);
// tgtProcessor=new BaseTgtProcessor();
}
public void run() {
byte[] bytes = new byte[1024 * 10];
try {
ois.read(bytes);
FirstRequest obj = (FirstRequest) serializer.byte2Object(bytes);
String ip=socket.getInetAddress().toString();
obj.setIp(ip);
FirstResponse responseBody = tgtProcessor.check(obj);
writeResponse(responseBody);
} catch (KerberosException e) {
logger.debug(e.getMessage(), e);
writeResponse(e.getMessage());
}catch (IOException e) {
logger.error(e.getMessage(), e);
} finally{
try {
ois.close();
socket.close();
} catch (IOException e) {
logger.error(e.getMessage(),e);
}
}
}
}
|
// Autogenerated from development/elements/position.i
package ideal.development.elements;
import ideal.library.elements.*;
public interface any_position extends any_data, any_reference_equality, any_stringable { }
|
<gh_stars>1-10
// Copyright 2021 99cloud
//
// 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.
const rolePermission = {
project_admin: t('Project Admin'),
project_reader: t('Project Reader'),
project_member: t('Project Member'),
system_admin: t('System Admin'),
system_reader: t('System Reader'),
admin: t('Admin'),
reader: t('Reader'),
member: t('Member'),
};
export default rolePermission;
|
<filename>public/TenantNewView.js
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([["TenantNewView"],{
/***/ "./node_modules/ts-loader/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/EditTenant.vue?vue&type=script&lang=ts&":
/*!***************************************************************************************************************************************************************!*\
!*** ./node_modules/ts-loader??ref--5!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/Views/Tenants/EditTenant.vue?vue&type=script&lang=ts& ***!
\***************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue */ "./node_modules/vue/dist/vue.esm.js");
// import { BEGIN_LOAD } from "../../Store/ActionTypes";
/* harmony default export */ __webpack_exports__["default"] = (vue__WEBPACK_IMPORTED_MODULE_0__["default"].extend({
data: function () {
return {
loading: false,
error: null,
tenant: {
id: null,
first_name: null,
surname: null
}
};
},
created: function () { },
methods: {}
}));
/***/ }),
/***/ "./node_modules/ts-loader/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/NewTenant.vue?vue&type=script&lang=ts&":
/*!**************************************************************************************************************************************************************!*\
!*** ./node_modules/ts-loader??ref--5!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/Views/Tenants/NewTenant.vue?vue&type=script&lang=ts& ***!
\**************************************************************************************************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var vue__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! vue */ "./node_modules/vue/dist/vue.esm.js");
// import tenantsAPI from "../../API/TenantAPI";
/* harmony default export */ __webpack_exports__["default"] = (vue__WEBPACK_IMPORTED_MODULE_0__["default"].extend({
data: function () {
return {
loading: false,
saving: false,
error: null,
saved: false,
tenant: {
first_name: "",
surname: "",
email: "",
landlord_id: -1,
property_id: -1,
lease_id: -1
},
validationErrs: {
first_name: [],
surname: [],
email: []
}
};
},
methods: {
// EditTenant(propName, propVal) {
// if (propName) {
// this.tenant[propName] = propVal;
// }
// },
// async StoreTenant() {
// this.saving = true;
// const response = await tenantsAPI.create(this.tenant);
// console.log(response);
// this.saving = false;
// if (response.status === 201) {
// this.saved = true;
// this.validationErrs = { first_name: [], surname: [], email: [] };
// setTimeout(() => (this.saved = false), 2000); //? Oddly 'this' refers to the vue instance here! Not true elsewhere
// } else if (response.status === 422) {
// this.error = response.data.message;
// this.validationErrs = response.data.errors;
// setTimeout(() => (this.error = null), 4000);
// }
// }
}
}));
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/EditTenant.vue?vue&type=template&id=21a89a8e&":
/*!****************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/Views/Tenants/EditTenant.vue?vue&type=template&id=21a89a8e& ***!
\****************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{ staticClass: "ui segment container p-0-b app-dark-accent-dark" },
[
_c("h1", [_vm._v("Edit Tenant Information")]),
_vm._v(" "),
_c("back-button", { attrs: { "steps-back": -1 } }),
_vm._v(" "),
_c(
"div",
{ staticClass: "ui basic segment" },
[
_c("model-form", {
attrs: {
"entity-name": "Tenant",
entity: _vm.tenant,
saving: _vm.saving,
"validation-errs": _vm.validationErrs
}
})
],
1
),
_vm._v(" "),
_c("sui-alert-loading"),
_vm._v(" "),
_c("sui-alert-saving")
],
1
)
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/NewTenant.vue?vue&type=template&id=7c1620d6&":
/*!***************************************************************************************************************************************************************************************************************!*\
!*** ./node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!./node_modules/vue-loader/lib??vue-loader-options!./resources/js/Views/Tenants/NewTenant.vue?vue&type=template&id=7c1620d6& ***!
\***************************************************************************************************************************************************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "render", function() { return render; });
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return staticRenderFns; });
var render = function() {
var _vm = this
var _h = _vm.$createElement
var _c = _vm._self._c || _h
return _c(
"div",
{ staticClass: "ui segment container p-0-b app-dark-accent-dark" },
[
_c("header-back-button", [_vm._v("New Tenant")]),
_vm._v(" "),
_c(
"div",
{ staticClass: "ui basic segment" },
[
_c("model-form", {
attrs: {
"new-entity": "",
"entity-name": "Tenant",
entity: _vm.tenant,
saving: _vm.saving,
"validation-errs": _vm.validationErrs
}
})
],
1
),
_vm._v(" "),
_c("sui-alert-saving")
],
1
)
}
var staticRenderFns = []
render._withStripped = true
/***/ }),
/***/ "./resources/js/Views/Tenants/EditTenant.vue":
/*!***************************************************!*\
!*** ./resources/js/Views/Tenants/EditTenant.vue ***!
\***************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _EditTenant_vue_vue_type_template_id_21a89a8e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./EditTenant.vue?vue&type=template&id=21a89a8e& */ "./resources/js/Views/Tenants/EditTenant.vue?vue&type=template&id=21a89a8e&");
/* harmony import */ var _EditTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./EditTenant.vue?vue&type=script&lang=ts& */ "./resources/js/Views/Tenants/EditTenant.vue?vue&type=script&lang=ts&");
/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])(
_EditTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_1__["default"],
_EditTenant_vue_vue_type_template_id_21a89a8e___WEBPACK_IMPORTED_MODULE_0__["render"],
_EditTenant_vue_vue_type_template_id_21a89a8e___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/Views/Tenants/EditTenant.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/Views/Tenants/EditTenant.vue?vue&type=script&lang=ts&":
/*!****************************************************************************!*\
!*** ./resources/js/Views/Tenants/EditTenant.vue?vue&type=script&lang=ts& ***!
\****************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_ts_loader_index_js_ref_5_node_modules_vue_loader_lib_index_js_vue_loader_options_EditTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/ts-loader??ref--5!../../../../node_modules/vue-loader/lib??vue-loader-options!./EditTenant.vue?vue&type=script&lang=ts& */ "./node_modules/ts-loader/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/EditTenant.vue?vue&type=script&lang=ts&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_ts_loader_index_js_ref_5_node_modules_vue_loader_lib_index_js_vue_loader_options_EditTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/Views/Tenants/EditTenant.vue?vue&type=template&id=21a89a8e&":
/*!**********************************************************************************!*\
!*** ./resources/js/Views/Tenants/EditTenant.vue?vue&type=template&id=21a89a8e& ***!
\**********************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_EditTenant_vue_vue_type_template_id_21a89a8e___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./EditTenant.vue?vue&type=template&id=21a89a8e& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/EditTenant.vue?vue&type=template&id=21a89a8e&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_EditTenant_vue_vue_type_template_id_21a89a8e___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_EditTenant_vue_vue_type_template_id_21a89a8e___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ }),
/***/ "./resources/js/Views/Tenants/NewTenant.vue":
/*!**************************************************!*\
!*** ./resources/js/Views/Tenants/NewTenant.vue ***!
\**************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _NewTenant_vue_vue_type_template_id_7c1620d6___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./NewTenant.vue?vue&type=template&id=7c1620d6& */ "./resources/js/Views/Tenants/NewTenant.vue?vue&type=template&id=7c1620d6&");
/* harmony import */ var _NewTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! ./NewTenant.vue?vue&type=script&lang=ts& */ "./resources/js/Views/Tenants/NewTenant.vue?vue&type=script&lang=ts&");
/* empty/unused harmony star reexport *//* harmony import */ var _node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! ../../../../node_modules/vue-loader/lib/runtime/componentNormalizer.js */ "./node_modules/vue-loader/lib/runtime/componentNormalizer.js");
/* normalize component */
var component = Object(_node_modules_vue_loader_lib_runtime_componentNormalizer_js__WEBPACK_IMPORTED_MODULE_2__["default"])(
_NewTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_1__["default"],
_NewTenant_vue_vue_type_template_id_7c1620d6___WEBPACK_IMPORTED_MODULE_0__["render"],
_NewTenant_vue_vue_type_template_id_7c1620d6___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"],
false,
null,
null,
null
)
/* hot reload */
if (false) { var api; }
component.options.__file = "resources/js/Views/Tenants/NewTenant.vue"
/* harmony default export */ __webpack_exports__["default"] = (component.exports);
/***/ }),
/***/ "./resources/js/Views/Tenants/NewTenant.vue?vue&type=script&lang=ts&":
/*!***************************************************************************!*\
!*** ./resources/js/Views/Tenants/NewTenant.vue?vue&type=script&lang=ts& ***!
\***************************************************************************/
/*! exports provided: default */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_ts_loader_index_js_ref_5_node_modules_vue_loader_lib_index_js_vue_loader_options_NewTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/ts-loader??ref--5!../../../../node_modules/vue-loader/lib??vue-loader-options!./NewTenant.vue?vue&type=script&lang=ts& */ "./node_modules/ts-loader/index.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/NewTenant.vue?vue&type=script&lang=ts&");
/* empty/unused harmony star reexport */ /* harmony default export */ __webpack_exports__["default"] = (_node_modules_ts_loader_index_js_ref_5_node_modules_vue_loader_lib_index_js_vue_loader_options_NewTenant_vue_vue_type_script_lang_ts___WEBPACK_IMPORTED_MODULE_0__["default"]);
/***/ }),
/***/ "./resources/js/Views/Tenants/NewTenant.vue?vue&type=template&id=7c1620d6&":
/*!*********************************************************************************!*\
!*** ./resources/js/Views/Tenants/NewTenant.vue?vue&type=template&id=7c1620d6& ***!
\*********************************************************************************/
/*! exports provided: render, staticRenderFns */
/***/ (function(module, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_NewTenant_vue_vue_type_template_id_7c1620d6___WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! -!../../../../node_modules/vue-loader/lib/loaders/templateLoader.js??vue-loader-options!../../../../node_modules/vue-loader/lib??vue-loader-options!./NewTenant.vue?vue&type=template&id=7c1620d6& */ "./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/vue-loader/lib/index.js?!./resources/js/Views/Tenants/NewTenant.vue?vue&type=template&id=7c1620d6&");
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "render", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_NewTenant_vue_vue_type_template_id_7c1620d6___WEBPACK_IMPORTED_MODULE_0__["render"]; });
/* harmony reexport (safe) */ __webpack_require__.d(__webpack_exports__, "staticRenderFns", function() { return _node_modules_vue_loader_lib_loaders_templateLoader_js_vue_loader_options_node_modules_vue_loader_lib_index_js_vue_loader_options_NewTenant_vue_vue_type_template_id_7c1620d6___WEBPACK_IMPORTED_MODULE_0__["staticRenderFns"]; });
/***/ })
}]);
//# sourceMappingURL=TenantNewView.js.map
|
# CREATE_INDEX
st2 run -d elasticsearch.indices.create_index name=orange-55 extra_settings='{ "settings" : {"number_of_shards" : 3, "number_of_replicas": 0}, "mappings": {"type1": {"properties": { "field1": {"type": "string", "index": "not_analyzed"}}}}}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
st2 run -d elasticsearch.indices.create_index name=apple-14 extra_settings='{ "settings" : {"number_of_shards" : 1, "number_of_replicas": 0}, "mappings": {"type1": {"properties": { "field1": {"type": "string", "index": "not_analyzed"}}}}}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# ALIAS
st2 run -d elasticsearch.indices.alias name='apple' extra_settings='{}' add='{"filtertype": "pattern", "kind": "prefix", "value": "apple-14"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# ALLOCATION
st2 run -d elasticsearch.indices.allocation key=tag | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# CLOSE
st2 run -d elasticsearch.indices.close filters='{"filtertype": "pattern", "kind": "prefix", "value": "app"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# SHOW
st2 run -d elasticsearch.indices.show dry_run=true | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# OPEN
st2 run -d elasticsearch.indices.open filters='{"filtertype": "opened"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# SHOW
st2 run -d elasticsearch.indices.show dry_run=true | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# FORCEMERGE
st2 run -d elasticsearch.indices.forcemerge max_num_segments=1 filters='{"filtertype": "pattern", "kind": "prefix", "value": "apple-14"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# INDEX_SETTINGS
st2 run -d elasticsearch.indices.index_settings index_settings='{"index": {"refresh_interval": "5s"}}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# REINDEX
st2 run -d elasticsearch.indices.reindex request_body='{"source": {"index": ["index1", "index2", "index3"]}, "dest": {"index": "apple-14"}}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# REPLICAS
st2 run -d elasticsearch.indices.replicas count=3 filters='{"filtertype": "pattern", "kind": "suffix", "value": "14"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# ROLLOVER
st2 run -d elasticsearch.indices.rollover name='apple' conditions='{"max_age": "1d"}'
# SHOW
st2 run -d elasticsearch.indices.show | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# SHRINK
# st2 run -d elasticsearch.indices.shrink filters='{"filtertype": "pattern", "kind": "prefix", "value": "orange"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# SNAPSHOT
# st2 run -d elasticsearch.indices.snapshot | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
# DELETE_INDICES
st2 run -d elasticsearch.indices.delete_indices filters='{"filtertype": "pattern", "kind": "prefix", "value": "app"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
st2 run -d elasticsearch.indices.delete_indices filters='{"filtertype": "pattern", "kind": "prefix", "value": "ora"}' | sed -e 's/\\n/\n/g' | sed -e 's/\\"/"/g'
|
import React, { useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { detailsUniversity } from '../../actions/universities/universitiesActions';
import { Link } from 'react-router-dom';
import Box from '@material-ui/core/Box';
import Typography from '@material-ui/core/Typography';
import StarBorderIcon from '@material-ui/icons/StarBorder';
import Rating from '@material-ui/lab/Rating';
import Footer from '../../common/Footer';
import './UniversityDetails.css';
const UniversityDetails = ({ match }) => {
const dispatch = useDispatch();
const universityDetails = useSelector(state => state.universityDetails);
const { loading, message, error, university } = universityDetails;
useEffect(() => {
dispatch(detailsUniversity(match.params.id));
}, [ dispatch, match ]);
return (
<>
<div className='header-wrapper'>
<Link to="/" style={{ textDecoration: 'none', fontSize: '20px', color: 'grey' }}>
Go Back to Universities
</Link>
{
loading ?
(<h1>Loading...</h1>)
:
error ?
(<h1>{error}!</h1>)
:
<div>
<h1 className='header font-weight-light display-1 text-center'>{ university && university.name }</h1>
<p className=''>Website: { university && university.website }</p>
<p className=''>Location: { university && university.location }</p>
<p className=''>School fees: $ 1{ university && university.fees } per annum</p>
<div>
<Box component="fieldset" mb={3} borderColor="transparent">
<Typography component="legend">Ratings</Typography>
<Rating
name="customized-empty"
defaultValue={3}
precision={0.5}
emptyIcon={<StarBorderIcon fontSize="inherit" />}
/>
</Box>
</div>
</div>
}
</div>
<Footer />
</>
)
}
export default UniversityDetails;
|
import React from 'react';
import ReactDOM from 'react-dom';
import s from './join.module.css'
import PostJoin from '../../API/PostJoin';
const joinTask = async (e,{hide,ob})=>{
e.preventDefault();
const json = await PostJoin(ob)
console.log(json)
if(json.status){
alert("Đăng kí tham gia thành công. "+ ob.name +
" sẽ liên hệ với bạn trong thời gian sớm nhất!")
}else{
alert("Không đăng kí được")
}
hide()
}
const Modal = ({ isShowing, hide, ob }) => isShowing ? ReactDOM.createPortal(
<React.Fragment>
<div className={s.modal_overlay}/>
<div className={s.modal_wrapper} aria-modal aria-hidden tabIndex={-1} role="dialog">
<div className={s.modal}>
<div className={s.top}>
Bạn muốn hỗ trợ: {ob.name} – Nội dung: {ob.content} – $ {ob.benefit} VNĐ
</div>
<div className={s.down}>
<div className={s.left}>
<button className={s.button_default} onClick={(e)=>{joinTask(e,{hide,ob})}}>Tham gia</button>
</div>
<div className={s.right}>
<button className={s.button_default} onClick={hide}>Đóng</button>
</div>
</div>
</div>
</div>
</React.Fragment>, document.body
) : null;
export default Modal;
|
TERMUX_PKG_HOMEPAGE=https://lxqt.github.io
TERMUX_PKG_DESCRIPTION="LXQt dialog showing information about LXQt and the system"
TERMUX_PKG_LICENSE="LGPL-2.1"
TERMUX_PKG_MAINTAINER="Simeon Huang <symeon@librehat.com>"
TERMUX_PKG_VERSION=0.17.0
TERMUX_PKG_REVISION=2
TERMUX_PKG_SRCURL="https://github.com/lxqt/lxqt-about/releases/download/${TERMUX_PKG_VERSION}/lxqt-about-${TERMUX_PKG_VERSION}.tar.xz"
TERMUX_PKG_SHA256=f5033a4eb339f64de5b0eea32ee9178ab06aad6b60fd428fc196add785c33113
TERMUX_PKG_DEPENDS="qt5-qtbase, liblxqt"
TERMUX_PKG_BUILD_DEPENDS="lxqt-build-tools, qt5-qtbase-cross-tools"
|
#!/bin/bash
# Stop container related functions
# Not exported functions
stop_container() {
status_container
if [ $? == 1 ]; then
echo "Stopping container ${CONTAINER_NAME}. This can take a few seconds"
docker stop ${CONTAINER_NAME}
fi
}
stop_container_help() {
echo "$(basename "$0") container stop"
echo
echo "This command stops the current container if its running."
echo
}
# End of not exported functions
# Exported functions
prepare_stop_container() {
case $1 in
"")
stop_container
;;
*|-h|--help)
stop_container_help
;;
esac
}
export -f prepare_stop_container
# End of exported functions
|
<reponame>edubossa/-spring-cloud-gcp-guestbook<gh_stars>1-10
package com.example.frontend;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import java.util.HashMap;
import java.util.Map;
@RefreshScope //curl -XPOST http://localhost:8080/actuator/refresh
@Controller
@SessionAttributes("name")
public class FrontendController {
@Autowired
private GuestbookMessagesClient client;
@Value("${greeting:Hello}")
private String greeting;
private static Logger log = LoggerFactory.getLogger(FrontendController.class);
@GetMapping("/")
public String index(Model model) {
log.info("Method index called ");
if (model.containsAttribute("name")) {
String name = (String) model.asMap().get("name");
model.addAttribute("greeting", String.format("%s %s", greeting, name));
log.info("greeting param --> " + this.greeting);
}
model.addAttribute("messages", client.getMessages());
return "index";
}
@PostMapping("/post")
public String post(@RequestParam String name, @RequestParam String message, Model model) {
log.info("adding new post now");
model.addAttribute("name", name);
if (message != null && !message.trim().isEmpty()) {
// Post the message to the backend service
Map<String, String> payload = new HashMap<>();
payload.put("name", name);
payload.put("message", message);
GuestbookMessage messageResponse = client.add(GuestbookMessage.builder().name(name).message(message).build());
log.info("Payload received --> " + messageResponse.toString());
}
return "redirect:/";
}
}
|
package ninjananas.mc.ColorfulNames;
import org.bukkit.ChatColor;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class Plugin extends JavaPlugin {
private static final ChatColor [] allColors = {
ChatColor.AQUA,
ChatColor.BLACK,
ChatColor.BLUE,
ChatColor.DARK_AQUA,
ChatColor.DARK_BLUE,
ChatColor.DARK_GRAY,
ChatColor.DARK_GREEN,
ChatColor.DARK_PURPLE,
ChatColor.DARK_RED,
ChatColor.GOLD,
ChatColor.GRAY,
ChatColor.GREEN,
ChatColor.LIGHT_PURPLE,
ChatColor.RED,
ChatColor.WHITE,
ChatColor.YELLOW,
};
@Override
public void onEnable() {
this.saveDefaultConfig();
this.getCommand("changenamecolor").setExecutor(new ChangeNameColorCommand(this));
this.getServer().getPluginManager().registerEvents(new PlayerJoinListener(this), this);
}
@Override
public void onDisable() {
}
public static void refreshPlayerColor(Player player, String color) {
String newName = "" + color + player.getName() + ChatColor.RESET;
player.setDisplayName(newName);
player.setPlayerListName(newName);
}
public static void refreshPlayerColor(Player player, ChatColor color) {
String newName = "" + color + player.getName() + ChatColor.RESET;
player.setDisplayName(newName);
player.setPlayerListName(newName);
}
public void refreshPlayerColorFromConfig(Player player) {
String color = this.getConfig().getString("name_colors." + player.getUniqueId());
if (color != null) {
Plugin.refreshPlayerColor(player, color);
} else if (this.getConfig().getBoolean("autocolor")) {
ChatColor chatColor = Plugin.allColors[Math.abs(player.getUniqueId().hashCode()) % Plugin.allColors.length];
Plugin.refreshPlayerColor(player, chatColor);
}
}
}
|
def long_words(sentence):
words = sentence.split(' ')
long_words = []
for word in words:
if len(word) > 5:
long_words.append(word)
return long_words
|
<reponame>alexandresantosm/clean-cache-control
export * from "./save-purchases";
export * from "./load-purchases";
|
<reponame>Mdamman/APP_MakeTheChange<gh_stars>0
import { EventEmitter, ElementRef, QueryList, AfterContentInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';
import { VgApiService } from '../../services/vg-api/vg-api.service';
import { VgFullscreenApiService } from '../../services/vg-fullscreen-api/vg-fullscreen-api.service';
import { VgControlsHiddenService } from '../../services/vg-controls-hidden/vg-controls-hidden.service';
import { VgMediaDirective } from '../../directives/vg-media/vg-media.directive';
import * as ɵngcc0 from '@angular/core';
export declare class VgPlayerComponent implements AfterContentInit, OnDestroy {
api: VgApiService;
fsAPI: VgFullscreenApiService;
private controlsHidden;
elem: HTMLElement;
isFullscreen: boolean;
isNativeFullscreen: boolean;
areControlsHidden: boolean;
zIndex: string;
onPlayerReady: EventEmitter<VgApiService>;
onMediaReady: EventEmitter<any>;
medias: QueryList<VgMediaDirective>;
subscriptions: Subscription[];
constructor(ref: ElementRef, api: VgApiService, fsAPI: VgFullscreenApiService, controlsHidden: VgControlsHiddenService);
ngAfterContentInit(): void;
onChangeFullscreen(fsState: boolean): void;
onHideControls(hidden: boolean): void;
ngOnDestroy(): void;
static ɵfac: ɵngcc0.ɵɵFactoryDeclaration<VgPlayerComponent, never>;
static ɵcmp: ɵngcc0.ɵɵComponentDeclaration<VgPlayerComponent, "vg-player", never, {}, { "onPlayerReady": "onPlayerReady"; "onMediaReady": "onMediaReady"; }, ["medias"], ["*"]>;
}
//# sourceMappingURL=vg-player.component.d.ts.map
|
#!/bin/bash -e
# stconfig.sh
# Author:
# Alex Soto <alexsoto@microsoft.com>
#
# Swift Toolchain Config vars
# If SOM_PATH is set it means we will use a custom build
# of the swift toolchain like the one produced by Pack-Man.
SCRIPT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
if [[ ! -z "${SOM_PATH}" ]] ; then
SWIFTBIN="${SOM_PATH}/bin/swift/bin"
SWIFTLIB="${SOM_PATH}/bin/swift/lib/swift"
SWIFTC="${SOM_PATH}/bin/swift/bin/swiftc"
SWIFTGLUEPREFIX="${SOM_PATH}/lib/SwiftInterop/"
SWIFTGLUESUFFIX="/XamGlue.framework"
SWIFTBINDINGS="${SOM_PATH}/bindings"
TOMSWIFTY="${SOM_PATH}/lib/binding-tools-for-swift/tom-swifty.exe"
else
SWIFTBIN="$SCRIPT_DIR/apple/build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin"
SWIFTLIB="$SCRIPT_DIR/apple/build/Ninja-ReleaseAssert/swift-macosx-x86_64/lib/swift"
SWIFTC="$SCRIPT_DIR/apple/build/Ninja-ReleaseAssert/swift-macosx-x86_64/bin/swiftc"
SWIFTGLUE="${PLATFORM}"
SWIFTGLUEPREFIX="$SCRIPT_DIR/swiftglue/bin/Debug/"
SWIFTGLUESUFFIX="/FinalProduct/XamGlue.framework"
SWIFTBINDINGS="$SCRIPT_DIR/bindings"
TOMSWIFTY="$SCRIPT_DIR/tom-swifty/bin/Debug/tom-swifty.exe"
fi
# Returns the absolute path of the input path.
# The returned path may contain symlinks.
abspath ()
{
if test -z "$1"; then
echo "abspath: Usage: abspath <path>"
exit 1
elif test -n "${2:-}"; then
echo "abspath: Only one argument, got at least two: $*"
exit 1
fi
if [ "$1" == "/" ]; then
echo "/"
exit 0
fi
local input
input="$1"
if [ "${input:0:1}" != "/" ]; then
# relative path, make it absolute
input=$(pwd)/$input
fi
local trailingslash
if [ "${input:-1}" == "/" ]; then
trailingslash="/"
fi
# split the input path into its components
IFS='/' read -r -a elements <<< "$input"
local rebuild=1
while [ "$rebuild" == "1" ]; do
rebuild=
# remove any empty entries (can happen if there are multiple path separators simultaneously, such as /foo//bar)
# this will also remove trailing slashes.
local elements2
for i in "${!elements[@]}"; do
elements2+=( "${elements[i]}" )
done
elements=("${elements2[@]}")
unset elements2
arraylength=${#elements[@]}
for (( i=1; i<arraylength+1; i++ )); do
# resolve . (remove current path component) and .. (remove current and previous (if it exists) path components).
if [ "${elements[$i]:-}" == "." ]; then
unset "elements[$i]"
elif [ "${elements[$i]:-}" == ".." ]; then
unset "elements[$i]"
if [ "$i" -gt "1" ]; then
# remove previous component as well
unset "elements[$((i-1))]"
fi
rebuild=1
break
fi
done
done
# create the return value
local path=""
for i in "${elements[@]}"; do
local element=$i
if test -n "$element"; then
path="$path/$element"
fi
done
path+="$trailingslash"
echo "$path"
#echo "ABSPATH ($1) => $path" >&2
return 0
}
# Make any paths absolute paths.
SWIFTBIN=$(abspath "$SWIFTBIN")
SWIFTLIB=$(abspath "$SWIFTLIB")
SWIFTC=$(abspath "$SWIFTC")
SWIFTGLUEPREFIX=$(abspath "$SWIFTGLUEPREFIX")/
SWIFTBINDINGS=$(abspath "$SWIFTBINDINGS")
TOMSWIFTY=$(abspath "$TOMSWIFTY")
# Write the output to a makefile fragment
FRAGMENT="$SCRIPT_DIR/stconfig.inc"
{
echo "# This file is generated from stconfig.sh"
echo "SWIFTBIN=$SWIFTBIN"
echo "SWIFTLIB=$SWIFTLIB"
echo "SWIFTC=$SWIFTC"
echo "SWIFTGLUE=$SWIFTGLUE"
echo "SWIFTGLUEPREFIX=$SWIFTGLUEPREFIX"
echo "SWIFTGLUESUFFIX=$SWIFTGLUESUFFIX"
echo "SWIFTBINDINGS=$SWIFTBINDINGS"
echo "TOMSWIFTY=$TOMSWIFTY"
} > "$FRAGMENT"
|
<filename>app/src/main/java/edu/hzuapps/androidlabs/homeworks/net1414080903220/knowdev/fragment/news/MobileFragment.java
package edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.fragment.news;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.squareup.okhttp.Response;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.R;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.activity.NewsDetailActivity1414080903220;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.adapter.KnowRecyclerView;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.adapter.NewsAdapter;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.bean.News;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.bean.NewsBaseBean;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.config.KnowAPIManager;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.net.OkHttpHelper;
import edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.net.ResponseCallback;
/**
* ProjectName: knowdev
* PackName:edu.hzuapps.androidlabs.homeworks.net1414080903220.knowdev.fragment
* Class describe:
* Author: cheng
* Create time: 2017/6/3 20:53
*/
public class MobileFragment extends Fragment {
private static final String TAG="MobileFragment";
NewsAdapter newsAdapter;
List<News> newlist;
View view;
OkHttpHelper okHttpHelper= OkHttpHelper.getOkInstance();
MaterialRefreshLayout materialRefreshLayout;
private static final int STATE_NORMAL=0;
private static final int STATE_REFREH=1;
private static final int STATE_MORE=2;
private int state=STATE_NORMAL;
Map<String,String> params=new LinkedHashMap<>();
private String num="10";
private KnowRecyclerView newsItemRV;
private View mEmptyView;
Button refreshBt;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view=inflater.inflate(R.layout.fragment_net1414080903220_newslist,container,false);
// newsItemRV= (RecyclerView) view.findViewById(R.id.recyclerview_news);
materialRefreshLayout= (MaterialRefreshLayout) view.findViewById(R.id.refresh);
initRefreshLayout();
initEmptyView(view);
requestData();
return view;
}
private void initEmptyView(View view) {
newsItemRV = (KnowRecyclerView) view.findViewById(R.id.emptyRecyclerView);
mEmptyView = view.findViewById(R.id.empty_bt);
refreshBt = (Button) view.findViewById(R.id.empty_bt);
refreshBt.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
refreshData();
}
});
}
private void initRefreshLayout() {
materialRefreshLayout.setLoadMore(true);
materialRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
@Override
public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
refreshData();
}
@Override
public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
//上拉刷新...
loadMoreData();
}
});
}
private void refreshData(){
state=STATE_REFREH;
requestData();
}
private void loadMoreData() {
state=STATE_MORE;
int n=Integer.parseInt(num);
n=n+10;
num=String.valueOf(n);
requestData();
}
public void requestData(){
Map<String,String> params=new LinkedHashMap<>();
params.put("key", KnowAPIManager.KEY);
params.put("num",num);
Log.i(TAG,""+params);
okHttpHelper.get(KnowAPIManager.TIANXIN,KnowAPIManager.API.TX_MOBILE_URL,params, new ResponseCallback<NewsBaseBean>(getContext()){
@Override
public void onSuccess(Response response, NewsBaseBean newsBaseBean) {
Log.i(TAG,"cy success:"+newsBaseBean);
newlist=newsBaseBean.getNewslist();
//Log.i(TAG,"list:"+newlist);
initData(newlist);
}
@Override
public void onError(Response response, int code, Exception e) {
Log.i(TAG,"error");
e.printStackTrace();
}
});
}
/**
*
* @param newses
*/
private void initData(List<News>newses) {
switch (state) {
case STATE_NORMAL:
if (newsAdapter == null) {
newsAdapter = new NewsAdapter(newses, getActivity());
newsItemRV.setAdapter(newsAdapter);
newsItemRV.setEmptyView(mEmptyView); //设置空布局
newsItemRV.setLayoutManager(new LinearLayoutManager(MobileFragment.this.getActivity()));
} else {
newsAdapter.clearData();
newsAdapter.addData(newses);
}
break;
case STATE_REFREH:
if (newsAdapter == null) {
newsAdapter = new NewsAdapter(newses, getActivity());
newsItemRV.setAdapter(newsAdapter);
newsItemRV.setLayoutManager(new LinearLayoutManager(MobileFragment.this.getActivity()));
}else {
if(newsAdapter.getAllData()!=null&&newsAdapter.getAllData().size()>0){
newsAdapter.clearData();
Log.i(TAG,"clear data");
}
newsAdapter.addData(newses);
newsItemRV.scrollToPosition(0);
materialRefreshLayout.finishRefresh();
}
break;
case STATE_MORE:
int oldSize=newsAdapter.getAllData().size();
newsAdapter.clearData();
newsAdapter.addData(newses);
newsItemRV.scrollToPosition(oldSize);
materialRefreshLayout.finishRefreshLoadMore();
break;
}
newsAdapter.setOnNewsTypeClickListener(new NewsAdapter.OnNewsTypeClickListener() {
@Override
public void onClick(View view, News news) {
//Log.i(TAG,url);
Intent intent = new Intent(getActivity(), NewsDetailActivity1414080903220.class);
intent.putExtra(KnowAPIManager.NEW_ID, news);
startActivity(intent);
}
});
}
}
|
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class GreetingController {
@RequestMapping("/greet")
public String greet(@RequestParam(value="name", default="world") String name) {
String greeting = "Hello " + name + "! Welcome!";
return "{\"greeting\":\"" + greeting + "\"}";
}
}
|
###############################################################################
# Copyright 2016 Cory Bennett
#
# 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.
###############################################################################
: ${OSHT_MKTEMP=mktemp -t osht.XXXXXX}
: ${OSHT_ABORT=}
: ${OSHT_DIFF=diff -u}
: ${OSHT_JUNIT=}
: ${OSHT_JUNIT_OUTPUT="$(cd "$(dirname "$0")"; pwd)/$(basename "$0")-tests.xml"}
: ${OSHT_STDOUT=$($OSHT_MKTEMP)}
: ${OSHT_STDERR=$($OSHT_MKTEMP)}
: ${OSHT_STDIO=$($OSHT_MKTEMP)}
: ${OSHT_VERBOSE=}
: ${OSHT_WATCH=}
: ${_OSHT_CURRENT_TEST_FILE=$($OSHT_MKTEMP)}
: ${_OSHT_CURRENT_TEST=0}
: ${_OSHT_DEPTH=2}
: ${_OSHT_RUNNER=$($OSHT_MKTEMP)}
: ${_OSHT_DIFFOUT=$($OSHT_MKTEMP)}
: ${_OSHT_FAILED_FILE=$($OSHT_MKTEMP)}
: ${_OSHT_INITPATH=$(pwd)}
: ${_OSHT_JUNIT=$($OSHT_MKTEMP)}
: ${_OSHT_LAPSE=}
: ${_OSHT_PLANNED_TESTS=}
: ${_OSHT_SKIP=}
: ${_OSHT_START=}
: ${_OSHT_TESTING=}
: ${_OSHT_TODO=}
export OSHT_VERSION=1.0.0
declare -a _OSHT_ARGS
function _osht_usage {
[ -n "${1:-}" ] && echo -e "Error: $1\n" >&2
cat <<EOF
Usage: $(basename $0) [--output <junit-output-file>] [--junit] [--verbose] [--abort]
Options:
-a|--abort On the first error abort the test execution
-h|--help This help message
-j|--junit Enable JUnit xml writing
-o|--output=<file> Location to write JUnit xml file [default: $OSHT_JUNIT_OUTPUT]
-v|--verbose Print extra output for debugging tests
-w|--watch Print output to stdout to allow watching progress on long-running tests
EOF
exit 0
}
while true; do
[[ $# == 0 ]] && break
case $1 in
-a | --abort) OSHT_ABORT=1; shift;;
-h | --help) _osht_usage;;
-j | --junit) OSHT_JUNIT=1; shift ;;
-o | --output) OSHT_JUNIT_OUTPUT=$2; shift 2 ;;
-v | --verbose) OSHT_VERBOSE=1; shift ;;
-w | --watch) OSHT_WATCH=1; shift ;;
-- ) shift; break ;;
-* ) (_osht_usage "Invalid argument $1") >&2 && exit 1;;
* ) break ;;
esac
done
function _osht_cleanup {
local rv=$?
if [ -z "$_OSHT_PLANNED_TESTS" ]; then
_OSHT_PLANNED_TESTS=$_OSHT_CURRENT_TEST
echo "1..$_OSHT_PLANNED_TESTS"
fi
if [[ -n $OSHT_JUNIT ]]; then
_osht_init_junit > $OSHT_JUNIT_OUTPUT
cat $_OSHT_JUNIT >> $OSHT_JUNIT_OUTPUT
_osht_end_junit >> $OSHT_JUNIT_OUTPUT
fi
local failed=$(_osht_failed)
rm -f $OSHT_STDOUT $OSHT_STDERR $OSHT_STDIO $_OSHT_CURRENT_TEST_FILE $_OSHT_JUNIT $_OSHT_FAILED_FILE $_OSHT_DIFFOUT $_OSHT_RUNNER
if [[ $_OSHT_PLANNED_TESTS != $_OSHT_CURRENT_TEST ]]; then
echo "Looks like you planned $_OSHT_PLANNED_TESTS tests but ran $_OSHT_CURRENT_TEST." >&2
rv=255
fi
if [[ $failed > 0 ]]; then
echo "Looks like you failed $failed test of $_OSHT_CURRENT_TEST." >&2
rv=$failed
fi
exit $rv
}
trap _osht_cleanup INT TERM EXIT
function _osht_xmlencode {
sed -e 's/\&/\&/g' -e 's/\"/\"/g' -e 's/</\</g' -e 's/>/\>/g' -e "s/'//g" # -e "s/'/\'/g"
}
function _osht_strip_terminal_escape {
sed -e $'s/\x1B\[[0-9]*;[0-9]*[m|K|G|A]//g' -e $'s/\x1B\[[0-9]*[m|K|G|A]//g'
}
function _osht_timestamp {
if [ -n "$_OSHT_TESTING" ]; then
echo "2016-01-01T08:00:00"
else
date "+%Y-%m-%dT%H:%M:%S"
fi
}
function _osht_init_junit {
cat <<EOF
<?xml version="1.0" encoding="UTF-8"?>
<testsuites failures="$(_osht_failed)" name="$0" tests="$_OSHT_PLANNED_TESTS" time="$SECONDS" timestamp="$(_osht_timestamp)" >
EOF
}
function _osht_add_junit {
if [[ -z $OSHT_JUNIT ]]; then
return
fi
failure=
if [[ $# != 0 ]]; then
failure="<failure message=\"test failed\"><![CDATA[$(_osht_debugmsg | _osht_strip_terminal_escape)]]></failure>
"
fi
local stdout=$(cat $OSHT_STDOUT | _osht_strip_terminal_escape)
local stderr=$(cat $OSHT_STDERR | _osht_strip_terminal_escape)
local _OSHT_DEPTH=$(($_OSHT_DEPTH+1))
cat <<EOF >> $_OSHT_JUNIT
<testcase classname="$(_osht_source)" name="$(printf "%03i" $_OSHT_CURRENT_TEST) - $(_osht_get_line | _osht_xmlencode)" time="$_OSHT_LAPSE" timestamp="$(_osht_timestamp)">
$failure<system-err><![CDATA[$stderr]]></system-err>
<system-out><![CDATA[$stdout]]></system-out>
</testcase>
EOF
}
function _osht_end_junit {
cat <<EOF
</testsuites>
EOF
}
function _osht_source {
local parts=($(caller $_OSHT_DEPTH))
local fn=$(basename ${parts[2]})
echo ${fn%.*}
}
function _osht_get_line {
local parts=($(caller $_OSHT_DEPTH))
(cd $_OSHT_INITPATH && sed "${parts[0]}q;d" ${parts[2]})
}
function _osht_source_file {
local parts=($(caller $_OSHT_DEPTH))
echo "${parts[2]}"
}
function _osht_source_linenum {
local parts=($(caller $_OSHT_DEPTH))
echo "${parts[0]}"
}
function _osht_increment_test {
_OSHT_CURRENT_TEST=$(cat $_OSHT_CURRENT_TEST_FILE)
let _OSHT_CURRENT_TEST=_OSHT_CURRENT_TEST+1
echo $_OSHT_CURRENT_TEST > $_OSHT_CURRENT_TEST_FILE
_osht_start
}
function _osht_increment_failed {
local _FAILED=$(_osht_failed)
let _FAILED=_FAILED+1
echo $_FAILED > $_OSHT_FAILED_FILE
}
function _osht_failed {
[[ -s $_OSHT_FAILED_FILE ]] && cat $_OSHT_FAILED_FILE || echo "0"
}
function _osht_start {
_OSHT_START=$(date +%s)
}
function _osht_stop {
local _now=$(date +%s)
_OSHT_LAPSE=$(($_now - $_OSHT_START))
}
function _osht_ok {
_osht_stop
_osht_debug
echo -n "ok $_OSHT_CURRENT_TEST - $(_osht_get_line)"
if [ -n "$_OSHT_TODO" ]; then
echo " # TODO Test Know to fail"
else
echo
fi
_osht_add_junit
}
function _osht_nok {
_osht_stop
if [ -z "$_OSHT_TODO" ]; then
echo "# ERROR: $(_osht_source_file) at line $(_osht_source_linenum)"
fi
_osht_debug
echo -n "not ok $_OSHT_CURRENT_TEST - $(_osht_get_line)"
if [ -n "$_OSHT_TODO" ]; then
echo " # TODO Test Know to fail"
else
_osht_increment_failed
echo
fi
_osht_add_junit "${_OSHT_ARGS[@]}"
if [ -n "$OSHT_ABORT" ]; then
exit 1
fi
}
function _osht_run {
# reset STDIO files
: >$OSHT_STDOUT
: >$OSHT_STDERR
: >$OSHT_STDIO
cat <<EOF > $_OSHT_RUNNER
#!/bin/bash
set -o monitor
exec 1> >(tee -a -- $OSHT_STDOUT $OSHT_STDIO)
exec 2> >(tee -a -- $OSHT_STDERR $OSHT_STDIO >&2)
function cleanup {
rv=\$?
platform=\$(uname -s)
if [[ \$platform == Darwin ]]; then
PGRP=\$(ps -p \$\$ -o pgid=)
else
PGRP=\$(ps -p \$\$ --no-header -o pgrp)
fi
if [[ \$platform == Darwin ]]; then
PIDS=\$(ps -o pgid=,ppid=,pid=,comm= | awk "\\\$1 == \$PGRP && \\\$4 == \"tee\" {print \\\$2\" \"\\\$3}")
else
PIDS=\$(ps --no-headers -o pgrp,ppid,pid,cmd | awk "\\\$1 == \$PGRP && \\\$4 == \"tee\" {print \\\$2\" \"\\\$3}")
fi
if [[ -n "\$PIDS" ]]; then
kill \$PIDS >/dev/null 2>&1
fi
return \$rv
}
trap cleanup INT TERM EXIT
"\$@"
EOF
chmod 755 $_OSHT_RUNNER
set +e
if [[ -n "$OSHT_WATCH" ]]; then
SEDBUFOPT=-u
if [ $(uname -s) == "Darwin" ]; then
SEDBUFOPT=-l
fi
$_OSHT_RUNNER "$@" 2>&1 | sed $SEDBUFOPT 's/^/# /'
OSHT_STATUS=${PIPESTATUS[0]}
else
$_OSHT_RUNNER "$@" >/dev/null 2>&1
OSHT_STATUS=$?
fi
set -e
}
function _osht_qq {
declare -a out
local p
for p in "$@"; do
out+=($(printf %q "$p"))
done
local IFS=" "
echo -n "${out[*]}"
}
function _osht_debug {
if [[ -n $OSHT_VERBOSE ]]; then
_osht_debugmsg | sed 's/^/# /g'
fi
}
function _osht_debugmsg {
local parts=($(caller $_OSHT_DEPTH))
local op=${parts[1]}
if [[ ${parts[1]} == "TODO" ]]; then
parts=($(caller $(($_OSHT_DEPTH-1))))
op=${parts[1]}
fi
case $op in
IS)
_osht_qq "${_OSHT_ARGS[@]}"; echo;;
ISNT)
_osht_qq \! "${_OSHT_ARGS[@]}"; echo;;
OK)
_osht_qq test "${_OSHT_ARGS[@]}"; echo;;
NOK)
_osht_qq test \! "${_OSHT_ARGS[@]}"; echo;;
NRUNS|RUNS)
echo "RUNNING: $(_osht_qq "${_OSHT_ARGS[@]}")"
echo "STATUS: $OSHT_STATUS"
echo "STDIO <<EOM"
cat $OSHT_STDIO
echo "EOM";;
DIFF|ODIFF|EDIFF)
cat $_OSHT_DIFFOUT;;
GREP|EGREP|OGREP)
_osht_qq grep -q "${_OSHT_ARGS[@]}"; echo;;
NGREP|NEGREP|NOGREP)
_osht_qq \! grep -q "${_OSHT_ARGS[@]}"; echo;;
esac
}
function _osht_args {
_OSHT_ARGS=("$@")
}
function SKIP {
local _OSHT_DEPTH=$(($_OSHT_DEPTH-1))
"$@" && _OSHT_SKIP=$(_osht_get_line)
if [ -n "$_OSHT_SKIP" ]; then
_OSHT_PLANNED_TESTS=0
echo "1..0 # $_OSHT_SKIP"
exit 0
fi
}
function PLAN {
echo "1..$1"
_OSHT_PLANNED_TESTS=$1
}
function IS {
_osht_args "$@"
_osht_increment_test
case "$2" in
=~) [[ $1 =~ $3 ]] && _osht_ok || _osht_nok;;
!=) [[ $1 != $3 ]] && _osht_ok || _osht_nok;;
=|==) [[ $1 == $3 ]] && _osht_ok || _osht_nok;;
*) [ "$1" $2 "$3" ] && _osht_ok || _osht_nok;;
esac
}
function ISNT {
_osht_args "$@"
_osht_increment_test
case "$2" in
=~) [[ ! $1 =~ $3 ]] && _osht_ok || _osht_nok;;
!=) [[ $1 == $3 ]] && _osht_ok || _osht_nok;;
=|==) [[ $1 != $3 ]] && _osht_ok || _osht_nok;;
*) [ ! "$1" $2 "$3" ] && _osht_ok || _osht_nok;;
esac
}
function OK {
_osht_args "$@"
_osht_increment_test
test "$@" && _osht_ok || _osht_nok
}
function NOK {
_osht_args "$@"
_osht_increment_test
test ! "$@" && _osht_ok || _osht_nok
}
function RUNS {
_osht_args "$@"
_osht_increment_test
_osht_run "$@"
[[ $OSHT_STATUS == 0 ]] && _osht_ok || _osht_nok
}
function NRUNS {
_osht_args "$@"
_osht_increment_test
_osht_run "$@"
[[ $OSHT_STATUS != 0 ]] && _osht_ok || _osht_nok
}
function GREP {
_osht_args "$@"
_osht_increment_test
grep -q "$@" $OSHT_STDIO && _osht_ok || _osht_nok
}
function EGREP {
_osht_args "$@"
_osht_increment_test
grep -q "$@" $OSHT_STDERR && _osht_ok || _osht_nok
}
function OGREP {
_osht_args "$@"
_osht_increment_test
grep -q "$@" $OSHT_STDOUT && _osht_ok || _osht_nok
}
function NGREP {
_osht_args "$@"
_osht_increment_test
! grep -q "$@" $OSHT_STDIO && _osht_ok || _osht_nok
}
function NEGREP {
_osht_args "$@"
_osht_increment_test
! grep -q "$@" $OSHT_STDERR && _osht_ok || _osht_nok
}
function NOGREP {
_osht_args "$@"
_osht_increment_test
! grep -q "$@" $OSHT_STDOUT && _osht_ok || _osht_nok
}
function DIFF {
_osht_args $OSHT_DIFF - $OSHT_STDIO
_osht_increment_test
tmpfile=$($OSHT_MKTEMP)
cat - > $tmpfile
$OSHT_DIFF $tmpfile $OSHT_STDIO | tee $_OSHT_DIFFOUT | sed 's/^/# /g'
local status=${PIPESTATUS[0]}
rm $tmpfile
[[ $status == 0 ]] && _osht_ok || _osht_nok
}
function ODIFF {
_osht_args $OSHT_DIFF - $OSHT_STDOUT
_osht_increment_test
tmpfile=$($OSHT_MKTEMP)
cat - > $tmpfile
$OSHT_DIFF $tmpfile $OSHT_STDOUT | tee $_OSHT_DIFFOUT | sed 's/^/# /g'
local status=${PIPESTATUS[0]}
rm $tmpfile
[[ $status == 0 ]] && _osht_ok || _osht_nok
}
function EDIFF {
_osht_args $OSHT_DIFF - $OSHT_STDERR
_osht_increment_test
tmpfile=$($OSHT_MKTEMP)
cat - > $tmpfile
$OSHT_DIFF $tmpfile $OSHT_STDERR | tee $_OSHT_DIFFOUT | sed 's/^/# /g'
local status=${PIPESTATUS[0]}
rm $tmpfile
[[ $status == 0 ]] && _osht_ok || _osht_nok
}
function TODO {
local _OSHT_TODO=1
local _OSHT_DEPTH=$(($_OSHT_DEPTH+1))
"$@"
}
|
<reponame>hieudt7/react-sample
import React from 'react'
import Modal from 'components/Modal'
import Rule from 'components/Rule'
import Top from 'components/Top'
import Chest from 'components/Chest'
import Exchange from 'components/Exchange'
import PigCard from 'components/PigCard'
import { CHEST_INFO } from 'components/common'
import swal from "sweetalert2"
class ZodiacView extends React.Component {
constructor(props) {
super(props)
this.state = {
modal: null,
draw_balance: 0,
zodiac_draw_count: 0,
zodiac_count: 0,
player_drawn_rewards: null,
stage_rewards: null,
chest: null,
chestStatus: null,
zodiac_pig: false,
unique_list: null,
}
}
componentDidMount() {
//define function,js to run
//--get api
this.props.getUserZodiac()
AOS.init({
disable: 'mobile'
});
this.setState({ chest: CHEST_INFO })
}
componentWillReceiveProps(nextProps) {
//check if have value
if (nextProps.zodiac.userZodiacInfo != undefined) {
this.setState({
draw_balance: nextProps.zodiac.userZodiacInfo.draw_balance,
zodiac_draw_count: nextProps.zodiac.userZodiacInfo.zodiac_draw_count,
zodiac_count: nextProps.zodiac.userZodiacInfo.zodiac_count,
player_drawn_rewards: nextProps.zodiac.userZodiacInfo.player_drawn_rewards,
stage_rewards: nextProps.zodiac.userZodiacInfo.stage_rewards
});
}
if (nextProps.zodiac.isShowModal != undefined) {
this.setState({
modal: nextProps.zodiac.isShowModal
});
}
if (nextProps.zodiac.chestStatus != undefined) {
this.setState({
chestStatus: nextProps.zodiac.chestStatus
});
}
if (nextProps.zodiac.userZodiacInfo.unique_list != undefined) {
this.setState({
unique_list: nextProps.zodiac.userZodiacInfo.unique_list
});
}
}
handleViewTop() {
if (!this.props.currentUser.login) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Vui lòng đăng nhập để tham gia sự kiện.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
else if (this.props.currentUser.userInfo.account_id == null) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Bạn vui lòng tạo tài khoản Garena Free Fire để tham gia sự kiện. Tải app tại: <a href="https://ff.garena.vn/">https://ff.garena.vn/</a>.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
this.props.getTop();
}
handleViewChest() {
if (!this.props.currentUser.login) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Vui lòng đăng nhập để tham gia sự kiện.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
else if (this.props.currentUser.userInfo.account_id == null) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Bạn vui lòng tạo tài khoản Garena Free Fire để tham gia sự kiện. Tải app tại: <a href="https://ff.garena.vn/">https://ff.garena.vn/</a>.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
this.props.getChestInfo()
}
handleExchange() {
if (!this.props.currentUser.login) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Vui lòng đăng nhập để tham gia sự kiện.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
else if (this.props.currentUser.userInfo.account_id == null) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Bạn vui lòng tạo tài khoản Garena Free Fire để tham gia sự kiện. Tải app tại: <a href="https://ff.garena.vn/">https://ff.garena.vn/</a>.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
else if (this.state.draw_balance == 0) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Bạn chưa có huy hiệu Tết để Đổi Thẻ</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
this.props.DrawZodiac(1);
}
checkGiftProgress(value, target) {
let classActive = ''
if (target >= value) {
classActive = 'active'
}
return classActive
}
checkUserCard(order, type) {
let ressult = ''
switch (type) {
case 'image':
let cardName = 'item_lock.png';
if (!this.state.player_drawn_rewards || !this.state.player_drawn_rewards == null || !this.state.player_drawn_rewards == undefined) {
return
}
let cardOwner = this.state.player_drawn_rewards.find(item => item[0] === order);
if (cardOwner) {
cardName = 'item_' + order + '.png'
}
ressult = cardName
break;
case 'classBox':
if (!this.state.player_drawn_rewards || !this.state.player_drawn_rewards == null || !this.state.player_drawn_rewards == undefined) {
return
}
let cardOwnerClass = this.state.player_drawn_rewards.find(item => item[0] === order);
if (cardOwnerClass) {
ressult = 'box-open'
}
break;
default:
break;
}
return ressult
}
renderZodiacItem(numberItem, index) {
let zodiacItem = []
for (let i = 1; i <= numberItem; i++) {
if (!this.props.currentUser.login || this.props.currentUser.userInfo.account_id == null) {
zodiacItem.push(
<li key={i}>
<div className='box'>
<img src='https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/item_lock.png' alt="" />
</div>
</li>
)
}
else {
zodiacItem.push(
<li key={i}>
<div className={`box ${this.checkUserCard(i + index, 'classBox')}`}>
<img src={'https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/' + this.checkUserCard(i + index, 'image')} alt="" />
</div>
</li>
)
}
}
return zodiacItem
}
buyChest(price, limited, buyTimes) {
if (limited == buyTimes) {
let chestType = ''
switch (parseInt(price)) {
case 10:
chestType = 'Hòm cấp thường'
break;
case 30:
chestType = 'Hòm cấp cao'
break;
case 100:
chestType = 'Hòm siêu cấp'
break;
default:
break;
}
swal({
title: 'Thông báo',
html: '<p class="pop-content">Bạn đã đạt giới hạn mua ' + chestType + ' ngày hôm nay. Vui lòng quay lại vào ngày mai</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn '
})
return
}
this.props.buyChest(parseInt(price))
}
handleClaimStage(type, stage) {
if (!this.props.currentUser.login) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Vui lòng đăng nhập để tham gia sự kiện.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
else if (this.props.currentUser.userInfo.account_id == null) {
swal({
title: 'Thông báo',
html: '<p class="pop-content">Bạn vui lòng tạo tài khoản Garena Free Fire để tham gia sự kiện. Tải app tại: <a href="https://ff.garena.vn/">https://ff.garena.vn/</a>.</p>',
confirmButtonText: 'Đóng',
animation: false,
customClass: 'custom-modal animated zoomIn'
})
return
}
this.props.claimReward(type, stage)
}
stageClaim(type, stage) {
if (this.state.stage_rewards == null || this.state.stage_rewards == undefined) {
return
}
let status = ''
let statusClass = this.state.stage_rewards.find(item => item[1] === stage);
if (statusClass) {
status = 'claimed'
}
return status
}
render() {
const { modal, draw_balance, zodiac_draw_count, zodiac_count, chest, chestStatus, unique_list } = this.state
let { currentUser, zodiac } = this.props;
return (
<React.Fragment>
<div className="event-content">
<div className="zodiac-content">
<div className="progress-left">
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/zo_logo.png" alt="" className="logo" />
<div className="progress-vertical">
<div className="progress-outline">
<div className="progress-line" style={{ height: zodiac_draw_count * 100 / 120 + '%' }}></div>
</div>
<div className="progress-target">
<a className={`${this.stageClaim('draw', 30)} ${this.checkGiftProgress(30, zodiac_draw_count)}`} href="#" onClick={e => this.handleClaimStage('draw', 30)}>
<span className={`number ${this.checkGiftProgress(30, zodiac_draw_count)}`}>30</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_4.png" alt="" />
</span>
<p>1000 Vàng</p>
</span>
</a>
<a className={`${this.stageClaim('draw', 60)} ${this.checkGiftProgress(60, zodiac_draw_count)}`} href="#" onClick={e => this.handleClaimStage('draw', 60)}>
<span className={`number ${this.checkGiftProgress(60, zodiac_draw_count)}`}>60</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_3.png" alt="" />
</span>
<p>1 Hộp mặt nạ phù thủy</p>
</span>
</a>
<a className={`${this.stageClaim('draw', 90)} ${this.checkGiftProgress(90, zodiac_draw_count)}`} href="#" onClick={e => this.handleClaimStage('draw', 90)}>
<span className={`number ${this.checkGiftProgress(90, zodiac_draw_count)}`}>90</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_2.png" alt="" />
</span>
<p>1 Hộp súng màu hồng</p>
</span>
</a>
<a className={`${this.stageClaim('draw', 120)} ${this.checkGiftProgress(120, zodiac_draw_count)}`} href="#" onClick={e => this.handleClaimStage('draw', 120)}>
<span className={`number ${this.checkGiftProgress(120, zodiac_draw_count)}`}>120</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_1.png" alt="" />
</span>
<p>Lựu Nước hoa nam (vĩnh viễn)</p>
</span>
</a>
</div>
</div>
<div className="progress-name">
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/arrow-up.png" alt="" className="art" />
<div className="box-name">
{zodiac_draw_count}
</div>
<p>huy hiệu <br /> đã đổi</p>
</div>
</div>
<div className="main-content">
<div className="top-menu">
<div className="group-label">
<a href="#" onClick={() => this.setState({ modal: 'rule' })} className="rule">
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/zo_thele.png" alt="" />
</a>
<h1 className="logo-main">
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/title-logo.png" alt="" className="main-logo" />
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/ff-logo-light.png" alt="" className="light ab" />
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/clound-1.png" alt="" className="clound-1 ab" />
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/clound-2.png" alt="" className="clound-2 ab" />
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/clound-3.png" alt="" className="clound-3 ab" />
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/clound-4.png" alt="" className="clound-4 ab" />
</h1>
<span className="count">
<span>{draw_balance}</span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/zo_huyhieu.png" alt="" />
</span>
</div>
</div>
<div className="zod-item">
<div className="row-gift">
<ul>
{this.renderZodiacItem(4, 0)}
</ul>
</div>
<div className="row-gift">
<ul>
{this.renderZodiacItem(4, 4)}
</ul>
</div>
<div className="row-gift">
<ul>
{this.renderZodiacItem(4, 8)}
</ul>
</div>
</div>
<div className="foot-menu text-center">
<div>
<a className="btn_xephang" href="#" onClick={e => this.handleViewTop(e)}><img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/btn_xephang.png" alt="" /></a>
</div>
<div>
<a className="btn_doithe" href="#" onClick={e => this.handleExchange(e)}><img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/btn_doithe.png" alt="" /></a>
</div>
<div>
<a className="btn_muahom" href="#" onClick={e => this.handleViewChest(e)}><img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/btn_muahom.png" alt="" /></a>
</div>
</div>
{(unique_list) &&
<marquee scrollamount="3" behavior="scroll">
{unique_list.map((list, index) => (
<span key={index} className="mrq-content">
{list.nickname} đã nhận được {list.display_name}
</span>
))}
</marquee>
}
</div>
<div className="progress-left progress-right">
<div className="progress-vertical">
<div className="progress-outline">
<div className="progress-line" style={{ height: zodiac_count * 100 / 12 + '%' }}></div>
</div>
<div className="progress-target">
<a className={`${this.stageClaim('zodiac', 4)} ${this.checkGiftProgress(4, zodiac_count)}`} href="#" onClick={e => this.handleClaimStage('zodiac', 4)}>
<span className={`number ${this.checkGiftProgress(4, zodiac_count)}`}>4</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_8.png" alt="" />
</span>
<p>4 Vé VQMM Vàng</p>
</span>
</a>
<a className={`${this.stageClaim('zodiac', 7)} ${this.checkGiftProgress(7, zodiac_count)}`} href="#" onClick={e => this.handleClaimStage('zodiac', 7)}>
<span className={`number ${this.checkGiftProgress(7, zodiac_count)}`}>7</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_7.png" alt="" />
</span>
<p>1 Vé VQMM <NAME></p>
</span>
</a>
<a className={`${this.stageClaim('zodiac', 10)} ${this.checkGiftProgress(10, zodiac_count)}`} href="#" onClick={e => this.handleClaimStage('zodiac', 10)}>
<span className={`number ${this.checkGiftProgress(10, zodiac_count)}`}>10</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_6.png" alt="" />
</span>
<p>1 Hộp ma thuật</p>
</span>
</a>
<a className={`${this.stageClaim('zodiac', 12)} ${this.checkGiftProgress(12, zodiac_count)}`} href="#" onClick={e => this.handleClaimStage('zodiac', 12)}>
<span className={`number ${this.checkGiftProgress(12, zodiac_count)}`}>12</span>
<span className="box">
<span>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/p_g_5.png" alt="" />
</span>
<p>12 nhân vật và 12 bộ VQMM</p>
</span>
</a>
</div>
</div>
<div className="ppr-name">
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/arrow-up.png" alt="" className="art" />
<p>THẺ</p>
</div>
</div>
</div>
<img src="https://cdn.vn.garenanow.com/web/ff/ff_new_year_2019/images/zodiac_bg.jpg" alt="" className="full-bg" />
</div>
<Modal show={modal === 'rule'} closeHandler={() => this.setState({ modal: null })}>
<Rule></Rule>
</Modal>
<Modal show={modal === 'top'} closeHandler={() => this.setState({ modal: null })}>
<Top tops={zodiac.topUser}></Top>
</Modal>
<Modal show={modal === 'chest'} customClass={'lg-size'} closeHandler={() => this.setState({ modal: null })}>
<Chest chest={chest} chestStatus={chestStatus} buyChest={this.buyChest.bind(this)}></Chest>
</Modal>
<Modal show={modal === 'exchange'} closeHandler={() => this.setState({ modal: null })}>
<Exchange itemReward={zodiac.drawItem}></Exchange>
</Modal>
<Modal show={modal === 'pig-card'} closeHandler={() => this.setState({ modal: null })}>
<PigCard></PigCard>
</Modal>
</React.Fragment>
)
}
}
export default ZodiacView
|
#!/bin/bash
cd /etc/init.d
echo '[Start Lock Server]'
./totvslockserver start
sleep 5
echo '[Start License Server]'
./totvslicense start
sleep 2
echo '[Start DBAccess Server]'
./totvsdbaccess start
sleep 2
echo '[Start Slave01]'
./totvslave01 start
|
<reponame>parti-coop/demosx<filename>src/main/java/seoul/democracy/common/handler/SiteAuthenticationSuccessHandler.java
package seoul.democracy.common.handler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
import org.springframework.security.web.savedrequest.HttpSessionRequestCache;
import org.springframework.security.web.savedrequest.RequestCache;
import org.springframework.security.web.savedrequest.SavedRequest;
import org.springframework.util.StringUtils;
import seoul.democracy.common.util.IpUtils;
import seoul.democracy.user.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
public class SiteAuthenticationSuccessHandler extends SimpleUrlAuthenticationSuccessHandler {
private RequestCache requestCache = new HttpSessionRequestCache();
private final UserService userService;
@Autowired
public SiteAuthenticationSuccessHandler(UserService userService) {
this.userService = userService;
}
@Override
public void onAuthenticationSuccess(HttpServletRequest request,
HttpServletResponse response, Authentication authentication) throws IOException {
// login ip, 시간 저장
String ip = IpUtils.getIp(request);
userService.login(ip);
// redirect url 확인
String target = getSavedRequestTarget(request, response);
HttpSession session = request.getSession(false);
if (session != null) {
if (target == null) {
target = (String) session.getAttribute("SITE_LOGIN_REDIRECT_URL");
}
session.removeAttribute("SITE_LOGIN_REDIRECT_URL");
}
clearAuthenticationAttributes(request);
// ajax login
if (request.getParameter("ajax") != null) {
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("{\"msg\":\"로그인하였습니다.\"}");
return;
}
if (StringUtils.hasText(target))
getRedirectStrategy().sendRedirect(request, response, target);
else getRedirectStrategy().sendRedirect(request, response, getDefaultTargetUrl());
}
private String getSavedRequestTarget(HttpServletRequest request,
HttpServletResponse response) {
SavedRequest savedRequest = requestCache.getRequest(request, response);
if (savedRequest == null) return null;
String targetUrl = savedRequest.getRedirectUrl();
requestCache.removeRequest(request, response);
if (StringUtils.hasText(targetUrl)) return targetUrl;
return null;
}
}
|
/**
* Created by cqh on 2014/11/24.
*/
/**
* Created by cqh on 2014/11/24.
*/
function DateToFormatString( date, sep){
if( !sep )
{
sep = "-";
}
var mm = date.getMonth() + 1;
if( mm < 10 ){
mm = "0" + mm;
}
var dd = date.getDate();
if(dd < 10){
dd = "0" + dd;
}
return date.getFullYear() + sep + mm + sep + dd;
}
|
#!/bin/bash
###############################################################################
#
# LIBCOPY v1.8 by psxc
######################
#
# This small script (ripped from glinstall.sh ;) will copy libs used by files
# in glftpd's bin dir.
# The script should be run after the zipscript is installed.
# You should also use this script any time there is changes in your bin dir, or
# you upgrade your system.
#
###############################################################################
# a list of possible paths to glroot
possible_glroot_paths="/glftpd /jail/glftpd /usr/glftpd /usr/jail/glftpd /usr/local/glftpd /usr/local/jail/glftpd /$HOME/glftpd /glftpd/glftpd /opt/glftpd"
# bins needed for pzs-ng to run
needed_bins="sh cat grep egrep unzip wc find ls bash mkdir rmdir rm mv cp awk ln basename dirname head tail cut tr wc sed date sleep touch gzip"
zs_bins="zipscript-c postdel postunnuke racestats cleanup datacleaner rescan ng-undupe ng-deldir ng-chown audiosort"
#
###################################
# CODEPART - PLEASE DO NOT CHANGE #
###################################
version="1.6 (pzs-ng version)"
# Set system type
case $(uname -s) in
Linux) os=linux ;;
*[oO][pP][eE][nN][bB][sS][dD]*) os=openbsd ;;
*[Dd][Aa][Rr][Ww][Ii][Nn]*) os=darwin ;;
*[Nn][Ee][Tt][Bb][Ss][Dd]*) os=netbsd ;;
*[fF][rR][eE][eE][bB][sS][dD]*)
bsdversion=`uname -r | tr -cd '0-9' | cut -b 1-2`
if [ $bsdversion -ge 52 ]; then
os=freebsd5
else
os=freebsd4
fi
;;
*)
echo "Sorry, but this util does not support the $(uname -s) platform."
exit 1
;;
esac
if [ "$os" = "darwin" ]; then
needed_bins="$needed_bins tcsh"
else
needed_bins="$needed_bins ldconfig"
fi
# Ensure we have all useful paths in our $PATH
PATH="$PATH:/bin:/usr/bin:/usr/local/bin:/sbin:/usr/sbin:/usr/local/sbin:\
/usr/libexec:/usr/compat/linux/bin:/usr/compat/linux/sbin:/usr/compat/linux/usr/bin:\
/usr/compat/linux/usr/sbin"
if [ $# -eq 0 ]; then
for possible_glroot in $possible_glroot_paths; do
if [ -e ${possible_glroot}/bin/glftpd ]; then
glroot=${possible_glroot}
break
fi
done
if [ -z ${glroot} ]; then
echo ""
echo "This util will try to copy the necessary libs into your"
echo "glftpd environment."
echo ""
echo "Usage: $0 /path/to/glftpd-root-dir"
echo ""
exit 0
fi
else
glroot=$1
if [ ! -e /$glroot/bin/glftpd ]; then
echo ""
echo "Oops! I think you wrote wrong path. I can't find"
echo "$glroot/bin/glftpd - Exiting."
exit 0
fi
fi
lddsequence() {
echo -n " $(basename $lib): "
libdir="$(dirname $lib)"
if [ -f "$lib" ]; then
mkdir -p "$glroot$libdir"
rm -f "$glroot$lib"
cp -fRH "$lib" "$glroot$libdir"
echo "$libdir" >> "$glroot/etc/ld.so.conf"
echo "OK"
elif [ -f "/usr/compat/linux/$lib" ]; then
mkdir -p "$glroot/usr/compat/linux"
rm -f "$glroot/usr/compat/linux/$(basename $lib)"
cp -fRH "/usr/compat/linux/$lib" "$glroot/usr/compat/linux/"
echo "$libdir" >> "$glroot/etc/ld.so.conf"
echo "OK"
else
echo -e '\033[1;31mFailed!\033[0m'" You must find & copy $(basename $lib) to $glroot$libdir manually."
fi
}
# homemade 'which' command by js
mywhich() {
unset binname; for p in `echo $PATH | tr -s ':' '\n'`; do test -x $p/$bin && { binname=$p/$bin; break; }; done;
}
if [ -z "$1" ]; then
clear 2>/dev/null
fi
echo -e "\n"'\033[1;31m'"LibCopy v$version"'\033[0m'"\n\nUsing glroot: $glroot\n\nMaking sure all bins are present:"
for bin in $needed_bins; do
echo -n "$bin:"
mywhich
if [ ! -z $binname ]; then
if [ -e ${binname}.real ]; then
rm -f "$glroot/bin/$bin"
cp ${binname}.real "$glroot/bin/$bin"
else
rm -f "$glroot/bin/$(basename $binname)"
cp ${binname} $glroot/bin/
fi
echo -n "COPIED "
else
echo -en '\033[1;31mNOT FOUND!!! \033[0m'
fi
done
for bin in $zs_bins; do
echo -n "$bin:"
if [ ! -e $glroot/bin/$bin ]; then
echo -en '\033[1;31mNOT FOUND!!! \033[0m'
else
echo -n "OK "
fi
done
echo -e "\n\nCopying required shared library files:"
echo -n "" > "$glroot/etc/ld.so.conf"
case $os in
openbsd)
openrel=`uname -r | tr -cd '0-9' | cut -b 1-2`
if [ $openrel -ge 40 ]; then
ldd $glroot/bin/* 2>/dev/null | awk '{print $7, $1}' | grep -e "^/" | grep -v "00000000$" | awk '{print $1}' | sort | uniq | while read lib; do
lddsequence
done
elif [ $openrel -ge 34 ]; then
ldd $glroot/bin/* 2>/dev/null | awk '{print $5, $1}' | grep -e "^/" | grep -v "00000000$" | awk '{print $1}' | sort | uniq | while read lib; do
lddsequence
done
else
ldd $glroot/bin/* 2>/dev/null | awk '{print $3, $4}' | grep -e "^/" | grep -v "00000000)$" | awk '{print $1}' | sort | uniq | while read lib; do
lddsequence
done
fi
;;
darwin)
otool -L $glroot/bin/* 2>/dev/null | awk '{print $1}' | grep -e "^/" | grep -v "$glroot/bin/" | sort | uniq | while read lib; do
lddsequence
done
;;
*)
bindir="`echo $glroot/bin | tr -s '/'`"
ldd $bindir/* 2>/dev/null | grep -v "^$bindir" | tr ' \t' '\n' | grep -e "^/" | sort | uniq | while read lib; do
lddsequence
done
esac
case $os in
freebsd4)
bsdlibs="/usr/libexec/ld-elf.so.1"
;;
freebsd5)
bsdlibs="/libexec/ld-elf.so.1"
;;
openbsd)
bsdlibs="/usr/libexec/ld.so"
;;
netbsd)
bsdlibs="/usr/libexec/ld.so /usr/libexec/ld.elf_so"
;;
linux)
bsdlibs="/lib/ld-linux.so.2"
echo -e "\nCopying needed resolv-libs (if needed)..."
for linuxlib in /lib/libnss_dns* /lib/libresolv* ; do
[[ -e "$linuxlib" ]] && {
echo -n " $(basename $linuxlib)"
rm -f "$glroot/lib/$(basename $linuxlib)"
cp -fRH $linuxlib $glroot/lib/
echo " OK"
}
done
for linuxlib in /lib/i386-linux-gnu/libnss_dns* /lib/i386-linux-gnu/libresolv* ; do
[[ -e "$linuxlib" ]] && {
echo -n " $(basename $linuxlib)"
rm -f "$glroot/lib/i386-linux-gnu/$(basename $linuxlib)"
[[ ! -e $glroot/lib/i386-linux-gnu/ ]] && mkdir $glroot/lib/i386-linux-gnu/
cp -fRH $linuxlib $glroot/lib/i386-linux-gnu/
echo " OK (32bit)"
}
done
for linuxlib in /lib/x86_64-linux-gnu/libnss_dns* /lib/i386-linux-gnu/libresolv* ; do
[[ -e "$linuxlib" ]] && {
echo -n " $(basename $linuxlib)"
rm -f "$glroot/lib/x86_64-linux-gnu/$(basename $linuxlib)"
[[ ! -e $glroot/lib/x86_64-linux-gnu/ ]] && mkdir $glroot/lib/x86_64-linux-gnu/
cp -fRH $linuxlib $glroot/lib/x86_64-linux-gnu/
echo " OK (64bit)"
}
done
echo -n " resolvconf"
[[ -d /etc/resolvconf ]] && {
cp -fRp /etc/resolvconf $glroot/etc/
echo " OK"
} || {
echo " NOT NEEDED"
}
echo ""
;;
darwin)
bsdlibs="/usr/lib/dyld /usr/lib/dylib1.o /usr/lib/system/libmathCommon.A.dylib"
;;
*)
echo "No special library needed on this platform."
bsdlibs=""
;;
esac
echo -e "\nCopying your system's run-time library linker(s):"
echo "(NOTE: Searches can take a couple of minutes, please be patient.)"
libfailed=0
if [ ! -z "$bsdlibs" ]; then
for bsdlib in $bsdlibs; do
bsdlibdir=${bsdlib%/*}
mkdir -p "$glroot$bsdlibdir"
echo -n " $(basename $bsdlib): "
if [ -e "$bsdlib" ]; then
rm -f "$glroot$bsdlibdir$(basename $bsdlib)"
cp -fRH "$bsdlib" "$glroot$bsdlibdir"
echo "OK"
else
echo -n "Searching . . . "
file=$(find / -name $(basename $bsdlib) | head -1)
if [ -n "$file" ]; then
rm -f "$glroot$bsdlibdir$(basename $file)"
cp -fRH "$file" "$glroot$bsdlibdir"
echo "OK"
else
echo -e '\033[1;31mFailed!\033[0m'
libfailed="1"
fi
fi
done
[ $libfailed -eq 1 ] && echo "You must install and copy the missing libraries to $glroot$bsdlibdir manually."
fi
echo -ne "\nConfiguring the shared library cache . . . "
sort "$glroot/etc/ld.so.conf" | uniq >"$glroot/etc/ld.so.temp" && mv "$glroot/etc/ld.so.temp" "$glroot/etc/ld.so.conf"
lddlist="`cat $glroot/etc/ld.so.conf | tr '\n' ' '`"
case $os in
linux)
chroot "$glroot" /bin/ldconfig
;;
*bsd*)
mkdir -p "$glroot/usr/lib"
mkdir -p "$glroot/var/run"
chroot "$glroot" /bin/ldconfig $lddlist
;;
esac
echo "Done."
echo
echo "If you got errors, please fix them and re-run the program."
echo "If you didn't get any errors - have phun!"
echo
exit 0
|
#!/bin/sh -e
# This file is part of boydemdb.
#
# Copyright (c) 2020 Dima Krasner
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
if [ ! -f $1/sqlite3.c ] || [ ! -f $1/sqlite3.h ]
then
tmp=`mktemp -d`
trap "rm -rf $tmp" EXIT INT TERM
cd $tmp
$1/sqlite/configure --disable-threadsafe --disable-tcl --disable-readline --disable-load-extension > /dev/null
make sqlite3.c > /dev/null
mv -f sqlite3.c sqlite3.h $1/
fi
cp -f $1/sqlite3.c $1/sqlite3.h $2/
|
<reponame>Ashindustry007/competitive-programming
// https://www.codechef.com/FEB20A/problems/LONGCOOK
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int n = 400 * 12;
int s[n];
bool isleap(int y) {
if (y % 400 == 0) return 1;
if (y % 100 == 0) return 0;
return y % 4 == 0;
}
int main() {
cin.tie(0), ios::sync_with_stdio(0);
ll d = 0;
for (int i = 0; i < n; i++) {
int y = (i / 12) + 1, m = (i % 12) + 1;
if (m == 2) {
if (isleap(y)) {
if (d % 7 == 5) s[i]++;
d += 29;
} else {
if (d % 7 >= 5) s[i]++;
d += 28;
}
} else if (m == 4 || m == 6 || m == 9 || m == 11) d += 30;
else d += 31;
if (i) s[i] += s[i-1];
}
int t;
cin >> t;
while (t--) {
ll m1, y1, m2, y2;
cin >> m1 >> y1 >> m2 >> y2;
m1--, y1--, m2--, y2--;
ll i1 = y1 * 12 + m1;
ll i2 = y2 * 12 + m2;
ll l = i1 ? ((i1 - 1) / n + 1) : 0;
ll r = (i2 + 1) / n - 1;
if (l > r) {
ll c = (i2 - i1) / n * s[n-1];
i1 %= n;
i2 %= n;
if (i1 > i2) c += s[n-1];
c += s[i2];
if (i1) c -= s[i1-1];
cout << c << '\n';
continue;
}
i1 %= n;
i2 %= n;
ll c = s[n-1] * (r - l + 1);
if (i1) c += s[n-1] - s[i1-1];
if (i2 < n-1) c += s[i2];
cout << c << '\n';
}
}
|
<reponame>skurapati583/Java-DataStructures-Examples<filename>src/examples/collections/MapsExample.java
package examples.collections;
import java.util.HashMap;
public class MapsExample {
public static void main(String[] args) {
HashMap<String, Integer> employerIds = new HashMap<>();
employerIds.put("John", 7782);
employerIds.put("Marah", 4353);
employerIds.put("Carl", 8948);
employerIds.put("Jerry", 38939);
System.out.println(employerIds);
System.out.printf("Carl's ID is: %d%n", employerIds.get("Carl"));
System.out.printf("Is Jerry exists: %b%n", employerIds.containsKey("Jerry"));
System.out.printf("Is Employer ID - 4333 exists: %b%n", employerIds.containsValue(4333));
employerIds.replace("John", 93849);
System.out.println(employerIds);
employerIds.replace("Bailey", 193849); // Only replaces the key-value is present. Else, no operation.
System.out.println(employerIds);
employerIds.putIfAbsent("Bailey", 384938);
employerIds.putIfAbsent("John", 384938); // No operation as John is already present.
System.out.println(employerIds);
employerIds.putIfAbsent("Steve", 384938); // Added as Steve is not present
System.out.println(employerIds);
employerIds.remove("Steve");
System.out.println(employerIds);
employerIds.remove("Steve"); // If key is not available, remove operation does nothing. If found, then
// removes the key-value pair.
System.out.println(employerIds);
}
}
|
<gh_stars>0
/**
* Implement Gatsby's Node APIs in this file.
*
* See: https://www.gatsbyjs.com/docs/node-apis/
*/
// You can delete this file if you're not using it
const path = require('path')
const { createFilePath } = require(`gatsby-source-filesystem`)
const { graphql } = require('gatsby')
exports.onCreateNode = ({ node, getNode, actions }) => {
const { createNodeField } = actions
if (node.internal.type === "MarkdownRemark") {
const slug = createFilePath({node, getNode, basePath: "content",
})
createNodeField({
node,
name:'slug',
value: `/blog${slug}`,
})
}
}
// creation page
exports.createPages = async function ({ actions, graphql }) {
const { data } = await graphql(`
query {
allMarkdownRemark {
edges {
node {
fields {
slug
}
}
}
totalCount
}
}
`)
// boucle page et pagination
data.allMarkdownRemark.edges.forEach(edge =>{
const {slug} = edge.node.fields
actions.createPage({
path: slug,
component: require.resolve('./src/templates/posts.jsx'),
context: { slug },
})
})
const perPage = 2;
const nbPage = Math.ceil(data.allMarkdownRemark.totalCount / perPage)
//creation index posts
for (let i = 0; i < nbPage; i++) {
actions.createPage({
path: i < 1 ? "/blog" : `/blog/${i + 1}`,
// path: '/blog',
component: require.resolve('./src/templates/list.jsx'),
context: {
limit: perPage,
skip: i * perPage,
},
})
}
}
|
import requests
import json
def get_stock_price(ticker):
url = 'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={ticker}&interval=1min&apikey=<Your_API_KEY>'.format(ticker=ticker)
response = requests.get(url)
data = json.loads(response.text)
if data:
ts = data['Time Series (1min)']
latest_data_point = list(ts.values())[0]
return latest_data_point['4. close']
if __name__ == '__main__':
g_price = get_stock_price('GOOGL')
m_price = get_stock_price('MSFT')
print(f'Google stock price: {g_price}')
print(f'Microsoft stock price: {m_price}')
|
<filename>public/js/addDateTimepicker.js
// Waiting for the DOM ready...
function datepResize() {
// Get width of parent container
var width = jQuery("#datetimepicker").width(); //attr('clientWidth');
if (width == null || width < 1){
// For IE, revert to offsetWidth if necessary
width = jQuery("#datetimepicker").attr('offsetWidth');
}
width = width - 2; // Fudge factor to prevent horizontal scrollbars
if (width > 0 &&
// Only resize if new width exceeds a minimal threshold
// Fixes IE issue with in-place resizing when mousing-over frame bars
Math.abs(width - jQuery("div ui-datepicker").width()) > 5)
{
if (width < 166){
jQuery("div.ui-datepicker").css({'font-size': '8px'});
jQuery(".ui-datepicker td .ui-state-default").css({'padding':'0px','font-size': '6px'});
}
else if (width > 228){
jQuery("div.ui-datepicker").css({'font-size': '13px','margin-top':'290px'});
jQuery(".ui-datepicker td .ui-state-default").css({'padding':'5px','font-size': '100%'});
}
else{
jQuery("div.ui-datepicker").css({'font-size': (width-43)/16+'px'});
}
}
}
$(function(){
$.datepicker.regional['es'] = {
closeText: 'Cerrar',
prevText: '<Ant',
nextText: 'Sig>',
currentText: 'Hoy',
monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
monthNamesShort: ['Ene','Feb','Mar','Abr', 'May','Jun','Jul','Ago','Sep', 'Oct','Nov','Dic'],
dayNames: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
dayNamesShort: ['Dom','Lun','Mar','Mié','Juv','Vie','Sáb'],
dayNamesMin: ['Do','Lu','Ma','Mi','Ju','Vi','Sá'],
weekHeader: 'Sm',
dateFormat: 'dd/mm/yy',
firstDay: 1,
isRTL: false,
showMonthAfterYear: false,
yearSuffix: ''
};
var nowDate = new Date();
$.datepicker.setDefaults( $.datepicker.regional[ "es" ] );
$.extend($.datepicker,{_checkOffset:function(inst,offset,isFixed){return offset}});
$( ".datetimepicker" ).datetimepicker({
timeFormat: 'HH:mm',
minDate: new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), nowDate.getHours(), nowDate.getMinutes(), 0, 0),
beforeShow: function (input, inst) {
setTimeout(function () {
//datepResize();
}, 0);
}
});
});
|
#pragma once
#include "TNAH/Renderer/RenderCommand.h"
#include "TNAH/Scene/SceneCamera.h"
#include "TNAH/Scene/Components/Components.h"
#include "TNAH/Renderer/Material.h"
#include "Light.h"
#include "Mesh.h"
#include "Texture.h"
namespace tnah {
/**
* @class Renderer
*
* @brief A renderer class responsible for the rendering of things such as meshes, terrain and skyboxes
*
* @author <NAME>
* @date 12/09/2021
*/
class Renderer
{
public:
/**
* @fn static void Renderer::Init();
*
* @brief Initializes this object
*
* @author <NAME>
* @date 12/09/2021
*/
static void Init();
/**
* @fn static void Renderer::Shutdown();
*
* @brief Shuts down this object and frees any resources it is using
*
* @author <NAME>
* @date 12/09/2021
*/
static void Shutdown();
/**
* @fn static void Renderer::OnWindowResize(uint32_t width, uint32_t height);
*
* @brief Executes when the window is resized
*
* @author <NAME>
* @date 12/09/2021
*
* @param width The width.
* @param height The height.
*/
static void OnWindowResize(uint32_t width, uint32_t height);
/**
* @fn static void Renderer::BeginScene(SceneCamera& camera);
*
* @brief Begins a scene
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] camera The camera.
*/
static void BeginScene(SceneCamera& camera);
/**
* @fn static void Renderer::BeginScene(SceneCamera& camera, TransformComponent& cameraTransform);
*
* @brief Begins a scene
*
* @author <NAME>
* @date 12/09/2021
*
* @param [in,out] camera The camera.
* @param [in,out] cameraTransform The camera transform.
*/
static void BeginScene(SceneCamera& camera, TransformComponent& cameraTransform);
/**
* @fn static void Renderer::EndScene();
*
* @brief Ends a scene
*
* @author <NAME>
* @date 12/09/2021
*/
static void EndScene();
/**
* @fn static void Renderer::IncrementTextureSlot()
*
* @brief Increment texture slot
*
* @author <NAME>
* @date 12/09/2021
*/
static void IncrementTextureSlot() { s_CurrentTextureSlot++; }
/**
* @fn static uint32_t Renderer::GetCurrentTextureSlot()
*
* @brief Gets current texture slot
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The current texture slot.
*/
static uint32_t GetCurrentTextureSlot() { return s_CurrentTextureSlot; }
/**
* @fn static uint32_t Renderer::GetAndIncrementTextureSlot()
*
* @brief Gets and increment texture slot
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The and increment texture slot.
*/
static uint32_t GetAndIncrementTextureSlot() { s_CurrentTextureSlot++; return s_CurrentTextureSlot - 1; }
/**
* @fn static void Renderer::SetCullMode(const CullMode& mode);
*
* @brief Sets cull mode
*
* @author <NAME>
* @date 12/09/2021
*
* @param mode The mode.
*/
static void SetCullMode(const CullMode& mode);
/**
* @fn static void Renderer::SetShaderLightInfo(Ref<Material> material, std::vector<Ref<Light>> lights);
*
* @brief Sets shader light information
*
* @author <NAME>
* @date 12/09/2021
*
* @param material The material.
* @param lights The lights.
*/
static void SetShaderLightInfo(Ref<Material> material, std::vector<Ref<Light>> lights);
/**
* @fn static void Renderer::Submit(Ref<VertexArray> vertexArray, Ref<Shader> shader, const glm::mat4& transform = glm::mat4(1.0f));
*
* @brief Submits to the renderer
*
* @author <NAME>
* @date 12/09/2021
*
* @param vertexArray Array of vertices.
* @param shader The shader.
* @param transform (Optional) The transform.
*/
static void Submit(Ref<VertexArray> vertexArray, Ref<Shader> shader, const glm::mat4& transform = glm::mat4(1.0f));
/**
* @fn static void Renderer::SubmitTerrain(Ref<VertexArray> vertexArray, Ref<Material> material, std::vector<Ref<Light>> sceneLights, const glm::mat4& transform = glm::mat4(1.0f));
*
* @brief Submit terrain
*
* @author <NAME>
* @date 12/09/2021
*
* @param vertexArray Array of vertices.
* @param material The material.
* @param sceneLights The scene lights.
* @param transform (Optional) The transform.
*/
static void SubmitTerrain(Ref<VertexArray> vertexArray, Ref<Material> material, std::vector<Ref<Light>> sceneLights, const glm::mat4& transform = glm::mat4(1.0f));
/**
* @fn static void Renderer::SubmitMesh(Ref<VertexArray> vertexArray, Ref<Material> material, std::vector<Ref<Light>> sceneLights, const glm::mat4& transform = glm::mat4(1.0f), const bool& isAnimated = false, const std::vector<glm::mat4>& animTransforms = {glm::mat4(1.0f)});
*
* @brief Submit mesh
*
* @author <NAME>
* @date 12/09/2021
*
* @param vertexArray Array of vertices.
* @param material The material.
* @param sceneLights The scene lights.
* @param transform (Optional) The transform.
* @param isAnimated (Optional) True if is animated, false if not.
* @param animTransforms (Optional) The animation transforms.
*/
static void SubmitMesh(Ref<VertexArray> vertexArray, Ref<Material> material, std::vector<Ref<Light>> sceneLights, const glm::mat4& transform = glm::mat4(1.0f), const bool& isAnimated = false, const std::vector<glm::mat4>& animTransforms = {glm::mat4(1.0f)});
/**
* @fn static void Renderer::SubmitSkybox(Ref<VertexArray> vertexArray, Ref<SkyboxMaterial> material);
*
* @brief Submit skybox
*
* @author <NAME>
* @date 12/09/2021
*
* @param vertexArray Array of vertices.
* @param material The material.
*/
static void SubmitSkybox(Ref<VertexArray> vertexArray, Ref<SkyboxMaterial> material);
/**
* @fn static void Renderer::SubmitCollider(Ref<VertexArray> lineVertexArray, Ref<VertexBuffer> lineVertexBuffer, Ref<VertexArray> triangleVertexArray, Ref<VertexBuffer> triangleVertexBuffer);
*
* @brief Submit collider
*
* @author <NAME>
* @date 12/09/2021
*
* @param lineVertexArray Array of vertices.
* @param lineVertexBuffer Buffer for line vertex data.
* @param triangleVertexArray Array of vertices.
* @param triangleVertexBuffer Buffer for triangle vertex data.
*/
static void SubmitCollider(Ref<VertexArray> lineVertexArray, Ref<VertexBuffer> lineVertexBuffer, Ref<VertexArray> triangleVertexArray, Ref<VertexBuffer> triangleVertexBuffer);
/**
* @fn static RendererAPI::API Renderer::GetAPI()
*
* @brief Gets the renderer API
*
* @author <NAME>
* @date 12/09/2021
*
* @returns the renderer API.
*/
static RendererAPI::API GetAPI() { return RendererAPI::GetAPI(); }
/**
* @fn static Ref<Texture2D> Renderer::GetWhiteTexture();
*
* @brief Gets white texture
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The white texture.
*/
static Ref<Texture2D> GetWhiteTexture();
/**
* @fn static Ref<Texture2D> Renderer::GetBlackTexture();
*
* @brief Gets black texture
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The black texture.
*/
static Ref<Texture2D> GetBlackTexture();
/**
* @fn static Ref<Texture2D> Renderer::GetMissingTexture();
*
* @brief Gets missing texture
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The missing texture.
*/
static Ref<Texture2D> GetMissingTexture();
/**
* @fn static std::vector<Ref<Texture2D>> Renderer::GetLoadedTextures();
*
* @brief Gets loaded textures
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The loaded textures.
*/
static std::vector<Ref<Texture2D>> GetLoadedTextures();
/**
* @fn static std::vector<Ref<Shader>> Renderer::GetLoadedShaders();
*
* @brief Gets loaded shaders
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The loaded shaders.
*/
static std::vector<Ref<Shader>> GetLoadedShaders();
/**
* @fn static void Renderer::RegisterTexture(Ref<Texture2D> texture);
*
* @brief Registers the texture described by texture
*
* @author <NAME>
* @date 12/09/2021
*
* @param texture The texture.
*/
static void RegisterTexture(Ref<Texture2D> texture);
/**
* @fn static void Renderer::RegisterShader(Ref<Shader> shader);
*
* @brief Registers the shader described by shader
*
* @author <NAME>
* @date 12/09/2021
*
* @param shader The shader.
*/
static void RegisterShader(Ref<Shader> shader);
/**
* @fn static std::vector<Ref<Model>> Renderer::GetLoadedModels();
*
* @brief Gets loaded models
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The loaded models.
*/
static std::vector<Ref<Model>> GetLoadedModels();
/**
* @fn static void Renderer::RegisterModel(Ref<Model> model);
*
* @brief Registers the model described by model
*
* @author <NAME>
* @date 12/09/2021
*
* @param model The model.
*/
static void RegisterModel(Ref<Model> model);
/**
* @fn static uint32_t Renderer::GetDrawCallsPerFrame();
*
* @brief Gets draw calls per frame
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The draw calls per frame.
*/
static uint32_t GetDrawCallsPerFrame();
/**
* @fn static uint32_t Renderer::GetTotalLoadedTextures();
*
* @brief Gets total loaded textures
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The total loaded textures.
*/
static uint32_t GetTotalLoadedTextures();
/**
* @fn static uint32_t Renderer::GetTotalLoadedShaders();
*
* @brief Gets total loaded shaders
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The total loaded shaders.
*/
static uint32_t GetTotalLoadedShaders();
/**
* @fn static uint32_t Renderer::GetTotalLoadedModels();
*
* @brief Gets total loaded models
*
* @author <NAME>
* @date 12/09/2021
*
* @returns The total loaded models.
*/
static uint32_t GetTotalLoadedModels();
private:
/**
* @fn static void Renderer::IncrementDrawCallsPerFrame();
*
* @brief Increment draw calls per frame
*
* @author <NAME>
* @date 12/09/2021
*/
static void IncrementDrawCallsPerFrame();
/**
* @fn static void Renderer::IncrementTotalLoadedTextures();
*
* @brief Increment total loaded textures
*
* @author <NAME>
* @date 12/09/2021
*/
static void IncrementTotalLoadedTextures();
/**
* @fn static void Renderer::IncrementTotalLoadedShaders();
*
* @brief Increment total loaded shaders
*
* @author <NAME>
* @date 12/09/2021
*/
static void IncrementTotalLoadedShaders();
/**
* @fn static void Renderer::IncrementTotalLoadedModels();
*
* @brief Increment total loaded models
*
* @author <NAME>
* @date 12/09/2021
*/
static void IncrementTotalLoadedModels();
/**
* @fn static void Renderer::ResetDrawCallsPerFrame();
*
* @brief Resets the draw calls per frame
*
* @author <NAME>
* @date 12/09/2021
*/
static void ResetDrawCallsPerFrame();
/**
* @fn static void Renderer::ResetTotalLoadedTextures();
*
* @brief Resets the total loaded textures
*
* @author <NAME>
* @date 12/09/2021
*/
static void ResetTotalLoadedTextures();
/**
* @fn static void Renderer::ResetTotalLoadedShaders();
*
* @brief Resets the total loaded shaders
*
* @author <NAME>
* @date 12/09/2021
*/
static void ResetTotalLoadedShaders();
/**
* @fn static void Renderer::ResetTotalLoadedModels();
*
* @brief Resets the total loaded models
*
* @author <NAME>
* @date 12/09/2021
*/
static void ResetTotalLoadedModels();
/**
* @struct SceneData
*
* @brief scene data.
*
* @author <NAME>
* @date 12/09/2021
*/
struct SceneData
{
/** @brief The view */
glm::mat4 View;
/** @brief The projection */
glm::mat4 Projection;
/** @brief The view projection */
glm::mat4 ViewProjection;
/** @brief The camera transform */
TransformComponent CameraTransform;
};
/** @brief The current texture slot */
static uint32_t s_CurrentTextureSlot;
/** @brief Information describing the scene */
static SceneData* s_SceneData;
};
}
|
<reponame>HenryRuiz332/comercial
import Servicios from '../Index'
import ServiciosContratados from '../ServiciosContratados'
const routes = [
...route('/servicios', Servicios, {
Auth: true,
}),
...route(`/servicios-contratados`, ServiciosContratados, {
Auth: true,
}),
]
function route(path, component = Default, meta = {}) {
return [{
path,
component,
meta
}]
}
export default routes
|
define(function(require, exports, module) {
var utils = require('utils');
var bs = require('./xsjsdfmxBS');
var viewConfig = {
initialize: function(data) {
var mode = WIS_EMAP_SERV.getModel(bs.api.pageModel, 'jsdfmx', 'form');
$("#emapForm").emapForm({
data: mode,
model: 'h',
readonly:true
});
$("#emapForm").emapForm("setValue", data);
$("[data-action=save]").hide();
this.eventMap = {
};
}
};
return viewConfig;
});
|
def dec_to_binary(num):
binary = bin(num)
return binary[2:]
print(dec_to_binary(5))
# Output: 101
|
<filename>psp/psplib/ctrl.h
/** PSP helper library ***************************************/
/** **/
/** ctrl.h **/
/** **/
/** This file contains declarations for the controller **/
/** interaction routines **/
/** **/
/** Copyright (C) <NAME> 2007 **/
/** You are not allowed to distribute this software **/
/** commercially. Please, notify me, if you make any **/
/** changes to this file. **/
/*************************************************************/
#ifndef _PSP_CTRL_H
#define _PSP_CTRL_H
#ifdef __cplusplus
extern "C" {
#endif
#include <pspctrl.h>
/* These bits are currently unused */
#define PSP_CTRL_ANALUP 0x00000002
#define PSP_CTRL_ANALDOWN 0x00000004
#define PSP_CTRL_ANALLEFT 0x00000400
#define PSP_CTRL_ANALRIGHT 0x00000800
#define PSP_CTRL_NORMAL 0
#define PSP_CTRL_AUTOREPEAT 1
void pspCtrlInit();
int pspCtrlGetPollingMode();
void pspCtrlSetPollingMode(int mode);
int pspCtrlPollControls(SceCtrlData *pad);
#ifdef __cplusplus
}
#endif
#endif // _PSP_FILEIO_H
|
def get_distinguished_cand(c, r, l, non_manip_rankmaps, strength_order):
# Create a dictionary to store the strength of each candidate
candidate_strength = {candidate: 0 for candidate in strength_order}
# Iterate through the non-manipulative voter rankings to calculate the strength of each candidate
for rankmap in non_manip_rankmaps:
for candidate, rank in rankmap.items():
candidate_strength[candidate] += 1 / rank # Increase the strength based on the inverse of the rank
# Sort the candidates based on their strength in descending order
sorted_candidates = sorted(candidate_strength, key=candidate_strength.get, reverse=True)
# Identify the potential distinguished candidates
distinguished_candidates = []
for candidate in sorted_candidates:
if candidate != c and candidate_strength[candidate] > candidate_strength[c]:
distinguished_candidates.append(candidate)
return distinguished_candidates[:l] # Return the top l distinguished candidates based on the l-bloc rule
|
#!/bin/bash
# Copyright 2015 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
set -ex
CONFIG=${CONFIG:-opt}
# change to grpc repo root
cd "$(dirname "$0")/../../.."
root=$(pwd)
export GRPC_LIB_SUBDIR=libs/$CONFIG
export CFLAGS="-Wno-parentheses-equality"
# build php
cd src/php
cd ext/grpc
phpize
if [ "$CONFIG" != "gcov" ] ; then
./configure --enable-grpc="$root" --enable-tests
else
./configure --enable-grpc="$root" --enable-coverage --enable-tests
fi
make
|
<reponame>djstaros/qmcpack
##################################################################
## (c) Copyright 2015- by <NAME> ##
##################################################################
#====================================================================#
# gamess_analyzer.py #
# Support for analysis of GAMESS output data. #
# #
# Content summary: #
# GamessAnalyzer #
# Analyzer class for the GAMESS code. #
# Reads numerical data from GAMESS output logs. #
# #
#====================================================================#
import os
from numpy import array,ndarray,abs
from generic import obj
from developer import DevBase
from fileio import TextFile
from debug import *
from simulation import SimulationAnalyzer,Simulation
from gamess_input import GamessInput
def assign_value(host,dest,file,string):
if file.seek(string)!=-1:
host[dest] = float(file.readtokens()[-1])
#end if
#end def assign_value
class GamessAnalyzer(SimulationAnalyzer):
lset_full = 'spdfg'
lxyz = obj(
s = set('s'.split()),
p = set('x y z'.split()),
d = set('xx yy zz xy xz yz'.split()),
f = set('xxx yyy zzz xxy xxz yyx yyz zzx zzy xyz'.split()),
g = set('xxxx yyyy zzzz xxxy xxxz yyyx yyyz zzzx zzzy xxyy xxzz yyzz xxyz yyxz zzxy'.split()),
)
lxyz_reverse = obj()
for l,xyzs in lxyz.items():
for xyz in xyzs:
lxyz_reverse[xyz] = l
#end for
#end for
def __init__(self,arg0=None,prefix=None,analyze=False,exit=False,**outfilenames):
self.info = obj(
exit = exit,
path = None,
input = None,
prefix = None,
files = obj(),
initialized = False
)
infile = None
if isinstance(arg0,Simulation):
sim = arg0
infile = os.path.join(sim.locdir,sim.infile)
else:
infile = arg0
#end if
if infile!=None:
info = self.info
info.path = os.path.dirname(infile)
info.input = GamessInput(infile)
infilename = os.path.split(infile)[1]
if prefix is None:
prefix = infilename.rsplit('.',1)[0]
#end if
info.prefix = prefix
files = info.files
for file,unit in GamessInput.file_units.items():
files[file.lower()] = '{0}.F{1}'.format(prefix,str(unit).zfill(2))
#end for
files.input = infilename
files.output = '{0}.out'.format(prefix)
for name,filename in outfilenames:
if name in files:
files[name] = filename
else:
self.error('unknown GAMESS file: {0}'.format(name))
#end if
#end for
info.initialized = True
if analyze:
self.analyze()
#end if
#end if
#end def __init__
def analyze(self):
if not self.info.initialized:
self.error('cannot perform analysis\nGamessAnalyzer has not been initialized')
#end if
self.analyze_log()
self.analyze_punch()
#end def analyze
def get_output(self,filetag):
filename = self.info.files[filetag]
outfile = os.path.join(self.info.path,filename)
if os.path.exists(outfile):
filepath = outfile
elif os.path.exists(filename):
filepath = filename
elif self.info.exit:
self.error('output file does not exist at either of the locations below:\n {0}\n {1}'.format(outfile,filename))
else:
return None
#end if
try:
return TextFile(filepath)
except:
return None
#end try
#end def get_output
def analyze_log(self):
# read the log file
log = self.get_output('output')
# try to get the energy components
energy = obj()
try:
self.read_energy_components(log,energy)
except:
if self.info.exit:
self.error('log file analysis failed (energy components)')
#end if
#end try
if len(energy)>0:
self.energy = energy
#end if
# try to get the orbital count from the log file
counts = obj()
try:
if log.seek('TOTAL NUMBER OF BASIS SET SHELLS',0)!=-1:
counts.shells = int(log.readtokens()[-1])
#end if
if log.seek('NUMBER OF CARTESIAN ATOMIC ORBITALS',0)!=-1:
counts.cao = int(log.readtokens()[-1])
#end if
if log.seek('TOTAL NUMBER OF MOS IN VARIATION SPACE',1)!=-1:
counts.mos = int(log.readtokens()[-1])
#end if
except:
if self.info.exit:
self.error('log file analysis failed (counts)')
#end if
#end try
if len(counts)>0:
self.counts = counts
#end if
# try to get the up/down orbitals
if 'counts' in self:
orbitals = obj()
try:
self.read_orbitals(log,orbitals,'up' ,'-- ALPHA SET --')
self.read_orbitals(log,orbitals,'down','-- BETA SET --' )
except:
if self.info.exit:
self.error('log file analysis failed (orbitals)')
#end if
#end try
if len(orbitals)>0:
self.orbitals = orbitals
#end if
#end if
# try to get the mulliken/lowdin populations in each ao
if 'counts' in self:
ao_populations = obj()
try:
self.read_ao_populations(log,ao_populations)
except:
if self.info.exit:
self.error('log file analysis failed (ao populations)')
#end if
#end try
if len(ao_populations)>0:
self.ao_populations = ao_populations
#end if
#end if
#end def analyze_log
def read_energy_components(self,log,energy):
if log!=None and log.seek('ENERGY COMPONENTS',0)!=-1:
for n in range(18):
line = log.readline()
if '=' in line and 'ENERGY' in line:
nameline,value = line.split('=')
tokens = nameline.lower().split()
name = ''
for token in tokens:
if token!='energy':
name += token.replace('-','_')+'_'
#end if
#end for
name = name[:-1]
value = float(value.strip())
energy[name]=value
#end if
#end for
#end if
if log!=None and log.seek('COUPLED-CLUSTER ENERGY',0)!=-1:
line = log.readline()
energy['ccsd(t)'] = float( line.split()[-1] )
# end if
#end def read_energy_components
def read_orbitals(self,log,orbs,spec,header):
success = True
cao_tot = self.counts.cao
mos_tot = self.counts.mos
mos_found = 0
eigenvalue = []
symmetry = []
coefficients = []
have_basis = False
element = []
spec_index = []
angular = []
if log.seek(header,0)!=-1:
imax = mos_tot
jmax = 100
i=0
while mos_found<mos_tot and i<imax:
j=0
norbs = -1
while j<jmax:
line = log.readline()
if line.strip().replace(' ','').isdigit():
found_orbs = True
norbs = len(line.split())
break
#end if
j+=1
#end while
if j==jmax:
success=False
if self.info.exit:
self.error('could not find start of orbitals for {0}\nnumber of orbitals read successfully: {1}\nnumber of orbitals not read: {2}'.format(header,mos_found,mos_tot-mos_found))
else:
break
#end if
#end if
eigenvalue.extend(log.readtokens())
symmetry.extend(log.readtokens())
coeff = []
for icao in range(cao_tot):
tokens = log.readtokens()
if not have_basis:
e = tokens[1]
element.append(e[0].upper()+e[1:].lower())
spec_index.append(tokens[2])
angular.append(tokens[3])
#end if
coeff.append(tokens[4:])
#end for
coefficients.extend(array(coeff,dtype=float).T)
if not have_basis:
stype = []
ptype = []
dtype = []
ftype = []
for ia in range(len(angular)):
a = angular[ia].lower()
if a in GamessAnalyzer.stypes:
stype.append(ia)
elif a in GamessAnalyzer.ptypes:
ptype.append(ia)
elif a in GamessAnalyzer.dtypes:
dtype.append(ia)
elif a in GamessAnalyzer.ftypes:
ftype.append(ia)
elif self.info.exit:
self.error('unrecognized angular type: {0}'.format(angular[ia]))
#end if
#end for
#end if
have_basis = True
mos_found = len(eigenvalue)
i+=1
#end while
if i==imax:
success=False
if self.info.exit:
self.error('orbital read failed for {0}\nnumber of orbitals read successfully: {1}\nnumber of orbitals not read: {2}'.format(header,mos_found,mos_tot-mos_found))
#end if
if success:
orbs[spec] = obj(
eigenvalue = array(eigenvalue ,dtype=float),
symmetry = array(symmetry ,dtype=str ),
# skip large coefficient data
#coefficients = array(coefficients,dtype=float),
#basis = obj(
# element = array(element ,dtype=str),
# spec_index = array(spec_index,dtype=int),
# angular = array(angular ,dtype=str),
# stype = array(stype ,dtype=int),
# ptype = array(ptype ,dtype=int),
# dtype = array(dtype ,dtype=int),
# ftype = array(ftype ,dtype=int),
# )
)
#end if
return success
else:
return False
#end if
#end def read_orbitals
def read_ao_populations(self,log,ao_populations):
cao_tot = self.counts.cao
if log.seek('-- POPULATIONS IN EACH AO --',0)!=-1:
log.readline()
log.readline()
mulliken = []
lowdin = []
element = []
spec_index = []
angular = []
linds = obj()
for l in GamessAnalyzer.lset_full:
linds[l]=[]
#end for
for icao in range(cao_tot):
tokens = log.readtokens()
e = tokens[1]
element.append(e[0].upper()+e[1:].lower())
if len(tokens)==6:
spec_index.append(tokens[2])
angular.append(tokens[3])
mulliken.append(tokens[4])
lowdin.append(tokens[5])
elif len(tokens)==5:
spec_index.append(tokens[2][:-4])
angular.append(tokens[2][-4:])
mulliken.append(tokens[3])
lowdin.append(tokens[4])
#end if
#end for
for ia in range(len(angular)):
a = angular[ia].lower()
if a in GamessAnalyzer.lxyz_reverse:
l = GamessAnalyzer.lxyz_reverse[a]
linds[l].append(ia)
elif self.info.exit:
self.error('unrecognized angular type: {0}'.format(angular[ia]))
#end if
#end for
mulliken = array(mulliken,dtype=float)
lowdin = array(lowdin ,dtype=float)
for l,lind in linds.items():
linds[l] = array(lind,dtype=int)
#end for
mulliken_shell = []
lowdin_shell = []
shell = obj()
n=0
for l in GamessAnalyzer.lset_full:
if l in GamessAnalyzer.lxyz:
lind = linds[l]
nxyz = len(GamessAnalyzer.lxyz[l])
nshell = len(lind)//nxyz
shellinds = []
for ns in range(nshell):
inds = lind[ns*nxyz:(ns+1)*nxyz]
mulliken_shell.append(mulliken[inds].sum())
lowdin_shell.append(lowdin[inds].sum())
shellinds.append(n)
n+=1
#end for
shell[l] = array(shellinds,dtype=int)
#end if
#end for
mulliken_shell = array(mulliken_shell)
lowdin_shell = array(lowdin_shell)
mulliken_angular = obj()
lowdin_angular = obj()
for l,shellinds in shell.items():
mulliken_angular[l] = mulliken_shell[shellinds].sum()
lowdin_angular[l] = lowdin_shell[shellinds].sum()
#end for
basis = obj(
element = array(element ,dtype=str),
spec_index = array(spec_index,dtype=int),
angular = array(angular ,dtype=str),
)
basis.transfer_from(linds)
ao_populations.set(
mulliken = mulliken,
lowdin = lowdin,
mulliken_shell = mulliken_shell,
lowdin_shell = lowdin_shell,
mulliken_angular = mulliken_angular,
lowdin_angular = lowdin_angular,
basis = basis,
shell = shell,
)
#end if
#end def read_ao_populations
def analyze_punch(self):
# read the punch file
try:
text = self.get_output('punch')
if text!=None:
#text = text.read()
punch = obj(norbitals=0)
group_name = None
group_text = ''
new = False
#for line in text.splitlines():
for line in text:
ls = line.strip()
if len(ls)>0 and ls[0]=='$':
if ls=='$END':
punch[group_name] = group_text
group_name = None
group_text = ''
else:
group_name = ls[1:].lower()
group_text = ''
new = True
#end if
#end if
if group_name!=None and not new:
group_text += line#+'\n'
#end if
new = False
#end for
if len(punch)>0:
self.punch=punch
#end if
if 'vec' in punch:
# count the orbitals in vec
norbs = 0
ind_counts = dict()
nbasis = 0
for line in punch.vec.splitlines()[1:-1]:
ind = int(line[:2])
iln = int(line[2:5])
nln = max(nbasis,iln)
if ind not in ind_counts:
ind_counts[ind] = 1
else:
ind_counts[ind] += 1
#end if
#end for
all_double = True
norbs = 0
for ind,cnt in ind_counts.items():
count = cnt//nln
norbs+=count
all_double = all_double and count%2==0
#end for
if all_double:
norbs = norbs//2
#end if
punch.norbitals = norbs
#end if
#end if
except:
if self.info.exit:
self.error('punch file analysis failed')
#end if
#end try
#end def analyze_punch
#end class GamessAnalyzer
|
#!/bin/bash
netcat 127.0.1 1234
|
#!/bin/env node
'use strict';
var fs = require('fs');
var request = require('request-promise-native');
var blessed = require('blessed');
var hostname = 'http://192.168.86.180'
var device_type = "my_hue_app#my_hostname"
var url;
process.title = 'hue_mungus';
process.on('unhandledRejection', (err, promise) => { throw err; /* =[ */ });
async function main() {
var api_key = await login();
url = hostname+"/api/"+api_key+"/";
var lights = await getLights();
console.log("LIGHTS: ", lights)
var screen, lights_box, controls, scripts, box, bar;
screen = blessed.screen({
fastCSR: true
});
screen.title = process.title;
lights_box = blessed.box({
parent: screen,
top: 0,
left: 0,
width: '20%',
//tags: true,
border: {
type: 'line',
left: false,
top: false,
right: true,
bottom: false
},
});
controls = blessed.box({
parent: screen,
top: 0,
right: 0,
//bottom: 1,
width: '80%',
//height: 1,
//tags: true,
border: {
type: 'line',
left: false,
top: false,
right: false,
bottom: true,
},
});
scripts = blessed.box({
parent: screen,
right: 0,
//top: 1,
bottom: 0,
height: 3,
width: '80%',
//tags: true,
border: {
type: 'line',
left: false,
top: true,
right: false,
bottom: false,
},
});
//box = blessed.box({
//parent: screen,
//left: 1,
//height: 1,
////tags: true,
//});
//bar = blessed.box({
//parent: screen,
//left: 1,
//height: 1,
////tags: true,
//});
lights_box.setContent("lights")
controls.setContent("controls")
scripts.setContent("scripts")
//box.setContent("box")
//bar.setContent("bar")
screen.render();
} main();
// ============ //
async function login() {
try {
return fs.readFileSync('api_key').toString();
} catch(e) {}
const response = await request({
url: hostname+'/api',
body: '{"devicetype":"'+device_type+'"}',
method: 'POST',
});
var body = JSON.parse(response)[0]
if (!body.success) {
if (body.error.description == "link button not pressed")
console.log("press button on hub then run again")
else console.log("ERROR:", body.error.description)
process.exit(1)
} else {
fs.writeFileSync('api_key', body.success.username);
return Promise.resolve(body.success.username)
}
}
async function getLights() {
var ll;
var state = JSON.parse(await request(url))
for (var g in state.groups) {
for (var l in state.groups[g].lights) {
ll = state.lights[ state.groups[g].lights[l] ];
ll.group_name = state.groups[g].name;
ll.group_index = l;
}
}
return (state.lights);
}
|
import {
AfterViewInit,
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ContentChild,
DoCheck,
ElementRef,
EventEmitter,
Inject,
InjectionToken,
Input,
OnChanges,
OnDestroy,
Optional,
Output,
Self,
SimpleChanges,
ViewChild,
ViewEncapsulation
} from '@angular/core';
import {DOCUMENT} from '@angular/common';
import {ControlValueAccessor, FormGroupDirective, NgControl, NgForm} from '@angular/forms';
import {coerceBooleanProperty} from '@angular/cdk/coercion';
import {Platform} from '@angular/cdk/platform';
import {Subject} from 'rxjs';
import {takeUntil} from 'rxjs/operators';
import {MDCComponent} from '@angular-mdc/web/base';
import {MdcRipple, MDCRippleCapableSurface} from '@angular-mdc/web/ripple';
import {MdcNotchedOutline} from '@angular-mdc/web/notched-outline';
import {MdcFloatingLabel} from '@angular-mdc/web/floating-label';
import {MdcMenu, MdcMenuSelectedEvent} from '@angular-mdc/web/menu';
import {MdcLineRipple} from '@angular-mdc/web/line-ripple';
import {
MdcFormField,
MdcFormFieldControl,
ErrorStateMatcher,
CanUpdateErrorState,
CanUpdateErrorStateCtor,
mixinErrorState
} from '@angular-mdc/web/form-field';
import {MdcSelectIcon} from './select-icon';
import {MdcSelectHelperTextFoundation} from './helper-text';
import {MDCRippleFoundation, MDCRippleAdapter} from '@material/ripple';
import {
strings,
MDCSelectFoundation,
MDCSelectAdapter,
MDCSelectFoundationMap
} from '@material/select';
/**
* Represents the default options for mdc-select that can be configured
* using an `MDC_SELECT_DEFAULT_OPTIONS` injection token.
*/
export interface MdcSelectDefaultOptions {
outlined?: boolean;
}
/**
* Injection token that can be used to configure the default options for all
* mdc-select usage within an app.
*/
export const MDC_SELECT_DEFAULT_OPTIONS =
new InjectionToken<MdcSelectDefaultOptions>('MDC_SELECT_DEFAULT_OPTIONS');
class MdcSelectBase extends MDCComponent<MDCSelectFoundation> {
constructor(
public _elementRef: ElementRef<HTMLElement>,
public _defaultErrorStateMatcher: ErrorStateMatcher,
public _parentForm: NgForm,
public _parentFormGroup: FormGroupDirective,
public ngControl: NgControl) {
super(_elementRef);
}
}
const _MdcSelectMixinBase: CanUpdateErrorStateCtor & typeof MdcSelectBase =
mixinErrorState(MdcSelectBase);
export class MdcSelectChange {
constructor(
public source: MdcSelect,
public index: number,
public value: any) {}
}
let nextUniqueId = 0;
@Component({
selector: 'mdc-select',
exportAs: 'mdcSelect',
host: {
'[id]': 'id',
'class': 'mdc-select',
'[class.mdc-select--disabled]': 'disabled',
'[class.mdc-select--outlined]': 'outlined',
'[class.mdc-select--required]': 'required',
'[class.mdc-select--no-label]': '!_hasPlaceholder',
'[class.mdc-select--with-leading-icon]': 'leadingIcon',
'[class.mdc-select--invalid]': 'errorState'
},
templateUrl: 'select.html',
providers: [
MdcRipple,
{provide: MdcFormFieldControl, useExisting: MdcSelect}
],
encapsulation: ViewEncapsulation.None,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MdcSelect extends _MdcSelectMixinBase implements AfterViewInit, DoCheck,
OnChanges, OnDestroy, ControlValueAccessor, CanUpdateErrorState, MDCRippleCapableSurface {
/** Emits whenever the component is destroyed. */
private _destroyed = new Subject<void>();
private _uniqueId: string = `mdc-select-${++nextUniqueId}`;
private _initialized = false;
_foundationHelper?: MdcSelectHelperTextFoundation;
_selectedText?: string = '';
_root!: Element;
@Input() id: string = this._uniqueId;
@Input() name?: string;
@Input() helper?: string;
@Input() validationMessage?: string;
/** Placeholder to be shown if no value has been selected. */
@Input() placeholder?: string;
@Input()
get disabled(): boolean {
return this._disabled;
}
set disabled(value: boolean) {
this.setDisabledState(value);
}
private _disabled = false;
@Input()
get outlined(): boolean {
return this._outlined;
}
set outlined(value: boolean) {
const newValue = coerceBooleanProperty(value);
this._outlined = newValue;
this.layout();
}
private _outlined = false;
@Input()
get required(): boolean {
return this._required;
}
set required(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._required) {
this._required = newValue;
if (this._initialized && !this._required) {
this.valid = true;
this._syncHelperValidityState();
this._changeDetectorRef.markForCheck();
}
}
}
private _required = false;
@Input()
get valid(): boolean | undefined {
return this._valid;
}
set valid(value: boolean | undefined) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._valid) {
this._valid = newValue;
this._foundation?.setValid(newValue);
}
}
private _valid?: boolean;
@Input() compareWith: (o1: any, o2: any) => boolean = (a1, a2) => a1 === a2;
/** Value of the select */
@Input()
get value(): any {
return this._value;
}
set value(newValue: any) {
if (newValue !== this._value) {
this.setSelectionByValue(newValue);
}
}
private _value: any;
@Input()
get helperPersistent(): boolean {
return this._helperPersistent;
}
set helperPersistent(value: boolean) {
const newValue = coerceBooleanProperty(value);
if (newValue !== this._helperPersistent) {
this._helperPersistent = newValue;
}
}
private _helperPersistent = false;
get _hasPlaceholder(): boolean {
return this.placeholder ? this.placeholder.length > 0 : false;
}
/** An object used to control when error messages are shown. */
@Input() errorStateMatcher?: ErrorStateMatcher;
/** Event emitted when the selected value has been changed by the user. */
@Output() readonly selectionChange: EventEmitter<MdcSelectChange> =
new EventEmitter<MdcSelectChange>();
/**
* Event that emits whenever the raw value of the select changes. This is here primarily
* to facilitate the two-way binding for the `value` input.
*/
@Output() readonly valueChange: EventEmitter<{index: number, value: any}> = new EventEmitter<any>();
@Output() readonly blur = new EventEmitter<any>();
@Output('focus') readonly _onFocus = new EventEmitter<boolean>();
@ViewChild(MdcFloatingLabel, {static: false}) _floatingLabel?: MdcFloatingLabel;
@ViewChild(MdcLineRipple, {static: false}) _lineRipple?: MdcLineRipple;
@ViewChild(MdcNotchedOutline, {static: false}) _notchedOutline?: MdcNotchedOutline;
@ViewChild('selectAnchor', {static: false}) _selectAnchor!: ElementRef<HTMLDivElement>;
@ViewChild('selectSelectedText', {static: true}) _selectSelectedText!: ElementRef<HTMLInputElement>;
@ContentChild(MdcMenu, {static: false}) _menu!: MdcMenu;
@ContentChild(MdcSelectIcon, {static: false}) leadingIcon?: MdcSelectIcon;
/** View to model callback called when value changes */
_onChange: (value: any) => void = () => {};
/** View to model callback called when select has been touched */
_onTouched = () => {};
getDefaultFoundation(): any {
// Do not initialize foundation until ngAfterViewInit runs
if (!this._initialized) {
return undefined;
}
const adapter: MDCSelectAdapter = {
...this._getSelectAdapterMethods(),
...this._getCommonAdapterMethods(),
...this._getOutlineAdapterMethods(),
...this._getLabelAdapterMethods(),
};
return new MDCSelectFoundation(adapter, this._getFoundationMap());
}
private _getSelectAdapterMethods() {
return {
removeSelectAnchorAttr: (attr: string) => this._selectAnchor.nativeElement.removeAttribute(attr),
getSelectedMenuItem: () =>
this._menu!.elementRef.nativeElement.querySelector(strings.SELECTED_ITEM_SELECTOR),
getMenuItemAttr: (menuItem: Element, attr: string) => menuItem.getAttribute(attr),
setSelectedText: (text: string) => this._selectedText = text,
isSelectAnchorFocused: () => this._platform.isBrowser ?
document.activeElement === this._selectAnchor.nativeElement : false,
getSelectAnchorAttr: (attr: string) => this._selectAnchor.nativeElement.getAttribute(attr),
setSelectAnchorAttr: (attr: string, value: string) => this._selectAnchor.nativeElement.setAttribute(attr, value),
openMenu: () => this._menu.open = true,
closeMenu: () => this._menu.open = false,
getAnchorElement: () => this._selectAnchor.nativeElement,
setMenuAnchorElement: (anchorEl: HTMLElement) => this._menu.anchorElement = anchorEl,
setMenuAnchorCorner: (anchorCorner: any) => this._menu.anchorCorner = anchorCorner,
setMenuWrapFocus: (wrapFocus: boolean) => this._menu.wrapFocus = wrapFocus,
setAttributeAtIndex: (index: number, attributeName: string, attributeValue: string) =>
this._menu._list!.items.toArray()[index].getListItemElement().setAttribute(attributeName, attributeValue),
removeAttributeAtIndex: (index: number, attributeName: string) =>
this._menu._list!.items.toArray()[index].getListItemElement().removeAttribute(attributeName),
focusMenuItemAtIndex: (index: number) => this._menu._list!.items.toArray()[index].focus(),
getMenuItemCount: () => this._menu._list!.items.length,
getMenuItemValues: () => this._menu._list!.items.map(el =>
el.getListItemElement().getAttribute(strings.VALUE_ATTR) || '') ?? [],
getMenuItemTextAtIndex: (index: number) =>
this._menu._list!.items.toArray()[index].getListItemElement().textContent ?? '',
addClassAtIndex: (index: number, className: string) =>
this._menu._list!.items.toArray()[index].getListItemElement().classList.add(className),
removeClassAtIndex: (index: number, className: string) =>
this._menu._list!.items.toArray()[index].getListItemElement().classList.remove(className)
};
}
private _getCommonAdapterMethods() {
return {
isTypeaheadInProgress: () => false,
typeaheadMatchItem: () => -1,
addMenuClass: (className: string) => this._menu.elementRef.nativeElement.classList.add(className),
removeMenuClass: (className: string) => this._menu.elementRef.nativeElement.classList.remove(className),
addClass: (className: string) => this._root.classList.add(className),
removeClass: (className: string) => this._root.classList.remove(className),
hasClass: (className: string) => this._root.classList.contains(className),
setRippleCenter: (normalizedX: number) => this._lineRipple?.setRippleCenter(normalizedX),
activateBottomLine: () => this._lineRipple?.activate(),
deactivateBottomLine: () => this._lineRipple?.deactivate(),
notifyChange: () => {}
};
}
private _getOutlineAdapterMethods() {
return {
hasOutline: () => !!this._notchedOutline,
notchOutline: (labelWidth: number) => this._notchedOutline?.notch(labelWidth),
closeOutline: () => this._notchedOutline?.closeNotch()
};
}
private _getLabelAdapterMethods() {
return {
setLabelRequired: (isRequired: boolean) => this._foundation.setRequired(isRequired),
hasLabel: () => this._hasPlaceholder,
floatLabel: (shouldFloat: boolean) => this._getFloatingLabel()?.float(shouldFloat),
getLabelWidth: () => this._getFloatingLabel()?.getWidth() ?? 0
};
}
/** Returns a map of all subcomponents to subfoundations.*/
private _getFoundationMap(): Partial<MDCSelectFoundationMap> {
return {
helperText: this._foundationHelper?.foundation
};
}
constructor(
private _platform: Platform,
private _changeDetectorRef: ChangeDetectorRef,
public elementRef: ElementRef<HTMLElement>,
public _defaultErrorStateMatcher: ErrorStateMatcher,
@Inject(DOCUMENT) private _document: any,
@Optional() private _parentFormField: MdcFormField,
@Optional() private _ripple: MdcRipple,
@Self() @Optional() public ngControl: NgControl,
@Optional() _parentForm: NgForm,
@Optional() _parentFormGroup: FormGroupDirective,
@Optional() @Inject(MDC_SELECT_DEFAULT_OPTIONS) private _defaults?: MdcSelectDefaultOptions) {
super(elementRef, _defaultErrorStateMatcher, _parentForm, _parentFormGroup, ngControl);
this._root = this.elementRef.nativeElement;
if (this.ngControl) {
// Note: we provide the value accessor through here, instead of
// the `providers` to avoid running into a circular import.
this.ngControl.valueAccessor = this;
}
if (this._parentFormField) {
_parentFormField.elementRef.nativeElement.classList.add('ngx-form-field-select');
}
// Force setter to be called in case id was not specified.
this.id = this.id;
this._setDefaultGlobalOptions();
}
ngOnChanges(changes: SimpleChanges) {
if (changes['helper'] || changes['helperPersistent'] || changes['validationMessage']) {
this._syncHelper();
}
}
ngAfterViewInit(): void {
this._initialized = true;
this._asyncBuildFoundation()
.then(() => {
this._selectBuilder();
});
this._initializeSelection();
this._subscribeToMenuEvents();
}
ngOnDestroy(): void {
this.destroy();
}
/** Override MdcSelectBase destroy method */
destroy(): void {
this._destroyed.next();
this._destroyed.complete();
this._lineRipple?.destroy();
this._ripple.destroy();
this._foundation.destroy();
}
ngDoCheck(): void {
if (this.ngControl) {
// We need to re-evaluate this on every change detection cycle, because there are some
// error triggers that we can't subscribe to (e.g. parent form submissions). This means
// that whatever logic is in here has to be super lean or we risk destroying the performance.
this.updateErrorState();
}
}
writeValue(value: any): void {
if (this._initialized) {
this.setSelectionByValue(value, false);
}
}
registerOnChange(fn: (value: any) => void): void {
this._onChange = fn;
}
registerOnTouched(fn: any): void {
this._onTouched = fn;
}
onFocus(): void {
if (!this.disabled) {
this._foundation.handleFocus();
this._onFocus.emit(true);
}
}
onBlur(): void {
this._foundation.handleBlur();
}
onClick(evt: MouseEvent | TouchEvent): void {
this._foundation.handleClick(this._getNormalizedXCoordinate(evt));
}
onKeydown(evt: KeyboardEvent): void {
this._foundation.handleKeydown(evt);
}
getSelectedIndex(): number {
return this._foundation?.getSelectedIndex() ?? -1;
}
focus(): void {
this._selectAnchor.nativeElement.focus();
}
setSelectedIndex(index: number): void {
this.setSelectionByValue(this._menu._list?.getListItemByIndex(index)?.value, true, index);
}
setSelectionByValue(value: any, isUserInput = true, index?: number): void {
if (!this._value && !value) {
return;
}
if (!index) {
index = this._menu._list?.getListItemIndexByValue(value);
}
this._value = value;
this._foundation.setSelectedIndex(index ?? -1, this._menu.closeSurfaceOnSelection);
if (isUserInput) {
this._onChange(this._value);
this.selectionChange.emit(new MdcSelectChange(this, this.getSelectedIndex(), value));
}
this.valueChange.emit({
index: this.getSelectedIndex(),
value: this._value
});
this._syncHelperValidityState();
this._foundation.handleChange();
this._changeDetectorRef.markForCheck();
}
// Implemented as part of ControlValueAccessor.
setDisabledState(disabled: boolean): void {
this._disabled = coerceBooleanProperty(disabled);
this._foundation?.setDisabled(this._disabled);
this._changeDetectorRef.markForCheck();
}
get _hasValue(): boolean {
return this._value?.length > 0;
}
/** Initialize Select internal state based on the environment state */
private layout(): void {
if (this._initialized) {
this._asyncBuildFoundation().then(() => {
this._selectBuilder();
this._foundation.layout();
});
}
}
private _initializeSelection(): void {
// Defer setting the value in order to avoid the "Expression
// has changed after it was checked" errors from Angular.
Promise.resolve().then(() => {
const value = this.ngControl?.value ?? this._value;
if (value) {
this.setSelectionByValue(value, false);
}
});
}
/** Set the default options. */
private _setDefaultGlobalOptions(): void {
if (this._defaults) {
if (this._defaults.outlined != null) {
this.outlined = this._defaults.outlined;
}
}
}
async _asyncBuildFoundation(): Promise<void> {
this._foundation = this.getDefaultFoundation();
}
async _asyncInitFoundation(): Promise<void> {
this._foundation.init();
}
private _selectBuilder(): void {
this._changeDetectorRef.detectChanges();
// initialize after running a detectChanges()
this._asyncInitFoundation()
.then(() => {
if (!this.outlined) {
this._ripple = this._createRipple();
this._ripple.init();
}
this._menu.wrapFocus = false;
this._menu.elementRef.nativeElement.setAttribute('role', 'listbox');
this._menu.elementRef.nativeElement.classList.add('mdc-select__menu');
if (this._menu._list) {
this._menu._list.useSelectedClass = true;
this._menu._list.singleSelection = true;
}
});
}
private _subscribeToMenuEvents(): void {
// When the list items change, re-subscribe
this._menu._list!.items.changes.pipe(takeUntil(this._destroyed))
.subscribe(() => this._initializeSelection());
// Subscribe to menu opened event
this._menu.opened.pipe(takeUntil(this._destroyed))
.subscribe(() => this._foundation.handleMenuOpened());
// Subscribe to menu closed event
this._menu.closed.pipe(takeUntil(this._destroyed))
.subscribe(() => {
this._foundation.handleMenuClosed();
this._blur();
});
// Subscribe to list-item action event
this._menu.selected.pipe(takeUntil(this._destroyed))
.subscribe((evt: MdcMenuSelectedEvent) => this.setSelectedIndex(evt.index));
}
private _blur(): void {
this._onTouched();
this.blur.emit(this.value);
this._onFocus.emit(false);
this._syncHelperValidityState();
}
private _isValid(): boolean {
return (!!this.validationMessage && !this._hasValue && this.required) || this.errorState;
}
private _getFloatingLabel(): MdcFloatingLabel | undefined {
return this._floatingLabel ?? this._notchedOutline?.floatingLabel;
}
private _syncHelper(): void {
if (this._shouldRenderHelperText()) {
this._initHelperFoundation();
}
this._foundationHelper!.setContent(this.helper ?? '');
this._foundationHelper!.setPersistent(this._helperPersistent);
}
private _syncHelperValidityState(): void {
const showValidationMessage = this._isValid();
if (this._shouldRenderHelperText()) {
this._foundationHelper?.setContent(showValidationMessage ?
this.validationMessage ?? '' : this.helper ?? '');
this._foundationHelper?.setValidation(showValidationMessage);
}
}
private _initHelperFoundation(): void {
if (!this._foundationHelper) {
this._foundationHelper = new MdcSelectHelperTextFoundation(this._elementRef, this._document);
this._foundationHelper.init();
}
}
private _shouldRenderHelperText(): boolean {
return !!this.helper || !!this.validationMessage;
}
/**
* Calculates where the line ripple should start based on the x coordinate within the component.
*/
private _getNormalizedXCoordinate(evt: MouseEvent | TouchEvent): number {
const targetClientRect = (<Element>evt.target).getBoundingClientRect();
if (evt instanceof MouseEvent) {
return evt.clientX - targetClientRect.left;
}
const clientX = evt.touches[0] && evt.touches[0].clientX;
return clientX - targetClientRect.left;
}
private _createRipple(): MdcRipple {
const adapter: MDCRippleAdapter = {
...MdcRipple.createAdapter({_root: this._selectAnchor.nativeElement}),
registerInteractionHandler: (evtType: any, handler: any) =>
this._selectAnchor.nativeElement.addEventListener(evtType, handler),
deregisterInteractionHandler: (evtType: any, handler: any) =>
this._selectAnchor.nativeElement.removeEventListener(evtType, handler)
};
return new MdcRipple(this._selectAnchor, new MDCRippleFoundation(adapter));
}
}
|
#!/bin/bash
set -e
./gradlew clean build
|
var searchData=
[
['nil',['Nil',['../namespacelua.html#classlua_1_1_nil',1,'lua']]]
];
|
from numpy import full
# Create an array filled with blank strings
board = full((6, 7), " ")
# Variable exists to stop main loop when someone wins
win = False
def clear():
# Clears the screen
print("\n" * 100)
def displayBoard():
# Prints the board
print(" " + str(board)[1:-1])
def p1Input():
selection = int(input("P1: Enter a row number between 1-7: "))
# Makes it so the player has to actually put in an input
done = False
while not done:
# Checks each row so the pieces can "stack" on each other
if board[5][selection - 1] == " ":
board[5][selection - 1] = "x"
done = True
elif board[4][selection - 1] == " ":
board[4][selection - 1] = "x"
done = True
elif board[3][selection - 1] == " ":
board[3][selection - 1] = "x"
done = True
elif board[2][selection - 1] == " ":
board[2][selection - 1] = "x"
done = True
elif board[1][selection - 1] == " ":
board[1][selection - 1] = "x"
done = True
elif board[0][selection - 1] == " ":
board[0][selection - 1] = "x"
done = True
else:
print("All spaces on this row are taken!")
p1Input()
done = True
def p2Input():
selection = int(input("P2: Enter a row number between 1-7: "))
# Makes it so the player has to actually put in an input
done = False
while not done:
# Checks each row so the pieces can "stack" on each other
if board[5][selection - 1] == " ":
board[5][selection - 1] = "o"
done = True
elif board[4][selection - 1] == " ":
board[4][selection - 1] = "o"
done = True
elif board[3][selection - 1] == " ":
board[3][selection - 1] = "o"
done = True
elif board[2][selection - 1] == " ":
board[2][selection - 1] = "o"
done = True
elif board[1][selection - 1] == " ":
board[1][selection - 1] = "o"
done = True
elif board[0][selection - 1] == " ":
board[0][selection - 1] = "o"
done = True
else:
print("All spaces on this row are taken!")
def main():
# Temp, might make a better way
while not win:
clear()
displayBoard()
p1Input()
clear()
displayBoard()
p2Input()
main()
|
<reponame>YourBetterAssistant/yourbetterassistant
import { Message } from "discord.js";
import model from "../Schemas/autoMod";
const badwords = require("badwords/array");
function isUpperCase(str: string) {
if (
str.includes("@") ||
str.includes("<") ||
str.includes(
">" ||
str.includes("!") ||
str.includes("%") ||
str.includes("#") ||
str.includes("&")
)
)
return false;
if (str.length < 5) return false;
else {
return str === str.toUpperCase();
}
}
class Model {
public message: any;
public client: any;
constructor(message: Message) {
this.message = message;
this.client = message.client;
}
async checkProfanity() {
const message = this.message;
badwords.forEach((word: string) => {
if (message.content.includes(word)) {
const channel = message.channel;
const author = message.author;
message.delete();
channel.send(
`${message.author}, Strict-Mode is Enabled Please Don't Use That Word Again`
);
}
});
}
async allCaps() {
const message = this.message;
if (isUpperCase(message.content) === true) {
return message.channel.send("Stop Spamming Caps!");
}
}
}
export default Model;
|
require 'twilio-ruby'
response = Twilio::TwiML::VoiceResponse.new
response.record
puts response
|
#!/bin/bash
git status
sleep 2
echo "-------Begin-------"
if [ ! $1 ]; then
read -r -p "Please input your Video commit message: " input
else
input=$1
fi
git add -A
if [ $input ]; then
git commit -am $input
else
git commit -am "自动化代码提交"
fi
git push origin master
git fetch
result=$(git tag --list)
OLD_IFS="$IFS"
arr=($result)
IFS="$OLD_IFS"
lastTag=${arr[${#arr[*]}-1]}
OLD_IFS=$IFS
IFS='.'
arr1=($lastTag)
IFS=$OLD_IFS
lastchar=${arr1[${#arr1[*]}-1]}
latestChar=$[$lastchar+1]
echo $latestChar
latestTag=${arr1[0]}.${arr1[1]}.$latestChar
for((k=0;k<100;k++)) do
if [[ "${arr[@]}" =~ $latestTag ]];then
latestChar=$[$latestChar+1]
latestTag=${arr1[0]}.${arr1[1]}.$latestChar
fi
done;
echo "自动升级tag为:"$latestTag
git tag $latestTag
git push -v origin refs/tags/$latestTag
sleep 3
echo "自动发版到MDSpecs"
#./publishHelper.sh
#获取podspec文件名称
packageDIR=`pwd`
podName=${packageDIR##*/}
podspecFile=${podName}'.podspec'
echo "podName ----->"${podName}
echo 'COMMIT-podspec-FILE'
sourceRepo='https://github.com/Leon0206/MDSpecs.git'
sourceRepoName='MDSpecs'
version=`git describe --abbrev=0 --tags 2>/dev/null`
cd ..
specsDir=`pwd`/${sourceRepoName}/
echo "specsdir ---->"$specsDir
if [ -d $specsDir ];
then
cd $specsDir
git pull
else
git clone $sourceRepo
cd $specsDir
fi
echo 'FILE-PATH:'
echo ${specsDir}${podName}/${version}
echo $packageDIR/${podspecFile}
mkdir -p ${specsDir}${podName}/${version}
echo ${specsDir}${podName}/${version}/${podspecFile}
cp $packageDIR/${podspecFile} ${specsDir}${podName}/${version}
echo '文件copy'
destSource='"'${version}'"'
sed -i '' 's/= smart_version/= '${destSource}'/g' ${specsDir}${podName}/${version}/${podspecFile}
echo '替换版本号'
nowDIR=`pwd`
echo 'nowDIR->' ${nowDIR}
git status
git add .
git commit -m "[Add] ${podName} (${version})"
git push
cd ..
rm -rf specs
echo "--------End--------"
|
<reponame>ParinModi2/Free-Door<gh_stars>1-10
var comment = require('../Model/Comment');
var user = require('../Model/User');
var Product = require('../Model/Product');
var Category = require('../Model/Category');
var offer = require('../Model/Offer');
var ejs = require("ejs");
exports.index = function(req, res){
res.render('Home');
};
exports.validateUser =function(req,res){
console.log("validate user");
var newUser = new user();
newUser.validateUser(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json(result);
}
},req.body);
console.log("Username "+ req.param('userName'));
};
exports.createuser =function(req,res){
var newUser = new user();
newUser.createUser(function(err,result) {
if(err){
console.log("Error"+err);
res.json(err);
}else
{
console.log(result);
res.json(result);
}
},req.body);
console.log("Username"+ req.param('userName'));
console.log("Username"+ req.param('password'));
};
exports.viewCustomers =function(req,res){
console.log("view customers");
var newUser = new user();
newUser.viewCustomers(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json(result);
}
},req.body);
};
exports.updateuser =function(req,res){
console.log("Update user");
var newUser = new user();
newUser.updateUser(function(err,result) {
if(err){
console.log("Error"+err);
res.json(err);
//throw(err);
}else
{
console.log("success");
res.json(result);
}
},req.body);
};
exports.getUserById = function(req,res){
console.log("In get user by id"+req.params.userId);
var newUser = new user();
newUser.getUserById(function(err,result){
if(err){
console.log("Get user by Id"+err);
res.json(err);
}else{
console.log("return "+result);
res.json(result);
}
}, req.params.userId);
};
exports.removeUser = function(req,res){
console.log("remove user error"+req.params.emailId);
var newUser = new user();
newUser.remove(function(err,result){
if(err){
console.log("remove user error"+err);
res.json(err);
}else{
console.log("return "+result);
res.json({"status": "success", "Message": "User Deleted"});
}
}, req.params.emailId);
};
//Product Related
exports.createProduct =function(req,res){
var newProduct = new Product();
newProduct.createProduct(function(err,result) {
if(err){
console.log("Error"+err);
res.json(err);
}else
{
res.json(result);
}
},req.body,req.params.categoryId);
};
exports.updateProduct =function(req,res){
console.log("Update Product");
var newProduct = new Product();
newProduct.updateProduct(function(err,result) {
if(err){
console.log("Error"+err);
res.json(err);
}else
{
console.log("success");
res.json(result);
}
},req.body,req.params.categoryId,req.params.productId);
};
exports.removeProduct = function(req,res){
var newProduct = new Product();
newProduct.remove(function(err,result){
if(err){
console.log("remove Product error"+err);
res.json(err);
}else{
console.log("return "+result);
res.json({});
}
}, req.params.productId,req.params.categoryId);
};
exports.getProductById = function(req,res){
console.log("In get user by id"+req.params.productId);
var newProduct = new Product();
newProduct.getProductById(function(err,result){
if(err){
console.log("Get Product by Id"+err);
res.json(err);
}else{
console.log("return "+result);
res.json(result);
}
}, req.params.productId,req.params.categoryId);
};
exports.getProductsBycatId = function(req,res){
console.log("In get Product by id"+req.params.categoryId);
var newProduct = new Product();
newProduct.getProductsBycatId(function(err,result){
if(err){
console.log("Get Product by Id"+err);
res.json(err);
}else{
console.log("return "+result);
res.json({'products':result});
}
}, req.params.categoryId);
};
//Category
exports.createCategory =function(req,res){
var newCategory = new Category();
newCategory.createCategory(function(err,result) {
if(err){
console.log("Error"+err);
res.json(err);
}else
{
res.json(result);
}
},req.body);
};
exports.viewCategories =function(req,res){
console.log("view categories");
var newCategory = new Category();
newCategory.viewCategories(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json({'categories':result});
}
},req.body);
};
exports.getCategoryById = function(req,res){
console.log("In get user by id"+req.params.categoryId);
var newCategory = new Category();
newCategory.getCategoryById(function(err,result){
if(err){
console.log("Get category by Id"+err);
res.json(err);
}else{
console.log("return "+result);
res.json(result);
}
}, req.params.categoryId);
};
exports.createoffer =function(req,res){
console.log("create offer\n");
var newOffer = new offer();
var a = req.param;
console.log("body: "+req.body);
console.log("req.params.productId: "+req.params.productId);
newOffer.createOffer(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json(result);
}
},req.params.productId,req.body);
};
exports.viewOffers =function(req,res){
console.log("view offers");
var newOffer = new offer();
newOffer.viewOffers(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json(result);
}
},req.params.categoryId);
};
exports.byofferid =function(req,res){
console.log("view offers by offerid");
var newOffer = new offer();
newOffer.byofferid(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json(result);
}
},req.params.offerId);
};
exports.byproductid =function(req,res){
console.log("view offers by product id");
var newOffer = new offer();
newOffer.viewOffers(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
res.json(result);
}
},req.params.productId,req.params.categoryId);
};
exports.updateoffer =function(req,res){
console.log("Update offer"+ req.params.offerId);
var newOffer = new offer();
newOffer.updateOffer(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
console.log("success");
res.json(result);
}
},req.params.offerId,req.params.productId,req.body);
};
exports.removeOffer = function(req,res){
var newOffer = new offer();
newOffer.remove(function(err,result){
if(err){
console.log("remove offer error"+err);
res.json(err);
}else{
console.log("return "+result);
res.json({});
}
}, req.params.productId,req.params.categoryId,req.params.offerId);
};
//comment
exports.postComment =function(req,res){
console.log("Post Comment");
var newcomment = new comment();
newcomment.postComment(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
console.log("success");
res.json(result);
}
},req.params,req.body);
};
exports.getCommentHistory =function(req,res){
console.log("Get Comment History");
var newComment = new comment();
newComment.getCommentHistory(function(err,result) {
if(err){
console.log("Error"+err);
throw(err);
}else
{
console.log("success");
res.json(result);
}
},req.body);
};
|
import React, { PureComponent } from 'react';
import { ThemeProvider } from 'styled-components';
import Loading from '../../utils/Loading';
import { SectionHeader, Section, ExpGrid, ExpHeaderGrid, ExpFooter, ExpContainer } from '../Styled';
import { key } from '../../utils';
import api from '../../api';
const theme = {
fontColor: '#fff',
};
class Experience extends PureComponent {
state = {
loading: true,
experience: [],
};
componentDidMount = async () => {
const experience = await api.experience();
await this.setState({ experience, loading: false });
};
renderExperience = experience => {
const output = experience.map(e => (
<div key={key()}>
<ExpGrid>
<ExpHeaderGrid>
<img src={e.companyLogo} alt={e.companyName} />
<div className="exp__companyName">
{e.companyName}
<span className="exp__jobTitle">{e.jobTitle}</span>
</div>
</ExpHeaderGrid>
<div className="exp__companyDescription">{e.companyDescription}</div>
<ol className="exp__responsibilities">
<span>Responsibilities</span>
{e.responsibilities.map(r => (
<li key={key()}>{r}</li>
))}
</ol>
</ExpGrid>
<ExpFooter>
{e.date} | {e.location}
</ExpFooter>
</div>
));
return <ExpContainer>{output}</ExpContainer>;
};
render() {
const { experience, loading } = this.state;
return (
<div style={{ background: '#fff' }}>
<ThemeProvider theme={theme}>
<Section bg="#090909">
<SectionHeader>experience.</SectionHeader>
</Section>
</ThemeProvider>
{loading ? <Loading /> : this.renderExperience(experience)}
</div>
);
}
}
export default Experience;
|
// Copyright 2019 Google LLC
//
// 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.
// Code generated by protoc-gen-go. DO NOT EDIT.
// source: backend/api/pipeline_spec.proto
package go_client // import "github.com/kubeflow/pipelines/backend/api/go_client"
import proto "github.com/golang/protobuf/proto"
import fmt "fmt"
import math "math"
// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = fmt.Errorf
var _ = math.Inf
// This is a compile-time assertion to ensure that this generated file
// is compatible with the proto package it is being compiled against.
// A compilation error at this line likely means your copy of the
// proto package needs to be updated.
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
type PipelineSpec struct {
PipelineId string `protobuf:"bytes,1,opt,name=pipeline_id,json=pipelineId,proto3" json:"pipeline_id,omitempty"`
WorkflowManifest string `protobuf:"bytes,2,opt,name=workflow_manifest,json=workflowManifest,proto3" json:"workflow_manifest,omitempty"`
PipelineManifest string `protobuf:"bytes,3,opt,name=pipeline_manifest,json=pipelineManifest,proto3" json:"pipeline_manifest,omitempty"`
Parameters []*Parameter `protobuf:"bytes,4,rep,name=parameters,proto3" json:"parameters,omitempty"`
XXX_NoUnkeyedLiteral struct{} `json:"-"`
XXX_unrecognized []byte `json:"-"`
XXX_sizecache int32 `json:"-"`
}
func (m *PipelineSpec) Reset() { *m = PipelineSpec{} }
func (m *PipelineSpec) String() string { return proto.CompactTextString(m) }
func (*PipelineSpec) ProtoMessage() {}
func (*PipelineSpec) Descriptor() ([]byte, []int) {
return fileDescriptor_pipeline_spec_c12474a229d1b653, []int{0}
}
func (m *PipelineSpec) XXX_Unmarshal(b []byte) error {
return xxx_messageInfo_PipelineSpec.Unmarshal(m, b)
}
func (m *PipelineSpec) XXX_Marshal(b []byte, deterministic bool) ([]byte, error) {
return xxx_messageInfo_PipelineSpec.Marshal(b, m, deterministic)
}
func (dst *PipelineSpec) XXX_Merge(src proto.Message) {
xxx_messageInfo_PipelineSpec.Merge(dst, src)
}
func (m *PipelineSpec) XXX_Size() int {
return xxx_messageInfo_PipelineSpec.Size(m)
}
func (m *PipelineSpec) XXX_DiscardUnknown() {
xxx_messageInfo_PipelineSpec.DiscardUnknown(m)
}
var xxx_messageInfo_PipelineSpec proto.InternalMessageInfo
func (m *PipelineSpec) GetPipelineId() string {
if m != nil {
return m.PipelineId
}
return ""
}
func (m *PipelineSpec) GetWorkflowManifest() string {
if m != nil {
return m.WorkflowManifest
}
return ""
}
func (m *PipelineSpec) GetPipelineManifest() string {
if m != nil {
return m.PipelineManifest
}
return ""
}
func (m *PipelineSpec) GetParameters() []*Parameter {
if m != nil {
return m.Parameters
}
return nil
}
func init() {
proto.RegisterType((*PipelineSpec)(nil), "api.PipelineSpec")
}
func init() {
proto.RegisterFile("backend/api/pipeline_spec.proto", fileDescriptor_pipeline_spec_c12474a229d1b653)
}
var fileDescriptor_pipeline_spec_c12474a229d1b653 = []byte{
// 219 bytes of a gzipped FileDescriptorProto
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0xff, 0xe2, 0x92, 0x4f, 0x4a, 0x4c, 0xce,
0x4e, 0xcd, 0x4b, 0xd1, 0x4f, 0x2c, 0xc8, 0xd4, 0x2f, 0xc8, 0x2c, 0x48, 0xcd, 0xc9, 0xcc, 0x4b,
0x8d, 0x2f, 0x2e, 0x48, 0x4d, 0xd6, 0x2b, 0x28, 0xca, 0x2f, 0xc9, 0x17, 0x62, 0x4e, 0x2c, 0xc8,
0x94, 0x92, 0x46, 0x51, 0x95, 0x58, 0x94, 0x98, 0x9b, 0x5a, 0x92, 0x5a, 0x04, 0x51, 0xa1, 0xb4,
0x93, 0x91, 0x8b, 0x27, 0x00, 0xaa, 0x33, 0xb8, 0x20, 0x35, 0x59, 0x48, 0x9e, 0x8b, 0x1b, 0x6e,
0x52, 0x66, 0x8a, 0x04, 0xa3, 0x02, 0xa3, 0x06, 0x67, 0x10, 0x17, 0x4c, 0xc8, 0x33, 0x45, 0x48,
0x9b, 0x4b, 0xb0, 0x3c, 0xbf, 0x28, 0x3b, 0x2d, 0x27, 0xbf, 0x3c, 0x3e, 0x37, 0x31, 0x2f, 0x33,
0x2d, 0xb5, 0xb8, 0x44, 0x82, 0x09, 0xac, 0x4c, 0x00, 0x26, 0xe1, 0x0b, 0x15, 0x07, 0x29, 0x86,
0x9b, 0x06, 0x57, 0xcc, 0x0c, 0x51, 0x0c, 0x93, 0x80, 0x2b, 0xd6, 0xe3, 0xe2, 0x82, 0x3b, 0xaf,
0x58, 0x82, 0x45, 0x81, 0x59, 0x83, 0xdb, 0x88, 0x4f, 0x2f, 0xb1, 0x20, 0x53, 0x2f, 0x00, 0x26,
0x1c, 0x84, 0xa4, 0xc2, 0xc9, 0x34, 0xca, 0x38, 0x3d, 0xb3, 0x24, 0xa3, 0x34, 0x49, 0x2f, 0x39,
0x3f, 0x57, 0x3f, 0xbb, 0x34, 0x29, 0x15, 0x64, 0x37, 0x3c, 0x20, 0x8a, 0xf5, 0x91, 0x3d, 0x9e,
0x9e, 0x1f, 0x9f, 0x9c, 0x93, 0x99, 0x9a, 0x57, 0x92, 0xc4, 0x06, 0xf6, 0xb9, 0x31, 0x20, 0x00,
0x00, 0xff, 0xff, 0x4e, 0x8a, 0xbc, 0x57, 0x3e, 0x01, 0x00, 0x00,
}
|
<filename>spec/logic/package/information_extractor_spec.rb
require 'spec_helper'
require_relative '../../../logic/package/information_extractor'
# Ideally we should be more concise about the different cases
# For brevity, I added the first 5 packages descriptions and their parsing results as test cases
RSpec.describe Logic::Package::InformationExtractor do
subject(:call) { described_class.call(package_description) }
context '.call' do
[
{
package_description: {
"Package" => "A3",
"Type" => "Package",
"Title" => "Accurate, Adaptable, and Accessible Error Metrics for ...",
"Version" => "1.0.0",
"Date" => "2015-08-15",
"Author" => "<NAME>",
"Maintainer" => "<NAME> <<EMAIL>>",
"Description" => "Supplies tools for tabulating and analyzing the results of ...",
"License" => "GPL (>= 2)",
"Depends" => "R (>= 2.15.0), xtable, pbapply",
"Suggests" => "randomForest, e1071",
"NeedsCompilation" => "no",
"Packaged" => "2015-08-16 14:17:33 UTC; scott",
"Repository" => "CRAN",
"Date/Publication" => "2015-08-16 23:05:52"
},
parsed_description: {
name: "A3",
version: "1.0.0",
publication_date: "2015-08-16 23:05:52",
title: "Accurate, Adaptable, and Accessible Error Metrics for ...",
description: "Supplies tools for tabulating and analyzing the results of ...",
authors: [
{
name: "<NAME>",
email: nil,
roles: ["aut"]
}
],
maintainers: [
{
name: "<NAME>",
email: "<EMAIL>",
roles: ["cre"]
}
]
}
},
{
package_description: {
"Package" => "abbyyR",
"Title" => "Access to Abbyy Optical Character Recognition (OCR) API",
"Version" => "0.5.4",
"Authors@R" => "person(\"Gaurav\", \"Sood\", email = \"<EMAIL>\", "\
"role = c(\"aut\", \"cre\"))",
"Maintainer" => "<NAME> <<EMAIL>>",
"Description" => "Get text from images of text using Abbyy Cloud Optical Cha ...",
"URL" => "http://github.com/soodoku/abbyyR",
"BugReports" => "http://github.com/soodoku/abbyyR/issues",
"Depends" => "R (>= 3.2.0)",
"License" => "MIT + file LICENSE",
"LazyData" => "true",
"VignetteBuilder" => "knitr",
"Imports" => "httr, XML, curl, readr, plyr, progress",
"Suggests" => "testthat, rmarkdown, knitr (>= 1.11), lintr",
"RoxygenNote" => "6.0.1.9000",
"NeedsCompilation" => "no",
"Packaged" => "2018-05-30 12:47:37 UTC; soodoku",
"Author" => "<NAME> [aut, cre]",
"Repository" => "CRAN",
"Date/Publication" => "2018-05-30 13:20:41 UTC"
},
parsed_description: {
name: "abbyyR",
version: "0.5.4",
publication_date: "2018-05-30 13:20:41 UTC",
title: "Access to Abbyy Optical Character Recognition (OCR) API",
description: "Get text from images of text using Abbyy Cloud Optical Cha ...",
authors: [
{
name: "<NAME>",
roles: ["aut", "cre"],
email: "<EMAIL>"
}
],
maintainers: [
{
name: "<NAME>",
roles: ["aut", "cre"],
email: "<EMAIL>"
},
{
name: "<NAME>",
email: "<EMAIL>",
roles: ["cre"]
}
]
}
},
{
package_description: {
"Package" => "abc",
"Type" => "Package",
"Title" => "Tools for Approximate Bayesian Computation (ABC)",
"Version" => "2.1",
"Date" => "2015-05-04",
"Authors@R" =>
"c( person(\"Csillery\", \"Katalin\", role = \"aut\", "\
"email=\"<EMAIL>\"), person(\"Lemaire\", \"Louisiane\", "\
"role = \"aut\"), person(\"Francois\", \"Olivier\", role = \"aut\"), "\
"person(\"Blum\", \"Michael\", email = \"<EMAIL>\", "\
"role = c(\"aut\", \"cre\")))",
"Depends" => "R (>= 2.10), abc.data, nnet, quantreg, MASS, locfit",
"Description" => "Implements several ABC algorithms for ...",
"Repository" => "CRAN",
"License" => "GPL (>= 3)",
"NeedsCompilation" => "no",
"Packaged" => "2015-05-05 08:35:25 UTC; mblum",
"Author" =>
"<NAME> [aut], <NAME> [aut], <NAME> [aut], <NAME> [aut, cre]",
"Maintainer" => "Bl<NAME> <<EMAIL>>",
"Date/Publication" => "2015-05-05 11:34:14"
},
parsed_description: {
name: "abc",
version: "2.1",
publication_date: "2015-05-05 11:34:14",
title: "Tools for Approximate Bayesian Computation (ABC)",
description: "Implements several ABC algorithms for ...",
authors: [
{
name: "<NAME>",
roles: ["aut"],
email: nil
},
{
name: "<NAME>",
roles: ["aut"],
email: nil
},
{
name: "<NAME>",
roles: ["aut", "cre"],
email: "<EMAIL>"
}
],
maintainers: [
{
name: "<NAME>",
roles: ["aut", "cre"],
email: "<EMAIL>"
},
{
name: "<NAME>",
email: "<EMAIL>",
roles: ["cre"]
}
]
}
},
{
package_description: {
"Package" => "abc.data",
"Type" => "Package",
"Title" => "Data Only: Tools for Approximate Bayesian Computation (ABC)",
"Version" => "1.0",
"Date" => "2015-05-04",
"Authors@R" => "c( person(\"Csillery\", \"Katalin\", role = \"aut\", "\
"email=\"<EMAIL>\"), person(\"Lemaire\", \"Louisiane\", "\
"role = \"aut\"), person(\"Francois\", \"Olivier\", role = \"aut\"), "\
"person(\"Blum\", \"Michael\", email = \"<EMAIL>\", "\
"role = c(\"aut\", \"cre\")))",
"Depends" => "R (>= 2.10)",
"Description" => "Contains data which are used by functions of the 'abc' package.",
"Repository" => "CRAN",
"License" => "GPL (>= 3)",
"NeedsCompilation" => "no",
"Packaged" => "2015-05-05 09:25:25 UTC; mblum",
"Author" => "<NAME> [aut], <NAME> [aut], "\
"<NAME> [aut], <NAME> [aut, cre]",
"Maintainer" => "<NAME> <<EMAIL>>",
"Date/Publication" => "2015-05-05 11:34:13"
},
parsed_description: {
name: "abc.data",
version: "1.0",
publication_date: "2015-05-05 11:34:13",
title: "Data Only: Tools for Approximate Bayesian Computation (ABC)",
description: "Contains data which are used by functions of the 'abc' package.",
authors: [
{
name: "<NAME>",
roles: ["aut"],
email: nil
},
{
name: "<NAME>",
roles: ["aut"],
email: nil
},
{
name: "<NAME>",
roles: ["aut", "cre"],
email: "<EMAIL>"
}
],
maintainers: [
{
name: "<NAME>",
roles: ["aut", "cre"],
email: "<EMAIL>"
},
{
name: "<NAME>",
email: "<EMAIL>",
roles: ["cre"]
}
]
}
},
{
package_description: {
"Package" => "ABC.RAP",
"Title" => "Array Based CpG Region Analysis Pipeline",
"Version" => "0.9.0",
"Author" => "<NAME> [cre, aut], <NAME>s [aut], "\
"<NAME> [aut], RStudio [ctb]",
"Maintainer" => "<NAME> <<EMAIL>>",
"Contact" => "<NAME> <<EMAIL>>",
"Description" => "It aims to identify candidate genes that are ...",
"License" => "GPL-3",
"Depends" => "R (>= 3.1.0)",
"Imports" => "graphics, stats, utils",
"Suggests" => "knitr, rmarkdown",
"VignetteBuilder" => "knitr",
"Encoding" => "UTF-8",
"SystemRequirements" => "GNU make",
"RoxygenNote" => "5.0.1.9000",
"NeedsCompilation" => "no",
"Packaged" => "2016-10-20 01:50:08 UTC; abdul",
"Repository" => "CRAN",
"Date/Publication" => "2016-10-20 10:52:16"
},
parsed_description: {
name: "ABC.RAP",
version: "0.9.0",
publication_date: "2016-10-20 10:52:16",
title: "Array Based CpG Region Analysis Pipeline",
description: "It aims to identify candidate genes that are ...",
authors: [
{ name: "<NAME>", email: nil, roles: ["cre", "aut"] },
{ name: "<NAME>", email: nil, roles: ["aut"] },
{ name: "<NAME>", email: nil, roles: ["aut"] }
],
maintainers: [
{
name: "<NAME>",
email: "<EMAIL>",
roles: ["cre"]
}
]
}
}
].each_with_index do |test_case, index|
context "Test case: #{index}" do
let(:package_description) { test_case[:package_description] }
let(:result) { test_case[:parsed_description] }
it 'runs successfully' do
expect(call).to eq result
end
end
end
end
end
|
// Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <grp.h>
#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include <memory>
#include <string>
#include <vector>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/files/scoped_temp_dir.h>
#include <dbus/mock_bus.h>
#include <gtest/gtest.h>
#include <cryptohome/proto_bindings/rpc.pb.h>
#include <cryptohome-client-test/cryptohome/dbus-proxy-mocks.h>
#include "debugd/src/log_tool.h"
using testing::_;
using testing::Invoke;
using testing::Return;
using testing::WithArg;
namespace {
bool CreateDirectoryAndWriteFile(const base::FilePath& path,
const std::string& contents) {
return base::CreateDirectory(path.DirName()) &&
base::WriteFile(path, contents.c_str(), contents.length()) ==
contents.length();
}
} // namespace
namespace debugd {
class FakeLog : public LogTool::Log {
public:
MOCK_METHOD(std::string, GetLogData, (), (const, override));
};
class LogToolTest : public testing::Test {
protected:
std::unique_ptr<LogTool> log_tool_;
base::ScopedTempDir temp_dir_;
void SetUp() override {
ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
log_tool_ = std::unique_ptr<LogTool>(new LogTool(
new dbus::MockBus(dbus::Bus::Options()),
std::make_unique<org::chromium::CryptohomeInterfaceProxyMock>(),
std::make_unique<FakeLog>(), temp_dir_.GetPath()));
ON_CALL(*GetFakeLog(), GetLogData).WillByDefault(Return("fake"));
}
FakeLog* GetFakeLog() {
return static_cast<FakeLog*>(log_tool_->arc_bug_report_log_.get());
}
std::string GetArcBugReport(const std::string& username, bool* is_backup) {
return log_tool_->GetArcBugReport(username, is_backup);
}
org::chromium::CryptohomeInterfaceProxyMock* GetCryptHomeProxy() {
return static_cast<org::chromium::CryptohomeInterfaceProxyMock*>(
log_tool_->cryptohome_proxy_.get());
}
void SetArcBugReportBackup(const std::string& userhash) {
log_tool_->arc_bug_report_backups_.insert(userhash);
}
};
TEST_F(LogToolTest, GetArcBugReport_ReturnsContents_WhenFileExists) {
std::string userhash = "0abcdef1230abcdef1230abcdef1230abcdef123";
base::FilePath logPath =
temp_dir_.GetPath().Append(userhash).Append("arc-bugreport.log");
EXPECT_TRUE(CreateDirectoryAndWriteFile(logPath, "test"));
EXPECT_TRUE(base::PathExists(logPath));
SetArcBugReportBackup(userhash);
EXPECT_CALL(*GetCryptHomeProxy(), GetSanitizedUsername("username", _, _, _))
.WillOnce(WithArg<1>(Invoke([&userhash](std::string* out_sanitized) {
*out_sanitized = userhash;
return true;
})));
bool is_backup;
std::string report = GetArcBugReport("username", &is_backup);
EXPECT_EQ(report, "test");
EXPECT_TRUE(is_backup);
}
TEST_F(LogToolTest, GetArcBugReport_Succeeds_WhenIsBackupIsNull) {
std::string userhash = "0abcdef1230abcdef1230abcdef1230abcdef123";
base::FilePath logPath =
temp_dir_.GetPath().Append(userhash).Append("arc-bugreport.log");
EXPECT_TRUE(CreateDirectoryAndWriteFile(logPath, "test"));
SetArcBugReportBackup(userhash);
EXPECT_CALL(*GetCryptHomeProxy(), GetSanitizedUsername("username", _, _, _))
.WillOnce(WithArg<1>(Invoke([&userhash](std::string* out_sanitized) {
*out_sanitized = userhash;
return true;
})));
std::string report = GetArcBugReport("username", nullptr /*is_backup*/);
EXPECT_EQ(report, "test");
}
TEST_F(LogToolTest, GetArcBugReport_DeletesFile_WhenBackupNotSet) {
std::string userhash = "0abcdef1230abcdef1230abcdef1230abcdef123";
base::FilePath logPath =
temp_dir_.GetPath().Append(userhash).Append("arc-bugreport.log");
EXPECT_TRUE(CreateDirectoryAndWriteFile(logPath, "test"));
EXPECT_TRUE(base::PathExists(logPath));
EXPECT_CALL(*GetFakeLog(), GetLogData);
EXPECT_CALL(*GetCryptHomeProxy(), GetSanitizedUsername("username", _, _, _))
.WillRepeatedly(
WithArg<1>(Invoke([&userhash](std::string* out_sanitized) {
*out_sanitized = userhash;
return true;
})));
bool is_backup;
std::string report = GetArcBugReport("username", &is_backup);
EXPECT_EQ(report, "fake");
EXPECT_FALSE(is_backup);
EXPECT_FALSE(base::PathExists(logPath));
}
TEST_F(LogToolTest, DeleteArcBugReportBackup) {
std::string userhash = "0abcdef1230abcdef1230abcdef1230abcdef123";
base::FilePath logPath =
temp_dir_.GetPath().Append(userhash).Append("arc-bugreport.log");
EXPECT_TRUE(CreateDirectoryAndWriteFile(logPath, userhash));
EXPECT_TRUE(base::PathExists(logPath));
EXPECT_CALL(*GetCryptHomeProxy(), GetSanitizedUsername("username", _, _, _))
.WillOnce(WithArg<1>(Invoke([&userhash](std::string* out_sanitized) {
*out_sanitized = userhash;
return true;
})));
log_tool_->DeleteArcBugReportBackup("username");
EXPECT_FALSE(base::PathExists(logPath));
}
TEST_F(LogToolTest, EncodeString) {
// U+1F600 GRINNING FACE
constexpr const char kGrinningFaceUTF8[] = "\xF0\x9F\x98\x80";
constexpr const char kGrinningFaceBase64[] = "<base64>: 8J+YgA==";
EXPECT_EQ(
kGrinningFaceUTF8,
LogTool::EncodeString(kGrinningFaceUTF8, LogTool::Encoding::kAutodetect));
EXPECT_EQ(kGrinningFaceUTF8,
LogTool::EncodeString(kGrinningFaceUTF8, LogTool::Encoding::kUtf8));
EXPECT_EQ(
kGrinningFaceBase64,
LogTool::EncodeString(kGrinningFaceUTF8, LogTool::Encoding::kBase64));
// .xz Stream Header Magic Bytes
constexpr const char kXzStreamHeaderMagicBytes[] = "\xFD\x37\x7A\x58\x5A\x00";
constexpr const char kXzStreamHeaderMagicUTF8[] =
"\xEF\xBF\xBD"
"7zXZ";
constexpr const char kXzStreamHeaderMagicBase64[] = "<base64>: /Td6WFo=";
EXPECT_EQ(kXzStreamHeaderMagicBase64,
LogTool::EncodeString(kXzStreamHeaderMagicBytes,
LogTool::Encoding::kAutodetect));
EXPECT_EQ(kXzStreamHeaderMagicUTF8,
LogTool::EncodeString(kXzStreamHeaderMagicBytes,
LogTool::Encoding::kUtf8));
EXPECT_EQ(kXzStreamHeaderMagicBase64,
LogTool::EncodeString(kXzStreamHeaderMagicBytes,
LogTool::Encoding::kBase64));
EXPECT_EQ(kXzStreamHeaderMagicBytes,
LogTool::EncodeString(kXzStreamHeaderMagicBytes,
LogTool::Encoding::kBinary));
}
class LogTest : public testing::Test {
protected:
void SetUp() override {
std::vector<char> buf(1024);
uid_t uid = getuid();
struct passwd pw_entry;
struct passwd* pw_result;
ASSERT_EQ(getpwuid_r(uid, &pw_entry, &buf[0], buf.size(), &pw_result), 0);
ASSERT_NE(pw_result, nullptr);
user_name_ = pw_entry.pw_name;
gid_t gid = getgid();
struct group gr_entry;
struct group* gr_result;
ASSERT_EQ(getgrgid_r(gid, &gr_entry, &buf[0], buf.size(), &gr_result), 0);
ASSERT_NE(gr_result, nullptr);
group_name_ = gr_entry.gr_name;
}
std::string user_name_;
std::string group_name_;
};
TEST_F(LogTest, GetFileLogData) {
base::ScopedTempDir temp;
ASSERT_TRUE(temp.CreateUniqueTempDir());
base::FilePath file_one = temp.GetPath().Append("test/file_one");
ASSERT_TRUE(CreateDirectoryAndWriteFile(file_one, "test_one_contents"));
const LogTool::Log log_one(LogTool::Log::kFile, "test_log_one",
file_one.value(), user_name_, group_name_);
EXPECT_EQ(log_one.GetLogData(), "test_one_contents");
base::FilePath file_two = temp.GetPath().Append("test/file_two");
ASSERT_TRUE(CreateDirectoryAndWriteFile(file_two, ""));
const LogTool::Log log_two(LogTool::Log::kFile, "test_log_two",
file_two.value(), user_name_, group_name_);
EXPECT_EQ(log_two.GetLogData(), "<empty>");
base::FilePath file_three = temp.GetPath().Append("test/file_three");
ASSERT_TRUE(CreateDirectoryAndWriteFile(file_three, "long input value"));
const LogTool::Log log_three(LogTool::Log::kFile, "test_log_three",
file_three.value(), user_name_, group_name_, 5);
EXPECT_EQ(log_three.GetLogData(), "value");
}
TEST_F(LogTest, GetCommandLogData) {
LogTool::Log log_one(LogTool::Log::kCommand, "test_log_one", "printf ''",
user_name_, group_name_);
log_one.DisableMinijailForTest();
EXPECT_EQ(log_one.GetLogData(), "<empty>");
LogTool::Log log_two(LogTool::Log::kCommand, "test_log_two",
"printf 'test_output'", user_name_, group_name_);
log_two.DisableMinijailForTest();
EXPECT_EQ(log_two.GetLogData(), "test_output");
LogTool::Log log_three(LogTool::Log::kCommand, "test_log_three",
"echo a,b,c | cut -d, -f2", user_name_, group_name_);
log_three.DisableMinijailForTest();
EXPECT_EQ(log_three.GetLogData(), "b\n");
}
} // namespace debugd
|
#pragma once
#include <vector>
#include <tbb/parallel_for.h>
#include <tbb/tbb.h>
template <typename T, typename Op>
T inclusive_scan(const std::vector<T> &in, const T &id, std::vector<T> &out, Op op)
{
out.resize(in.size(), id);
using range_type = tbb::blocked_range<size_t>;
T sum = tbb::parallel_scan(
range_type(0, in.size()),
id,
[&](const range_type &r, T sum, bool is_final_scan) {
T tmp = sum;
for (size_t i = r.begin(); i < r.end(); ++i) {
tmp = op(tmp, in[i]);
if (is_final_scan) {
out[i] = tmp;
}
}
return tmp;
},
[&](const T &a, const T &b) { return op(a, b); });
return sum;
}
template <typename T, typename Op>
T exclusive_scan(const std::vector<T> &in, const T &id, std::vector<T> &out, Op op)
{
// Exclusive scan is the same as inclusive, but shifted by one
out.resize(in.size() + 1, id);
using range_type = tbb::blocked_range<size_t>;
T sum = tbb::parallel_scan(
range_type(0, in.size()),
id,
[&](const range_type &r, T sum, bool is_final_scan) {
T tmp = sum;
for (size_t i = r.begin(); i < r.end(); ++i) {
tmp = op(tmp, in[i]);
if (is_final_scan) {
out[i + 1] = tmp;
}
}
return tmp;
},
[&](const T &a, const T &b) { return op(a, b); });
out.pop_back();
return sum;
}
|
function createHierarchalName(baseName, errorMessage) {
return `${baseName} - ${errorMessage}`;
}
globals.harness.pushTestResult();
const error_message = "Some error message"; // Assuming error_message is defined
globals.harness.setResultName(createHierarchalName("Assertion Site Error", error_message));
|
#!/bin/sh
PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin
cd $1
npm run forever
|
<gh_stars>100-1000
/**
* @jest-environment ./prisma/prisma-test-environment.js
*/
import request from 'supertest'
import { v4 as uuid } from 'uuid'
import { prisma } from '@infra/prisma/client'
import { redisConnection } from '@infra/redis/connection'
import { app } from '@infra/sns-webhook/app'
import { validEventTypes } from '../../domain/event/type'
describe('Register Event (e2e)', () => {
afterAll(async () => {
redisConnection.disconnect()
await prisma.$disconnect()
})
it('should be able to register event', async () => {
const messageId = uuid()
const contactId = uuid()
await prisma.message.create({
data: {
id: messageId,
subject: 'My new message',
body: 'A message to be sent with a whole body',
sender: {
create: {
id: uuid(),
name: '<NAME>',
email: '<EMAIL>',
},
},
tags: {
create: {
id: uuid(),
tag: {
create: {
id: uuid(),
title: 'New tag',
subscribers: {
create: {
id: uuid(),
contact: {
create: {
id: contactId,
name: '<NAME>',
email: '<EMAIL>',
},
},
},
},
},
},
},
},
},
})
const awsMessage = {
eventType: 'Delivery',
mail: {
timestamp: '2016-10-19T23:20:52.240Z',
source: '<EMAIL>',
sourceArn:
'arn:aws:ses:us-east-1:123456789012:identity/johnsender@example.com',
sendingAccountId: '123456789012',
messageId:
'EXAMPLE7c191be45-e9aedb9a-02f9-4d12-a87d-dd0099a07f8a-000000',
destination: ['<EMAIL>'],
headersTruncated: false,
headers: [
{
name: 'From',
value: '<EMAIL>',
},
{
name: 'To',
value: '<EMAIL>',
},
{
name: 'Subject',
value: 'Message sent from Amazon SES',
},
{
name: 'MIME-Version',
value: '1.0',
},
{
name: 'Content-Type',
value: 'text/html; charset=UTF-8',
},
{
name: 'Content-Transfer-Encoding',
value: '7bit',
},
],
commonHeaders: {
from: ['<EMAIL>'],
to: ['<EMAIL>'],
messageId:
'EXAMPLE7c191be45-e9aedb9a-02f9-4d12-a87d-dd0099a07f8a-000000',
subject: 'Message sent from Amazon SES',
},
tags: {
'ses:configuration-set': ['ConfigSet'],
'ses:source-ip': ['192.0.2.0'],
'ses:from-domain': ['example.com'],
'ses:caller-identity': ['ses_user'],
'ses:outgoing-ip': ['192.0.2.0'],
contactId: [contactId],
messageId: [messageId],
},
},
delivery: {
timestamp: '2016-10-19T23:21:04.133Z',
processingTimeMillis: 11893,
recipients: ['<EMAIL>'],
smtpResponse: '250 2.6.0 Message received',
reportingMTA: 'mta.<EMAIL>',
},
}
const response = await request(app)
.post(`/events/notifications`)
.send({
Type: 'Notification',
Message: JSON.stringify(awsMessage),
})
expect(response.status).toBe(200)
const recipientInDatabase = await prisma.recipient.findUnique({
where: {
message_id_contact_id: {
contact_id: contactId,
message_id: messageId,
},
},
include: {
events: true,
},
})
expect(recipientInDatabase).toBeTruthy()
expect(validEventTypes).toContain(recipientInDatabase.events[0].type)
})
it('should filter GoogleImageProxy open events', async () => {
const messageId = uuid()
const contactId = uuid()
await prisma.message.create({
data: {
id: messageId,
subject: 'My new message',
body: 'A message to be sent with a whole body',
sender: {
create: {
id: uuid(),
name: '<NAME>',
email: '<EMAIL>',
},
},
tags: {
create: {
id: uuid(),
tag: {
create: {
id: uuid(),
title: 'New tag 02',
subscribers: {
create: {
id: uuid(),
contact: {
create: {
id: contactId,
name: '<NAME>',
email: '<EMAIL>',
},
},
},
},
},
},
},
},
},
})
const awsMessage = {
eventType: 'Open',
open: {
ipAddress: '172.16.17.32',
timestamp: '2021-08-03T22:59:04.831Z',
userAgent:
'Mozilla/5.0 (Windows NT 5.1; rv:11.0) Gecko Firefox/11.0 (via ggpht.com GoogleImageProxy)',
},
}
const response = await request(app)
.post(`/events/notifications`)
.send({
Type: 'Notification',
Message: JSON.stringify(awsMessage),
})
expect(response.status).toBe(200)
const recipientInDatabase = await prisma.recipient.findUnique({
where: {
message_id_contact_id: {
contact_id: contactId,
message_id: messageId,
},
},
})
expect(recipientInDatabase).toBeFalsy()
})
it('should store desired metadata on each notification type', async () => {
const messageId = uuid()
const contactId = uuid()
await prisma.message.create({
data: {
id: messageId,
subject: 'My new message',
body: 'A message to be sent with a whole body',
sender: {
create: {
id: uuid(),
name: '<NAME>',
email: '<EMAIL>',
},
},
tags: {
create: {
id: uuid(),
tag: {
create: {
id: uuid(),
title: 'New tag 03',
subscribers: {
create: {
id: uuid(),
contact: {
create: {
id: contactId,
name: '<NAME>',
email: '<EMAIL>',
},
},
},
},
},
},
},
},
},
})
await prisma.recipient.create({
data: {
id: uuid(),
contact_id: contactId,
message_id: messageId,
},
})
const deliveryMessage = {
eventType: 'Delivery',
mail: { tags: { contactId: [contactId], messageId: [messageId] } },
deliver: {
timestamp: '2021-08-03T22:50:04.072Z',
recipients: ['<EMAIL>'],
reportingMTA: 'a48-78.smtp-out.amazonses.com',
smtpResponse:
'250 2.6.0 <0<EMAIL>017b0e35a8c6-<EMAIL>-<EMAIL>> [InternalId=95992519094146, Hostname=HE1EUR04HT112.eop-eur04.prod.protection.outlook.com] 13478 bytes in 0.277, 47.373 KB/sec Queued mail for delivery -> 250 2.1.5',
processingTimeMillis: 1250,
},
}
await request(app)
.post(`/events/notifications`)
.send({
Type: 'Notification',
Message: JSON.stringify(deliveryMessage),
})
const openMessage = {
eventType: 'Open',
mail: { tags: { contactId: [contactId], messageId: [messageId] } },
open: {
ipAddress: '172.16.17.32',
timestamp: '2021-08-03T22:59:04.831Z',
userAgent:
'Microsoft Office/16.0 (Microsoft Outlook 16.0.13426; Pro), Mozilla/4.0 (compatible; ms-office; MSOffice 16)',
},
}
await request(app)
.post(`/events/notifications`)
.send({
Type: 'Notification',
Message: JSON.stringify(openMessage),
})
const clickMessage = {
eventType: 'Click',
mail: { tags: { contactId: [contactId], messageId: [messageId] } },
click: {
link: 'https://www.youtube.com/watch?v=PmEDq--R6vA&ab_channel=Rocketseat',
linkTags: null,
ipAddress: '192.168.127.12',
timestamp: '2021-08-05T13:21:06.409Z',
userAgent:
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36',
},
}
await request(app)
.post(`/events/notifications`)
.send({
Type: 'Notification',
Message: JSON.stringify(clickMessage),
})
const bounceMessage = {
eventType: 'Bounce',
mail: { tags: { contactId: [contactId], messageId: [messageId] } },
bounce: {
timestamp: '2021-08-03T22:50:01.805Z',
bounceType: 'Permanent',
feedbackId:
'0100017b0e35a44c-10286004-c645-4b2b-979a-6af049c3d564-000000',
reportingMTA: 'dns; a11-18.smtp-out.amazonses.com',
bounceSubType: 'General',
bouncedRecipients: [
{
action: 'failed',
status: '5.1.1',
emailAddress: '<NAME> <<EMAIL>>',
diagnosticCode:
'smtp; 550 5.1.1 <<EMAIL>> User unknown',
},
],
},
}
await request(app)
.post(`/events/notifications`)
.send({
Type: 'Notification',
Message: JSON.stringify(bounceMessage),
})
const recipientInDatabase = await prisma.recipient.findUnique({
where: {
message_id_contact_id: {
contact_id: contactId,
message_id: messageId,
},
},
include: {
events: true,
},
})
expect(recipientInDatabase.events[0].meta).toEqual({})
expect(recipientInDatabase.events[1].meta).toEqual({
ipAddress: expect.any(String),
userAgent: expect.any(String),
})
expect(recipientInDatabase.events[2].meta).toEqual({
link: expect.any(String),
linkTags: null,
ipAddress: expect.any(String),
userAgent: expect.any(String),
})
expect(recipientInDatabase.events[3].meta).toEqual({
bounceType: expect.any(String),
bounceSubType: expect.any(String),
diagnosticCode: expect.any(String),
})
})
})
|
import { GetServerSideProps } from 'next';
export const getServerSideProps: GetServerSideProps = async () => {
const images = [
'/images/home/undraw_annotation_7das.svg',
'/images/home/undraw_Notebook_re_id0r.svg',
'/images/home/undraw_Task_re_wi3v.svg',
'/images/home/undraw_Website_builder_re_ii6e.svg',
'/images/home/undraw_Add_tasks_re_s5yj.svg',
'/images/home/undraw_Wireframing_re_q6k6.svg',
'/images/home/undraw_secure_files_re_6vdh.svg',
];
const randomNumber = Math.floor(Math.random() * images.length);
const heroImage = images[randomNumber];
return {
props: {
heroImage: heroImage,
},
};
};
|
<reponame>nabeelkhan/Oracle-DBA-Life<filename>INFO/Books Codes/Oracle PLSQL Tips and Techniques/OutputChapter15/15_12.sql
-- ***************************************************************************
-- File: 15_12.sql
--
-- Developed By TUSC
--
-- Disclaimer: Neither Osborne/McGraw-Hill, TUSC, nor the author warrant
-- that this source code is error-free. If any errors are
-- found in this source code, please report them to TUSC at
-- (630)960-2909 ext 1011 or <EMAIL>.
-- ***************************************************************************
SPOOL 15_12.lis
-- DO_QUERY executes the query on the specified columns and table.
-- The OWA_UTIL.IDENT_ARR datatype is defined as:
-- type ident_arr is table of VARCHAR2(30) index by binary_integer
CREATE OR REPLACE PROCEDURE do_query
(p_table_txt IN VARCHAR2,
p_cols_rec IN owa_util.ident_arr) IS
lv_column_list_txt VARCHAR2(32000);
lv_col_counter_num INTEGER;
lv_ignore_bln BOOLEAN;
BEGIN
-- For PL/SQL tables, have to just loop through until you raise
-- the NO_DATA_FOUND exception. Start the counter at 2 since we
-- put in a dummy hidden field.
lv_col_counter_num := 2;
LOOP
-- build a comma-delimited list of columns
lv_column_list_txt := lv_column_list_txt ||
p_cols_rec(lv_col_counter_num) || ',';
lv_col_counter_num := lv_col_counter_num + 1;
END LOOP;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- strip out the last trailing comma
lv_column_list_txt := SUBSTR(lv_column_list_txt, 1,
LENGTH(lv_column_list_txt) - 1);
-- print the table - assumes HTML table support
lv_ignore_bln := OWA_UTIL.TABLEPRINT(p_table_txt, 'BORDER',
OWA_UTIL.HTML_TABLE, lv_column_list_txt);
END do_query;
/
SPOOL OFF
|
#!/bin/bash
set -eu
exec diff -u <(sed -e 's/secure: "[^"]*"/secure: "SECURE"/g' "$1") "$2"
|
<filename>mctstree.cpp<gh_stars>0
#include "mctstree.h"
#include <algorithm>
#include <thread>
#include <future>
#include <math.h>
#include <QDebug>
#include "debug.h"
unsigned MCTSTree::NODE_EXPLORATIONS_TO_EXPAND = 32;
MCTSTree::MCTSTree(short evalColor) {
_root = new MCTSNode();
_root->setParent(nullptr);
_evalColor = evalColor;
unsigned int n = std::thread::hardware_concurrency();
_maxTreads = std::min(std::max(n, _maxTreads), 24u);
}
void MCTSTree::selectChild(short x, short y) {
unsigned long userDataBlack = 0;
userDataBlack = writePositionX(x, userDataBlack);
userDataBlack = writePositionY(y, userDataBlack);
userDataBlack = writeColorData(BLACK_PIECE_COLOR, userDataBlack);
unsigned long userDataWhite = 0;
userDataWhite = writePositionX(x, userDataWhite);
userDataWhite = writePositionY(y, userDataWhite);
userDataWhite = writeColorData(WHITE_PIECE_COLOR, userDataWhite);
MCTSNode* node = _root->getChildHead();
while (node) {
if (node->getUserData() == userDataBlack || node->getUserData() == userDataWhite) {
break;
}
node = node->getNextNode();
}
if (!node) {
short color = extractColorData(_root->getUserData());
unsigned long userData = 0;
userData = writePositionX(x, userData);
userData = writePositionY(y, userData);
userData = writeColorData(getNextPlayerColor(color), userData);
node = new MCTSNode();
node->setUserData(userData);
node->__x = x;
node->__y = y;
node->__color = getNextPlayerColor(color);
_root->addChild(node);
}
_root = node;
}
std::vector<AIMoveData> MCTSTree::getNodesData() const {
std::vector<AIMoveData> result;
MCTSNode* node = _root->getChildHead();
float rootVisits = _root->getPlayouts();
while (node) {
auto nodeUserData = node->getUserData();
short x = extractPositionX(nodeUserData);
short y = extractPositionY(nodeUserData);
float nodeAddScore = node->getPlayouts() > 0 && rootVisits > 0 ? std::sqrt(std::log(rootVisits) / sqrt(node->getPlayouts())) : rootVisits;
float nodeScore = node->getPlayouts() > 0 ? node->getScore() / node->getPlayouts() : 0.f;
AIMoveData moveData;
moveData.position = getHashedPosition(x, y);
moveData.scores = nodeScore;
moveData.color = extractColorData(nodeUserData);
moveData.nodeVisits = node->getPlayouts();
moveData.selectionScore = nodeScore + nodeAddScore;
result.push_back(moveData);
node = node->getNextNode();
}
return result;
}
std::vector<AIMoveData> MCTSTree::getBestPlayout(short x, short y) const {
std::vector<AIMoveData> result;
auto node = _root->getChildHead();
while (node) {
auto nodeUserData = node->getUserData();
short nodeX = extractPositionX(nodeUserData);
short nodeY = extractPositionY(nodeUserData);
if (nodeX == x && nodeY == y) {
break;
}
node = node->getNextNode();
}
unsigned topIndex = node ? node->__depth : 0;
while (node) {
auto nodeUserData = node->getUserData();
short x = extractPositionX(nodeUserData);
short y = extractPositionY(nodeUserData);
float nodeScore = node->getPlayouts() > 0 ? node->getScore() / node->getPlayouts() : 0.f;
AIMoveData moveData;
moveData.position = getHashedPosition(x, y);
moveData.scores = nodeScore;
moveData.color = extractColorData(nodeUserData);
moveData.nodeVisits = node->getPlayouts();
moveData.selectionScore = 0.f;
moveData.moveIndex = node->__depth - topIndex + 1;
result.push_back(moveData);
auto child = node->getChildHead();
auto bestChild = child;
float bestScore = -100.f;
while (child) {
float childScore = child->getPlayouts() > 0 ? child->getScore() / child->getPlayouts() : 0.f;
if (childScore >= bestScore) {
bestScore = childScore;
bestChild = child;
}
child = child->getNextNode();
}
node = bestChild;
}
return result;
}
void MCTSTree::update(const BitField* const rootState) {
explore(_root, rootState);
}
void MCTSTree::expand(MCTSNode* root, const BitField* const rootState) {
// create nodes
if (rootState->getGameStatus() != 0) {
return;
}
short color = extractColorData(root->getUserData());
const auto& moves = rootState->getBestMoves(getNextPlayerColor(color));
for (const auto& move : moves) {
MCTSNode* child = new MCTSNode();
unsigned long userData = 0;
userData = writePositionX(extractHashedPositionX(move), userData);
userData = writePositionY(extractHashedPositionY(move), userData);
userData = writeColorData(getNextPlayerColor(color), userData);
child->setUserData(userData);
child->__x = extractHashedPositionX(move);
child->__y = extractHashedPositionY(move);
child->__color = getNextPlayerColor(color);
root->addChild(child);
}
}
void MCTSTree::explore(MCTSNode* root, const BitField* const rootState) {
Debug::getInstance().startTrack(DebugTimeTracks::NODE_SELECTION);
MCTSNode* node = root;
BitField field(*rootState);
while (node->getChildHead()) {
MCTSNode* nextNode = selectBestChild(node, &field);
node = nextNode;
short x = extractPositionX(node->getUserData());
short y = extractPositionY(node->getUserData());
short color = extractColorData(node->getUserData());
field.makeMove(x, y, color);
}
if (field.getGameStatus() == BLACK_PIECE_COLOR || field.getGameStatus() == WHITE_PIECE_COLOR) {
node->setTerminal();
}
Debug::getInstance().stopTrack(DebugTimeTracks::NODE_SELECTION);
Debug::getInstance().startTrack(DebugTimeTracks::AI_UPDATE);
float playoutScore = 0;
unsigned playouts = 1;
if (field.getGameStatus() != 0) {
if (field.getGameStatus() == _evalColor) {
playoutScore = 1.f;
} else if (field.getGameStatus() == getNextPlayerColor(_evalColor)) {
playoutScore = -1.f;
}
} else {
short moveColor = extractColorData(node->getUserData());
std::vector<std::future<float>> threads;
for (unsigned i = 0; i < _maxTreads; ++i) {
threads.push_back(std::async([this](const BitField* const rootState, short rootColor) {
return playout(rootState, rootColor);
}, &field, moveColor));
}
for (auto& result : threads) {
playoutScore += result.get();
}
playoutScore = playoutScore / static_cast<float>(_maxTreads);
playouts = _maxTreads;
// playoutScore = playout(&field, moveColor);
}
Debug::getInstance().stopTrack(DebugTimeTracks::AI_UPDATE);
Debug::getInstance().startTrack(DebugTimeTracks::TRAVERSE_AND_EXPAND);
MCTSNode* traversBackNode = node;
while (traversBackNode) {
short color = extractColorData(traversBackNode->getUserData());
traversBackNode->addScore(color == _evalColor ? playoutScore : -playoutScore);
traversBackNode->addPlayout();
traversBackNode->addRealPlayouts(playouts);
traversBackNode = traversBackNode->getParent();
}
if (node->isLeaf() && node->getRealPlayouts() >= NODE_EXPLORATIONS_TO_EXPAND) {
expand(node, &field);
}
Debug::getInstance().stopTrack(DebugTimeTracks::TRAVERSE_AND_EXPAND);
}
MCTSNode* MCTSTree::selectBestChild(MCTSNode* root, const BitField* const rootState) const {
unsigned long rootVisits = root->getPlayouts();
float bestScore = -1000.f;
MCTSNode* bestNode = root->getChildHead();
MCTSNode* node = root->getChildHead();
double p = 1.f - std::min(root->getPlayouts() / 500000.0, 1.0);
double rndHit = ((double) rand() / (RAND_MAX));
int rndChildIndex = -1;
if (p < rndHit) {
rndChildIndex = rand() % root->getChildrenCount();
MCTSNode* randomNode = root->getChildHead();
while (randomNode && rndChildIndex > 0) {
rndChildIndex--;
randomNode = randomNode->getNextNode();
}
return randomNode;
}
while (node && rootVisits > 0) {
float nodeAddScore = node->getPlayouts() > 0 ? std::sqrt(std::log(rootVisits) / sqrt(node->getPlayouts())) : rootVisits;
float nodeScore = node->getPlayouts() > 0 ? node->getScore() / node->getPlayouts() : 0.f;
// short x = extractPositionX(node->getUserData());
// short y = extractPositionY(node->getUserData());
// short color = extractColorData(node->getUserData());
float nodePriority = 0;//rootState->getMovePriority(getHashedPosition(x, y), color) / 5.f;
if (node->isTerminal()) {
nodeScore += 100;
}
float totalScore = nodeScore + nodeAddScore + nodePriority;
if (totalScore >= bestScore) {
bestScore = totalScore;
bestNode = node;
}
node = node->getNextNode();
}
return bestNode;
}
float MCTSTree::playout(const BitField* const rootState, short rootColor) {
short x = 0;
short y = 0;
short color = rootColor;
BitField field(*rootState);
while (field.getGameStatus() == 0) {
// find move position
color = getNextPlayerColor(color);
auto move = field.getMoveByPriority(color);
x = extractHashedPositionX(move);
y = extractHashedPositionY(move);
if (!field.makeMove(x, y, color)) {
break;
}
}
if (field.getGameStatus() == _evalColor) {
return 1.f;
} else if (field.getGameStatus() == getNextPlayerColor(_evalColor)) {
return -1.f;
}
return 0.f;
}
|
def isPalindrome(word):
n = len(word)
i = 0
j = n - 1
while (i <= j):
if (word[i] != word[j]):
return False
i = i + 1
j = j - 1
return True
|
function translatePhrases(array $phrases, string $languageCode): array {
$translations = [];
switch ($languageCode) {
case 'fr':
$translations = [
'translatable.site_name' => 'Nom du site',
'site_email' => 'E-mail du site',
// ... additional French translations
];
break;
case 'es':
$translations = [
'translatable.site_name' => 'Nombre del sitio',
'site_email' => 'Correo electrónico del sitio',
// ... additional Spanish translations
];
break;
// Add cases for other languages as needed
default:
// If the language code is not supported, return the original phrases
$translations = $phrases;
break;
}
return $translations;
}
|
<reponame>weltam/idylfin
/**
* Copyright (C) 2011 - present by OpenGamma Inc. and the OpenGamma group of companies
*
* Please see distribution for license.
*/
package com.opengamma.analytics.financial.equity.future.derivative;
import com.opengamma.util.money.Currency;
/**
* A cash-settled futures contract on the value of a published stock market index on the _fixingDate
*/
public class EquityIndexFuture extends EquityFuture {
public EquityIndexFuture(final double timeToFixing, final double timeToDelivery, final double strike, final Currency currency, final double unitValue) {
super(timeToFixing, timeToDelivery, strike, currency, unitValue);
}
}
|
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from social_django.models import UserSocialAuth
@receiver(post_save, sender=User)
def create_user_social_auth(sender, instance, created, **kwargs):
if created:
UserSocialAuth.objects.create(
user=instance,
# Add any additional fields required for the UserSocialAuth instance
)
# Register the signal handler
post_save.connect(create_user_social_auth, sender=User)
|
<reponame>EllaSharakanski/salto
/*
* Copyright 2021 Salto Labs Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
Change, ElemID, Field, InstanceElement, ObjectType, ReferenceExpression, toChange,
} from '@salto-io/adapter-api'
import { Types } from '../../src/transformers/transformer'
import picklistPromoteValidator from '../../src/change_validators/picklist_promote'
import { API_NAME, VALUE_SET_FIELDS } from '../../src/constants'
import { createField } from '../utils'
import * as constants from '../../src/constants'
import { GLOBAL_VALUE_SET } from '../../src/filters/global_value_sets'
describe('picklist promote change validator', () => {
describe('onUpdate', () => {
const createGlobalValueSetInstanceElement = (): InstanceElement =>
new InstanceElement('global_value_set_test', new ObjectType({
elemID: new ElemID(constants.SALESFORCE, 'global_value_set'),
annotations: { [constants.METADATA_TYPE]: GLOBAL_VALUE_SET },
}))
const gvs: InstanceElement = createGlobalValueSetInstanceElement()
const createAfterField = (beforeField: Field): Field => {
const afterField = beforeField.clone()
afterField.annotations[VALUE_SET_FIELDS.VALUE_SET_NAME] = new ReferenceExpression(new ElemID(''), gvs)
return afterField
}
const pickListFieldName = 'pick__c'
let obj: ObjectType
let beforeField: Field
let afterField: Field
let pickListChange: Change
let gvsChange: Change
beforeEach(() => {
obj = new ObjectType({
elemID: new ElemID('salesforce', 'obj'),
})
beforeField = createField(obj, Types.primitiveDataTypes.Picklist, pickListFieldName)
beforeField.name = pickListFieldName
afterField = createAfterField(beforeField)
pickListChange = toChange({ before: beforeField, after: afterField })
gvsChange = toChange({ after: gvs })
})
it('should have created 2 errors (for picklist & value-set)', async () => {
const changeErrors = await picklistPromoteValidator([pickListChange, gvsChange])
expect(changeErrors).toHaveLength(2)
const errorElemsNamesSet = new Set(changeErrors.map(changeErr => changeErr.elemID.name))
expect(errorElemsNamesSet).toEqual(new Set(['pick__c', 'global_value_set_test']))
})
it('should have created just picklist error when value-set change doesn\'t exist', async () => {
const changeErrors = await picklistPromoteValidator([pickListChange])
expect(changeErrors).toHaveLength(1)
const errorElemsNamesSet = new Set(changeErrors.map(changeErr => changeErr.elemID.name))
expect(new Set(['pick__c'])).toEqual(errorElemsNamesSet)
})
it('should have created just picklist error when extra change isn\'t reference', async () => {
afterField.annotations[VALUE_SET_FIELDS.VALUE_SET_NAME] = 'some string'
const changeErrors = await picklistPromoteValidator([pickListChange, gvsChange])
expect(changeErrors).toHaveLength(1)
const errorElemsNamesSet = new Set(changeErrors.map(changeErr => changeErr.elemID.name))
expect(new Set(['pick__c'])).toEqual(errorElemsNamesSet)
})
it('should not have errors for non-custom picklist', async () => {
beforeField.annotations[API_NAME] = 'pick'
const changeErrors = await picklistPromoteValidator([pickListChange, gvsChange])
expect(changeErrors).toHaveLength(0)
})
it('should not have errors for already global value-set picklist field', async () => {
beforeField.annotations[VALUE_SET_FIELDS.VALUE_SET_NAME] = 'something'
const changeErrors = await picklistPromoteValidator([pickListChange, gvsChange])
expect(changeErrors).toHaveLength(0)
})
it('should not have errors for moving to a non-global value-set change', async () => {
delete afterField.annotations[VALUE_SET_FIELDS.VALUE_SET_NAME]
const changeErrors = await picklistPromoteValidator([pickListChange])
expect(changeErrors).toHaveLength(0)
})
})
})
|
<reponame>zaidmukaddam/linkto<filename>packages/core/src/hooks/useSafeLayoutEffect.tsx
import { useEffect, useLayoutEffect } from "react";
/**
* useSafeLayoutEffect enables us to safely call `useLayoutEffect` on the browser
* (for SSR reasons)
*
* React currently throws a warning when using useLayoutEffect on the server.
* To get around it, we can conditionally useEffect on the server (no-op) and
* useLayoutEffect in the browser.
*
* @see https://gist.github.com/gaearon/e7d97cdf38a2907924ea12e4ebdf3c85
*/
const useSafeLayoutEffect =
typeof window !== "undefined" ? useLayoutEffect : useEffect;
export default useSafeLayoutEffect;
|
<filename>spec/functions/delete_values_spec.rb
# frozen_string_literal: true
require 'spec_helper'
describe 'delete_values' do
it { is_expected.not_to eq(nil) }
it { is_expected.to run.with_params.and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) }
it { is_expected.to run.with_params(1).and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) }
it { is_expected.to run.with_params('one').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) }
it { is_expected.to run.with_params('one', 'two', 'three').and_raise_error(Puppet::ParseError, %r{Wrong number of arguments}) }
describe 'when the first argument is not a hash' do
it { is_expected.to run.with_params(1, 'two').and_raise_error(TypeError, %r{First argument must be a Hash}) }
it { is_expected.to run.with_params('one', 'two').and_raise_error(TypeError, %r{First argument must be a Hash}) }
it { is_expected.to run.with_params([], 'two').and_raise_error(TypeError, %r{First argument must be a Hash}) }
end
describe 'when deleting from a hash' do
it { is_expected.to run.with_params({}, 'value').and_return({}) }
it {
is_expected.to run \
.with_params({ 'key1' => 'value1' }, 'non-existing value') \
.and_return('key1' => 'value1')
}
it {
is_expected.to run \
.with_params({ 'ҝếỵ1 ' => 'νâĺūẹ1', 'ҝếỵ2' => 'value to delete' }, 'value to delete') \
.and_return('ҝếỵ1 ' => 'νâĺūẹ1')
}
it {
is_expected.to run \
.with_params({ 'key1' => 'value1', 'key2' => 'νǎŀữ℮ ťớ đêłểťė' }, 'νǎŀữ℮ ťớ đêłểťė') \
.and_return('key1' => 'value1')
}
it {
is_expected.to run \
.with_params({ 'key1' => 'value1', 'key2' => 'value to delete', 'key3' => 'value to delete' }, 'value to delete') \
.and_return('key1' => 'value1')
}
end
it 'leaves the original argument intact' do
argument = { 'key1' => 'value1', 'key2' => 'value2' }
original = argument.dup
_result = subject.execute(argument, 'value2')
expect(argument).to eq(original)
end
end
|
def BFS(tree):
queue = []
visited = []
root = tree.root
queue.append(root)
while len(queue) > 0:
node = queue.pop(0)
visited.append(node)
for child in node.children:
if child not in visited and child not in queue:
queue.append(child)
return visited
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.