text stringlengths 1 1.05M |
|---|
<filename>src/modules/knowledgeBase/containers/knowledge/index.js
import KnowledgeForm from './KnowledgeForm';
import KnowledgeList from './KnowledgeList';
export { KnowledgeForm, KnowledgeList };
|
<gh_stars>100-1000
/**
* This program uses Selenium to run a Stopify benchmark in a browser.
*
* There are a few steps involved:
*
* 1. We serve the dist/ directory and the directory containing the benchmark
* on port 9999.
*
* 2. We use Selenium to start a browser (in headless mode, if we know how).
*
* 3. Using Selenium, we direct the browser to fetch the page.
*/
import * as selenium from 'selenium-webdriver';
import * as chrome from 'selenium-webdriver/chrome';
import * as path from 'path';
import { parseRuntimeOpts } from './parse-runtime-opts';
import { benchmarkUrl } from './browserLine';
import * as express from 'express';
process.env.MOZ_HEADLESS = "1";
const stdout = process.stdout;
const [ browser, ...args ] = process.argv.slice(2);
const opts = parseRuntimeOpts(args);
const src = benchmarkUrl(args);
// NOTE(sam): No typing for `headless()` option as of 8/30/2017.
// I've opened a PR to DefinitelyTyped to fix this.
// https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19463
const chromeOpts = (<any>new chrome.Options())
.headless()
.addArguments(['--js-flags', '--harmony_tailcalls']);
const loggingPrefs = new selenium.logging.Preferences();
loggingPrefs.setLevel('browser', 'all');
let builder = new selenium.Builder()
.forBrowser(browser)
.setLoggingPrefs(loggingPrefs)
.setChromeOptions(chromeOpts);
const driver = builder.build();
const app = express();
app.use(express.static(path.join(__dirname, '../../dist')));
app.use(express.static(path.dirname(opts.filename)));
app.use(express.static(path.join(__dirname, '../../../stopify-continuations/dist')));
let exitCode = 0;
const server = app.listen(() => {
const port = server.address().port;
const url = `http://127.0.0.1:${port}/benchmark.html#${src}`;
console.log(`GET ${url}`);
driver.get(url)
.then(_ => driver.wait(selenium.until.titleIs('done'), 8 * 60 * 1000))
.then(_ => driver.findElement(selenium.By.id('data')))
.then(e => e.getAttribute("value"))
.then(s => {
stdout.write(s);
if (!s.endsWith('OK.\n')) {
exitCode = 1;
}
})
.catch(exn => {
stdout.write(`Got an exception: ${exn}`);
exitCode = 1;
})
.then(_ => driver.quit())
.then(_ => server.close())
.then(_ => process.exit(exitCode));
});
|
<reponame>Goxiaoy/go-saas-kit<filename>pkg/kratos/kratos.go
package kratos
import (
"context"
"github.com/go-kratos/kratos/v2/transport"
"github.com/go-kratos/kratos/v2/transport/http"
http2 "net/http"
)
func ResolveHttpRequest(ctx context.Context) (*http2.Request, bool) {
if t, ok := transport.FromServerContext(ctx); ok {
if ht, ok := t.(*http.Transport); ok {
return ht.Request(), true
}
}
return nil, false
}
|
#!/bin/bash
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=1 NPCOLS=1 NUM_BLOCKS=32 STARPU_NCPU=2 BLOCK_SIZE=256 sbatch -c 32 -n 1 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=1 NPCOLS=1 NUM_BLOCKS=64 STARPU_NCPU=2 BLOCK_SIZE=256 sbatch -c 32 -n 1 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=1 NPCOLS=1 NUM_BLOCKS=32 BLOCK_SIZE=256 sbatch -c 32 -n 1 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=1 NPCOLS=1 NUM_BLOCKS=64 BLOCK_SIZE=256 sbatch -c 32 -n 1 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=1 NPCOLS=1 NUM_BLOCKS=128 BLOCK_SIZE=256 sbatch -c 32 -n 1 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=4 NPCOLS=2 NUM_BLOCKS=32 BLOCK_SIZE=256 sbatch -c 32 -n 8 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=4 NPCOLS=2 NUM_BLOCKS=64 BLOCK_SIZE=256 sbatch -c 32 -n 8 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=4 NPCOLS=2 NUM_BLOCKS=128 BLOCK_SIZE=256 sbatch -c 32 -n 8 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=4 NPCOLS=2 NUM_BLOCKS=256 BLOCK_SIZE=256 sbatch -c 32 -n 8 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=32 BLOCK_SIZE=256 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=64 BLOCK_SIZE=256 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=128 BLOCK_SIZE=256 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=256 BLOCK_SIZE=256 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=512 BLOCK_SIZE=256 sbatch -c 32 -n 64 run_cholesky.sh
#
#echo "Now doing block size plot"
#
RANDOM_SIZES=2048 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=32 BLOCK_SIZE=2048 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=1024 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=64 BLOCK_SIZE=1024 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=512 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=128 BLOCK_SIZE=512 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=256 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=256 BLOCK_SIZE=256 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=128 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=512 BLOCK_SIZE=128 sbatch -c 32 -n 64 run_cholesky.sh
RANDOM_SIZES=64 PRUNE=0 TEST=0 SCHED=lws NPROWS=8 NPCOLS=8 NUM_BLOCKS=1024 BLOCK_SIZE=64 sbatch -c 32 -n 64 run_cholesky.sh
|
<reponame>vaskoz/jruby
/*
* Copyright (c) 2015, 2016 Oracle and/or its affiliates. All rights reserved. This
* code is released under a tri EPL/GPL/LGPL license. You can use it,
* redistribute it and/or modify it under the terms of the:
*
* Eclipse Public License version 1.0
* GNU General Public License version 2
* GNU Lesser General Public License version 2.1
*/
package org.jruby.truffle.core.adapaters;
import com.oracle.truffle.api.object.DynamicObject;
import org.jcodings.Encoding;
import org.jruby.truffle.RubyContext;
import org.jruby.truffle.core.Layouts;
import org.jruby.truffle.core.string.StringOperations;
import org.jruby.util.ByteList;
import org.jruby.util.StringSupport;
import java.io.IOException;
import java.io.OutputStream;
public class OutputStreamAdapter extends OutputStream {
private final RubyContext context;
private final DynamicObject object;
private final Encoding encoding;
public OutputStreamAdapter(RubyContext context, DynamicObject object, Encoding encoding) {
this.context = context;
this.object = object;
this.encoding = encoding;
}
@Override
public void write(int bite) throws IOException {
context.send(object, "write", null, Layouts.STRING.createString(context.getCoreLibrary().getStringFactory(),
StringOperations.ropeFromByteList(new ByteList(new byte[]{(byte) bite}, encoding), StringSupport.CR_VALID)));
}
}
|
// Assuming the user's password is stored in a variable named "userPassword"
String userPassword = "user123password";
// Setting the user's password for authentication
.setLoginEndpoint(server + SymptomSvcApi.TOKEN_PATH)
.setUsername(user)
.setPassword(userPassword) // Setting the user's password
.setClientId(SymptomValues.CLIENT_ID)
.setEndpoint(server)
.setLogLevel(LogLevel.FULL).build().create(SymptomSvcApi.class); |
#!/bin/sh
sed -i \
-e 's/rgb(0%,0%,0%)/#353b45/g' \
-e 's/rgb(100%,100%,100%)/#b6bdca/g' \
-e 's/rgb(50%,0%,0%)/#282c34/g' \
-e 's/rgb(0%,50%,0%)/#c678dd/g' \
-e 's/rgb(0%,50.196078%,0%)/#c678dd/g' \
-e 's/rgb(50%,0%,50%)/#3e4451/g' \
-e 's/rgb(50.196078%,0%,50.196078%)/#3e4451/g' \
-e 's/rgb(0%,0%,50%)/#c8ccd4/g' \
"$@"
|
package ru.autometry.obd.exception;
/**
* Created by jeck on 14/08/14
*/
public class OBDAdaptationException extends OBDException {
public OBDAdaptationException(String cause) {
super(cause);
}
}
|
import React from 'react'
import {connect} from 'react-redux'
import {updateEmail} from '../store/user'
class Profile extends React.Component {
constructor() {
super()
this.state = {
oldEmail: '',
newEmail: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit(event) {
event.preventDefault()
console.log('before', this.props.user)
if (this.state.oldEmail === this.props.user.email) {
this.props.updateEmail(
this.props.user.id,
this.props.user,
this.state.newEmail
)
} else {
console.log('current email entered was wrong')
}
console.log('after', this.props.user)
this.setState({
oldEmail: '',
newEmail: ''
})
}
render() {
return (
<div className="email">
<div className="email-container">
<div className="email_change">Email Change Form</div>
<form onSubmit={this.handleSubmit}>
<div className="email-edit">
<label>Enter Current Email:</label>
<input
type="text"
name="oldEmail"
value={this.state.oldEmail}
onChange={this.handleChange}
className="email-input"
/>
</div>
<div className="email-edit">
<label>Enter New Email:</label>
<input
type="text"
name="newEmail"
value={this.state.newEmail}
onChange={this.handleChange}
className="email-input"
/>
</div>
<button type="submit" className="login-btn">
Submit
</button>
</form>
</div>
</div>
)
}
}
const mapStateToProps = state => {
return {
user: state.user
}
}
const mapDispatchToProps = dispatch => {
return {
updateEmail: (userId, user, newEmail) =>
dispatch(updateEmail(userId, user, newEmail))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile)
|
save_path=/path/to/save/folder/
data_path=/path/to/data/folder/
OMP_NUM_THREADS=2 CUDA_VISIBLE_DEVICES=0,1 python3.6 -u ./train_free.py \
--random_seed 10 \
--net sngan_imgnet128 \
--dim_z 128 \
--img_c 3 \
--fm_base_d 64 --fm_base_g 64 \
--n_classes 1000 \
--num_bp 1 \
--r_batch_size 64 --data_path ${data_path} \
--g_batch_size 64 \
--shuffle \
--out_path ${save_path} \
--bottom_width 4 \
--img_width 128 \
--itr_d 1 --lr_d 0.0002 --beta1_d 0.0 --beta2_d 0.99 \
--itr_g 1 --lr_g 0.0002 --beta1_g 0.0 --beta2_g 0.99 \
--anneal_lr exp --anneal_lr_p1 0.5 --anneal_lr_p2 500000 \
--n_gpu 2 --dali --n_workers 2 --da \
--G_total_itrs 1200000 --save_bias 1000 --start_itr 0 \
--bn_g \
--b_metric hinge --c_metric ce_kl \
--c_alph_f 0.05 --c_alph_g 0.2 \
--pgd_type Linf --pgd_free_steps 2 --pgd_eps 0.01 --pgd_tau 0.01
|
#! /bin/sh
# TSO login script, to be run via the x3270 Script() action.
# sh version
set -x
me=`echo $0 | sed 's/.*\///'`
# Make sure we're in the right environment.
if [ -z "$X3270INPUT" -o -z "$X3270OUTPUT" ]
then echo >&2 "$me: must be run via the x3270 Script() action."
exit 1
fi
# Set up login parameters
tcp_host=${1-ibmsys}
dial_user=${2-VTAM}
sna_host=${3-TSO}
userid=${4-USERID}
password=${5-PASSWORD}
# Verbose flag for x3270if
v="-v"
# Define some handly local functions.
# Common x3270 Ascii function
ascii()
{
x3270if $v 'Ascii('$1')'
}
# Common x3270 String function
string()
{
x3270if $v 'String("'"$@"'")'
}
# x3270 cursor column
cursor_col()
{
x3270if $v -s 10
}
# x3270 connection status
cstatus()
{
x3270if $v -s 4
}
# Failure.
die()
{
x3270if $v "Info(\"$me error: $@\")"
x3270if $v "CloseScript(1)"
exit 1
}
# Make sure we're connected.
x3270if $v Wait
[ "`cstatus`" = N ] && die "Not connected."
# Get to a VM command screen
x3270if $v Enter
# Wait for VM's prompt
while [ "`ascii 1,0,5`" != "Enter" ]
do sleep 2
done
# Dial out to VTAM
string "DIAL $dial_user"
x3270if $v Enter
len0=`expr length $dial_user`
sl=`expr 10 + $len0`
dl=`expr 5 + $len0`
while [ "`ascii 0,64,4`" != VTAM ]
do s="`ascii 8,0,$sl | sed 's/^ *//'`"
if [ "$s" != "DIALED TO $dial_user" -a "$s" != "" ]
then if [ "`ascii 7,0,$dl`" = "DIAL $dial_user" ]
then die "Couldn't get to VTAM"
fi
fi
sleep 2
done
# Get to the SNA host
string "$sna_host $userid"
x3270if $v Enter
# Pass VTAM digestion message and initial blank TSO screen
while [ "`ascii 0,21,20`" = "USS COMMAND HAS BEEN" ]
do sleep 2
done
while :
do s="`ascii 0,33,11 | sed 's/^ *//'`"
[ "$s" != "" ] && break
sleep 2
done
# Now verify the "TSO/E LOGON" screen
[ "$s" = "TSO/E LOGON" ] || die "Couldn't get to TSO logon screen"
# Pump in the password
string "$password"
x3270if $v Enter
# Now look for "LOGON IN PROGRESS"
len0=`expr length $userid`
nl=`expr 18 + $len0`
[ "`ascii 0,11,$nl`" = "$userid LOGON IN PROGRESS" ] || die "Couldn't log on"
# Make sure TSO is waiting for a '***' enter
[ "`cursor_col`" -eq 5 ] || die "Don't understand logon screen"
# Off to ISPF
x3270if $v Enter
# No need to explicitly call CloseScript -- x3270 will interpret EOF as success.
|
<gh_stars>0
package io.mainframe.hacs.log_view;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import org.pmw.tinylog.Logger;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import io.mainframe.hacs.R;
import io.mainframe.hacs.common.Constants;
public class LogViewerActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log_viewer);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
// Show the Up button in the action bar.
actionBar.setDisplayHomeAsUpEnabled(true);
}
final boolean writeLogFiles = PreferenceManager.getDefaultSharedPreferences(this).getBoolean(
getString(R.string.PREFS_ENABLE_LOGGING), false);
if (!writeLogFiles) {
findViewById(R.id.logs_disabled_info).setVisibility(View.VISIBLE);
}
final File folder = new File(Environment.getExternalStorageDirectory(), Constants.LOG_FILE_FOLDER);
if (folder.exists()) {
final TextView contentTextView = findViewById(R.id.logs_content);
final TabLayout tabView = findViewById(R.id.logs_tabview);
tabView.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
StringBuilder content = new StringBuilder();
final File logFile = new File(folder, tab.getText().toString());
if (!logFile.exists()) {
contentTextView.setText("Log file not found?!");
return;
}
try {
BufferedReader br = new BufferedReader(new FileReader(logFile));
String line;
while ((line = br.readLine()) != null) {
content.append(line);
content.append('\n');
}
br.close();
contentTextView.setText(content.toString());
} catch (IOException e) {
Logger.error(e, e.getMessage());
contentTextView.setText("Error: " + e.getMessage());
}
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
// ignore
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
// ignore
}
});
final String[] files = folder.list();
if (files.length == 0) {
contentTextView.setText("No log files found.");
return;
}
for (String file : files) {
final TabLayout.Tab tab = tabView.newTab();
tab.setText(file);
tabView.addTab(tab);
}
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
// go back?
if (id == android.R.id.home) {
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
export default {
elem: 'svg',
attrs: {
xmlns: 'http://www.w3.org/2000/svg',
viewBox: '0 0 32 32',
width: 20,
height: 20,
},
content: [
{ elem: 'circle', attrs: { cx: '9', cy: '7', r: '1' } },
{
elem: 'path',
attrs: {
d:
'M27 22.14V18a2 2 0 0 0-2-2h-8v-4h9a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h9v4H7a2 2 0 0 0-2 2v4.14a4 4 0 1 0 2 0V18h8v4h-3v8h8v-8h-3v-4h8v4.14a4 4 0 1 0 2 0zM8 26a2 2 0 1 1-2-2 2 2 0 0 1 2 2zm10-2v4h-4v-4zM6 10V4h20v6zm20 18a2 2 0 1 1 2-2 2 2 0 0 1-2 2z',
},
},
],
name: 'data--structured',
size: 20,
};
|
package com.example.searchapidemo;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.BaseAdapter;
import android.widget.ListView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
public class MainActivity extends AppCompatActivity implements SongListViewAdapter.ListBtnClickListener {
public static final String url = "https://itunes.apple.com/search?term=greenday&entity=song";
private static final String TAG = "SONG";
private SongHandler msgHandler;
private SongData listSong;
private SongData favoriteSong;
private BottomNavigationView bottomNavigationView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
msgHandler = new SongHandler();
listSong = new SongData(SongData.SongDataCategory.List, this);
favoriteSong = new SongData(SongData.SongDataCategory.Favorite, this);
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
ListView favoriteView = (ListView)findViewById(R.id.songfavoriteview);
ListView listView = (ListView)findViewById(R.id.songlistview);
switch (menuItem.getItemId()) {
case R.id.list_page:
Log.d(TAG, "List Page");
favoriteView.setVisibility(View.INVISIBLE) ;
listView.setVisibility(View.VISIBLE);
return true;
case R.id.favorite_page:
Log.d(TAG, "Favorite Page");
listView.setVisibility(View.INVISIBLE);
favoriteView.setVisibility(View.VISIBLE) ;
favoriteSong.getAdapter().notifyDataSetChanged();
return true;
}
return false;
}
}
);
makeSongList();
Log.d(TAG,"starting a query thread");
}
@Override
public void onConfigurationChanged(@NonNull Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
private void makeSongList() {
if(favoriteSong.isExistJson()) {
try {
Thread t1 = new Thread(new DataRunnable(favoriteSong));
t1.start();
t1.join();
}
catch (Exception e) {
e.printStackTrace();
Log.e(TAG,"failed to make a favoriteSong");
}
}
Thread t = new Thread(new DataRunnable(listSong));
t.start();
}
public class SongHandler extends Handler {
@Override
public void handleMessage(Message msg) {
if (msg.what == SongData.MSG_UPDATE_UI) {
ListAdapterData data = (ListAdapterData) msg.obj;
if(data == null) {
Log.d(TAG,"object is null");
return;
}
boolean checkedFavorite = false;
if(favoriteSong.getAdapter().getCount()>0) {
checkedFavorite = favoriteSong.getAdapter().isExistItem(data);
}
data.adapter.addItem(data.trackName, data.collectionName, data.artistName,data.artworkUrl,checkedFavorite, data.img);
if(data.adapter.getCount() == 9)
data.adapter.notifyDataSetChanged();
Log.d(TAG,"updated UI");
}
else if(msg.what == SongData.MSG_COMPELTED) {
Log.d(TAG,"completed to update UI");
SongListViewAdapter adapter = (SongListViewAdapter)msg.obj;
adapter.notifyDataSetChanged();
}
else if(msg.what == SongData.MSG_UPDATE_FAVORITE_UI) {
ListAdapterData data = (ListAdapterData) msg.obj;
data.adapter.addItem(data.trackName, data.collectionName, data.artistName,data.artworkUrl, true, data.img);
Log.d(TAG,"updated Favorite UI");
}
}
}
@Override
public void onListBtnClick(int position) {
Log.d(TAG,"position: " + position);
SongListItem item = (SongListItem)listSong.getAdapter().getItem(position);
if(item.getFavoriteValue() == true) {
favoriteSong.getAdapter().addItem(item);
}
else {
favoriteSong.getAdapter().removeItem(item);
}
}
@Override
public void onStop() {
super.onStop();
favoriteSong.saveFavoriteItemToFile();
}
public Handler getUIHandler() { return msgHandler;}
class DataRunnable implements Runnable {
private SongData data;
DataRunnable(SongData data) {
this.data = data;
}
@Override
public void run() {
if(data.getCategory() == SongData.SongDataCategory.List)
data.querySongList(url);
else
favoriteSong.makeFavoriteList();
msgHandler.obtainMessage(SongData.MSG_COMPELTED, data.getAdapter()).sendToTarget();
}
}
} |
#!/bin/bash
#-------------------------------------------------------------------------------
# Copyright 2017 Congduc Pham, University of Pau, France.
#
# Congduc.Pham@univ-pau.fr
#
# This file is part of the low-cost LoRa gateway developped at University of Pau
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with the program. If not, see <http://www.gnu.org/licenses/>.
#-------------------------------------------------------------------------------
choice="Z"
if [ ! -f gateway_id.txt ]
then
echo "ERROR: gateway_id.txt file not found"
echo "should create it by running echo \"000000XXXXXXXXXX\" > gateway_id.txt"
echo "where XXXXXXXXXX is the last 5 bytes of your MAC Ethernet interface address"
echo "Example: echo \"00000027EBBEDA21\" > gateway_id.txt"
echo "Here is your MAC Ethernet interface address:"
echo "-------------------------------------------------------"
ifconfig | grep "eth0"
echo "-------------------------------------------------------"
echo "Enter the last 5 hex bytes of your MAC Ethernet interface address"
echo "in capital character and without the : separator"
echo "example: HWaddr b8:27:eb:be:da:21 then just enter 27EBBEDA21"
read macaddr
echo "Will write 000000$macaddr into gateway_id.txt"
echo "000000$macaddr" > gateway_id.txt
echo "Done"
echo "Replacing gw id in gateway_conf.json"
sed -i -- 's/"000000.*"/"000000'"$macaddr"'"/g' gateway_conf.json
echo "Done"
fi
gatewayid=`cat gateway_id.txt`
while [ "$choice" != "Q" ]
do
echo "=======================================* Gateway $gatewayid *==="
echo "0- sudo python start_gw.py & ; disown %1 +"
echo "1- sudo ./lora_gateway --mode 1 +"
echo "2- sudo ./lora_gateway --mode 1 | python post_processing_gw.py +"
echo "3- ps aux | grep -e start_gw -e lora_gateway -e post_proc -e log_gw +"
echo "4- tail --line=25 ../Dropbox/LoRa-test/post-processing_*.log +"
echo "5- tail --line=25 -f ../Dropbox/LoRa-test/post-processing_*.log +"
echo "6- less ../Dropbox/LoRa-test/post-processing_*.log +"
echo "------------------------------------------------------* Bluetooth *--+"
echo "a- run: sudo hciconfig hci0 piscan +"
echo "b- run: sudo python rfcomm-server.py +"
echo "c- run: nohup sudo python rfcomm-server.py -bg > rfcomm.log & +"
echo "d- run: ps aux | grep rfcomm +"
echo "e- run: tail -f rfcomm.log +"
echo "---------------------------------------------------* Connectivity *--+"
echo "f- test: ping www.univ-pau.fr +"
echo "--------------------------------------------------* Filtering msg *--+"
echo "l- List LoRa reception indications +"
echo "m- List radio module reset indications +"
echo "n- List boot indications +"
echo "o- List post-processing status +"
echo "p- List low-level gateway status +"
echo "--------------------------------------------------* Configuration *--+"
echo "A- show gateway_conf.json +"
echo "B- edit gateway_conf.json +"
echo "C- show clouds.json +"
echo "D- edit clouds.json +"
echo "-----------------------------------------------------------* kill *--+"
echo "K- kill all gateway related processes +"
echo "k- kill rfcomm-server process +"
echo "R- reboot gateway +"
echo "S- shutdown gateway +"
echo "---------------------------------------------------------------------+"
echo "Q- quit +"
echo "======================================================================"
echo "Enter your choice: "
read choice
echo "----------------------------------------------------------------------"
echo "BEGIN OUTPUT"
if [ "$choice" = "0" ]
then
echo "Running in background the full LoRa gateway"
sudo python start_gw.py &
disown %1
echo "Check ../Dropbox/LoRa-test/post-processing_$gatewayid.log file (select command 5)"
fi
if [ "$choice" = "1" ]
then
echo "Running simple lora_gateway... CTRL-C to exit"
sudo ./lora_gateway --mode 1
fi
if [ "$choice" = "2" ]
then
echo "Running lora_gateway with post-processing... CTRL-C to exit"
sudo ./lora_gateway --mode 1 | python post_processing_gw.py
fi
if [ "$choice" = "3" ]
then
echo "Check for lora_gateway process"
echo "##############################"
ps aux | grep -e start_gw -e lora_gateway -e post_processing -e log_gw
echo "##############################"
echo "The gateway is running if you see the lora_gateway process"
fi
if [ "$choice" = "4" ]
then
echo "Displaying last 25 lines of ../Dropbox/LoRa-test/post-processing_$gatewayid.log"
echo "Current UTC date is"
date --utc
tail --line=25 ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "5" ]
then
echo "Following last lines of ../Dropbox/LoRa-test/post-processing_$gatewayid.log. CTRL-C to return"
echo "Current UTC date is"
date --utc
trap "echo" SIGINT
tail --line=25 -f ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "6" ]
then
echo "Display ../Dropbox/LoRa-test/post-processing_$gatewayid.log. Q to return"
echo "Current UTC date is"
date --utc
trap "echo" SIGINT
less ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "a" ]
then
echo "Testing the Bluetooth interface"
echo "###############################"
sudo hciconfig hci0 piscan
echo "###############################"
echo "if no error then the RPI is visible with Bluetooth"
fi
if [ "$choice" = "b" ]
then
echo "Running rfcomm server for Bluetooth queries... CTRL-C to exit"
sudo python rfcomm-server.py
fi
if [ "$choice" = "c" ]
then
echo "Running in background the rfcomm server for Bluetooth queries. Logs in rfcomm.log"
nohup sudo python rfcomm-server.py -bg > rfcomm.log &
fi
if [ "$choice" = "d" ]
then
echo "Check for rfcomm-server process"
echo "###############################"
ps aux | grep rfcomm-server
echo "###############################"
echo "You should see python rfcomm-server.py for Bluetooth queries"
fi
if [ "$choice" = "e" ]
then
echo "Following last lines of rfcomm.log. CTRL-C to return"
echo "Current UTC date is"
date --utc
trap "echo" SIGINT
tail -f rfcomm.log
fi
if [ "$choice" = "f" ]
then
echo "Test Internet connectivity. CTRL-C to return"
trap "echo" SIGINT
ping www.univ-pau.fr
fi
if [ "$choice" = "l" ]
then
echo "List LoRa reception indications"
grep "rxlora" ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "m" ]
then
echo "List radio module reset"
grep "Resetting radio module" ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "n" ]
then
echo "List boot indications"
grep "**********Power ON" ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "o" ]
then
echo "List post-processing status"
grep "post status: gw ON" ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "p" ]
then
echo "List low-level gateway status"
grep "Low-level gw status ON" ../Dropbox/LoRa-test/post-processing_$gatewayid.log
fi
if [ "$choice" = "A" ]
then
echo "Showing global_conf.json"
cat gateway_conf.json
fi
if [ "$choice" = "B" ]
then
if [ -f gateway_conf.json ]
then
echo "Editing gateway_conf.json. CTRL-O to save, CTRL-X to return"
nano gateway_conf.json
else
echo "Error: gateway_conf.json does not exist"
fi
fi
if [ "$choice" = "C" ]
then
echo "Showing clouds.json"
cat clouds.json
fi
if [ "$choice" = "D" ]
then
if [ -f clouds.json ]
then
echo "Editing clouds.json. CTRL-O to save, CTRL-X to return"
nano clouds.json
else
echo "Error: clouds.json does not exist"
fi
fi
if [ "$choice" = "K" ]
then
echo "Killing all gateway related processes"
sudo kill $(ps aux | grep -e start_gw -e lora_gateway -e post_processing -e log_gw | awk '{print $2}')
fi
if [ "$choice" = "k" ]
then
echo "Killing rfcomm-server process"
sudo kill $(ps aux | grep -e rfcomm-server | awk '{print $2}')
fi
if [ "$choice" = "R" ]
then
echo "Reboot gateway"
sudo shutdown -r now
fi
if [ "$choice" = "S" ]
then
echo "Shutdown gateway"
sudo shutdown -h now
fi
echo "END OUTPUT"
if [ "$choice" != "Q" ]
then
echo "Press RETURN/ENTER..."
read k
fi
done
echo "Bye."
|
/**
*
*/
package net.abi.abisEngine.rendering.mesh;
import java.util.HashMap;
import net.abi.abisEngine.rendering.asset.AssetI;
/**
* Contains the reference count to the mesh along with the size of the indices
* and VAOID and MeshData.
*
* @author abinash
*
*/
public class MeshResource implements AssetI {
String name;
int size, refCount;
HashMap<String, VertexArrayObject> vaos;
MeshData meshData;
boolean initialized = false;
/**
* @param size
* @param meshData
*/
public MeshResource(String name, MeshData meshData) {
this.name = name;
this.size = meshData.model.getIndices().size() - 1;
this.refCount = 1;
this.meshData = meshData;
this.vaos = new HashMap<String, VertexArrayObject>();
}
VertexArrayObject addVAO(String name) {
VertexArrayObject _vao = new VertexArrayObject(name);
this.vaos.put(name, _vao);
return _vao;
}
VertexArrayObject getVAO(String name) {
return vaos.get(name);
}
public void incRef() {
refCount++;
}
public void decRef() {
refCount--;
}
public int decAndGetRef() {
refCount--;
return refCount;
}
int getAndDecRef() {
int _refs = refCount;
refCount--;
return _refs;
}
public int incAndGetRef() {
refCount++;
return refCount;
}
int getAndIncRef() {
int _refs = refCount;
refCount++;
return _refs;
}
@Override
public void dispose() {
}
@Override
public int getRefs() {
return refCount;
}
} |
package it.unical.mat.map_generator;
import java.util.Random;
import it.unical.mat.util.ConfigurationFile;
import tools.Utils;
import tracks.ArcadeMachine;
public class Main {
public static void main(String[] args) throws Exception {
ConfigurationFile configurationFile = new ConfigurationFile();
MapGenerator map = new MapGenerator(configurationFile);
map.generateMap();
// // Available tracks:
// String sampleRandomController = "tracks.singlePlayer.simple.sampleRandom.Agent";
// String doNothingController = "tracks.singlePlayer.simple.doNothing.Agent";
// String sampleOneStepController = "tracks.singlePlayer.simple.sampleonesteplookahead.Agent";
// String sampleFlatMCTSController = "tracks.singlePlayer.simple.greedyTreeSearch.Agent";
//
// String sampleMCTSController = "tracks.singlePlayer.advanced.sampleMCTS.Agent";
// String sampleRSController = "tracks.singlePlayer.advanced.sampleRS.Agent";
// String sampleRHEAController = "tracks.singlePlayer.advanced.sampleRHEA.Agent";
// String sampleOLETSController = "tracks.singlePlayer.advanced.olets.Agent";
//
// //Load available games
// String spGamesCollection = "examples/all_games_sp.csv";
// String[][] games = Utils.readGames(spGamesCollection);
//
// //Game settings
// boolean visuals = true;
// int seed = new Random().nextInt();
//
// // Game and level to play
// int gameIdx = 100;
// int levelIdx = 0; // level names from 0 to 4 (game_lvlN.txt).
// String gameName = games[gameIdx][1];
// String game = games[gameIdx][0];
// String level1 = "level_map/level_map";
//
// String recordActionsFile = null;
//
// // 1. This starts a game, in a level, played by a human.
// ArcadeMachine.playOneGame(game, level1, recordActionsFile, seed);
}
}
|
class Request {
setRequest (request) {
this.request = request
}
getRequest () {
return this.request
}
}
const request = new Request
module.exports = request
module.exports.Request = function () {
return request.getRequest()
}
|
#! /bin/bash
# -o, --bibliography=, --csl=, -M enable-upload=true/false
execdir="`dirname $0`"
settingsdir="${execdir}/../settings"
filterdir="${execdir}/../filter"
function usage {
cat <<EOF
convert LaTeX source to HTML with syntax provided by hatenablog.com
Usage:
$(basename ${0}) [options] INPUT.tex
Options:
-o FILE output file path. if not specified, to Stdout
--bibliography=FILE PATH bib.file path
-M ... pandoc meta file arguments
EOF
}
if [ $# -eq 0 ]; then
usage
exit 1
fi
pandoc --mathjax --wrap=auto -F pandoc-crossref -F pandoc-citeproc -F ${filterdir}/hateblo-filter.py -f latex -M reference-section-title='参考文献' -M crossrefYaml=${settingsdir}/pandoc-crossref-settings.yaml $@
|
# utils.py
def calculate_average(numbers):
"""
Calculate the average of a list of numbers.
Args:
numbers (list): A list of numbers.
Returns:
float: The average of the input numbers.
"""
if not numbers:
return 0
return sum(numbers) / len(numbers)
def find_max(numbers):
"""
Find the maximum value in a list of numbers.
Args:
numbers (list): A list of numbers.
Returns:
float: The maximum value in the input list.
"""
if not numbers:
return None
return max(numbers) |
import { Container, makeStyles, Paper } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import Card from "@material-ui/core/Card";
import CardContent from "@material-ui/core/CardContent";
import Typography from "@material-ui/core/Typography";
import URL_API_KEY from "../../../API_KEY/API_KEYS.json";
const useStyles = makeStyles({
WrapperStyle: {
height: `684px`,
display: `flex`,
marginLeft: `4px`,
marginRight: `4px`,
padding: `0px`,
position: `center`,
justifyContent: `center`,
},
root: {
minWidth: 275,
},
title: {
fontSize: 14,
},
});
function News() {
const classes = useStyles();
const [blogs, setBlogs] = useState([]);
const URL = URL_API_KEY.API_KEY.Blogger.Key;
useEffect(() => {
const fetchData = async () => {
const response = await fetch(URL);
const data = await response.json();
setBlogs(data.items);
};
fetchData();
}, [URL]);
console.log(blogs);
//const URL_IFRAME = "https://testtesttestasddsa.blogspot.com/";
return (
<Container disableGutters maxWidth={false}>
{/* <Iframe
url={URL_IFRAME}
width="100%"
height="80%"
id="myId"
className="myClassname"
display="inline"
position="absolute"
overflow
frameBorder="0"
allowFullScreen={true}
/> */}
{blogs.map((item) => (
<Container maxWidth="lg" key={item.id}>
<Paper variant="elevation" square elevation={15}>
<Card className={classes.root}>
<CardContent>
<Typography
variant="body2"
dangerouslySetInnerHTML={{ __html: item.content }}
component="p"
/>
</CardContent>
</Card>
</Paper>
<br />
</Container>
))}
</Container>
);
}
export default News;
|
import requests
from bs4 import BeautifulSoup
url = 'https://example.com'
response = requests.get(url)
if response.status_code == 200:
html = response.content
soup = BeautifulSoup(html, 'html.parser')
data = soup.find_all('p')
for paragraph in data:
print(paragraph.text) |
<filename>project/gardener/src/main/java/kr/co/gardener/admin/dao/object/TopClassDao.java
package kr.co.gardener.admin.dao.object;
import java.util.List;
import kr.co.gardener.admin.model.object.TopClass;
import kr.co.gardener.admin.model.object.list.TopClassList;
import kr.co.gardener.main.vo.TopClassVO;
import kr.co.gardener.util.Pager;
public interface TopClassDao {
void insert(List<TopClass> list);
List<TopClass> list(Pager pager);
void delete(List<TopClass> list);
void update(List<TopClass> list);
float total(Pager pager);
List<TopClassVO> includMidClassList();
}
|
const stub = {
__packager_asset: true,
fileSystemLocation: '/full/path/to/directory',
httpServerLocation: '/assets/full/path/to/directory',
width: 100,
height: 100,
scales: [1, 2, 3],
hash: 'nonsense',
name: 'icon',
type: 'png',
};
jest.mock('react-native/Libraries/Image/RelativeImageStub', stub)
module.exports = stub;
|
package cryptoutil
import (
"crypto/x509"
"encoding/pem"
"os"
)
// ReadCertificateFile reads a certificate PEM file.
func ReadCertificateFile(path string) ([]*x509.Certificate, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
return ParseCertificatePEM(data)
}
// ParseCertificatePEM parses a certificate PEM.
func ParseCertificatePEM(data []byte) ([]*x509.Certificate, error) {
var certs []*x509.Certificate
block, rest := pem.Decode(data)
for block != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
return nil, err
}
certs = append(certs, cert)
block, rest = pem.Decode(rest)
}
return certs, nil
}
|
from typing import List
from myapp.models import Post, Tag
def tag_post(post: Post, tag_names: List[str]) -> None:
for tag_name in tag_names:
tag, created = Tag.objects.get_or_create(name=tag_name)
post.tags.add(tag) |
<filename>src/utils/hasAccessibleChild.js
const getElementType = require("./getElementType");
const isHiddenFromScreenReader = require("./isHiddenFromScreenReader");
const hasAccessibleChild = (node, accessibleChildTypes = []) =>
node.children.some((child) => {
switch (child.type) {
case "VText":
return child.value.trim().length > 0;
case "VElement": {
const elementType = getElementType(child);
return (
accessibleChildTypes.includes(elementType) ||
child.rawName === "slot" ||
(!isHiddenFromScreenReader(child) &&
hasAccessibleChild(child, accessibleChildTypes))
);
}
case "VExpressionContainer":
if (child.expression && child.expression.type === "Identifier") {
return child.expression.name !== "undefined";
}
return true;
default:
return false;
}
});
module.exports = hasAccessibleChild;
|
<filename>packages/react-integration/cypress/integration/descriptionlistbreakpoints.spec.ts<gh_stars>100-1000
describe('Description List Breakpoints Demo Test', () => {
it('Navigate to demo section', () => {
cy.visit('http://localhost:3000/description-list-breakpoints-demo-nav-link');
});
it('Verify 1Col modifier applied for all viewport sizes ', () => {
cy.get('#1-col-description-list.pf-m-1-col').should('exist');
cy.get('#1-col-description-list.pf-m-1-col-on-md').should('exist');
cy.get('#1-col-description-list.pf-m-1-col-on-lg').should('exist');
cy.get('#1-col-description-list.pf-m-1-col-on-xl').should('exist');
cy.get('#1-col-description-list.pf-m-1-col-on-2xl').should('exist');
});
it('Verify 2Col modifier applied for all viewport sizes ', () => {
cy.get('#2-col-description-list.pf-m-2-col').should('exist');
cy.get('#2-col-description-list.pf-m-2-col-on-md').should('exist');
cy.get('#2-col-description-list.pf-m-2-col-on-lg').should('exist');
cy.get('#2-col-description-list.pf-m-2-col-on-xl').should('exist');
cy.get('#2-col-description-list.pf-m-2-col-on-2xl').should('exist');
});
it('Verify 3Col modifier applied for all viewport sizes ', () => {
cy.get('#3-col-description-list.pf-m-3-col').should('exist');
cy.get('#3-col-description-list.pf-m-3-col-on-md').should('exist');
cy.get('#3-col-description-list.pf-m-3-col-on-lg').should('exist');
cy.get('#3-col-description-list.pf-m-3-col-on-xl').should('exist');
cy.get('#3-col-description-list.pf-m-3-col-on-2xl').should('exist');
});
it('Verify description list has layout breakpoints', () => {
const list = cy.get('#orientation-description-list');
list.should('have.class', 'pf-m-horizontal-on-sm');
list.should('have.class', 'pf-m-vertical-on-md');
list.should('have.class', 'pf-m-horizontal-on-lg');
list.should('have.class', 'pf-m-vertical-on-xl');
list.should('have.class', 'pf-m-horizontal-on-2xl');
});
});
|
/*
* Copyright (c) 2015, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* o Neither the name of Freescale Semiconductor, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fsl_uart_edma.h"
#include "fsl_dmamux.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/* Array of UART handle. */
#if (defined(UART5))
#define UART_HANDLE_ARRAY_SIZE 6
#else /* UART5 */
#if (defined(UART4))
#define UART_HANDLE_ARRAY_SIZE 5
#else /* UART4 */
#if (defined(UART3))
#define UART_HANDLE_ARRAY_SIZE 4
#else /* UART3 */
#if (defined(UART2))
#define UART_HANDLE_ARRAY_SIZE 3
#else /* UART2 */
#if (defined(UART1))
#define UART_HANDLE_ARRAY_SIZE 2
#else /* UART1 */
#if (defined(UART0))
#define UART_HANDLE_ARRAY_SIZE 1
#else /* UART0 */
#error No UART instance.
#endif /* UART 0 */
#endif /* UART 1 */
#endif /* UART 2 */
#endif /* UART 3 */
#endif /* UART 4 */
#endif /* UART 5 */
/*<! Structure definition for uart_edma_private_handle_t. The structure is private. */
typedef struct _uart_edma_private_handle
{
UART_Type *base;
uart_edma_handle_t *handle;
} uart_edma_private_handle_t;
/* UART EDMA transfer handle. */
enum _uart_edma_tansfer_states
{
kUART_TxIdle, /* TX idle. */
kUART_TxBusy, /* TX busy. */
kUART_RxIdle, /* RX idle. */
kUART_RxBusy /* RX busy. */
};
/*******************************************************************************
* Definitions
******************************************************************************/
/*<! Private handle only used for internally. */
static uart_edma_private_handle_t s_edmaPrivateHandle[UART_HANDLE_ARRAY_SIZE];
/*******************************************************************************
* Prototypes
******************************************************************************/
/*!
* @brief UART EDMA send finished callback function.
*
* This function is called when UART EDMA send finished. It disables the UART
* TX EDMA request and sends @ref kStatus_UART_TxIdle to UART callback.
*
* @param handle The EDMA handle.
* @param param Callback function parameter.
*/
static void UART_SendEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds);
/*!
* @brief UART EDMA receive finished callback function.
*
* This function is called when UART EDMA receive finished. It disables the UART
* RX EDMA request and sends @ref kStatus_UART_RxIdle to UART callback.
*
* @param handle The EDMA handle.
* @param param Callback function parameter.
*/
static void UART_ReceiveEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds);
/*!
* @brief Get the UART instance from peripheral base address.
*
* @param base UART peripheral base address.
* @return UART instance.
*/
extern uint32_t UART_GetInstance(UART_Type *base);
/*******************************************************************************
* Code
******************************************************************************/
static void UART_SendEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds)
{
uart_edma_private_handle_t *uartPrivateHandle = (uart_edma_private_handle_t *)param;
/* Avoid the warning for unused variables. */
handle = handle;
tcds = tcds;
if (transferDone)
{
UART_TransferAbortSendEDMA(uartPrivateHandle->base, uartPrivateHandle->handle);
if (uartPrivateHandle->handle->callback)
{
uartPrivateHandle->handle->callback(uartPrivateHandle->base, uartPrivateHandle->handle, kStatus_UART_TxIdle,
uartPrivateHandle->handle->userData);
}
}
}
static void UART_ReceiveEDMACallback(edma_handle_t *handle, void *param, bool transferDone, uint32_t tcds)
{
uart_edma_private_handle_t *uartPrivateHandle = (uart_edma_private_handle_t *)param;
/* Avoid warning for unused parameters. */
handle = handle;
tcds = tcds;
if (transferDone)
{
/* Disable transfer. */
UART_TransferAbortReceiveEDMA(uartPrivateHandle->base, uartPrivateHandle->handle);
if (uartPrivateHandle->handle->callback)
{
uartPrivateHandle->handle->callback(uartPrivateHandle->base, uartPrivateHandle->handle, kStatus_UART_RxIdle,
uartPrivateHandle->handle->userData);
}
}
}
void UART_TransferCreateHandleEDMA(UART_Type *base,
uart_edma_handle_t *handle,
uart_edma_transfer_callback_t callback,
void *userData,
edma_handle_t *txEdmaHandle,
edma_handle_t *rxEdmaHandle)
{
assert(handle);
uint32_t instance = UART_GetInstance(base);
s_edmaPrivateHandle[instance].base = base;
s_edmaPrivateHandle[instance].handle = handle;
memset(handle, 0, sizeof(*handle));
handle->rxState = kUART_RxIdle;
handle->txState = kUART_TxIdle;
handle->rxEdmaHandle = rxEdmaHandle;
handle->txEdmaHandle = txEdmaHandle;
handle->callback = callback;
handle->userData = userData;
#if defined(FSL_FEATURE_UART_HAS_FIFO) && FSL_FEATURE_UART_HAS_FIFO
/* Note:
Take care of the RX FIFO, EDMA request only assert when received bytes
equal or more than RX water mark, there is potential issue if RX water
mark larger than 1.
For example, if RX FIFO water mark is 2, upper layer needs 5 bytes and
5 bytes are received. the last byte will be saved in FIFO but not trigger
EDMA transfer because the water mark is 2.
*/
if (rxEdmaHandle)
{
base->RWFIFO = 1U;
}
#endif
/* Configure TX. */
if (txEdmaHandle)
{
EDMA_SetCallback(handle->txEdmaHandle, UART_SendEDMACallback, &s_edmaPrivateHandle[instance]);
}
/* Configure RX. */
if (rxEdmaHandle)
{
EDMA_SetCallback(handle->rxEdmaHandle, UART_ReceiveEDMACallback, &s_edmaPrivateHandle[instance]);
}
}
status_t UART_SendEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer)
{
assert(handle->txEdmaHandle);
edma_transfer_config_t xferConfig;
status_t status;
/* Return error if xfer invalid. */
if ((0U == xfer->dataSize) || (NULL == xfer->data))
{
return kStatus_InvalidArgument;
}
/* If previous TX not finished. */
if (kUART_TxBusy == handle->txState)
{
status = kStatus_UART_TxBusy;
}
else
{
handle->txState = kUART_TxBusy;
handle->txDataSizeAll = xfer->dataSize;
/* Prepare transfer. */
EDMA_PrepareTransfer(&xferConfig, xfer->data, sizeof(uint8_t), (void *)UART_GetDataRegisterAddress(base),
sizeof(uint8_t), sizeof(uint8_t), xfer->dataSize, kEDMA_MemoryToPeripheral);
/* Submit transfer. */
EDMA_SubmitTransfer(handle->txEdmaHandle, &xferConfig);
EDMA_StartTransfer(handle->txEdmaHandle);
/* Enable UART TX EDMA. */
UART_EnableTxDMA(base, true);
status = kStatus_Success;
}
return status;
}
status_t UART_ReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle, uart_transfer_t *xfer)
{
assert(handle->rxEdmaHandle);
edma_transfer_config_t xferConfig;
status_t status;
/* Return error if xfer invalid. */
if ((0U == xfer->dataSize) || (NULL == xfer->data))
{
return kStatus_InvalidArgument;
}
/* If previous RX not finished. */
if (kUART_RxBusy == handle->rxState)
{
status = kStatus_UART_RxBusy;
}
else
{
handle->rxState = kUART_RxBusy;
handle->rxDataSizeAll = xfer->dataSize;
/* Prepare transfer. */
EDMA_PrepareTransfer(&xferConfig, (void *)UART_GetDataRegisterAddress(base), sizeof(uint8_t), xfer->data,
sizeof(uint8_t), sizeof(uint8_t), xfer->dataSize, kEDMA_PeripheralToMemory);
/* Submit transfer. */
EDMA_SubmitTransfer(handle->rxEdmaHandle, &xferConfig);
EDMA_StartTransfer(handle->rxEdmaHandle);
/* Enable UART RX EDMA. */
UART_EnableRxDMA(base, true);
status = kStatus_Success;
}
return status;
}
void UART_TransferAbortSendEDMA(UART_Type *base, uart_edma_handle_t *handle)
{
assert(handle->txEdmaHandle);
/* Disable UART TX EDMA. */
UART_EnableTxDMA(base, false);
/* Stop transfer. */
EDMA_AbortTransfer(handle->txEdmaHandle);
handle->txState = kUART_TxIdle;
}
void UART_TransferAbortReceiveEDMA(UART_Type *base, uart_edma_handle_t *handle)
{
assert(handle->rxEdmaHandle);
/* Disable UART RX EDMA. */
UART_EnableRxDMA(base, false);
/* Stop transfer. */
EDMA_AbortTransfer(handle->rxEdmaHandle);
handle->rxState = kUART_RxIdle;
}
status_t UART_TransferGetReceiveCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count)
{
assert(handle->rxEdmaHandle);
if (kUART_RxIdle == handle->rxState)
{
return kStatus_NoTransferInProgress;
}
if (!count)
{
return kStatus_InvalidArgument;
}
*count = handle->rxDataSizeAll - EDMA_GetRemainingBytes(handle->rxEdmaHandle->base, handle->rxEdmaHandle->channel);
return kStatus_Success;
}
status_t UART_TransferGetSendCountEDMA(UART_Type *base, uart_edma_handle_t *handle, uint32_t *count)
{
assert(handle->txEdmaHandle);
if (kUART_TxIdle == handle->txState)
{
return kStatus_NoTransferInProgress;
}
if (!count)
{
return kStatus_InvalidArgument;
}
*count = handle->txDataSizeAll - EDMA_GetRemainingBytes(handle->txEdmaHandle->base, handle->txEdmaHandle->channel);
return kStatus_Success;
}
|
from pyspark.sql import SparkSession
from pyspark.sql.functions import sum, col
def find_max_destination_flights(flightData2015):
max_flights = flightData2015.groupBy("DEST_COUNTRY_NAME").agg(sum("count").alias("total_flights")) \
.orderBy(col("total_flights").desc()).first()
return max_flights["DEST_COUNTRY_NAME"], max_flights["total_flights"]
# Example usage
spark = SparkSession.builder.appName("flightData").getOrCreate()
data = [("United States", 125), ("Canada", 75), ("Mexico", 100), ("Canada", 200), ("United States", 300)]
columns = ["DEST_COUNTRY_NAME", "count"]
flightData2015 = spark.createDataFrame(data, columns)
result = find_max_destination_flights(flightData2015)
print(result) # Output: ('United States', 425) |
#!/bin/bash
PROJECT=$(gcloud config list project 2>/dev/null | grep = | sed "s/^[^=]*= //")
# Leave this variable blank if you want to enable doing all tasks at once
#DISABLE_ALL_TASK=1
splitter(){
i=$(tput cols)
while [ $i -gt "0" ]; do
echo -n =
i=$(($i - 1))
done
echo ""
}
pause(){
read -p "Press Enter to continue"
}
check_return(){
if [ $1 -ne "0" ]; then
echo "Error detected"
pause
fi
}
echo_cmd(){
splitter
echo $@
eval $@
RET=$?
if [ $RET -ne "0" ]; then
echo "Error occured! You can ignore this message and press enter to continue."
pause
fi
}
checkpoint(){
splitter
echo "Checkpoint reached"
pause
}
# TODO: PUT THE TASKS HERE
ZONE=us-central1-b
VPC=acme-vpc
task1(){
cat << EOF
Task 1 - Delete overly open firewall rule
$(splitter)
EOF
pause
echo_cmd gcloud compute firewall-rules delete open-access
checkpoint
} # End of task 1
task2(){
cat << EOF
Task 2 - Start "bastion" instance
$(splitter)
EOF
pause
echo_cmd gcloud compute instances start bastion --zone=$ZONE
checkpoint
} # End of task 2
task3(){
echo "Preparing task 3..."
MGMT_NET=$(gcloud compute networks subnets list --filter="name:acme-mgmt-subnet" --format="csv(RANGE)" --limit=1 | tail -n +2)
read -p "Please paste the tag for allowing IAP SSH access: " TAG_IAP_SSH
read -p "Please paste the tag for HTTP access: " TAG_HTTP
read -p "Please paste the tag for allowing internal SSH access: " TAG_INT_SSH
splitter
cat << EOF
Task 3 - Create proper firewall rules
$(splitter)
Here's the firewall rules to be created:
Name Rule Source Target
=======================================================================
acme-vpc-allow-iap-ssh-ingress tcp:22 35.235.240.0/20 tag($TAG_IAP_SSH)
acme-vpc-allow-http-ingress tcp:80 any tag($TAG_HTTP)
acme-vpc-allow-internal-ssh tcp:22 $MGMT_NET tag($TAG_INT_SSH)
EOF
pause
# SSH IAP rule
echo_cmd gcloud compute firewall-rules create acme-vpc-allow-iap-ssh-ingress \
--network=$VPC \
--source-ranges=35.235.240.0/20 \
--target-tags=$TAG_IAP_SSH \
--rules=tcp:22 \
--direction=INGRESS \
--action=ALLOW
echo_cmd gcloud compute instances add-tags bastion --zone=$ZONE --tags=$TAG_IAP_SSH
# HTTP public access rule
echo_cmd gcloud compute firewall-rules create acme-vpc-allow-http-ingress \
--network=$VPC \
--source-ranges=0.0.0.0/0 \
--target-tags=$TAG_HTTP \
--rules=tcp:80 \
--direction=INGRESS \
--action=ALLOW
# Internal SSH rule
echo_cmd gcloud compute firewall-rules create acme-vpc-allow-internal-ssh \
--network=$VPC \
--source-ranges=$MGMT_NET \
--target-tags=$TAG_INT_SSH \
--rules=tcp:22 \
--direction=INGRESS \
--action=ALLOW
echo_cmd gcloud compute instances add-tags juice-shop --zone=$ZONE --tags=$TAG_INT_SSH,$TAG_HTTP
checkpoint
} # End of task 3
task4(){
TARGET_IP=$(gcloud compute instances list --filter="name:juice-shop" --format="csv(INTERNAL_IP)" --limit=1 | tail -n +2)
cat << EOF
Task 4 - Connect to "juice-shop" via IAP SSH session to bastion
$(splitter)
This task cannot be done here. Go to the "Compute Engine" => "VM Instances" page on Google Cloud Platform console, enter this command:
\`\`\`
ssh $TARGET_IP
\`\`\`
It should be able to establish connection to juice-shop.
EOF
pause
}
case "$1" in
"all")
if [ $DISABLE_ALL_TASK ] ; then
echo "Doing all tasks at once has been disabled"
exit 1
else
if [ "$PROJECT" == "" ]; then
echo "Warning: No selected project"
echo "You can still proceed to execute anyway or press Ctrl-C to exit"
else
echo "Please confirm your target project is $PROJECT"
fi
pause
task=${START_TASK:-$([ "$(echo $@ | wc -w)" -ge "2" ] && echo $2 || echo "1")}
echo "Starting from task $task"
echo ""
echo "No argument will be able to passed to any task."
echo "Are you sure you wanna do all at once?"
pause
while [[ $(type -t task$task) == function ]]; do
splitter
task$task
task=$(($task + 1))
done
fi
;;
"help" | "")
cat << EOF
Usage:
$0 <task_number> <additional_args_for_task>
Execute specified task.
$0 all
Execute all tasks from task 1.
START_TASK=<task_number> $0 all
- or -
$0 all <task_number>
Execute tasks start from specified task.
$0 help
Display this message
EOF
;;
*)
if [ "$PROJECT" == "" ]; then
echo "Warning: No selected project"
echo "You can still proceed to execute anyway or Ctrl-C to exit"
else
echo "Please confirm your target project is $PROJECT"
fi
pause
splitter
[[ $(type -t task$1) == function ]] && task$1 $@ || echo "No task named task$1"
;;
esac
|
<filename>src/containers/Account/ResetPasswordForm/index.js<gh_stars>1-10
import React, { PureComponent } from 'react'
import { connect } from 'react-redux'
import ResetPasswordForm from 'components/forms/ResetPassword'
import {
updateForm,
updateFormError,
resetForm,
changePassword
} from 'actions/account/ResetPassword'
import { resetPasswordValidators } from 'utils/validation/ResetPassword'
import { addToastSuccess, addToastError } from 'actions/toast'
import { UPDATED_USER_DETAILS } from 'texts/successmessages'
class ResetPasswordFormContainer extends PureComponent {
constructor (props) {
super(props)
}
componentWillUnmount () {
this.props.clearForm()
}
render () {
return <ResetPasswordForm {...this.props} />
}
}
const mapStateToProps = (state, ownProps) => {
const {
account
} = state
const {
currentPassword,
newPassword,
confirmPassword,
errors
} = account.resetPassword
let canProgress = true
for (let key in errors) {
let error = errors[key]
if (error.length > 0) {
canProgress = false
}
}
console.log(errors)
return {
values: {
currentPassword,
newPassword,
confirmPassword
},
errors,
canProgress,
validators: resetPasswordValidators
}
}
const mapDispatchToProps = (dispatch, ownProps) => {
return {
update: (name, value) => {
dispatch(updateForm(name, value))
},
updateErrors: (errors, name) => {
dispatch(updateFormError(errors, name))
},
submitForm: (values) => {
let {currentPassword, newPassword} = values
dispatch(changePassword({oldPassword: currentPassword, newPassword}))
.then(() => {
dispatch(addToastSuccess(UPDATED_USER_DETAILS))
dispatch(resetForm())
ownProps.onFormCancel && ownProps.onFormCancel()
return Promise.resolve()
})
.catch(error => {
if (error.message === 'Login failed') {
dispatch(addToastError('Please check your password'))
}
else if (error && error.errors && error.errors.password) {
dispatch(addToastError(error.errors.password))
}
else if (error && error.message) {
dispatch(addToastError(error.message))
}
})
},
clearForm: () => {
dispatch(resetForm())
},
onCancel: () => {
dispatch(resetForm())
ownProps.onFormCancel && ownProps.onFormCancel()
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(ResetPasswordFormContainer)
|
#!/bin/bash
# author: Martin Liu
# url:martinliu.cn
#指定安装的版本
elastic_version='7.8.1'
#开始安装流程
echo "Provisioning a Elasticsearch "$elastic_version" Server..."
sudo date > /etc/vagrant_provisioned_at
#配置 ES 需要的操作系统参数
sudo swapoff -a
sudo sysctl -w vm.max_map_count=262144
sudo sysctl -p
sudo sh -c "echo 'elasticsearch - nofile 65535' >> /etc/security/limits.conf"
sudo sh -c "echo 'vagrant - nofile 65535' >> /etc/security/limits.conf"
#设置个性化 SSH 登录提示信息
sudo sh -c "echo '**** -- -- -- -- -- -- -- -- ****' > /etc/motd"
sudo sh -c "echo '**** Welcome to Elastic Stack Labs' >> /etc/motd"
sudo sh -c "echo '**** -- -- -- -- -- -- -- -- ****' >> /etc/motd"
sudo sh -c "echo '*' >> /etc/motd"
#安装 ES 软件包
sudo rpm -ivh /vagrant/rpm/elasticsearch-$elastic_version-x86_64.rpm
#创建 ES 集群内部通信加密数字证书,提前清理就的证书文件和目录
sudo rm -f /vagrant/certs/certs.zip
sudo rm -rf /vagrant/certs/es*
sudo rm -rf /vagrant/certs/ca
sudo rm -rf /vagrant/certs/lk
sudo /usr/share/elasticsearch/bin/elasticsearch-certutil cert -in /vagrant/certs/instance.yml -pem -out /vagrant/certs/certs.zip -s
#解压缩所有证书备用
sudo /usr/bin/unzip /vagrant/certs/certs.zip -d /vagrant/certs/
#部署节点需要的秘钥
sudo cp /vagrant/certs/ca/ca.crt /etc/elasticsearch/
sudo cp /vagrant/certs/es1/* /etc/elasticsearch/
#更新 ES 默认的配置文件
sudo cp /vagrant/es1.yml /etc/elasticsearch/elasticsearch.yml
#配置和启动 ES 系统服务
sudo systemctl daemon-reload
sudo systemctl enable elasticsearch.service
sudo systemctl start elasticsearch.service
sudo systemctl status elasticsearch
#初始化 ES 服务器内建用户的密码,这些密码需要在控制台上复制保存备用
sudo /usr/share/elasticsearch/bin/elasticsearch-setup-passwords auto -b
#成功顺利的完成了安装
echo Provisioning script works good!
echo Please access Elasticsearch https://192.168.50.11:9200 |
import string
import random
def random_password():
"""Function to generate a random password"""
characters = string.ascii_letters + string.digits
password = ''.join(random.choice(characters) for i in range(8))
return password
password = random_password()
print(password) |
<reponame>palantir/godel-refreshables-plugin<filename>config/config.go
// Copyright (c) 2021 <NAME> Inc. All rights reserved.
// Use of this source code is governed by the Apache License, Version 2.0
// that can be found in the LICENSE file.
package config
import (
"io/ioutil"
v0 "github.com/palantir/godel-refreshables-plugin/config/internal/v0"
"github.com/pkg/errors"
"gopkg.in/yaml.v2"
)
type Config v0.Config
func ToConfig(in *Config) *v0.Config {
return (*v0.Config)(in)
}
func ReadConfigFromFile(f string) (Config, error) {
bytes, err := ioutil.ReadFile(f)
if err != nil {
return Config{}, errors.WithStack(err)
}
return ReadConfigFromBytes(bytes)
}
func ReadConfigFromBytes(inputBytes []byte) (Config, error) {
var cfg Config
if err := yaml.UnmarshalStrict(inputBytes, &cfg); err != nil {
return Config{}, errors.WithStack(err)
}
return cfg, nil
}
|
<filename>mvp_tips/CPUID/CPUID/InfoDisplay.cpp
// InfoDisplay.cpp : implementation file
//
#include "stdafx.h"
#include "InfoDisplay.h"
// CInfoDisplay
IMPLEMENT_DYNAMIC(CInfoDisplay, CWnd)
CInfoDisplay::CInfoDisplay()
{
}
CInfoDisplay::~CInfoDisplay()
{
}
BEGIN_MESSAGE_MAP(CInfoDisplay, CWnd)
ON_MESSAGE(WM_SETFONT, OnSetFont)
ON_MESSAGE(WM_GETFONT, OnGetFont)
ON_WM_PAINT()
ON_WM_ERASEBKGND()
END_MESSAGE_MAP()
// CInfoDisplay message handlers
/****************************************************************************
* CInfoDisplay::OnPaint
* Result: void
*
* Effect:
* Draws the contents
****************************************************************************/
void CInfoDisplay::OnPaint()
{
CPaintDC dc(this); // device context for painting
CFont * f = GetFont();
dc.SelectObject(f);
// First, we compute the maximum line width, and set the rectangle wide enough to
// hold this. Then we use DrawText/DT_CALCRECT to compute the height
CString text;
GetWindowText(text);
CSize box = CSize(0,0);
TEXTMETRIC tm;
dc.GetTextMetrics(&tm);
int inf; // inflation factor
{ /* compute box size */
CString s = text;
while(TRUE)
{ /* scan string */
CString line;
int p = s.Find(_T("\n"));
if(p < 0)
line = s;
else
{ /* one line */
line = s.Left(p);
s = s.Mid(p + 1);
} /* one line */
CSize sz = dc.GetTextExtent(line);
box.cx = max(box.cx, sz.cx);
box.cy += tm.tmHeight + tm.tmInternalLeading;
if(p < 0)
break;
} /* scan string */
//================================
// Having computed the width,
// allow for the borders
// and extra space for margins
//================================
inf = 4 * ::GetSystemMetrics(SM_CXBORDER);
box.cx += 2 * inf;
box.cy += 2 * inf;
CRect r(0,0,0,0);
r.right = box.cx;
r.bottom = box.cy;
//================================
// Set the window size
//================================
SetWindowPos(NULL, 0, 0, r.Width(), r.Height(), SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE);
} /* compute box size */
CRect r;
GetClientRect(&r);
r.InflateRect(-inf, -inf);
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(COLOR_INFOTEXT);
CString s = text;
int y = r.top;
while(TRUE)
{ /* scan string */
CString line;
int p = s.Find(_T("\n"));
if(p < 0)
line = s;
else
{ /* one line */
line = s.Left(p);
s = s.Mid(p + 1);
} /* one line */
dc.TextOut(r.left, y, line);
y += tm.tmHeight + tm.tmInternalLeading;
if(p < 0)
break;
} /* scan string */
// Do not call CWnd::OnPaint() for painting messages
}
/****************************************************************************
* CInfoDisplay::OnEraseBkgnd
* Inputs:
* CDC * pDC:
* Result: BOOL
* TRUE, always
* Effect:
* Erases the background
****************************************************************************/
BOOL CInfoDisplay::OnEraseBkgnd(CDC* pDC)
{
CRect r;
GetClientRect(&r);
pDC->FillSolidRect(&r, ::GetSysColor(COLOR_INFOBK));
return TRUE;
}
/****************************************************************************
* CInfoDisplay::Create
* Inputs:
* int x: Desired left of window
* int y: Desired right of window
* LPCTSTR text: Desired text to put in window
* CWnd * parent: Parent window
* Result: BOOL
* TRUE if successful
* FALSE if error
* Effect:
* Shows a multiline help window
****************************************************************************/
BOOL CInfoDisplay::Create(int x, int y, LPCTSTR text, CWnd * parent)
{
ASSERT(parent != NULL);
if(parent == NULL)
return FALSE;
LPCTSTR infoclass = AfxRegisterWndClass(0, // mo class styles
NULL, // default arrow cursor
(HBRUSH)(COLOR_INFOBK + 1),
NULL);
ASSERT(infoclass != NULL);
if(infoclass == NULL)
return FALSE;
CFont * f = parent->GetFont();
if(f == NULL && parent->GetParent() != NULL)
f = parent->GetParent()->GetFont();
CRect r(0,0,10,10); // meaningless values, will be recomputed after creation
BOOL result = CreateEx(WS_EX_NOACTIVATE, // extended styles
infoclass,
text,
/* not WS_VISIBLE */ WS_POPUP | WS_BORDER,
r,
parent,
NULL);
ASSERT(result);
if(!result)
return FALSE;
SetFont(f);
return TRUE;
} // CInfoDisplay::Create
/****************************************************************************
* CInfoDisplay::PostNcDestroy
* Result: void
*
* Effect:
* Deletes the instance
****************************************************************************/
void CInfoDisplay::PostNcDestroy()
{
CWnd::PostNcDestroy();
delete this;
}
/****************************************************************************
* CInfoDisplay::OnSetFont
* Inputs:
* WPARAM: (WPARAM)(HFONT) handle to font
* LPARAM: (LPARAM)(MAKELONG(BOOL, ?))
* Result: LRESULT
* Logically void, 0, always
* Effect:
* Saves the font. Forces a redraw if LOWORD(lParam) is non-zero
****************************************************************************/
LRESULT CInfoDisplay::OnSetFont(WPARAM wParam, LPARAM lParam)
{
font = (HFONT)wParam;
if(LOWORD(lParam))
{ /* force redraw */
Invalidate();
UpdateWindow();
} /* force redraw */
return 0;
} // CInfoDisplay::OnSetFont
/****************************************************************************
* CInfoDisplay::OnGetFont
* Inputs:
* WPARAM: ignored
* LPARAM: ignored
* Result: LRESULT
* (LRESULT)(HFONT)
****************************************************************************/
LRESULT CInfoDisplay::OnGetFont(WPARAM, LPARAM)
{
return (LRESULT)font;
} // CInfoDisplay::OnGetFont
/****************************************************************************
* CInfoDisplay::SetWindowText
* Inputs:
* LPCTSTR s: Text to set
* Result: void
a*
* Effect:
* Sets the text. Avoids flicker by doing nothing if
* the text is the same
****************************************************************************/
void CInfoDisplay::SetWindowText(LPCTSTR s)
{
CString old;
GetWindowText(old);
if(old != s)
{ /* different */
CWnd::SetWindowText(s);
Invalidate();
} /* different */
} // CInfoDisplay::SetWindowText
/****************************************************************************
* CInfoDisplay::ShowTip
* Inputs:
* CWnd * parent: Window in which tip is being displayed
* CPoint pt: Display point
* const CString & text: Text to display
* BOOL visible: Visibility
* Result: CInfoDisplay *
* If the info display already exists, returns 'this'
* If it does not exist, creates it and returns the created value
* Effect:
* Displays the tooltip
* Notes:
* 'this' can be NULL!
****************************************************************************/
CInfoDisplay * CInfoDisplay::ShowTip(CWnd * parent, CPoint pt, const CString & text, BOOL visible)
{
CInfoDisplay * result = NULL;
CPoint target = pt;
parent->ClientToScreen(&target);
target.y += ::GetSystemMetrics(SM_CYCURSOR);
if(visible && text.IsEmpty())
visible = FALSE;
if(GetSafeHwnd() != NULL)
{ /* already exists */
SetWindowText(text);
result = this;
SetWindowPos(NULL, target.x, target.y,
0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
result->ShowWindow(visible ? SW_SHOWNA : SW_HIDE);
} /* already exists */
else
{ /* must create */
result = new CInfoDisplay();
if(!result->Create(target.x, target.y, text, parent))
{ /* failed */
delete result;
result = NULL;
} /* failed */
else
{ /* created window */
TRACKMOUSEEVENT tme = { sizeof(TRACKMOUSEEVENT), TME_LEAVE, parent->m_hWnd, 0};
VERIFY(TrackMouseEvent(&tme));
result->SetWindowPos(NULL, target.x, target.y,
0, 0,
SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE);
result->ShowWindow(visible ? SW_SHOWNA : SW_HIDE);
} /* created window */
} /* must create */
return result;
} // CInfoDisplay::ShowTip
|
import React from 'react';
import { CodeEditor, Language } from '@patternfly/react-code-editor';
import { Checkbox } from '@patternfly/react-core';
export const CodeEditorBasic: React.FunctionComponent = () => {
const [isDarkTheme, setIsDarkTheme] = React.useState(false);
const [isLineNumbersVisible, setIsLineNumbersVisible] = React.useState(true);
const [isReadOnly, setIsReadOnly] = React.useState(false);
const [isMinimapVisible, setIsMinimapVisible] = React.useState(false);
const toggleDarkTheme = checked => {
setIsDarkTheme(checked);
};
const toggleLineNumbers = checked => {
setIsLineNumbersVisible(checked);
};
const toggleReadOnly = checked => {
setIsReadOnly(checked);
};
const toggleMinimap = checked => {
setIsMinimapVisible(checked);
};
const onEditorDidMount = (editor, monaco) => {
// eslint-disable-next-line no-console
console.log(editor.getValue());
editor.layout();
editor.focus();
monaco.editor.getModels()[0].updateOptions({ tabSize: 5 });
};
const onChange = value => {
// eslint-disable-next-line no-console
console.log(value);
};
return (
<>
<Checkbox
label="Dark theme"
isChecked={isDarkTheme}
onChange={toggleDarkTheme}
aria-label="dark theme checkbox"
id="toggle-theme"
name="toggle-theme"
/>
<Checkbox
label="Line numbers"
isChecked={isLineNumbersVisible}
onChange={toggleLineNumbers}
aria-label="line numbers checkbox"
id="toggle-line-numbers"
name="toggle-line-numbers"
/>
<Checkbox
label="Read only"
isChecked={isReadOnly}
onChange={toggleReadOnly}
aria-label="read only checkbox"
id="toggle-read-only"
name="toggle-read-only"
/>
<Checkbox
label="Minimap"
isChecked={isMinimapVisible}
onChange={toggleMinimap}
aria-label="display minimap checkbox"
id="toggle-minimap"
name="toggle-minimap"
/>
<CodeEditor
isDarkTheme={isDarkTheme}
isLineNumbersVisible={isLineNumbersVisible}
isReadOnly={isReadOnly}
isMinimapVisible={isMinimapVisible}
isLanguageLabelVisible
code="Some example content"
onChange={onChange}
language={Language.javascript}
onEditorDidMount={onEditorDidMount}
height="400px"
/>
</>
);
};
|
import { Class } from '../wrserver';
export class Decorator {
protected decorators: any[] = [];
constructor(protected parameters: any[]){ }
protected apply(...args: any[]): any{ return this.decorators.map(d => typeof d == 'function' ? d.apply(this, args) : d); }
protected mixin(derived: Class, base: Class[]): any{
let exclude = ['length', 'prototype', 'name'];
base.forEach(b => {
Object.getOwnPropertyNames(b.prototype).forEach(name => {
if(name == 'constructor' && derived.constructor){ return; }
derived.prototype[name] = b.prototype[name];
});
Object.getOwnPropertyNames(b).filter(x => !exclude.includes(x)).forEach(name => { derived[name] = b[name]; })
});
return derived;
}
public decore(...args: any[]): Decorator{ return null; }
public function(name: string): any{
let self = this;
return function(...args: any[]){ if(typeof (self as any)[name] == 'function'){ return (self as any)[name].apply(self, args.concat(self.apply(...args))); } return null; }
}
public static target(name: string, ...args: any[]): any{ return new this(args).function(name as any); }
public static decore(...args: any[]): any{ return this.target('decore', ...args); }
} |
<gh_stars>0
const path = require('path');
const Generator = require('yeoman-generator');
const utils = require('./utils');
const currentDir = path.basename(process.cwd());
module.exports = class extends Generator {
constructor(args, opts) {
super(args, opts);
this.argument('addonName', {
type: String,
desc: 'Addon name, e.g.: @plone-collective/volto-custom-block',
default: currentDir,
});
this.option('interactive', {
type: Boolean,
desc: 'Enable/disable interactive prompt',
default: true,
});
this.option('template', {
type: String,
desc: 'Use github repo template, e.g.: eea/volto-addon-template',
default: '',
});
this.args = args;
this.opts = opts;
}
async prompting() {
const updateNotifier = require('update-notifier');
const pkg = require('../../package.json');
const notifier = updateNotifier({
pkg,
shouldNotifyInNpmScript: true,
updateCheckInterval: 0,
});
notifier.notify({
defer: false,
message: `Update available: {currentVersion} -> {latestVersion}
It's important to have the generators updated!
Run "npm install -g @plone/generator-volto" to update.`,
});
this.globals = {
addonName: '',
name: '',
scope: '',
template: '',
};
let props;
// Add-on name
if (this.args[0]) {
this.globals.addonName = this.args[0];
} else {
if (this.opts['interactive']) {
props = await this.prompt([
{
type: 'input',
name: 'addonName',
message: 'Addon name, e.g.: @plone-collective/volto-custom-block',
default: path.basename(process.cwd()),
},
]);
this.globals.addonName = props.addonName;
} else {
this.globals.addonName = path.basename(process.cwd());
}
}
if (this.globals.addonName.includes('/')) {
[this.globals.scope, this.globals.name] = this.globals.addonName.split(
'/',
);
} else {
this.globals.name = this.globals.addonName;
}
// Template
if (this.opts.template) {
this.globals.template = this.opts.template;
}
}
writing() {
const base =
currentDir === this.globals.name
? '.'
: './src/addons/' + this.globals.name;
if (this.globals.template) {
utils.githubTpl(
this.globals.template,
this.destinationPath(base),
this.globals,
);
} else {
this.fs.copyTpl(
this.templatePath('package.json.tpl'),
this.destinationPath(base, 'package.json'),
this.globals,
);
this.fs.copy(this.templatePath(), this.destinationPath(base), {
globOptions: {
ignore: ['**/*.tpl', '**/*~'],
dot: true,
},
});
this.fs.delete(this.destinationPath(base, 'package.json.tpl'));
}
}
install() {}
end() {
this.log("Done. Now run 'yarn' to install dependencies");
}
};
|
#!/usr/bin/env bash
#SBATCH --cluster=gpu
#SBATCH --gres=gpu:1
#SBATCH --partition=gtx1080
#SBATCH --account=hdaqing
#SBATCH --job-name=one2seq-rnn-length_reverse-kp20k
#SBATCH --output=slurm_output/one2seq-rnn-length_reverse-kp20k.out
#SBATCH --nodes=1
#SBATCH --ntasks-per-node=1
#SBATCH --cpus-per-task=1
#SBATCH --mem=64GB
#SBATCH --time=6-00:00:00 # 6 days walltime in dd-hh:mm format
#SBATCH --qos=long
# Load modules
#module restore
#module load cuda/10.0.130
#module load gcc/6.3.0
#module load python/anaconda3.6-5.2.0
#source activate py36
#module unload python/anaconda3.6-5.2.0
# Run the job
export CONFIG_PATH="config/train/pt/3rd/config-kpgen-one2seq-length_reverse-rnn-kp20k.yml"
cmd="python train.py -config $CONFIG_PATH"
echo $CONFIG_PATH
echo $cmd
$cmd |
package pulse.search.statistics;
import static pulse.properties.NumericProperties.derive;
import static pulse.properties.NumericPropertyKeyword.OPTIMISER_STATISTIC;
import pulse.tasks.SearchTask;
/**
* The standard optimality criterion of the L2 norm condition, or simply
* ordinary least squares.
*
*/
public class SumOfSquares extends OptimiserStatistic {
public SumOfSquares() {
super();
}
public SumOfSquares(SumOfSquares sos) {
super(sos);
}
/**
* Calculates the sum of squared deviations using {@code curve} as
* reference.
* <p>
* This calculates
* <math><munderover><mo>∑</mo><mrow><mi>i</mi><mo>=</mo><msub><mi>i</mi><mn>1</mn></msub></mrow><msub><mi>i</mi><mn>2</mn></msub></munderover><mo>(</mo><mover><mi>T</mi><mo>⏞</mo></mover><mo>(</mo><msub><mi>t</mi><mi>i</mi></msub><mo>)</mo><mo>-</mo><mi>T</mi><mo>(</mo><msub><mi>t</mi><mi>i</mi></msub><msup><mo>)</mo><mrow><mi>r</mi><mi>e</mi><mi>f</mi></mrow></msup><msup><mo>)</mo><mn>2</mn></msup></math>,
* where
* <math><msubsup><mi>T</mi><mi>i</mi><mrow><mi>r</mi><mi>e</mi><mi>f</mi></mrow></msubsup></math>
* is the temperature value corresponding to the {@code time} at index
* {@code i} for the reference {@code curve}. Note that the time
* <math><msub><mi>t</mi><mi>i</mi></msub></math> corresponds to the
* <b>reference's</b> time list, which generally does not match to that of
* this heating curve. The
* <math><mover><mi>T</mi><mo>⏞</mo></mover><mo>(</mo><msub><mi>t</mi><mi>i</mi></msub><mo>)</mo></math>
* is the interpolated value.
*
* @param t The task containing the reference and calculated curves
* @see calculateResiduals()
*/
@Override
public void evaluate(SearchTask t) {
calculateResiduals(t);
final double statistic = getResiduals().stream().map(r -> r[1] * r[1])
.reduce(Double::sum).get() / getResiduals().size();
setStatistic(derive(OPTIMISER_STATISTIC, statistic));
}
@Override
public String getDescriptor() {
return "Ordinary Least Squares";
}
@Override
public double variance() {
return (double) getStatistic().getValue();
}
@Override
public OptimiserStatistic copy() {
return new SumOfSquares(this);
}
}
|
<filename>src/app/hm-admin/services/schema/schema.service.mock.ts
import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';
import { EntryPoint } from '../models/EntryPoint';
import { Model } from '../models/Model';
@Injectable()
export class MockSchemaService {
schema: BehaviorSubject<any>;
entrypoints: BehaviorSubject<Array<EntryPoint>>;
availableEntrypoints: Array<EntryPoint> = [];
constructor() {
let definitions = {'title': 'title'};
let person = new Model({title: 'Person'}, definitions);
let blogPosting = new Model({title: 'BlogPosting'}, definitions);
this.schema = new BehaviorSubject({
models: [person, blogPosting]
});
this.entrypoints = new BehaviorSubject([]);
}
}
|
// server.js
const express = require('express');
const app = express();
const port = 3000;
const items = [
{ id: 1, name: 'Apples', price: 0.50 },
{ id: 2, name: 'Bananas', price: 0.80 },
{ id: 3, name: 'Strawberries', price: 1.50 },
];
app.get('/items', (req, res) => {
// Return a list of all items
res.json(items);
});
app.get('/items/:id', (req, res) => {
// Get the item details for the specified id
const item = items.find(item => item.id === parseInt(req.params.id));
res.json(item);
});
app.listen(port, () => {
console.log(`Listening on port ${port}`);
});
// App.js
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const ListView = () => {
const [items, setItems] = useState([]);
useEffect(() => {
axios.get('/items')
.then(res => setItems(res.data))
.catch(err => console.log(err));
}, []);
return (
<div>
<h2>Items</h2>
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
</div>
);
};
const ItemView = ({ match }) => {
const [item, setItem] = useState(null);
useEffect(() => {
axios.get(`/items/${match.params.id}`)
.then(res => setItem(res.data))
.catch(err => console.log(err));
}, [match.params.id]);
if (!item) return <p>Loading...</p>;
return (
<div>
<h2>{item.name}</h2>
<p>Price: {item.price}</p>
</div>
);
};
// index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<React.StrictMode>
<Router>
<Switch>
<Route exact path="/" component={ListView} />
<Route exact path="/items/:id" component={ItemView} />
</Switch>
</Router>
</React.StrictMode>,
document.getElementById('root')
); |
<gh_stars>0
const { TransactionImpl } = require('../dist/index')
const SYMBOL_START = Symbol('start')
const SYMBOL_END = Symbol('end')
const testModelSync = new TransactionImpl({
initial: [ctx => (ctx.ret = SYMBOL_START)],
close: [ctx => (ctx.ret = SYMBOL_END)]
})
const testModelAsync = new TransactionImpl({
initial: [async ctx => (ctx.ret = SYMBOL_START)],
close: [async ctx => (ctx.ret = SYMBOL_END)]
})
const delayConsole = async a => {
return await new Promise(resolve => {
setTimeout(() => {
console.log(a)
resolve(a)
}, 1000)
})
}
describe('Transaction Test', () => {
test('PerformSync', () => {
const ret = testModelSync.performSync(console.log, null, 'done')
expect(ret).toBe(SYMBOL_END)
})
test('PerformAsync', async () => {
const ret = await testModelAsync.performAsync(delayConsole, null, 'done')
expect(ret).toBe(SYMBOL_END)
})
})
|
import { Buyer as IBuyer, BuyerPOJO } from "../../public";
import { ContactInfo, ContactInfoBase, hideAndFreeze, Identifiers, Joi, _internal } from "../common";
export class Buyer extends ContactInfoBase implements IBuyer {
public static readonly [_internal] = {
label: "buyer",
schema: ContactInfo[_internal].schema.keys({
id: Joi.string().trim().singleLine().min(1).max(100).required(),
identifiers: Identifiers[_internal].schema,
}),
};
public readonly id: string;
public readonly identifiers: Identifiers;
public constructor(pojo: BuyerPOJO) {
super(pojo);
this.id = pojo.id;
this.identifiers = new Identifiers(pojo.identifiers);
// Make this object immutable
hideAndFreeze(this);
}
}
|
<filename>frontend/components/plugins.ts
import * as ko from 'knockout';
import * as CodeMirror from 'codemirror';
import * as hljs from 'highlight.js';
import * as select2 from 'select2';
//import 'select2';
import 'knockout-switch-case';
import * as MarkdownIt from 'markdown-it';
import JSONEditor, {JSONEditorMode} from 'jsoneditor';
// The CSS for jsoneditor is loaded via assets.py
//import 'jsoneditor/dist/jsoneditor.css';
// Knockout codemirror binding handler
ko.bindingHandlers.codemirror = {
init: function (element, valueAccessor) {
let options = ko.unwrap(valueAccessor());
element.editor = CodeMirror(element, ko.toJS(options));
element.editor.on('change', function (cm: any) {
if (!options.readOnly) {
options.value(cm.getValue());
}
});
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
let wrapper = element.editor.getWrapperElement();
wrapper.parentNode.removeChild(wrapper);
});
},
update: function (element, valueAccessor) {
let value = ko.toJS(valueAccessor()).value;
if (element.editor) {
let cur = element.editor.getCursor();
element.editor.setValue(value);
element.editor.setCursor(cur);
element.editor.refresh();
}
}
};
// Knockout jsoneditor binding handler
ko.bindingHandlers.jsoneditor = {
init: function (element, valueAccessor) {
let initialValue = ko.unwrap(valueAccessor());
let options = {
onChangeText: function (newValue: any) {
element.flag = true;
initialValue.value(newValue);
},
modes: ['tree', 'code', 'text'] as JSONEditorMode[],
mode: 'code' as JSONEditorMode
};
element.editor = new JSONEditor(element, options, JSON.parse(initialValue.value() || "{}"));
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
element.editor.destroy();
});
},
update: function (element, valueAccessor) {
let value = ko.toJS(valueAccessor()).value;
if (element.flag) {
element.flag = false;
} else {
element.editor.set(JSON.parse(value || "{}"));
}
}
};
// Knockout jsoneditor binding handler
ko.bindingHandlers.markdowneditor = {
init: function (element, valueAccessor) {
let initialValue = ko.unwrap(valueAccessor());
// @ts-ignore
element.editor = new EasyMDE({
element: element,
autoDownloadFontAwesome: false,
forceSync: true,
minHeight: "500px",
// TODO: imageUploadFunction
renderingConfig: {
codeSyntaxHighlighting: true,
},
indentWithTabs: false,
tabSize: 4,
});
element.editor.codemirror.on("change", (newValue: any) => {
element.flag = true;
initialValue.value(element.editor.value());
})
element.editor.value(initialValue.value());
element.flag = false;
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
//element.editor.cleanup();
element.editor = null;
});
},
update: function (element, valueAccessor) {
let value = ko.toJS(valueAccessor()).value;
if (element.flag) {
element.flag = false;
} else {
element.editor.value(value);
}
}
};
// Highlighted Code Area
hljs.configure({
languages: ["python"]
})
ko.bindingHandlers.highlightedCode = {
update: function (element, valueAccessor) {
let code = ko.unwrap(valueAccessor());
element.innerHTML = code;
hljs.highlightBlock(element);
if (code.trim()) {
// @ts-ignore
hljs.lineNumbersBlock(element);
}
}
};
export let md = new MarkdownIt({
html: true,
highlight: function (str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
// @ts-ignore
return hljs.highlight(str, { language: lang }).value;
} catch (__) {}
}
return ''; // use external default escaping
}
});
ko.bindingHandlers.markdowned = {
'init': function() {
return { 'controlsDescendantBindings': true };
},
update: function (element, valueAccessor, allBindings, vieModel, bindingContext) {
let code = ko.unwrap(valueAccessor());
element.innerHTML = md.render(code);
let codeBlocks = element.querySelectorAll("pre code");
codeBlocks.forEach((block: HTMLElement) => hljs.highlightBlock(block));
ko.applyBindingsToDescendants(bindingContext, element);
//hljs.highlightBlock(element.querySelector("pre code"));
/*if (code.trim()) {
hljs.lineNumbersBlock(element.querySelector("pre code"));
}*/
}
};
/**
* https://github.com/knockout/knockout/issues/416#issuecomment-4877853
* Adds a new function to the ObservableArray class to efficiently push multiple values
* @param valuesToPush
*/
export function pushObservableArray<T>(array: KnockoutObservableArray<T>, values: T[]): KnockoutObservableArray<T> {
let underlyingArray = array();
array.valueWillMutate();
ko.utils.arrayPushAll(underlyingArray, values);
array.valueHasMutated();
return array;
}
// https://stackoverflow.com/a/60766129
export class TwoWayReadonlyMap {
map: Map<string, string>;
lefts: string[];
rights: string[];
constructor(map: Record<string, string>) {
this.map = new Map<string, string>();
this.lefts = [];
this.rights = [];
for (let member in map) {
this.lefts.push(member);
this.rights.push(map[member]);
this.map.set(member, map[member]);
this.map.set(map[member], member);
}
}
get(key: string) {
return this.map.get(key);
}
}
export function capitalize(str: string): string {
if (typeof str !== 'string') {
return '';
}
return str.charAt(0).toUpperCase() + str.slice(1);
}
export function last<T>(array: T[]): T {
return array[array.length - 1];
}
/*
ko.bindingHandlers.select2 = {
after: ["options", "value"],
init: function (el, valueAccessor, allBindingsAccessor, viewModel) {
$(el).select2(ko.unwrap(valueAccessor()));
ko.utils.domNodeDisposal.addDisposeCallback(el, function () {
$(el).select2('destroy');
});
},
update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
var select2 = $(el).data("select2");
if ("value" in allBindings) {
var newValue = "" + ko.unwrap(allBindings.value);
if ((allBindings.select2.multiple || el.multiple) && newValue.constructor !== Array) {
// @ts-ignore
select2.val([newValue.split(",")]);
}
else {
// @ts-ignore
select2.val([newValue]);
}
}
}
};*/
ko.bindingHandlers.multiselect = {
init: function (element, valueAccessor, allBindingAccessors) {
let options = valueAccessor();
// Pay attention to model updates
ko.bindingHandlers['options'].update(element, () => options.options, allBindingAccessors);
// TypeScript thinks that this bindingHandler has a smaller number of args for some reason
// @ts-ignore
ko.bindingHandlers['selectedOptions'].init(element, () => options.selectedOptions, allBindingAccessors);
// @ts-ignore
ko.bindingHandlers['selectedOptions'].update(element, () => options.selectedOptions, allBindingAccessors);
// @ts-ignore
$(element).multiSelect(options.config);
//make view model know about select/deselect changes
// @ts-ignore
$(element).multiSelect({
afterSelect: function (values: any) {
for (let i = 0; i < values.length; i += 1) {
options.selectedOptions.push(values[i]);
}
}, afterDeselect: function (values: any) {
for (let i = 0; i < values.length; i += 1) {
options.selectedOptions.remove(values[i]);
}
}
});
},
update: function (element, valueAccessor, allBindingAccessors) {
let options = valueAccessor();
console.log(options.options(), options.selectedOptions());
//update html if items set through code
// @ts-ignore
ko.bindingHandlers.selectedOptions.update(element, () => options.selectedOptions, allBindingAccessors);
options.options().forEach((option: any) => {
// @ts-ignore
$(element).multiSelect("addOption", {value: option.id, text: option[options.optionsText]()})
});
// @ts-ignore
$(element).multiSelect("refresh");
}
};
/** assumes array elements are primitive types
* check whether 2 arrays are equal sets.
* @param {} a1 is an array
* @param {} a2 is an array
*/
export function areArraysEqualSets(a1: number[], a2: number[]) {
const superSet: Record<number, number> = {};
for (const i of a1) {
superSet[i] = 1;
}
for (const i of a2) {
if (!superSet[i]) {
return false;
}
superSet[i] = 2;
}
for (let i in superSet) {
if (superSet[i] === 1) {
return false;
}
}
return true;
}
/** Simple binding for handling optgroups **/
ko.bindingHandlers.option = {
update: function(element, valueAccessor) {
let value = ko.utils.unwrapObservable(valueAccessor());
ko.selectExtensions.writeValue(element, value);
}
};
|
# Autoenv
AUTOENV_ENABLE_LEAVE="yes"
#source ~/.autoenv/activate.sh
|
import React from 'react'
import "./Cabecalho.scss"
export default function index(props) {
return (
<header>
<nav></nav>
</header>
)
}
|
<filename>packages/amplication-client/src/VersionControl/PendingChange.tsx
import React from "react";
import { Tooltip } from "@amplication/design-system";
import classNames from "classnames";
import { Link } from "react-router-dom";
import * as models from "../models";
import "./PendingChange.scss";
const CLASS_NAME = "pending-change";
const TOOLTIP_DIRECTION = "ne";
type Props = {
change: models.PendingChange;
applicationId: string;
linkToResource?: boolean;
};
const ACTION_TO_LABEL: {
[key in models.EnumPendingChangeAction]: string;
} = {
[models.EnumPendingChangeAction.Create]: "C",
[models.EnumPendingChangeAction.Delete]: "D",
[models.EnumPendingChangeAction.Update]: "U",
};
const PendingChange = ({
change,
applicationId,
linkToResource = false,
}: Props) => {
/**@todo: update the url for other types of blocks */
const url =
change.resourceType === models.EnumPendingChangeResourceType.Entity
? `/${applicationId}/entities/${change.resourceId}`
: `/${applicationId}/update`;
const isDeletedEntity =
change.action === models.EnumPendingChangeAction.Delete;
const getEntityHeading = () => {
if (isDeletedEntity) {
return (
<Tooltip
wrap
direction={TOOLTIP_DIRECTION}
aria-label="The entity has been deleted"
className={`${CLASS_NAME}__tooltip_deleted`}
>
<div className={classNames(`${CLASS_NAME}__deleted`)}>
{change.resource.displayName}
</div>
</Tooltip>
);
}
if (linkToResource) {
return <Link to={url}>{change.resource.displayName}</Link>;
}
return change.resource.displayName;
};
return (
<div className={CLASS_NAME}>
<div
className={classNames(
`${CLASS_NAME}__action`,
change.action.toLowerCase()
)}
>
{ACTION_TO_LABEL[change.action]}
</div>
{getEntityHeading()}
<div className={`${CLASS_NAME}__spacer`} />
</div>
);
};
export default PendingChange;
|
#!/bin/bash -xe
# Copyright (C) 2014 Hewlett-Packard Development Company, L.P.
#
# 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.
if [ -f /etc/dib-builddate.txt ]; then
echo "Image build date"
echo "================"
cat /etc/dib-builddate.txt
fi
source /etc/nodepool/provider
NODEPOOL_MIRROR_HOST=${NODEPOOL_MIRROR_HOST:-mirror.$NODEPOOL_REGION.$NODEPOOL_CLOUD.openstack.org}
NODEPOOL_MIRROR_HOST=$(echo $NODEPOOL_MIRROR_HOST|tr '[:upper:]' '[:lower:]')
# Write the default value for NODEPOOL_MIRROR_HOST into the mirror_info
# script first. This allows us to set a default while allowing consumers
# to override values if necessary.
echo "export NODEPOOL_MIRROR_HOST=\${NODEPOOL_MIRROR_HOST:-$NODEPOOL_MIRROR_HOST}" > /tmp/mirror_info.sh
# Copy AFS Slug generation details into mirror_info.sh so that consumers
# don't have to know about generating the wheel mirror's
# distro-release-processor tuple.
cat /usr/local/jenkins/slave_scripts/afs-slug.sh >> /tmp/mirror_info.sh
# We write this as a heredoc so that the same information used by this script
# is useable by others without double accounting. Note that the quoted EOF
# means we don't do variable expansion.
cat << "EOF" >> /tmp/mirror_info.sh
export NODEPOOL_DEBIAN_MIRROR=${NODEPOOL_DEBIAN_MIRROR:-http://$NODEPOOL_MIRROR_HOST/debian}
export NODEPOOL_PYPI_MIRROR=${NODEPOOL_PYPI_MIRROR:-http://$NODEPOOL_MIRROR_HOST/pypi/simple}
export NODEPOOL_WHEEL_MIRROR=${NODEPOOL_WHEEL_MIRROR:-http://$NODEPOOL_MIRROR_HOST/wheel/$AFS_SLUG}
export NODEPOOL_UBUNTU_MIRROR=${NODEPOOL_UBUNTU_MIRROR:-http://$NODEPOOL_MIRROR_HOST/ubuntu}
export NODEPOOL_CENTOS_MIRROR=${NODEPOOL_CENTOS_MIRROR:-http://$NODEPOOL_MIRROR_HOST/centos}
export NODEPOOL_DEBIAN_OPENSTACK_MIRROR=${NODEPOOL_DEBIAN_OPENSTACK_MIRROR:-http://$NODEPOOL_MIRROR_HOST/debian-openstack}
export NODEPOOL_EPEL_MIRROR=${NODEPOOL_EPEL_MIRROR:-http://$NODEPOOL_MIRROR_HOST/epel}
export NODEPOOL_FEDORA_MIRROR=${NODEPOOL_FEDORA_MIRROR:-http://$NODEPOOL_MIRROR_HOST/fedora}
export NODEPOOL_OPENSUSE_MIRROR=${NODEPOOL_OPENSUSE_MIRROR:-http://$NODEPOOL_MIRROR_HOST/opensuse}
export NODEPOOL_CEPH_MIRROR=${NODEPOOL_CEPH_MIRROR:-http://$NODEPOOL_MIRROR_HOST/ceph-deb-hammer}
export NODEPOOL_UCA_MIRROR=${NODEPOOL_UCA_MIRROR:-http://$NODEPOOL_MIRROR_HOST/ubuntu-cloud-archive}
export NODEPOOL_MARIADB_MIRROR=${NODEPOOL_MARIADB_MIRROR:-http://$NODEPOOL_MIRROR_HOST/ubuntu-mariadb}
# Reverse proxy servers
export NODEPOOL_DOCKER_REGISTRY_PROXY=${NODEPOOL_DOCKER_REGISTRY_PROXY:-http://$NODEPOOL_MIRROR_HOST:8081/registry-1.docker}
export NODEPOOL_RDO_PROXY=${NODEPOOL_RDO_PROXY:-http://$NODEPOOL_MIRROR_HOST:8080/rdo}
EOF
sudo mkdir -p /etc/ci
sudo mv /tmp/mirror_info.sh /etc/ci/mirror_info.sh
source /etc/ci/mirror_info.sh
LSBDISTID=$(lsb_release -is)
LSBDISTCODENAME=$(lsb_release -cs)
# Double check that when the node is made ready it is able
# to resolve names against DNS.
# NOTE(pabelanger): Because it is possible for nodepool to SSH into a node but
# DNS has not been fully started, we try up to 300 seconds (10 attempts) to
# resolve DNS once.
for COUNT in {1..10}; do
set +e
host -W 30 git.openstack.org
res=$?
set -e
if [ $res == 0 ]; then
break
elif [ $COUNT == 10 ]; then
exit 1
fi
done
host $NODEPOOL_MIRROR_HOST
PIP_CONF="\
[global]
timeout = 60
index-url = $NODEPOOL_PYPI_MIRROR
trusted-host = $NODEPOOL_MIRROR_HOST
extra-index-url = $NODEPOOL_WHEEL_MIRROR"
PYDISTUTILS_CFG="\
[easy_install]
index_url = $NODEPOOL_PYPI_MIRROR
allow_hosts = *.openstack.org"
UBUNTU_SOURCES_LIST="\
deb $NODEPOOL_UBUNTU_MIRROR $LSBDISTCODENAME main universe
deb $NODEPOOL_UBUNTU_MIRROR $LSBDISTCODENAME-updates main universe
deb $NODEPOOL_UBUNTU_MIRROR $LSBDISTCODENAME-backports main universe
deb $NODEPOOL_UBUNTU_MIRROR $LSBDISTCODENAME-security main universe"
CEPH_SOURCES_LIST="deb $NODEPOOL_CEPH_MIRROR $LSBDISTCODENAME main"
UCA_SOURCES_LIST_LIBERTY="deb $NODEPOOL_UCA_MIRROR trusty-updates/liberty main"
UCA_SOURCES_LIST_MITAKA="deb $NODEPOOL_UCA_MIRROR trusty-updates/mitaka main"
UCA_SOURCES_LIST_NEWTON="deb $NODEPOOL_UCA_MIRROR xenial-updates/newton main"
UCA_SOURCES_LIST_OCATA="deb $NODEPOOL_UCA_MIRROR xenial-updates/ocata main"
UCA_SOURCES_LIST_PIKE="deb $NODEPOOL_UCA_MIRROR xenial-updates/pike main"
MARIADB_SOURCES_LIST_10_0="deb $NODEPOOL_MARIADB_MIRROR/10.0 $LSBDISTCODENAME main"
MARIADB_SOURCES_LIST_10_1="deb $NODEPOOL_MARIADB_MIRROR/10.1 $LSBDISTCODENAME main"
APT_CONF_UNAUTHENTICATED="APT::Get::AllowUnauthenticated \"true\";"
DEBIAN_DEFAULT_SOURCES_LIST="\
deb $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME main
deb-src $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME main"
DEBIAN_UPDATES_SOURCES_LIST="\
deb $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME-updates main
deb-src $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME-updates main"
DEBIAN_BACKPORTS_SOURCES_LIST="\
deb $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME-backports main
deb-src $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME-backports main"
DEBIAN_SECURITY_SOURCES_LIST="\
deb $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME-security main
deb-src $NODEPOOL_DEBIAN_MIRROR $LSBDISTCODENAME-security main"
DEBIAN_OPENSTACK_NEWTON_SOURCES_LIST="\
deb $NODEPOOL_DEBIAN_OPENSTACK_MIRROR $LSBDISTCODENAME-newton main
deb $NODEPOOL_DEBIAN_OPENSTACK_MIRROR $LSBDISTCODENAME-newton-backports main"
YUM_REPOS_FEDORA="\
[fedora]
name=Fedora \$releasever - \$basearch
failovermethod=priority
baseurl=$NODEPOOL_FEDORA_MIRROR/releases/\$releasever/Everything/\$basearch/os/
enabled=1
metadata_expire=7d
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-\$releasever-\$basearch
skip_if_unavailable=False
deltarpm=False
deltarpm_percentage=0"
YUM_REPOS_FEDORA_UPDATES="\
[updates]
name=Fedora \$releasever - \$basearch - Updates
failovermethod=priority
baseurl=$NODEPOOL_FEDORA_MIRROR/updates/\$releasever/\$basearch/
enabled=1
gpgcheck=1
metadata_expire=6h
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-fedora-\$releasever-\$basearch
skip_if_unavailable=False
deltarpm=False
deltarpm_percentage=0"
YUM_REPOS_CENTOS_BASE="\
[base]
name=CentOS-\$releasever - Base
baseurl=$NODEPOOL_CENTOS_MIRROR/\$releasever/os/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
#released updates
[updates]
name=CentOS-\$releasever - Updates
baseurl=$NODEPOOL_CENTOS_MIRROR/\$releasever/updates/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever
#additional packages that may be useful
[extras]
name=CentOS-\$releasever - Extras
baseurl=$NODEPOOL_CENTOS_MIRROR/\$releasever/extras/\$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-\$releasever"
YUM_REPOS_EPEL="\
[epel]
name=Extra Packages for Enterprise Linux \$releasever - \$basearch
baseurl=$NODEPOOL_EPEL_MIRROR/\$releasever/\$basearch
failovermethod=priority
enabled=0
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL-\$releasever"
# Write global pip configuration
echo "$PIP_CONF" >/tmp/pip.conf
sudo mv /tmp/pip.conf /etc/
sudo chown root:root /etc/pip.conf
sudo chmod 0644 /etc/pip.conf
# NOTE(pabelanger): We can remove the jenkins user once we have migrated
# nl01.o.o to production
# Write jenkins user distutils/setuptools configuration used by easy_install
echo "$PYDISTUTILS_CFG" | sudo tee /home/jenkins/.pydistutils.cfg
sudo chown jenkins:jenkins /home/jenkins/.pydistutils.cfg
# Write zuul user distutils/setuptools configuration used by easy_install
echo "$PYDISTUTILS_CFG" | sudo tee /home/zuul/.pydistutils.cfg
sudo chown zuul:zuul /home/zuul/.pydistutils.cfg
if [ "$LSBDISTID" == "Ubuntu" ]; then
echo "$UBUNTU_SOURCES_LIST" >/tmp/sources.list
sudo mv /tmp/sources.list /etc/apt/
sudo chown root:root /etc/apt/sources.list
sudo chmod 0644 /etc/apt/sources.list
# Opt in repos. Jobs that want to take advantage of them can copy or
# symlink them into /etc/apt/sources.list.d/
sudo mkdir -p /etc/apt/sources.list.available.d
# Ceph
echo "$CEPH_SOURCES_LIST" >/tmp/ceph-deb-hammer.list
sudo mv /tmp/ceph-deb-hammer.list /etc/apt/sources.list.available.d/
# Ubuntu Cloud Archive
echo "$UCA_SOURCES_LIST_LIBERTY" >/tmp/ubuntu-cloud-archive-liberty.list
sudo mv /tmp/ubuntu-cloud-archive-liberty.list /etc/apt/sources.list.available.d/
echo "$UCA_SOURCES_LIST_MITAKA" >/tmp/ubuntu-cloud-archive-mitaka.list
sudo mv /tmp/ubuntu-cloud-archive-mitaka.list /etc/apt/sources.list.available.d/
echo "$UCA_SOURCES_LIST_NEWTON" >/tmp/ubuntu-cloud-archive-newton.list
sudo mv /tmp/ubuntu-cloud-archive-newton.list /etc/apt/sources.list.available.d/
echo "$UCA_SOURCES_LIST_OCATA" >/tmp/ubuntu-cloud-archive-ocata.list
sudo mv /tmp/ubuntu-cloud-archive-ocata.list /etc/apt/sources.list.available.d/
echo "$UCA_SOURCES_LIST_PIKE" >/tmp/ubuntu-cloud-archive-pike.list
sudo mv /tmp/ubuntu-cloud-archive-pike.list /etc/apt/sources.list.available.d/
# Ubuntu Mariadb
echo "$MARIADB_SOURCES_LIST_10_0" >/tmp/ubuntu-mariadb-10-0.list
sudo mv /tmp/ubuntu-mariadb-10-0.list /etc/apt/sources.list.available.d/
echo "$MARIADB_SOURCES_LIST_10_1" >/tmp/ubuntu-mariadb-10-1.list
sudo mv /tmp/ubuntu-mariadb-10-1.list /etc/apt/sources.list.available.d/
sudo chown root:root /etc/apt/sources.list.available.d/*
sudo chmod 0644 /etc/apt/sources.list.available.d/*
# Turn off multi-arch
sudo dpkg --remove-architecture i386
# Turn off checking of GPG signatures
echo "$APT_CONF_UNAUTHENTICATED" >/tmp/99unauthenticated
sudo mv /tmp/99unauthenticated /etc/apt/apt.conf.d/
sudo chown root:root /etc/apt/apt.conf.d/99unauthenticated
sudo chmod 0644 /etc/apt/apt.conf.d/99unauthenticated
elif [ "$LSBDISTID" == "Debian" ] ; then
echo "$DEBIAN_DEFAULT_SOURCES_LIST" >/tmp/default.list
sudo mv /tmp/default.list /etc/apt/sources.list.d/
echo "$DEBIAN_UPDATES_SOURCES_LIST" >/tmp/updates.list
sudo mv /tmp/updates.list /etc/apt/sources.list.d/
echo "$DEBIAN_BACKPORTS_SOURCES_LIST" >/tmp/backports.list
sudo mv /tmp/backports.list /etc/apt/sources.list.d/
echo "$DEBIAN_SECURITY_SOURCES_LIST" >/tmp/security.list
sudo mv /tmp/security.list /etc/apt/sources.list.d/
sudo chown root:root /etc/apt/sources.list.d/*.list
sudo chmod 0644 /etc/apt/sources.list.d/*.list
# Opt in repos. Jobs that want to take advantage of them can copy or
# symlink them into /etc/apt/sources.list.d/
sudo mkdir -p /etc/apt/sources.list.available.d
# Debian OpenStack Newton
echo "$DEBIAN_OPENSTACK_NEWTON_SOURCES_LIST" >/tmp/debian-openstack-newton.list
sudo mv /tmp/debian-openstack-newton.list /etc/apt/sources.list.available.d/
sudo chown root:root /etc/apt/sources.list.available.d/*
sudo chmod 0644 /etc/apt/sources.list.available.d/*
# Turn off checking of GPG signatures
echo "$APT_CONF_UNAUTHENTICATED" >/tmp/99unauthenticated
sudo mv /tmp/99unauthenticated /etc/apt/apt.conf.d/
sudo chown root:root /etc/apt/apt.conf.d/99unauthenticated
sudo chmod 0644 /etc/apt/apt.conf.d/99unauthenticated
elif [ "$LSBDISTID" == "CentOS" ]; then
echo "$YUM_REPOS_CENTOS_BASE" >/tmp/CentOS-Base.repo
sudo mv /tmp/CentOS-Base.repo /etc/yum.repos.d/
echo "$YUM_REPOS_EPEL" >/tmp/epel.repo
sudo mv /tmp/epel.repo /etc/yum.repos.d/
sudo chown root:root /etc/yum.repos.d/*
sudo chmod 0644 /etc/yum.repos.d/*
elif [ "$LSBDISTID" == "Fedora" ]; then
echo "$YUM_REPOS_FEDORA" >/tmp/fedora.repo
sudo mv /tmp/fedora.repo /etc/yum.repos.d/
echo "$YUM_REPOS_FEDORA_UPDATES" >/tmp/fedora-updates.repo
sudo mv /tmp/fedora-updates.repo /etc/yum.repos.d/
sudo chown root:root /etc/yum.repos.d/*
sudo chmod 0644 /etc/yum.repos.d/*
elif [ "$LSBDISTID" == "openSUSE project" ]; then
sudo sed -i -e "s,http://download.opensuse.org/,$NODEPOOL_OPENSUSE_MIRROR/," /etc/zypp/repos.d/*.repo
fi
if [ "$LSBDISTID" == "Debian" ] || [ "$LSBDISTID" == "Ubuntu" ]; then
# Make sure our indexes are up to date.
sudo apt-get update
fi
|
/*
* Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. This
* code is released under a tri EPL/GPL/LGPL license. You can use it,
* redistribute it and/or modify it under the terms of the:
*
* Eclipse Public License version 1.0
* GNU General Public License version 2
* GNU Lesser General Public License version 2.1
*/
package org.jruby.truffle.nodes.cast;
import org.jruby.truffle.nodes.RubyNode;
import org.jruby.truffle.nodes.core.KernelNodes;
import org.jruby.truffle.nodes.core.KernelNodesFactory;
import org.jruby.truffle.nodes.dispatch.CallDispatchHeadNode;
import org.jruby.truffle.nodes.dispatch.DispatchHeadNodeFactory;
import org.jruby.truffle.nodes.dispatch.MissingBehavior;
import org.jruby.truffle.runtime.RubyContext;
import org.jruby.truffle.runtime.control.RaiseException;
import org.jruby.truffle.runtime.core.RubyBasicObject;
import com.oracle.truffle.api.CompilerDirectives;
import com.oracle.truffle.api.dsl.Fallback;
import com.oracle.truffle.api.dsl.NodeChild;
import com.oracle.truffle.api.dsl.Specialization;
import com.oracle.truffle.api.frame.VirtualFrame;
import com.oracle.truffle.api.source.SourceSection;
/**
* Casts a value into a Ruby Float (double).
*/
@NodeChild(value = "child", type = RubyNode.class)
public abstract class NumericToFloatNode extends RubyNode {
@Child private KernelNodes.IsANode isANode;
@Child CallDispatchHeadNode toFloatCallNode;
private final String method;
public NumericToFloatNode(RubyContext context, SourceSection sourceSection, String method) {
super(context, sourceSection);
isANode = KernelNodesFactory.IsANodeFactory.create(context, sourceSection, new RubyNode[] { null, null });
this.method = method;
}
public NumericToFloatNode(NumericToFloatNode prev) {
super(prev.getContext(), prev.getSourceSection());
isANode = prev.isANode;
method = prev.method;
}
public abstract double executeFloat(VirtualFrame frame, RubyBasicObject value);
private Object callToFloat(VirtualFrame frame, RubyBasicObject value) {
if (toFloatCallNode == null) {
CompilerDirectives.transferToInterpreterAndInvalidate();
toFloatCallNode = insert(DispatchHeadNodeFactory.createMethodCall(getContext(), MissingBehavior.RETURN_MISSING));
}
return toFloatCallNode.call(frame, value, method, null);
}
@Specialization(guards = "isNumeric")
protected double castNumeric(VirtualFrame frame, RubyBasicObject value) {
final Object result = callToFloat(frame, value);
if (result instanceof Double) {
return (double) result;
} else {
CompilerDirectives.transferToInterpreter();
throw new RaiseException(getContext().getCoreLibrary().typeErrorCantConvertTo(
value, getContext().getCoreLibrary().getFloatClass(), method, result, this));
}
}
@Fallback
protected double fallback(Object value) {
CompilerDirectives.transferToInterpreter();
throw new RaiseException(getContext().getCoreLibrary().typeErrorCantConvertInto(
value, getContext().getCoreLibrary().getFloatClass(), this));
}
protected boolean isNumeric(VirtualFrame frame, Object value) {
return isANode.executeIsA(frame, value, getContext().getCoreLibrary().getNumericClass());
}
}
|
<gh_stars>100-1000
import * as React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { Container } from '@material-ui/core';
export function CenteredColumn(props: any) {
const classes = useStyles();
return (
<div className={classes.centered}>
<Container maxWidth={props.maxWidth || 'lg'} style={props.style}>
{props.children}
</Container>
</div>
);
}
const useStyles = makeStyles((theme) => ({
centered: {
display: 'flex',
alignItems: 'center',
},
}));
|
/*******************************************************************************
* Copyright (c) 2001-2014 <NAME> and Robocode contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://robocode.sourceforge.net/license/epl-v10.html
*******************************************************************************/
package net.sf.robocode.battle.peer;
import net.sf.robocode.peer.BulletStatus;
import net.sf.robocode.security.HiddenAccess;
import robocode.*;
import robocode.control.snapshot.BulletState;
import robocode.control.snapshot.MissileState;
import robocode.naval.Components.CannonComponents.CannonComponent;
import robocode.naval.NavalRules;
import robocode.util.Collision;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
import static net.sf.robocode.io.Logger.logMessage;
import java.util.List;
/**
* @author <NAME> (original)
* @author <NAME> (contributor)
* @author <NAME> (contributor)
* @author <NAME> (contributor)
* @author <NAME> (constributor)
* @author <NAME> (constributor)
*/
public class BulletPeer extends ProjectilePeer{
BulletState state;
private CannonComponent cannon;
private int bulletId;
private double distance=0;
BulletPeer(RobotPeer owner, CannonComponent cannon, BattleRules battleRules, int bulletId) {
super();
this.owner = owner;
this.cannon = cannon;
this.battleRules = battleRules;
this.bulletId = bulletId;
state = BulletState.FIRED;
color = owner.getBulletColor(); // Store current bullet color set on robot
}
/**
* An extra constructor for the ShipPeer.
* This is done because the BulletColor is held within the WeaponComponents, not the ShipPeer
* @param owner The owner of the bullet
* @param battleRules The rules of this battle
* @param bulletId The id of the bullet
* @param color The color of the bullet. This parameter is why this constructor was made.
*/
BulletPeer(ShipPeer owner, CannonComponent cannon, BattleRules battleRules, int bulletId, int color){
this(owner, cannon, battleRules, bulletId);
this.color = color;
}
public void update(List<RobotPeer> robots, List<BulletPeer> bullets, List<MissilePeer> missiles) {
frame++;
if (isActive()) {
if (getState() == BulletState.MOVING) {
updateMovement();
checkWallCollision();
}
if (isActive()) {
if(HiddenAccess.getNaval()){
checkCollisionWithShip(robots);
if (distance > battleRules.getBulletRange(cannon)) {
setProjectileStateMissed();
addProjectileMissedEvent();
}
if (bullets != null) {
checkBulletCollisionWithBullet(bullets);
}
if(isActive() && missiles != null){
checkBulletCollisionWithMissile(missiles);
}
}
else{
checkRobotCollision(robots);
}
}
}
updateBulletState();
owner.addBulletStatus(createStatus());
}
private void updateMovement() {
if(frame == 2) {
originX = x;
originY = y;
}
lastX = x;
lastY = y;
double v = getVelocity();
x += v * sin(heading);
y += v * cos(heading);
distance = x - originX + y - originY;
if(distance < 0){
distance *=-1;
}
boundingBox.setRect(x-(getPower()), y-(getPower()), getPower()*2, getPower()*2);
boundingLine.setLine(lastX, lastY, x, y);
}
/**This checkRobotCollision method is used for the regular robocode version. NOT NAVAL.**/
private void checkRobotCollision(List<RobotPeer> robots) {
for (RobotPeer otherRobot : robots) {
if (!(otherRobot == null || otherRobot == owner || otherRobot.isDead())
&& otherRobot.getBoundingBox().intersectsLine(boundingLine)) {
state = BulletState.HIT_VICTIM;
frame = 0;
victim = otherRobot;
double damage = cannon.getBulletDamage(power);
if (owner.isSentryRobot()) {
if (victim.isSentryRobot()) {
damage = 0;
} else {
int range = battleRules.getSentryBorderSize();
if (x > range && x < (battleRules.getBattlefieldWidth() - range) && y > range
&& y < (battleRules.getBattlefieldHeight() - range)) {
damage = 0;
}
}
}
double score = damage;
if (score > otherRobot.getEnergy()) {
score = otherRobot.getEnergy();
}
otherRobot.updateEnergy(-damage);
boolean teamFire = (owner.getTeamPeer() != null && owner.getTeamPeer() == otherRobot.getTeamPeer());
if (!teamFire && !otherRobot.isSentryRobot()) {
owner.getRobotStatistics().scoreBulletDamage(otherRobot.getName(), score);
}
if (otherRobot.getEnergy() <= 0 && otherRobot.isAlive()) {
otherRobot.kill();
if (!teamFire && !otherRobot.isSentryRobot()) {
double bonus = owner.getRobotStatistics().scoreBulletKill(otherRobot.getName());
if (bonus > 0) {
owner.println(
"SYSTEM: Bonus for killing "
+ (owner.getNameForEvent(otherRobot) + ": " + (int) (bonus + .5)));
}
}
}
if (!victim.isSentryRobot()) {
owner.updateEnergy(cannon.getBulletHitBonus(power));
}
otherRobot.addEvent(
new HitByBulletEvent(
robocode.util.Utils.normalRelativeAngle(heading + Math.PI - otherRobot.getBodyHeading()),
createBullet(true))); // Bugfix #366
owner.addEvent(
new BulletHitEvent(owner.getNameForEvent(otherRobot), otherRobot.getEnergy(), createBullet(false))); // Bugfix #366
double newX, newY;
if (otherRobot.getBoundingBox().contains(lastX, lastY)) {
newX = lastX;
newY = lastY;
setX(newX);
setY(newY);
} else {
newX = x;
newY = y;
}
deltaX = newX - otherRobot.getX();
deltaY = newY - otherRobot.getY();
break;
}
}
}
/**Collision methods**/
void collideBulletWithShip(RobotPeer otherRobot){
setBulletStateBulletHitShip();
updateEnergyAndScoreBulletHitShip(otherRobot);
updateKillWithBullet(otherRobot);
addBulletHitShipEvent(otherRobot);
setNewBulletCoordinatesShipCollision(otherRobot);
}
private void checkBulletCollisionWithBullet(List<BulletPeer> otherBullets) {//check if bullet hit another bullet
for (BulletPeer b : otherBullets) {
if (b != null && b != this && b.isActive() && Collision.doBoxesIntersect(getBoundingBox(),b.getBoundingBox())) {
if(getOwner() != b.getOwner()) {
setBulletStateBulletHitBullet(b);
addBulletHitBulletEvent(b);
}
break;
}
}
}
private void checkBulletCollisionWithMissile(List<MissilePeer> missiles) {//check if bullet hit a missile
for (MissilePeer missile : missiles) {
if (missile != null && missile.isActive() && Collision.doBoxesIntersect(getBoundingBox(), missile.getBoundingBox())) {
setBulletStateBulletHitMissile();
x = lastX;
y = lastY;
missile.detonate();
addBulletHitMissileEvent(missile);
break;
}
}
}
/**State methods**/
void updateBulletState() {
switch (state) {
case FIRED:
// Note that the bullet must be in the FIRED state before it goes to the MOVING state
if (frame > 0) {
state = BulletState.MOVING;
}
break;
case HIT_BULLET:
case HIT_VICTIM:
case HIT_WALL:
case EXPLODED:
// Note that the bullet explosion must be ended before it goes into the INACTIVE state
if (frame >= getExplosionLength()) {
state = BulletState.INACTIVE;
}
break;
default:
}
}
Bullet createBullet(boolean hideOwnerName) {
String ownerName = (owner == null) ? null : (hideOwnerName ? getNameForEvent(owner) : owner.getName());
String victimName = (victim == null) ? null : (hideOwnerName ? victim.getName() : getNameForEvent(victim));
return new Bullet(heading, x, y, power, cannon.getBulletSpeed(power), ownerName, victimName, isActive(), bulletId);
}
private BulletStatus createStatus() {
return new BulletStatus(bulletId, x, y, victim == null ? null : getNameForEvent(victim), isActive());
}
void setState(BulletState newState) {
state = newState;
}
private void setBulletStateBulletHitBullet(BulletPeer b) {
setState(BulletState.HIT_BULLET);
frame = 0;
x = lastX;
y = lastY;
b.setState(BulletState.HIT_BULLET);
b.frame = 0;
b.x = b.lastX;
b.y = b.lastY;
}
private void setBulletStateBulletHitShip() {
setState(BulletState.HIT_VICTIM);
frame = 0;
}
private void setBulletStateBulletHitMissile() {
setState(BulletState.HIT_BULLET);
frame = 0;
}
void setBulletStateMissileHitBullet() {
setState(BulletState.HIT_BULLET);
frame = 0;
x = getLastX();
y = getLastY();
}
/**Event methods**/
private void addBulletHitBulletEvent(BulletPeer otherBullet){
getOwner().addEvent(new BulletHitBulletEvent(createBullet(false), otherBullet.createBullet(true)));
otherBullet.getOwner().addEvent(new BulletHitBulletEvent(otherBullet.createBullet(false), createBullet(true)));
logMessage("Event: " +getOwner().getName()+" his Bullet hit "+otherBullet.getOwner().getName()+ "his Bullet.");
}
private void addBulletHitShipEvent(RobotPeer otherRobot) {
otherRobot.addEvent(
new HitByBulletEvent(
robocode.util.Utils.normalRelativeAngle(heading + Math.PI - otherRobot.getBodyHeading()),
createBullet(true)));
getOwner().addEvent(
new BulletHitEvent(getOwner().getNameForEvent(otherRobot), otherRobot.getEnergy(), createBullet(false)));
}
private void addBulletHitMissileEvent(MissilePeer missile){
getOwner().addEvent(new BulletHitMissileEvent(createBullet(false), missile.createMissile(true)));
logMessage("Event: " +getOwner().getName()+" his Bullet hit "+missile.getOwner().getName()+ "his Missile.");
}
/**Update Energy and Score methods**/
private void updateEnergyAndScoreBulletHitShip(RobotPeer otherRobot) {
double damage = cannon.getBulletDamage(power);
double score = damage;
if (score > otherRobot.getEnergy()) {
score = otherRobot.getEnergy();
}
otherRobot.updateEnergy(-damage);
getOwner().getRobotStatistics().scoreBulletDamage(otherRobot.getName(), score);
getOwner().updateEnergy(cannon.getBulletHitBonus(power));
}
private void updateKillWithBullet(RobotPeer otherRobot){
if (otherRobot.getEnergy() <= 0 && otherRobot.isAlive()) {
otherRobot.kill();
double bonus = getOwner().getRobotStatistics().scoreBulletKill(otherRobot.getName());
if (bonus > 0) {
getOwner().println(
"SYSTEM: Bonus for killing "
+ (getOwner().getNameForEvent(otherRobot) + ": " + (int) (bonus + .5)));
}
}
}
boolean isActive() {
return state.isActive();
}
/**----GETTERS & SETTERS----**/
private void setNewBulletCoordinatesShipCollision(RobotPeer otherRobot) {
double newX, newY;
if (otherRobot.getBoundingBox().contains(lastX, lastY)) {
newX = lastX;
newY = lastY;
setX(newX);
setY(newY);
} else {
newX = x;
newY = y;
}
deltaX = newX - otherRobot.getX();
deltaY = newY - otherRobot.getY();
}
public int getBulletId() {
return bulletId;
}
String getNameForEvent(RobotPeer otherRobot) {
if (battleRules.getHideEnemyNames() && !owner.isTeamMate(otherRobot)) {
return otherRobot.getAnnonymousName();
}
return otherRobot.getName();
}
public BulletState getState() {
return state;
}
public double getPaintX() {
return (state == BulletState.HIT_VICTIM && victim != null) ? victim.getX() + deltaX : x;
}
public double getPaintY() {
return (state == BulletState.HIT_VICTIM && victim != null) ? victim.getY() + deltaY : y;
}
public double getVelocity() {
return cannon.getBulletSpeed(power);
}
@Override
public String toString() {
return getOwner().getName() + " V" + getVelocity() + " *" + (int) power + " X" + (int) x + " Y" + (int) y + " H"
+ heading + " " + state.toString();
}
@Override
public int getShipFlag() {
return -1;
}
}
|
#!/bin/bash
# Copyright 2017, 2019, Oracle Corporation and/or affiliates. All rights reserved.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl
git clone https://github.com/kubernetes-sigs/metrics-server.git /tmp/metricserver
cd /tmp/metricserver
#kubectl create -f manifests/
#kubectl apply -f https://github.com/kubernetes-sigs/metrics-server/releases/latest/download/components.yaml
sleep 5
rm -rf /tmp/metricserver/
|
#!/usr/bin/env bash
exe_dir="/data/local/tmp/bin"
work_dir=$(pwd)
os=android
abi=armv8
lang=gcc
function print_usage {
echo "----------------------------------------"
echo -e " ./push2device.sh --arm_os=<os> --arm_abi=<abi> --arm_lang=<lang>"
echo -e "--arm_os:\t android, only support android now"
echo -e "--arm_abi:\t armv8|armv7"
echo -e "--arm_lang:\t gcc|clang"
echo -e "make sure directory: PaddleLite/build.lite.${arm_os}.${arm_abi}.${arm_lang} exsits!"
echo "----------------------------------------"
}
function main {
for i in "$@"; do
case $i in
--arm_os=*)
os="${i#*=}"
shift
;;
--arm_abi=*)
abi="${i#*=}"
shift
;;
--arm_lang=*)
lang="${i#*=}"
shift
;;
*)
print_usage
exit 1
;;
esac
done
build_dir=$work_dir/../../../build.lite.${os}.${abi}.${lang}
lib_path=$build_dir/lite/tests/benchmark
lib_files=$lib_path/get*latency
adb shell mkdir ${exe_dir}
for file in ${lib_files}
do
adb push ${file} ${exe_dir}
done
}
main $@
python get_latency_lookup_table.py --arm_v7_v8 ${abi}
|
#!/usr/bin/env bash
docker build -t tabhid/explore . |
#!/bin/bash
. ./script/common.sh
PGCONFIG=${CONFIG_DIR}/postgresql-logstore.conf
RELOAD_DELAY=3
STORE_DELAY=1
trap stop_all_database EXIT
echo "/*---- Initialize repository DB ----*/"
setup_repository ${REPOSITORY_DATA} ${REPOSITORY_USER} ${REPOSITORY_PORT} ${REPOSITORY_CONFIG}
echo "/*---- Initialize monitored instance ----*/"
setup_dbcluster ${PGDATA} ${PGUSER} ${PGPORT} ${PGCONFIG} "" "" ""
sleep 3
createuser -SDRl user01
createuser -SDRl user02
[ $(server_version) -lt 90000 ] &&
createlang plpgsql
psql << EOF
CREATE TABLE tbl01 (id bigint);
CREATE FUNCTION statsinfo.elog(text, text) RETURNS void AS
\$\$
DECLARE
BEGIN
IF \$1 = 'DEBUG' THEN
RAISE DEBUG '%', \$2;
ELSIF \$1 = 'INFO' THEN
RAISE INFO '%', \$2;
ELSIF \$1 = 'NOTICE' THEN
RAISE NOTICE '%', \$2;
ELSIF \$1 = 'WARNING' THEN
RAISE WARNING '%', \$2;
ELSIF \$1 = 'ERROR' THEN
RAISE EXCEPTION '%', \$2;
ELSIF \$1 = 'LOG' THEN
RAISE LOG '%', \$2;
ELSIF \$1 = 'ALL' THEN
RAISE DEBUG '%', \$2;
RAISE INFO '%', \$2;
RAISE NOTICE '%', \$2;
RAISE WARNING '%', \$2;
RAISE LOG '%', \$2;
RAISE EXCEPTION '%', \$2;
ELSE
RAISE EXCEPTION 'message level % not support', \$1;
END IF;
END;
\$\$ LANGUAGE plpgsql;
EOF
echo "/*---- Server Log Accumulation ----*/"
echo "/**--- Log Storing (repolog_min_messages = disable) ---**/"
update_pgconfig ${PGDATA} "<guc_prefix>.repolog_min_messages" "disable"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT statsinfo.elog('ALL', 'log storing test (disable)')" > /dev/null
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, message FROM statsrepo.log WHERE message = 'log storing test (disable)'"
echo "/**--- Log Storing (repolog_min_messages = error) ---**/"
update_pgconfig ${PGDATA} "<guc_prefix>.repolog_min_messages" "error"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT statsinfo.elog('ALL', 'log storing test (error)')" > /dev/null
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, message FROM statsrepo.log WHERE message = 'log storing test (error)'"
echo "/**--- Sets the nologging filter (repolog_nologging_users = 'user01') ---**/"
set_pgconfig ${PGCONFIG} ${PGDATA}
update_pgconfig ${PGDATA} "<guc_prefix>.repolog_nologging_users" "'user01'"
update_pgconfig ${PGDATA} "log_statement" "'all'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -U user01 -c "SELECT 1" > /dev/null
psql -U user02 -c "SELECT 1" > /dev/null
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, username, message FROM statsrepo.log WHERE username IN ('user01','user02')"
echo "/**--- Adjust log level (adjust_log_level = off) ---**/"
set_pgconfig ${PGCONFIG} ${PGDATA}
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_level" "off"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_info" "'42P01'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT * FROM xxx" > /dev/null 2>&1
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '42P01' AND elevel = 'ERROR'"
echo "/**--- Adjust log level (adjust_log_info = '42P01') ---**/"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_level" "on"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_info" "'42P01'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT * FROM xxx" > /dev/null 2>&1
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '42P01' AND elevel = 'INFO'"
echo "/**--- Adjust log level (adjust_log_notice = '42P01') ---**/"
delete_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_info"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_notice" "'42P01'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT * FROM xxx" > /dev/null 2>&1
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '42P01' AND elevel = 'NOTICE'"
echo "/**--- Adjust log level (adjust_log_warning = '42P01') ---**/"
delete_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_notice"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_warning" "'42P01'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT * FROM xxx" > /dev/null 2>&1
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '42P01' AND elevel = 'WARNING'"
echo "/**--- Adjust log level (adjust_log_error = '00000') ---**/"
delete_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_warning"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_error" "'00000'"
update_pgconfig ${PGDATA} "log_statement" "'all'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT 1" > /dev/null
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '00000' AND elevel = 'ERROR'"
echo "/**--- Adjust log level (adjust_log_log = '42P01') ---**/"
delete_pgconfig ${PGDATA} "log_statement"
delete_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_error"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_log" "'42P01'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT * FROM xxx" > /dev/null 2>&1
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '42P01' AND elevel = 'LOG'"
echo "/**--- Adjust log level (adjust_log_fatal = '42P01') ---**/"
delete_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_log"
update_pgconfig ${PGDATA} "<guc_prefix>.adjust_log_fatal" "'42P01'"
pg_ctl reload && sleep ${RELOAD_DELAY}
psql -c "SELECT * FROM xxx" > /dev/null 2>&1
sleep ${STORE_DELAY}
send_query -c "SELECT elevel, sqlstate, message FROM statsrepo.log WHERE sqlstate = '42P01' AND elevel = 'FATAL'"
|
<filename>src/pages/login.tsx<gh_stars>1-10
import { GetServerSideProps, NextPage } from 'next';
import Link from 'next/link';
import Head from 'next/head';
import { useRouter } from 'next/router';
import { useMemo } from 'react';
import Layout from '../components/ResidentLayout';
type LoginProps = { appUrl: string; feedbackUrl: string };
const Home: NextPage<LoginProps> = ({ appUrl, feedbackUrl }) => {
const router = useRouter();
const loginUrl = useMemo(() => {
let { redirect } = router.query as { redirect?: string };
if (!redirect || redirect == '/') redirect = '/teams';
return `https://auth.hackney.gov.uk/auth?redirect_uri=${appUrl}${redirect}`;
}, [router, appUrl]);
return (
<Layout feedbackUrl={feedbackUrl}>
<Head>
<title>Login | Document Evidence Service | Hackney Council</title>
</Head>
<h1 className="lbh-heading-h1">Staff sign in</h1>
<Link href={loginUrl}>
<a className="govuk-button lbh-button lbh-button--start govuk-button--start">
Sign in with Google{' '}
<svg
className="govuk-button__start-icon"
xmlns="http://www.w3.org/2000/svg"
width="17.5"
height="19"
viewBox="0 0 33 40"
role="presentation"
focusable="false"
>
<path fill="currentColor" d="M0 0h13l20 20-20 20H0l20-20z" />
</svg>
</a>
</Link>
<p className="lbh-body">
If you think you should be able to access this but can’t, contact
Hackney IT.
</p>
<p className="lbh-body">
If you’re trying to upload a document, follow the link you were sent.
</p>
</Layout>
);
};
export const getServerSideProps: GetServerSideProps<LoginProps> = async () => {
const appUrl = process.env.APP_URL;
if (!appUrl) throw new Error('Missing APP_URL');
const feedbackUrl = process.env.FEEDBACK_FORM_RESIDENT_URL as string;
return { props: { appUrl, feedbackUrl } };
};
export default Home;
|
<filename>es/types/reply.py
from elasticsearch_dsl import (
DocType,
MetaField,
String,
)
from ..analysis import (
luno_english,
raw_analyzer,
shingle_analyzer,
)
class ReplyV1(DocType):
title = String(analyzer=luno_english)
titleV2 = String(
analyzer=luno_english,
fields={
'raw': String(
analyzer=raw_analyzer,
),
'shingles': String(
analyzer=shingle_analyzer,
),
},
)
body = String(
analyzer=luno_english,
fields={
'shingles': String(
analyzer=shingle_analyzer,
),
},
)
keywords = String(
analyzer=luno_english,
fields={
'raw': String(
analyzer=raw_analyzer,
),
'shingles': String(
analyzer=shingle_analyzer,
),
},
)
topic = String(
analyzer=luno_english,
fields={
'raw': String(
analyzer=raw_analyzer,
),
'shingles': String(
analyzer=shingle_analyzer,
),
},
)
topicId = String(index='not_analyzed')
teamId = String(index='not_analyzed')
class Meta:
doc_type = 'reply'
all = MetaField(enabled=False)
dynamic = MetaField('false')
routing = MetaField(required=True)
|
#!/usr/bin/env python
import numpy as np
from scipy.interpolate import interp1d
def daylightCCT_2_xy(cct):
"""
Calculate CIE xy chromaticity coordinates for CIE daylight from the
Correlated Color Temperature.
Parameters
----------
cct : numeric
Correlated Color Temperature.
Returns
-------
ndarray
CIE xy chromaticity coordinates for CIE daylight.
References
----------
- CIE 15:2004 Section 3.1
"""
# Check input values
if cct < 4000 or cct > 25000:
raise ValueError(
'D-Illuminants for CCT values < 4000 and > 25000 are not defined')
# Apply polynomials
if cct <= 7000:
x = 0.244063 + 0.09911 * ((10**3) / cct) + 2.9678 * (
(10**6) / cct**2) - 4.6070 * ((10**9) / (cct**3))
else:
x = 0.237040 + 0.24748 * (10**3 / cct) + 1.9018 * (
10**6 / cct**2) - 2.0064 * (10**9 / cct**3)
y = -3 * (x**2) + 2.87 * x - 0.275
# Place x and y in an array and return
xy = np.array([x, y])
return xy
def daylight(cct, wl):
"""
Calculate a CIE daylight spectral power distribution.
Parameters
----------
cct : numeric
Correlated Color Temperature.
wl : array_like
Wavelengths to calculate the spectral power distribution for.
Returns
-------
ndarray
CIE daylight spectral power distribution.
References
----------
- CIE 15:2004 Section 3.1
"""
# Check input values
if cct < 4000 or cct > 25000:
raise ValueError(
'D-Illuminants for CCT values < 4000 and > 25000 are not defined')
# Define s_series wl array
wl_s = np.arange(300, 835, 5)
# Define s_series values
s0 = np.array([
0.04, 3.02, 6, 17.8, 29.6, 42.45, 55.3, 56.3, 57.3, 59.55, 61.8, 61.65,
61.5, 65.15, 68.8, 66.1, 63.4, 64.6, 65.8, 80.3, 94.8, 99.8, 104.8,
105.35, 105.9, 101.35, 96.8, 105.35, 113.9, 119.75, 125.6, 125.55,
125.5, 123.4, 121.3, 121.3, 121.3, 117.4, 113.5, 113.3, 113.1, 111.95,
110.8, 108.65, 106.5, 107.65, 108.8, 107.05, 105.3, 104.85, 104.4,
102.2, 100, 98, 96, 95.55, 95.1, 92.1, 89.1, 89.8, 90.5, 90.4, 90.3,
89.35, 88.4, 86.2, 84, 84.55, 85.1, 83.5, 81.9, 82.25, 82.6, 83.75,
84.9, 83.1, 81.3, 76.6, 71.9, 73.1, 74.3, 75.35, 76.4, 69.85, 63.3,
67.5, 71.7, 74.35, 77, 71.1, 65.2, 56.45, 47.7, 58.15, 68.6, 66.8, 65,
65.5, 66, 63.5, 61, 57.15, 53.3, 56.1, 58.9, 60.4, 61.9
])
s1 = np.array([
0.02, 2.26, 4.5, 13.45, 22.4, 32.2, 42, 41.3, 40.6, 41.1, 41.6, 39.8,
38, 40.2, 42.4, 40.45, 38.5, 36.75, 35, 39.2, 43.4, 44.85, 46.3, 45.1,
43.9, 40.5, 37.1, 36.9, 36.7, 36.3, 35.9, 34.25, 32.6, 30.25, 27.9,
26.1, 24.3, 22.2, 20.1, 18.15, 16.2, 14.7, 13.2, 10.9, 8.6, 7.35, 6.1,
5.15, 4.2, 3.05, 1.9, 0.95, 0, -0.8, -1.6, -2.55, -3.5, -3.5, -3.5,
-4.65, -5.8, -6.5, -7.2, -7.9, -8.6, -9.05, -9.5, -10.2, -10.9, -10.8,
-10.7, -11.35, -12, -13, -14, -13.8, -13.6, -12.8, -12, -12.65, -13.3,
-13.1, -12.9, -11.75, -10.6, -11.1, -11.6, -11.9, -12.2, -11.2, -10.2,
-9, -7.8, -9.5, -11.2, -10.8, -10.4, -10.5, -10.6, -10.15, -9.7, -9,
-8.3, -8.8, -9.3, -9.55, -9.8
])
s2 = np.array([
0, 1, 2, 3, 4, 6.25, 8.5, 8.15, 7.8, 7.25, 6.7, 6, 5.3, 5.7, 6.1, 4.55,
3, 2.1, 1.2, 0.05, -1.1, -0.8, -0.5, -0.6, -0.7, -0.95, -1.2, -1.9,
-2.6, -2.75, -2.9, -2.85, -2.8, -2.7, -2.6, -2.6, -2.6, -2.2, -1.8,
-1.65, -1.5, -1.4, -1.3, -1.25, -1.2, -1.1, -1, -0.75, -0.5, -0.4,
-0.3, -0.15, 0, 0.1, 0.2, 0.35, 0.5, 1.3, 2.1, 2.65, 3.2, 3.65, 4.1,
4.4, 4.7, 4.9, 5.1, 5.9, 6.7, 7, 7.3, 7.95, 8.6, 9.2, 9.8, 10, 10.2,
9.25, 8.3, 8.95, 9.6, 9.05, 8.5, 7.75, 7, 7.3, 7.6, 7.8, 8, 7.35, 6.7,
5.95, 5.2, 6.3, 7.4, 7.1, 6.8, 6.9, 7, 6.7, 6.4, 5.95, 5.5, 5.8, 6.1,
6.3, 6.5
])
# Define interpolation function
f_s0 = interp1d(wl_s, s0, kind='linear')
f_s1 = interp1d(wl_s, s1, kind='linear')
f_s2 = interp1d(wl_s, s2, kind='linear')
# Interpolate s_series
s0_i = f_s0(wl)
s1_i = f_s1(wl)
s2_i = f_s2(wl)
# Calculate CIE xy chromaticity coordinates for daylight CCT
xy = daylightCCT_2_xy(cct)
x = xy[0]
y = xy[1]
# Calculate m0, m1, and m2
m0 = 0.0241 + 0.2562 * x - 0.7341 * y
m1 = -1.3515 - 1.7703 * x + 5.9114 * y
m2 = 0.03000 - 31.4424 * x + 30.0717 * y
m1 = np.round(m1 / m0, decimals=3)
m2 = np.round(m2 / m0, decimals=3)
# Calculate the spectral power distribution from interpolated s_series
# and m values
spec = (s0_i + np.tile(m1, (1, s1_i.shape[0])) * s1_i +
np.tile(m2, (1, s2_i.shape[0])) * s2_i)
return spec
def illumXYZ(spec, wl):
"""
Calculate the CIE XYZ tristimulus values of an illuminant spectral power
distribution.
Parameters
----------
spec : array_like
Illuminant spectral power distribution.
wl : array_like
Wavelengths of the spectral power distribution.
Returns
-------
ndarray
CIE XYZ tristimulus values.
References
----------
- CIE 15:2004 Section 7.1
"""
# CIE 1931 standard observer data
cie2 = np.array([
[360, 0.000129900000, 0.000003917000, 0.000606100000],
[361, 0.000145847000, 0.000004393581, 0.000680879200],
[362, 0.000163802100, 0.000004929604, 0.000765145600],
[363, 0.000184003700, 0.000005532136, 0.000860012400],
[364, 0.000206690200, 0.000006208245, 0.000966592800],
[365, 0.000232100000, 0.000006965000, 0.001086000000],
[366, 0.000260728000, 0.000007813219, 0.001220586000],
[367, 0.000293075000, 0.000008767336, 0.001372729000],
[368, 0.000329388000, 0.000009839844, 0.001543579000],
[369, 0.000369914000, 0.000011043230, 0.001734286000],
[370, 0.000414900000, 0.000012390000, 0.001946000000],
[371, 0.000464158700, 0.000013886410, 0.002177777000],
[372, 0.000518986000, 0.000015557280, 0.002435809000],
[373, 0.000581854000, 0.000017442960, 0.002731953000],
[374, 0.000655234700, 0.000019583750, 0.003078064000],
[375, 0.000741600000, 0.000022020000, 0.003486000000],
[376, 0.000845029600, 0.000024839650, 0.003975227000],
[377, 0.000964526800, 0.000028041260, 0.004540880000],
[378, 0.001094949000, 0.000031531040, 0.005158320000],
[379, 0.001231154000, 0.000035215210, 0.005802907000],
[380, 0.001368000000, 0.000039000000, 0.006450001000],
[381, 0.001502050000, 0.000042826400, 0.007083216000],
[382, 0.001642328000, 0.000046914600, 0.007745488000],
[383, 0.001802382000, 0.000051589600, 0.008501152000],
[384, 0.001995757000, 0.000057176400, 0.009414544000],
[385, 0.002236000000, 0.000064000000, 0.010549990000],
[386, 0.002535385000, 0.000072344210, 0.011965800000],
[387, 0.002892603000, 0.000082212240, 0.013655870000],
[388, 0.003300829000, 0.000093508160, 0.015588050000],
[389, 0.003753236000, 0.000106136100, 0.017730150000],
[390, 0.004243000000, 0.000120000000, 0.020050010000],
[391, 0.004762389000, 0.000134984000, 0.022511360000],
[392, 0.005330048000, 0.000151492000, 0.025202880000],
[393, 0.005978712000, 0.000170208000, 0.028279720000],
[394, 0.006741117000, 0.000191816000, 0.031897040000],
[395, 0.007650000000, 0.000217000000, 0.036210000000],
[396, 0.008751373000, 0.000246906700, 0.041437710000],
[397, 0.010028880000, 0.000281240000, 0.047503720000],
[398, 0.011421700000, 0.000318520000, 0.054119880000],
[399, 0.012869010000, 0.000357266700, 0.060998030000],
[400, 0.014310000000, 0.000396000000, 0.067850010000],
[401, 0.015704430000, 0.000433714700, 0.074486320000],
[402, 0.017147440000, 0.000473024000, 0.081361560000],
[403, 0.018781220000, 0.000517876000, 0.089153640000],
[404, 0.020748010000, 0.000572218700, 0.098540480000],
[405, 0.023190000000, 0.000640000000, 0.110200000000],
[406, 0.026207360000, 0.000724560000, 0.124613300000],
[407, 0.029782480000, 0.000825500000, 0.141701700000],
[408, 0.033880920000, 0.000941160000, 0.161303500000],
[409, 0.038468240000, 0.001069880000, 0.183256800000],
[410, 0.043510000000, 0.001210000000, 0.207400000000],
[411, 0.048995600000, 0.001362091000, 0.233692100000],
[412, 0.055022600000, 0.001530752000, 0.262611400000],
[413, 0.061718800000, 0.001720368000, 0.294774600000],
[414, 0.069212000000, 0.001935323000, 0.330798500000],
[415, 0.077630000000, 0.002180000000, 0.371300000000],
[416, 0.086958110000, 0.002454800000, 0.416209100000],
[417, 0.097176720000, 0.002764000000, 0.465464200000],
[418, 0.108406300000, 0.003117800000, 0.519694800000],
[419, 0.120767200000, 0.003526400000, 0.579530300000],
[420, 0.134380000000, 0.004000000000, 0.645600000000],
[421, 0.149358200000, 0.004546240000, 0.718483800000],
[422, 0.165395700000, 0.005159320000, 0.796713300000],
[423, 0.181983100000, 0.005829280000, 0.877845900000],
[424, 0.198611000000, 0.006546160000, 0.959439000000],
[425, 0.214770000000, 0.007300000000, 1.039050100000],
[426, 0.230186800000, 0.008086507000, 1.115367300000],
[427, 0.244879700000, 0.008908720000, 1.188497100000],
[428, 0.258777300000, 0.009767680000, 1.258123300000],
[429, 0.271807900000, 0.010664430000, 1.323929600000],
[430, 0.283900000000, 0.011600000000, 1.385600000000],
[431, 0.294943800000, 0.012573170000, 1.442635200000],
[432, 0.304896500000, 0.013582720000, 1.494803500000],
[433, 0.313787300000, 0.014629680000, 1.542190300000],
[434, 0.321645400000, 0.015715090000, 1.584880700000],
[435, 0.328500000000, 0.016840000000, 1.622960000000],
[436, 0.334351300000, 0.018007360000, 1.656404800000],
[437, 0.339210100000, 0.019214480000, 1.685295900000],
[438, 0.343121300000, 0.020453920000, 1.709874500000],
[439, 0.346129600000, 0.021718240000, 1.730382100000],
[440, 0.348280000000, 0.023000000000, 1.747060000000],
[441, 0.349599900000, 0.024294610000, 1.760044600000],
[442, 0.350147400000, 0.025610240000, 1.769623300000],
[443, 0.350013000000, 0.026958570000, 1.776263700000],
[444, 0.349287000000, 0.028351250000, 1.780433400000],
[445, 0.348060000000, 0.029800000000, 1.782600000000],
[446, 0.346373300000, 0.031310830000, 1.782968200000],
[447, 0.344262400000, 0.032883680000, 1.781699800000],
[448, 0.341808800000, 0.034521120000, 1.779198200000],
[449, 0.339094100000, 0.036225710000, 1.775867100000],
[450, 0.336200000000, 0.038000000000, 1.772110000000],
[451, 0.333197700000, 0.039846670000, 1.768258900000],
[452, 0.330041100000, 0.041768000000, 1.764039000000],
[453, 0.326635700000, 0.043766000000, 1.758943800000],
[454, 0.322886800000, 0.045842670000, 1.752466300000],
[455, 0.318700000000, 0.048000000000, 1.744100000000],
[456, 0.314025100000, 0.050243680000, 1.733559500000],
[457, 0.308884000000, 0.052573040000, 1.720858100000],
[458, 0.303290400000, 0.054980560000, 1.705936900000],
[459, 0.297257900000, 0.057458720000, 1.688737200000],
[460, 0.290800000000, 0.060000000000, 1.669200000000],
[461, 0.283970100000, 0.062601970000, 1.647528700000],
[462, 0.276721400000, 0.065277520000, 1.623412700000],
[463, 0.268917800000, 0.068042080000, 1.596022300000],
[464, 0.260422700000, 0.070911090000, 1.564528000000],
[465, 0.251100000000, 0.073900000000, 1.528100000000],
[466, 0.240847500000, 0.077016000000, 1.486111400000],
[467, 0.229851200000, 0.080266400000, 1.439521500000],
[468, 0.218407200000, 0.083666800000, 1.389879900000],
[469, 0.206811500000, 0.087232800000, 1.338736200000],
[470, 0.195360000000, 0.090980000000, 1.287640000000],
[471, 0.184213600000, 0.094917550000, 1.237422300000],
[472, 0.173327300000, 0.099045840000, 1.187824300000],
[473, 0.162688100000, 0.103367400000, 1.138761100000],
[474, 0.152283300000, 0.107884600000, 1.090148000000],
[475, 0.142100000000, 0.112600000000, 1.041900000000],
[476, 0.132178600000, 0.117532000000, 0.994197600000],
[477, 0.122569600000, 0.122674400000, 0.947347300000],
[478, 0.113275200000, 0.127992800000, 0.901453100000],
[479, 0.104297900000, 0.133452800000, 0.856619300000],
[480, 0.095640000000, 0.139020000000, 0.812950100000],
[481, 0.087299550000, 0.144676400000, 0.770517300000],
[482, 0.079308040000, 0.150469300000, 0.729444800000],
[483, 0.071717760000, 0.156461900000, 0.689913600000],
[484, 0.064580990000, 0.162717700000, 0.652104900000],
[485, 0.057950010000, 0.169300000000, 0.616200000000],
[486, 0.051862110000, 0.176243100000, 0.582328600000],
[487, 0.046281520000, 0.183558100000, 0.550416200000],
[488, 0.041150880000, 0.191273500000, 0.520337600000],
[489, 0.036412830000, 0.199418000000, 0.491967300000],
[490, 0.032010000000, 0.208020000000, 0.465180000000],
[491, 0.027917200000, 0.217119900000, 0.439924600000],
[492, 0.024144400000, 0.226734500000, 0.416183600000],
[493, 0.020687000000, 0.236857100000, 0.393882200000],
[494, 0.017540400000, 0.247481200000, 0.372945900000],
[495, 0.014700000000, 0.258600000000, 0.353300000000],
[496, 0.012161790000, 0.270184900000, 0.334857800000],
[497, 0.009919960000, 0.282293900000, 0.317552100000],
[498, 0.007967240000, 0.295050500000, 0.301337500000],
[499, 0.006296346000, 0.308578000000, 0.286168600000],
[500, 0.004900000000, 0.323000000000, 0.272000000000],
[501, 0.003777173000, 0.338402100000, 0.258817100000],
[502, 0.002945320000, 0.354685800000, 0.246483800000],
[503, 0.002424880000, 0.371698600000, 0.234771800000],
[504, 0.002236293000, 0.389287500000, 0.223453300000],
[505, 0.002400000000, 0.407300000000, 0.212300000000],
[506, 0.002925520000, 0.425629900000, 0.201169200000],
[507, 0.003836560000, 0.444309600000, 0.190119600000],
[508, 0.005174840000, 0.463394400000, 0.179225400000],
[509, 0.006982080000, 0.482939500000, 0.168560800000],
[510, 0.009300000000, 0.503000000000, 0.158200000000],
[511, 0.012149490000, 0.523569300000, 0.148138300000],
[512, 0.015535880000, 0.544512000000, 0.138375800000],
[513, 0.019477520000, 0.565690000000, 0.128994200000],
[514, 0.023992770000, 0.586965300000, 0.120075100000],
[515, 0.029100000000, 0.608200000000, 0.111700000000],
[516, 0.034814850000, 0.629345600000, 0.103904800000],
[517, 0.041120160000, 0.650306800000, 0.096667480000],
[518, 0.047985040000, 0.670875200000, 0.089982720000],
[519, 0.055378610000, 0.690842400000, 0.083845310000],
[520, 0.063270000000, 0.710000000000, 0.078249990000],
[521, 0.071635010000, 0.728185200000, 0.073208990000],
[522, 0.080462240000, 0.745463600000, 0.068678160000],
[523, 0.089739960000, 0.761969400000, 0.064567840000],
[524, 0.099456450000, 0.777836800000, 0.060788350000],
[525, 0.109600000000, 0.793200000000, 0.057250010000],
[526, 0.120167400000, 0.808110400000, 0.053904350000],
[527, 0.131114500000, 0.822496200000, 0.050746640000],
[528, 0.142367900000, 0.836306800000, 0.047752760000],
[529, 0.153854200000, 0.849491600000, 0.044898590000],
[530, 0.165500000000, 0.862000000000, 0.042160000000],
[531, 0.177257100000, 0.873810800000, 0.039507280000],
[532, 0.189140000000, 0.884962400000, 0.036935640000],
[533, 0.201169400000, 0.895493600000, 0.034458360000],
[534, 0.213365800000, 0.905443200000, 0.032088720000],
[535, 0.225749900000, 0.914850100000, 0.029840000000],
[536, 0.238320900000, 0.923734800000, 0.027711810000],
[537, 0.251066800000, 0.932092400000, 0.025694440000],
[538, 0.263992200000, 0.939922600000, 0.023787160000],
[539, 0.277101700000, 0.947225200000, 0.021989250000],
[540, 0.290400000000, 0.954000000000, 0.020300000000],
[541, 0.303891200000, 0.960256100000, 0.018718050000],
[542, 0.317572600000, 0.966007400000, 0.017240360000],
[543, 0.331438400000, 0.971260600000, 0.015863640000],
[544, 0.345482800000, 0.976022500000, 0.014584610000],
[545, 0.359700000000, 0.980300000000, 0.013400000000],
[546, 0.374083900000, 0.984092400000, 0.012307230000],
[547, 0.388639600000, 0.987418200000, 0.011301880000],
[548, 0.403378400000, 0.990312800000, 0.010377920000],
[549, 0.418311500000, 0.992811600000, 0.009529306000],
[550, 0.433449900000, 0.994950100000, 0.008749999000],
[551, 0.448795300000, 0.996710800000, 0.008035200000],
[552, 0.464336000000, 0.998098300000, 0.007381600000],
[553, 0.480064000000, 0.999112000000, 0.006785400000],
[554, 0.495971300000, 0.999748200000, 0.006242800000],
[555, 0.512050100000, 1.000000000000, 0.005749999000],
[556, 0.528295900000, 0.999856700000, 0.005303600000],
[557, 0.544691600000, 0.999304600000, 0.004899800000],
[558, 0.561209400000, 0.998325500000, 0.004534200000],
[559, 0.577821500000, 0.996898700000, 0.004202400000],
[560, 0.594500000000, 0.995000000000, 0.003900000000],
[561, 0.611220900000, 0.992600500000, 0.003623200000],
[562, 0.627975800000, 0.989742600000, 0.003370600000],
[563, 0.644760200000, 0.986444400000, 0.003141400000],
[564, 0.661569700000, 0.982724100000, 0.002934800000],
[565, 0.678400000000, 0.978600000000, 0.002749999000],
[566, 0.695239200000, 0.974083700000, 0.002585200000],
[567, 0.712058600000, 0.969171200000, 0.002438600000],
[568, 0.728828400000, 0.963856800000, 0.002309400000],
[569, 0.745518800000, 0.958134900000, 0.002196800000],
[570, 0.762100000000, 0.952000000000, 0.002100000000],
[571, 0.778543200000, 0.945450400000, 0.002017733000],
[572, 0.794825600000, 0.938499200000, 0.001948200000],
[573, 0.810926400000, 0.931162800000, 0.001889800000],
[574, 0.826824800000, 0.923457600000, 0.001840933000],
[575, 0.842500000000, 0.915400000000, 0.001800000000],
[576, 0.857932500000, 0.907006400000, 0.001766267000],
[577, 0.873081600000, 0.898277200000, 0.001737800000],
[578, 0.887894400000, 0.889204800000, 0.001711200000],
[579, 0.902318100000, 0.879781600000, 0.001683067000],
[580, 0.916300000000, 0.870000000000, 0.001650001000],
[581, 0.929799500000, 0.859861300000, 0.001610133000],
[582, 0.942798400000, 0.849392000000, 0.001564400000],
[583, 0.955277600000, 0.838622000000, 0.001513600000],
[584, 0.967217900000, 0.827581300000, 0.001458533000],
[585, 0.978600000000, 0.816300000000, 0.001400000000],
[586, 0.989385600000, 0.804794700000, 0.001336667000],
[587, 0.999548800000, 0.793082000000, 0.001270000000],
[588, 1.009089200000, 0.781192000000, 0.001205000000],
[589, 1.018006400000, 0.769154700000, 0.001146667000],
[590, 1.026300000000, 0.757000000000, 0.001100000000],
[591, 1.033982700000, 0.744754100000, 0.001068800000],
[592, 1.040986000000, 0.732422400000, 0.001049400000],
[593, 1.047188000000, 0.720003600000, 0.001035600000],
[594, 1.052466700000, 0.707496500000, 0.001021200000],
[595, 1.056700000000, 0.694900000000, 0.001000000000],
[596, 1.059794400000, 0.682219200000, 0.000968640000],
[597, 1.061799200000, 0.669471600000, 0.000929920000],
[598, 1.062806800000, 0.656674400000, 0.000886880000],
[599, 1.062909600000, 0.643844800000, 0.000842560000],
[600, 1.062200000000, 0.631000000000, 0.000800000000],
[601, 1.060735200000, 0.618155500000, 0.000760960000],
[602, 1.058443600000, 0.605314400000, 0.000723680000],
[603, 1.055224400000, 0.592475600000, 0.000685920000],
[604, 1.050976800000, 0.579637900000, 0.000645440000],
[605, 1.045600000000, 0.566800000000, 0.000600000000],
[606, 1.039036900000, 0.553961100000, 0.000547866700],
[607, 1.031360800000, 0.541137200000, 0.000491600000],
[608, 1.022666200000, 0.528352800000, 0.000435400000],
[609, 1.013047700000, 0.515632300000, 0.000383466700],
[610, 1.002600000000, 0.503000000000, 0.000340000000],
[611, 0.991367500000, 0.490468800000, 0.000307253300],
[612, 0.979331400000, 0.478030400000, 0.000283160000],
[613, 0.966491600000, 0.465677600000, 0.000265440000],
[614, 0.952847900000, 0.453403200000, 0.000251813300],
[615, 0.938400000000, 0.441200000000, 0.000240000000],
[616, 0.923194000000, 0.429080000000, 0.000229546700],
[617, 0.907244000000, 0.417036000000, 0.000220640000],
[618, 0.890502000000, 0.405032000000, 0.000211960000],
[619, 0.872920000000, 0.393032000000, 0.000202186700],
[620, 0.854449900000, 0.381000000000, 0.000190000000],
[621, 0.835084000000, 0.368918400000, 0.000174213300],
[622, 0.814946000000, 0.356827200000, 0.000155640000],
[623, 0.794186000000, 0.344776800000, 0.000135960000],
[624, 0.772954000000, 0.332817600000, 0.000116853300],
[625, 0.751400000000, 0.321000000000, 0.000100000000],
[626, 0.729583600000, 0.309338100000, 0.000086133330],
[627, 0.707588800000, 0.297850400000, 0.000074600000],
[628, 0.685602200000, 0.286593600000, 0.000065000000],
[629, 0.663810400000, 0.275624500000, 0.000056933330],
[630, 0.642400000000, 0.265000000000, 0.000049999990],
[631, 0.621514900000, 0.254763200000, 0.000044160000],
[632, 0.601113800000, 0.244889600000, 0.000039480000],
[633, 0.581105200000, 0.235334400000, 0.000035720000],
[634, 0.561397700000, 0.226052800000, 0.000032640000],
[635, 0.541900000000, 0.217000000000, 0.000030000000],
[636, 0.522599500000, 0.208161600000, 0.000027653330],
[637, 0.503546400000, 0.199548800000, 0.000025560000],
[638, 0.484743600000, 0.191155200000, 0.000023640000],
[639, 0.466193900000, 0.182974400000, 0.000021813330],
[640, 0.447900000000, 0.175000000000, 0.000020000000],
[641, 0.429861300000, 0.167223500000, 0.000018133330],
[642, 0.412098000000, 0.159646400000, 0.000016200000],
[643, 0.394644000000, 0.152277600000, 0.000014200000],
[644, 0.377533300000, 0.145125900000, 0.000012133330],
[645, 0.360800000000, 0.138200000000, 0.000010000000],
[646, 0.344456300000, 0.131500300000, 0.000007733333],
[647, 0.328516800000, 0.125024800000, 0.000005400000],
[648, 0.313019200000, 0.118779200000, 0.000003200000],
[649, 0.298001100000, 0.112769100000, 0.000001333333],
[650, 0.283500000000, 0.107000000000, 0.000000000000],
[651, 0.269544800000, 0.101476200000, 0.000000000000],
[652, 0.256118400000, 0.096188640000, 0.000000000000],
[653, 0.243189600000, 0.091122960000, 0.000000000000],
[654, 0.230727200000, 0.086264850000, 0.000000000000],
[655, 0.218700000000, 0.081600000000, 0.000000000000],
[656, 0.207097100000, 0.077120640000, 0.000000000000],
[657, 0.195923200000, 0.072825520000, 0.000000000000],
[658, 0.185170800000, 0.068710080000, 0.000000000000],
[659, 0.174832300000, 0.064769760000, 0.000000000000],
[660, 0.164900000000, 0.061000000000, 0.000000000000],
[661, 0.155366700000, 0.057396210000, 0.000000000000],
[662, 0.146230000000, 0.053955040000, 0.000000000000],
[663, 0.137490000000, 0.050673760000, 0.000000000000],
[664, 0.129146700000, 0.047549650000, 0.000000000000],
[665, 0.121200000000, 0.044580000000, 0.000000000000],
[666, 0.113639700000, 0.041758720000, 0.000000000000],
[667, 0.106465000000, 0.039084960000, 0.000000000000],
[668, 0.099690440000, 0.036563840000, 0.000000000000],
[669, 0.093330610000, 0.034200480000, 0.000000000000],
[670, 0.087400000000, 0.032000000000, 0.000000000000],
[671, 0.081900960000, 0.029962610000, 0.000000000000],
[672, 0.076804280000, 0.028076640000, 0.000000000000],
[673, 0.072077120000, 0.026329360000, 0.000000000000],
[674, 0.067686640000, 0.024708050000, 0.000000000000],
[675, 0.063600000000, 0.023200000000, 0.000000000000],
[676, 0.059806850000, 0.021800770000, 0.000000000000],
[677, 0.056282160000, 0.020501120000, 0.000000000000],
[678, 0.052971040000, 0.019281080000, 0.000000000000],
[679, 0.049818610000, 0.018120690000, 0.000000000000],
[680, 0.046770000000, 0.017000000000, 0.000000000000],
[681, 0.043784050000, 0.015903790000, 0.000000000000],
[682, 0.040875360000, 0.014837180000, 0.000000000000],
[683, 0.038072640000, 0.013810680000, 0.000000000000],
[684, 0.035404610000, 0.012834780000, 0.000000000000],
[685, 0.032900000000, 0.011920000000, 0.000000000000],
[686, 0.030564190000, 0.011068310000, 0.000000000000],
[687, 0.028380560000, 0.010273390000, 0.000000000000],
[688, 0.026344840000, 0.009533311000, 0.000000000000],
[689, 0.024452750000, 0.008846157000, 0.000000000000],
[690, 0.022700000000, 0.008210000000, 0.000000000000],
[691, 0.021084290000, 0.007623781000, 0.000000000000],
[692, 0.019599880000, 0.007085424000, 0.000000000000],
[693, 0.018237320000, 0.006591476000, 0.000000000000],
[694, 0.016987170000, 0.006138485000, 0.000000000000],
[695, 0.015840000000, 0.005723000000, 0.000000000000],
[696, 0.014790640000, 0.005343059000, 0.000000000000],
[697, 0.013831320000, 0.004995796000, 0.000000000000],
[698, 0.012948680000, 0.004676404000, 0.000000000000],
[699, 0.012129200000, 0.004380075000, 0.000000000000],
[700, 0.011359160000, 0.004102000000, 0.000000000000],
[701, 0.010629350000, 0.003838453000, 0.000000000000],
[702, 0.009938846000, 0.003589099000, 0.000000000000],
[703, 0.009288422000, 0.003354219000, 0.000000000000],
[704, 0.008678854000, 0.003134093000, 0.000000000000],
[705, 0.008110916000, 0.002929000000, 0.000000000000],
[706, 0.007582388000, 0.002738139000, 0.000000000000],
[707, 0.007088746000, 0.002559876000, 0.000000000000],
[708, 0.006627313000, 0.002393244000, 0.000000000000],
[709, 0.006195408000, 0.002237275000, 0.000000000000],
[710, 0.005790346000, 0.002091000000, 0.000000000000],
[711, 0.005409826000, 0.001953587000, 0.000000000000],
[712, 0.005052583000, 0.001824580000, 0.000000000000],
[713, 0.004717512000, 0.001703580000, 0.000000000000],
[714, 0.004403507000, 0.001590187000, 0.000000000000],
[715, 0.004109457000, 0.001484000000, 0.000000000000],
[716, 0.003833913000, 0.001384496000, 0.000000000000],
[717, 0.003575748000, 0.001291268000, 0.000000000000],
[718, 0.003334342000, 0.001204092000, 0.000000000000],
[719, 0.003109075000, 0.001122744000, 0.000000000000],
[720, 0.002899327000, 0.001047000000, 0.000000000000],
[721, 0.002704348000, 0.000976589600, 0.000000000000],
[722, 0.002523020000, 0.000911108800, 0.000000000000],
[723, 0.002354168000, 0.000850133200, 0.000000000000],
[724, 0.002196616000, 0.000793238400, 0.000000000000],
[725, 0.002049190000, 0.000740000000, 0.000000000000],
[726, 0.001910960000, 0.000690082700, 0.000000000000],
[727, 0.001781438000, 0.000643310000, 0.000000000000],
[728, 0.001660110000, 0.000599496000, 0.000000000000],
[729, 0.001546459000, 0.000558454700, 0.000000000000],
[730, 0.001439971000, 0.000520000000, 0.000000000000],
[731, 0.001340042000, 0.000483913600, 0.000000000000],
[732, 0.001246275000, 0.000450052800, 0.000000000000],
[733, 0.001158471000, 0.000418345200, 0.000000000000],
[734, 0.001076430000, 0.000388718400, 0.000000000000],
[735, 0.000999949300, 0.000361100000, 0.000000000000],
[736, 0.000928735800, 0.000335383500, 0.000000000000],
[737, 0.000862433200, 0.000311440400, 0.000000000000],
[738, 0.000800750300, 0.000289165600, 0.000000000000],
[739, 0.000743396000, 0.000268453900, 0.000000000000],
[740, 0.000690078600, 0.000249200000, 0.000000000000],
[741, 0.000640515600, 0.000231301900, 0.000000000000],
[742, 0.000594502100, 0.000214685600, 0.000000000000],
[743, 0.000551864600, 0.000199288400, 0.000000000000],
[744, 0.000512429000, 0.000185047500, 0.000000000000],
[745, 0.000476021300, 0.000171900000, 0.000000000000],
[746, 0.000442453600, 0.000159778100, 0.000000000000],
[747, 0.000411511700, 0.000148604400, 0.000000000000],
[748, 0.000382981400, 0.000138301600, 0.000000000000],
[749, 0.000356649100, 0.000128792500, 0.000000000000],
[750, 0.000332301100, 0.000120000000, 0.000000000000],
[751, 0.000309758600, 0.000111859500, 0.000000000000],
[752, 0.000288887100, 0.000104322400, 0.000000000000],
[753, 0.000269539400, 0.000097335600, 0.000000000000],
[754, 0.000251568200, 0.000090845870, 0.000000000000],
[755, 0.000234826100, 0.000084800000, 0.000000000000],
[756, 0.000219171000, 0.000079146670, 0.000000000000],
[757, 0.000204525800, 0.000073858000, 0.000000000000],
[758, 0.000190840500, 0.000068916000, 0.000000000000],
[759, 0.000178065400, 0.000064302670, 0.000000000000],
[760, 0.000166150500, 0.000060000000, 0.000000000000],
[761, 0.000155023600, 0.000055981870, 0.000000000000],
[762, 0.000144621900, 0.000052225600, 0.000000000000],
[763, 0.000134909800, 0.000048718400, 0.000000000000],
[764, 0.000125852000, 0.000045447470, 0.000000000000],
[765, 0.000117413000, 0.000042400000, 0.000000000000],
[766, 0.000109551500, 0.000039561040, 0.000000000000],
[767, 0.000102224500, 0.000036915120, 0.000000000000],
[768, 0.000095394450, 0.000034448680, 0.000000000000],
[769, 0.000089023900, 0.000032148160, 0.000000000000],
[770, 0.000083075270, 0.000030000000, 0.000000000000],
[771, 0.000077512690, 0.000027991250, 0.000000000000],
[772, 0.000072313040, 0.000026113560, 0.000000000000],
[773, 0.000067457780, 0.000024360240, 0.000000000000],
[774, 0.000062928440, 0.000022724610, 0.000000000000],
[775, 0.000058706520, 0.000021200000, 0.000000000000],
[776, 0.000054770280, 0.000019778550, 0.000000000000],
[777, 0.000051099180, 0.000018452850, 0.000000000000],
[778, 0.000047676540, 0.000017216870, 0.000000000000],
[779, 0.000044485670, 0.000016064590, 0.000000000000],
[780, 0.000041509940, 0.000014990000, 0.000000000000],
[781, 0.000038733240, 0.000013987280, 0.000000000000],
[782, 0.000036142030, 0.000013051550, 0.000000000000],
[783, 0.000033723520, 0.000012178180, 0.000000000000],
[784, 0.000031464870, 0.000011362540, 0.000000000000],
[785, 0.000029353260, 0.000010600000, 0.000000000000],
[786, 0.000027375730, 0.000009885877, 0.000000000000],
[787, 0.000025524330, 0.000009217304, 0.000000000000],
[788, 0.000023793760, 0.000008592362, 0.000000000000],
[789, 0.000022178700, 0.000008009133, 0.000000000000],
[790, 0.000020673830, 0.000007465700, 0.000000000000],
[791, 0.000019272260, 0.000006959567, 0.000000000000],
[792, 0.000017966400, 0.000006487995, 0.000000000000],
[793, 0.000016749910, 0.000006048699, 0.000000000000],
[794, 0.000015616480, 0.000005639396, 0.000000000000],
[795, 0.000014559770, 0.000005257800, 0.000000000000],
[796, 0.000013573870, 0.000004901771, 0.000000000000],
[797, 0.000012654360, 0.000004569720, 0.000000000000],
[798, 0.000011797230, 0.000004260194, 0.000000000000],
[799, 0.000010998440, 0.000003971739, 0.000000000000],
[800, 0.000010253980, 0.000003702900, 0.000000000000],
[801, 0.000009559646, 0.000003452163, 0.000000000000],
[802, 0.000008912044, 0.000003218302, 0.000000000000],
[803, 0.000008308358, 0.000003000300, 0.000000000000],
[804, 0.000007745769, 0.000002797139, 0.000000000000],
[805, 0.000007221456, 0.000002607800, 0.000000000000],
[806, 0.000006732475, 0.000002431220, 0.000000000000],
[807, 0.000006276423, 0.000002266531, 0.000000000000],
[808, 0.000005851304, 0.000002113013, 0.000000000000],
[809, 0.000005455118, 0.000001969943, 0.000000000000],
[810, 0.000005085868, 0.000001836600, 0.000000000000],
[811, 0.000004741466, 0.000001712230, 0.000000000000],
[812, 0.000004420236, 0.000001596228, 0.000000000000],
[813, 0.000004120783, 0.000001488090, 0.000000000000],
[814, 0.000003841716, 0.000001387314, 0.000000000000],
[815, 0.000003581652, 0.000001293400, 0.000000000000],
[816, 0.000003339127, 0.000001205820, 0.000000000000],
[817, 0.000003112949, 0.000001124143, 0.000000000000],
[818, 0.000002902121, 0.000001048009, 0.000000000000],
[819, 0.000002705645, 0.000000977058, 0.000000000000],
[820, 0.000002522525, 0.000000910930, 0.000000000000],
[821, 0.000002351726, 0.000000849251, 0.000000000000],
[822, 0.000002192415, 0.000000791721, 0.000000000000],
[823, 0.000002043902, 0.000000738090, 0.000000000000],
[824, 0.000001905497, 0.000000688110, 0.000000000000],
[825, 0.000001776509, 0.000000641530, 0.000000000000],
[826, 0.000001656215, 0.000000598090, 0.000000000000],
[827, 0.000001544022, 0.000000557575, 0.000000000000],
[828, 0.000001439440, 0.000000519808, 0.000000000000],
[829, 0.000001341977, 0.000000484612, 0.000000000000],
[830, 0.000001251141, 0.000000451810, 0.000000000000],
])
# Define interpolation function
f_xbar = interp1d(
cie2[:, 0],
cie2[:, 1],
kind='linear',
bounds_error=False,
fill_value=0)
f_ybar = interp1d(
cie2[:, 0],
cie2[:, 2],
kind='linear',
bounds_error=False,
fill_value=0)
f_zbar = interp1d(
cie2[:, 0],
cie2[:, 3],
kind='linear',
bounds_error=False,
fill_value=0)
# Interpolate the standard observer data
xbar = f_xbar(wl)
ybar = f_ybar(wl)
zbar = f_zbar(wl)
# Put the interpolated standard observer data into an array
cmf = np.array([xbar, ybar, zbar])
# Multiply the standard observer data by the spectra
XYZ = cmf.dot(spec.T).T
# Normalize the CIE XYZ values so that Y equals 1
XYZ = XYZ[:] / XYZ[:, 1]
return XYZ
def XYZ_2_xyY(XYZ):
"""
Calculate CIE XYZ tristimulus values to CIE xyY chromaticity coordinates.
Parameters
----------
XYZ : array_like
CIE XYZ tristimulus values.
Returns
-------
ndarray
CIE xyY chromaticity coordinates.
References
----------
- CIE 15:2004 Section 7.3
"""
# Convert CIE XYZ to CIE xyY
x = XYZ[:, 0] / (XYZ[:, 0] + XYZ[:, 1] + XYZ[:, 2])
y = XYZ[:, 1] / (XYZ[:, 0] + XYZ[:, 1] + XYZ[:, 2])
Y = XYZ[:, 1]
xyY = np.array([x, y, Y]).T
return xyY
if __name__ == "__main__":
""""
Implementation of the procedure outlined in Acadmey Technical Bulletin
TB-2018-001 to calcualte the ACES CIE xyY chromaticity coordinates of the
white point used in various ACES encodings.
""""
# Define wavelenghts from 300 to 830 in 1nm increments and CCT of 6000K
wl = np.arange(300, 831, 1)
cct = 6000
# Calculate the CIE daylight spectral power distribution for CCT of 6000K
spec = daylight(cct, wl)
# Determine the XYZ values of the CIE daylight spectral power distribution
XYZ = illumXYZ(spec, wl)
# Calculate the CIE xy chromaticity coordinates from the CIE XYZ values
xyY = XYZ_2_xyY(XYZ)
# Round to 5 decimal places
aces_wp_xyY = np.round(xyY, decimals=5)
# Print the results
print(aces_wp_xyY)
|
<gh_stars>0
const router = require('express').Router();
const auth = require('../middleware/auth');
const ToDo = require('../models/todo.model');
router.post("/", async(req,res) => {
try{
const { title } = req.body;
if(!title)
return res.status(400).json({msg: "Not all fields have been entered"});
const newToDo = new ToDo({
title,
userId: req.user
});
const savedToDo = await newToDo.save();
res.json(savedToDo);
} catch (err) {
res.status(500).json({ error: err.message });
}
})
router.get("/all", auth, async(req,res) => {
const todos = await ToDo.find({ userId: req.user});
res.json(todos);
})
router.delete("/:id", auth, async(req,res) => {
const todo = await ToDo.findOne({userId: req.user, _id: req.params.id });
if(!todo)
return res.status(400).json({msg: "No todo item found !!"});
const deletedItem = await ToDo.findByIdAndDelete(req.params.id);
res.json(deletedItem);
});
module.exports = router; |
package ru.zzz.demo.sber.shs.service.impl;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.test.StepVerifier;
import ru.zzz.demo.sber.shs.CircuitBreaker.device.DeviceCircuitBreaker;
import ru.zzz.demo.sber.shs.CircuitBreaker.storage.DeviceStorageCircuitBreaker;
import ru.zzz.demo.sber.shs.db.DbActionException;
import ru.zzz.demo.sber.shs.db.DeviceDto;
import ru.zzz.demo.sber.shs.device.Reply;
import ru.zzz.demo.sber.shs.device.Request;
import ru.zzz.demo.sber.shs.model.device.DeviceAddress;
import ru.zzz.demo.sber.shs.service.api.DeviceDescriptor;
import ru.zzz.demo.sber.shs.service.api.DeviceManagementException;
import ru.zzz.demo.sber.shs.service.api.UnknownDeviceException;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static java.util.concurrent.TimeUnit.SECONDS;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class InMemoryDeviceManagerTest {
private DeviceCircuitBreaker dcb = mock(DeviceCircuitBreaker.class);
private DeviceStorageCircuitBreaker dscb = mock(DeviceStorageCircuitBreaker.class);
@BeforeEach
void beforeEach() {
when(dscb.readAll()).thenReturn(Flux.empty());
}
@Test
void cannotRegisterDevicesWithSameAddresses() {
//setup
when(dscb.readAll()).thenReturn(Flux.empty());
when(dscb.setDeviceIsOff(eq("a"))).thenReturn(Mono.just(TRUE));
//test and assert
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
StepVerifier.create(dm.register(DeviceAddress.of("a"))).expectComplete().log().verify();
verify(dscb, times(1)).setDeviceIsOff(eq("a"));
StepVerifier.create(dm.register(DeviceAddress.of("a"))).expectError().log().verify();
}
@Test
void registrationAfterUnregistrationDevicesWithSameAddresses() {
//setup
when(dscb.readAll()).thenReturn(Flux.empty());
when(dscb.setDeviceIsOff(eq("a"))).thenReturn(Mono.just(TRUE));
when(dscb.removeDevice(eq("a"))).thenReturn(Mono.just(TRUE));
//test and assert
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
// register a
StepVerifier.create(dm.register(DeviceAddress.of("a"))).expectComplete().log().verify();
verify(dscb, times(1)).setDeviceIsOff(eq("a"));
// unregister a
StepVerifier.create(dm.unregister(DeviceAddress.of("a")))
.expectNext(TRUE)
.expectComplete()
.log()
.verify();
verify(dscb, times(1)).removeDevice(eq("a"));
// register a
StepVerifier.create(dm.register(DeviceAddress.of("a"))).expectComplete().log().verify();
verify(dscb, times(2)).setDeviceIsOff(eq("a"));
}
@Test
void unregisterAbsentDevice() {
// setup
when(dscb.readAll()).thenReturn(Flux.empty());
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
// unregister a
StepVerifier.create(dm.unregister(DeviceAddress.of("a")))
.expectNext(FALSE)
.expectComplete()
.log()
.verify();
}
@Test
void switchOnAnUnknownDevice() {
// setup
when(dscb.readAll()).thenReturn(Flux.empty());
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
StepVerifier.create(dm.on(DeviceAddress.of("a")))
.expectError(UnknownDeviceException.class)
.log()
.verify();
}
@Test
void switchDeviceOn_Successfully() {
//setup
DeviceDto a = DeviceDto.of("a", true, 0, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dscb.setDeviceValue(eq("a"), eq(0))).thenReturn(Mono.just(TRUE));
when(dcb.accept(any(Request.class))).thenReturn(Reply.ok());
// set a on
StepVerifier.create(dm.on(DeviceAddress.of("a"))).expectComplete().verify();
verify(dcb, times(2)).accept(any(Request.class));
verify(dscb, times(1)).setDeviceValue(eq("a"), eq(0));
}
@Test
void switchDeviceOn_DoNotUpdateDbIfDeviceCommunicationFails() {
//setup
DeviceDto a = DeviceDto.of("a", true, 0, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dcb.accept(any(Request.class))).thenReturn(Reply.error("fail"));
when(dscb.setDeviceIsOff(eq("a"))).thenReturn(Mono.just(TRUE));// for registration
when(dscb.setDeviceValue(anyString(), anyInt())).thenThrow(
new RuntimeException("Must not be called"));
// set a on
StepVerifier.create(dm.on(DeviceAddress.of("a")))
.expectError(DeviceManagementException.class)
.log()
.verify();
verify(dcb, times(1)).accept(any(Request.class));
}
@Test
void switchDeviceOn_IfDbUpdateFailsTheDeviceIsStillConsideredToBeOn() {
//setup
DeviceDto a = DeviceDto.of("a", false, 0, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dcb.accept(any(Request.class))).thenReturn(Reply.ok());
when(dscb.setDeviceValue(anyString(), anyInt())).thenReturn(
Mono.error(new DbActionException("DB fail", new SQLException("sql"))));
// set a on
StepVerifier.create(dm.on(DeviceAddress.of("a"))).expectError(DbActionException.class).log().verify();
// accept called twice to set device on and to set ins value
verify(dcb, times(2)).accept(any(Request.class));
// verify a is considered to be on. Verification uses an in memory list.
List<DeviceDescriptor> list = dm.listWithCurrentStatus();
assertEquals(1, list.size());
DeviceDescriptor dev = list.get(0);
assertEquals("a", dev.getAddress());
assertTrue(dev.isOn());
}
@Test
void switchOffAnUnknownDevice() {
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
StepVerifier.create(dm.off(DeviceAddress.of("a")))
.expectError(UnknownDeviceException.class)
.log()
.verify();
}
@Test
void switchDeviceOff_Successfully() {
//setup: a exists and is on
DeviceDto a = DeviceDto.of("a", true, 0, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dscb.setDeviceIsOff(eq("a"))).thenReturn(Mono.just(TRUE));
when(dcb.accept(any(Request.class))).thenReturn(Reply.ok());
// set a off
StepVerifier.create(dm.off(DeviceAddress.of("a"))).expectComplete().verify();
// verify
verify(dcb, times(1)).accept(any(Request.class));
verify(dscb, times(1)).setDeviceIsOff(eq("a"));
}
@Test
void switchDeviceOff_DoNotUpdateDbIfDeviceCommunicationFails() {
//setup: a exists and is on
DeviceDto a = DeviceDto.of("a", true, 0, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dcb.accept(any(Request.class))).thenReturn(Reply.error("fail"));
when(dscb.setDeviceValue(anyString(), anyInt())).thenThrow(
new RuntimeException("Must not be called"));
// set a off
StepVerifier.create(dm.off(DeviceAddress.of("a")))
.expectError(DeviceManagementException.class)
.log()
.verify();
// verify
verify(dcb, times(1)).accept(any(Request.class));
}
@Test
void switchDeviceOn_IfDbUpdateFailsTheDeviceIsStillConsideredToBeOff() {
//setup
DeviceDto a = DeviceDto.of("a", true, 0, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dcb.accept(any(Request.class))).thenReturn(Reply.ok());
when(dscb.setDeviceIsOff(eq("a"))).thenReturn(
Mono.error(new DbActionException("DB fail", new SQLException("sql"))));
// set a on
StepVerifier.create(dm.off(DeviceAddress.of("a")))
.expectError(DbActionException.class)
.log()
.verify();
verify(dcb, times(1)).accept(any(Request.class));
// verify a is considered to be on. Verification uses an in memory list.
List<DeviceDescriptor> list = dm.listWithCurrentStatus();
assertEquals(1, list.size());
DeviceDescriptor dev = list.get(0);
assertEquals("a", dev.getAddress());
assertFalse(dev.isOn());
}
@Test
void incrementOfAnUnknownDevice() {
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
StepVerifier.create(dm.increment(DeviceAddress.of("a")))
.expectError(UnknownDeviceException.class)
.log()
.verify();
}
@Test
void increment_Successfully() {
//setup: a exists and is on
DeviceDto a = DeviceDto.of("a", true, 42, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dscb.setDeviceValue(eq("a"), eq(43))).thenReturn(Mono.just(TRUE));
when(dcb.accept(any(Request.Set.class))).thenReturn(Reply.ok());
// set a off
StepVerifier.create(dm.increment(DeviceAddress.of("a"))).expectNext(43).expectComplete().verify();
// verify
verify(dcb, times(1)).accept(any(Request.class));
verify(dscb, times(1)).setDeviceValue(eq("a"), eq(43));
}
@Test
void concurrentOperationsOnTheSameDeviceAreNotAllowed() throws InterruptedException {
//setup: a exists and is on
DeviceDto a = DeviceDto.of("a", true, 42, LocalDateTime.now());
when(dscb.readAll()).thenReturn(Flux.fromArray(new DeviceDto[]{a}));
InMemoryDeviceManager dm = new InMemoryDeviceManager(dcb, dscb);
when(dscb.setDeviceValue(eq("a"), anyInt())).thenReturn(Mono.just(TRUE));
CountDownLatch parallelThreadStartedLatch = new CountDownLatch(1);
CountDownLatch mainThreadFinishedLatch = new CountDownLatch(1);
when(dcb.accept(any(Request.Set.class))).thenAnswer(invocation -> {
parallelThreadStartedLatch.countDown();
if (!mainThreadFinishedLatch.await(1, SECONDS)) fail("Latch wait failed.");
return Reply.ok();
});
Thread t = new Thread(() -> {
StepVerifier.create(dm.increment(DeviceAddress.of("a"))).expectNext(43).expectComplete().verify();
}, "TestParallelCall-concurrentOperationsOnTheSameDeviceAreNotAllowed");
t.setDaemon(true);
t.start();
parallelThreadStartedLatch.await(1, SECONDS);
StepVerifier.create(dm.increment(DeviceAddress.of("a")))
.expectError(DeviceManagementException.class)
.verify();
mainThreadFinishedLatch.countDown();
// verify
t.join(100);
verify(dcb, times(1)).accept(any(Request.class));
verify(dscb, times(1)).setDeviceValue(eq("a"), eq(43));
}
} |
<reponame>mongodb/docs-screencapture-tool
'use strict';
const screenshotNames = ['clusterselect2.png'];
const screenshotDir = './screenshots-temp';
const origImageDir = './source/images';
exports.run = async function (options) {
const nightmare = options.nightmare;
const originalPath = `${origImageDir}/${screenshotNames[0]}`;
const screenshotPath = `${screenshotDir}/${screenshotNames[0]}`;
await options.loginToAtlas()
await nightmare.wait(2000)
await nightmare.wait('.mms-body-main')
await nightmare.wait('a[name=buildCluster]')
await nightmare.click('a[name=buildCluster]')
await nightmare.wait(2000)
await nightmare.wait('.mms-body-main')
await nightmare.wait('section.accordion:nth-child(2) > div:nth-child(1) > div:nth-child(1)')
await nightmare.click('section.accordion:nth-child(2) > div:nth-child(1) > div:nth-child(1)')
await nightmare.wait(1000)
const global_cluster_config_clip = await nightmare.evaluate(() => {
// store the button in a variable
const global_cluster_config_selector = document.querySelector('section.accordion:nth-child(2)');
// use the getClientRects() function on the button to determine
// the size and location
const [rect] = global_cluster_config_selector.getClientRects();
// convert the rectangle to a clip object and return it
return {
top: rect.top,
right: rect.right,
bottom: rect.bottom,
left: rect.left,
width: rect.width,
height: rect.height
};
})
const buildClip = {
x: Math.floor(global_cluster_config_clip.left) - 20,
y: Math.floor(global_cluster_config_clip.top) - 20,
width: Math.floor(global_cluster_config_clip.width) + 40,
height: Math.floor(global_cluster_config_clip.height) - 80
};
await nightmare.screenshot(screenshotPath, buildClip)
await nightmare.wait(500)
await nightmare.end();
return [[originalPath, screenshotPath]];
}
exports.nightmare_props = {
show: true,
typeInterval: 20,
height: 1200,
width: 1200,
webPreferences: {
zoomFactor: 0.9
}
}
|
#!/bin/bash
function func_init_logging(){
# generate a random 12 char string
random_str=$(uuidgen | sed 's/-//g' | cut -c 1-12)
log_folder="/var/log/swarm-test/$random_str"
mkdir -p "$log_folder"
dtl_log_file="$log_folder/details.log"
summary_log_file="$log_folder/summary.log"
}
function func_log_test_result(){
result=$1
shift
message="Test:$current_test_name; Result:$result; message:$@"
if [ "$result" == "$SUCCESS_PREFIX" ]; then
current_test_success_counter=$(($current_test_success_counter + 1))
current_test_results=("${current_test_results[@]}" "$message")
func_log_dtl "$message"
elif [ "$result" == "$FAILURE_PREFIX" ]; then
current_test_failure_counter=$(($current_test_failure_counter + 1))
current_test_results=("${current_test_results[@]}" "$message")
echo ""
func_log "$message"
elif [ "$result" == "$WARN_PREFIX" ]; then
current_test_warning_counter=$(($current_test_warning_counter + 1))
current_test_results=("${current_test_results[@]}" "$message")
echo ""
func_log "$message"
else
func_log_dtl "Unknown first argument:$result. Other arguments are $@"
fi
}
function func_log_result(){
result=$1
shift
message="Test:$current_test_name; Phase:$current_test_phase; Step:$current_test_step; Result:$result; message:$@"
if [ "$result" == "$SUCCESS_PREFIX" ]; then
current_test_success_counter=$(($current_test_success_counter + 1))
current_test_results=("${current_test_results[@]}" "$message")
func_log_dtl "$message"
elif [ "$result" == "$FAILURE_PREFIX" ]; then
current_test_failure_counter=$(($current_test_failure_counter + 1))
current_test_results=("${current_test_results[@]}" "$message")
echo ""
func_log "$message"
elif [ "$result" == "$WARN_PREFIX" ]; then
current_test_warning_counter=$(($current_test_warning_counter + 1))
current_test_results=("${current_test_results[@]}" "$message")
echo ""
func_log "$message"
else
func_log_dtl "Unknown first argument:$result. Other arguments are $@"
fi
}
function func_log(){
curr_date=$(date '+%Y-%m-%d.%H:%M:%S-%3N')
#echo
#echo on console
echo "$curr_date" "$*"
# log in summary_file
echo "$curr_date" "$*" >> $summary_log_file
#log in detail file
echo "$curr_date" "$*" >> $dtl_log_file
}
function func_log_dtl(){
curr_date=$(date '+%Y-%m-%d.%H:%M:%S-%3N')
# log in summary_file
#echo "$curr_date" "$*" >> $summary_log_file
#log in detail file
echo "$curr_date" "$*" >> $dtl_log_file
} |
export default {
id: {
type: String,
required: true
},
title: {
type: String,
required: true
}
}
|
/*
* Copyright [2018] [<NAME>]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jacpfx.vxms.common.concurrent;
import io.vertx.core.AsyncResult;
import io.vertx.core.Context;
import io.vertx.core.Future;
import io.vertx.core.Handler;
import io.vertx.core.Vertx;
import io.vertx.core.impl.Arguments;
import io.vertx.core.impl.VertxInternal;
import io.vertx.core.shareddata.Counter;
import io.vertx.core.shareddata.Lock;
import io.vertx.core.shareddata.impl.AsynchronousCounter;
import io.vertx.core.shareddata.impl.LocalAsyncLocks;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
/**
* Created by amo on 23.03.17. Local Data implementation to get lock and counters without involving
* cluster manager when running in clustered mode
*/
@SuppressWarnings("unchecked")
public class LocalData {
private final ConcurrentMap<String, Counter> localCounters = new ConcurrentHashMap();
private final ConcurrentMap<String, LocalAsyncLocks> localLocks = new ConcurrentHashMap();
private final Vertx vertx;
public LocalData(Vertx vertx) {
this.vertx = vertx;
}
/**
* Get a local counter. The counter will be passed to the handler.
*
* @param name the name of the counter.
* @param resultHandler the handler
*/
public void getCounter(String name, Handler<AsyncResult<Counter>> resultHandler) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(resultHandler, "resultHandler");
Counter counter = this.localCounters
.computeIfAbsent(name, (n) -> new AsynchronousCounter((VertxInternal) this.vertx));
Context context = this.vertx.getOrCreateContext();
context.runOnContext((v) -> resultHandler.handle(Future.succeededFuture(counter)));
}
/**
* Get a local lock with the specified name with specifying a timeout. The lock will be passed to
* the handler when it is available. If the lock is not obtained within the timeout a failure
* will be sent to the handler
*
* @param name the name of the lock
* @param timeout the timeout in ms
* @param resultHandler the handler
*/
public void getLockWithTimeout(String name, long timeout,
Handler<AsyncResult<Lock>> resultHandler) {
Objects.requireNonNull(name, "name");
Objects.requireNonNull(resultHandler, "resultHandler");
Arguments.require(timeout >= 0L, "timeout must be >= 0");
LocalAsyncLocks lock = this.localLocks
.computeIfAbsent(name, (n) -> new LocalAsyncLocks());
lock.acquire(this.vertx.getOrCreateContext(),name,timeout, resultHandler);
}
}
|
<filename>boot-jpa-jwt/src/main/java/cn/crabapples/system/service/UserService.java
package cn.crabapples.system.service;
import cn.crabapples.system.entity.SysUser;
import cn.crabapples.system.form.UserForm;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* TODO 用户相关服务
*
* @author Mr.He
* 2020/1/27 2:10
* e-mail <EMAIL>
* qq 294046317
* pc-name 29404
*/
public interface UserService {
/**
* 根据 [用户名] 查询用户
*
* @param username 用户名
* @return 查询到的用户
*/
SysUser findByUsername(String username);
/**
* 添加用户
*/
SysUser addUser(UserForm form);
/**
* 修改用户
*/
SysUser editUser(UserForm form);
/**
* 删除用户
*/
void delUser(String id);
/**
* 根据 [姓名] 查找用户
*
* @param name 姓名
* @return 查找到的用户列表
*/
List<SysUser> findByName(String name);
/**
* 修改用户状态
*
* @param id 用户ID
*/
void changeStatus(String id);
/**
* 根据 [用户名] [密码] [状态] [删除标记] 查询用户
*
* @param username 用户名
* @param password 密码
* @param status 状态
* @param delFlag 删除标记
* @return 查询到的用户
*/
SysUser findByUsernameAndPasswordAndStatusNotAndDelFlagNot(String username, String password, int status, int delFlag);
List<SysUser> findAll();
/**
* 获取当前用户信息
*
* @return 当前用户信息
*/
SysUser getUserInfo(HttpServletRequest request);
}
|
<gh_stars>0
from typing import Dict
from typing import Optional
from ddtrace.internal import agent
from ddtrace.internal.dogstatsd import get_dogstatsd_client
class Metrics(object):
"""Higher-level DogStatsD interface.
This class provides automatic handling of namespaces for metrics, with the
possibility of enabling and disabling them at runtime.
Example::
The following example shows how to create the counter metric
'datadog.tracer.writer.success' and how to increment it. Note that
metrics are emitted only while the metrics object is enabled.
>>> tracer_metrics = Metrics(namespace='datadog.tracer')
>>> tracer_metrics.enable()
>>> writer_meter = dd_metrics.get_meter('writer')
>>> writer_meter.increment('success')
>>> tracer_metrics.disable()
>>> writer_meter.increment('success') # won't be emitted
"""
def __init__(self, dogstats_url=None, namespace=None):
# type: (Optional[str], Optional[str]) -> None
self.dogstats_url = dogstats_url
self.namespace = namespace
self.enabled = False
self._client = get_dogstatsd_client(dogstats_url or agent.get_stats_url(), namespace=namespace)
class Meter(object):
def __init__(self, metrics, name):
# type: (Metrics, str) -> None
self.metrics = metrics
self.name = name
def increment(self, name, value=1.0, tags=None):
# type: (str, float, Optional[Dict[str, str]]) -> None
if not self.metrics.enabled:
return None
self.metrics._client.increment(
".".join((self.name, name)), value, [":".join(_) for _ in tags.items()] if tags else None
)
def distribution(self, name, value=1.0, tags=None):
# type: (str, float, Optional[Dict[str, str]]) -> None
if not self.metrics.enabled:
return None
self.metrics._client.distribution(
".".join((self.name, name)), value, [":".join(_) for _ in tags.items()] if tags else None
)
def enable(self):
# type: () -> None
self.enabled = True
def disable(self):
# type: () -> None
self.enabled = False
def get_meter(self, name):
# type: (str) -> Metrics.Meter
return self.Meter(self, name)
|
#!/usr/bin/env sh
# This scripts downloads the CIFAR10 (binary version) data and unzips it.
DIR="$( cd "$(dirname "$0")" ; pwd -P )"
cd $DIR
echo "Downloading..."
wget --no-check-certificate http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz
echo "Unzipping..."
tar -xf cifar-10-binary.tar.gz && rm -f cifar-10-binary.tar.gz
mv cifar-10-batches-bin/* . && rm -rf cifar-10-batches-bin
# Creation is split out because leveldb sometimes causes segfault
# and needs to be re-created.
echo "Done."
|
#!/usr/bin/env bash
scp -r certs/ $1:/root/docker-wikijs/certs/
scp .env $1:/root/docker-wikijs/.env
|
<filename>electron/renderer-backend/src/index.ts
import { sendToFrontend } from "./message-bus"; // initialize the message bus
// setup the FE route
sendToFrontend({ type: "frontend_set-route", payload: "START_PAGE" });
|
<reponame>mindscms/upload-space
require('./bootstrap');
import confetti from "canvas-confetti";
Livewire.on('confetti', () => {
confetti({
particleCount: 80,
speard: 200,
origin: {y: 0.6}
});
});
|
<gh_stars>0
import { useEffect, useState, useCallback, useMemo } from 'react';
import request from 'axios';
import './App.css';
import { useRef } from 'react/cjs/react.production.min';
function App() {
const [mons, setMons] = useState([])
const [selected, setSelected] = useState(null);
const [update, setUpdate] = useState(1);
// Load monitors on initial load
useEffect(() => {
const interval = setInterval(() => {
request("/monitors")
.then(resp => {
setMons(resp.data)
})
}, 2000)
return () => clearInterval(interval)
}, []);
// Update selected monitor
const setMon = useCallback((address) => {
const mon = mons.find(m => m.address = address)
setSelected(mon)
}, [mons]);
// update active screenshot
useEffect(() => {
if (false && selected) {
// Toggle update increment between 1 and 2 instead of
// incrementing indefinitely to avoid it running to Infinity
const interval = setInterval(() => setUpdate(u => u == 1 ? 2 : 1), 950);
return () => clearInterval(interval)
}
}, [selected]);
// Get user to display in active monitor section
const userTitle = useMemo(() => {
return selected ? selected.user : null;
}, [selected]);
// Create image source urls
const urls = [];
if (selected) {
for (let i = 0; i < selected.screenCount; i++) {
urls.push(`/monitors/${selected.address}/${i}?r=${Math.random()}`);
}
}
// canvas ref
const canvas = useRef()
// Connect to websocket to receive data
useEffect(() => {
if (selected) {
const socket = new WebSocket(`wss://${window.location.host}/ws/${selected.address}/0`)
socket.onmessage = (message) => {
const ctx = canvas.current.getContext("2d")
var img = new Image();
img.onload = function() {
canvas.current.width = img.width
canvas.current.height = img.height
ctx.drawImage(img, 0, 0)
}
img.src = URL.createObjectURL(message.data);
}
socket.onopen = () => {
console.log("WS connected.");
}
socket.onclose = () => {
console.log("WS disconnected.");
}
return () => socket.close();
}
}, [selected])
// Generate image width
const imWidth = selected ? Math.min(Math.max(100 / selected.screenCount, 50), 35) : 50;
return (
<div>
<h1>Go Screen Monit</h1>
<ul>
{mons.map(mon => (
<li key={mon.address}><a href="#" onClick={setMon.bind(null, mon.address)}>{mon.user} ({mon.host} - {mon.address})</a></li>
))}
</ul>
{
userTitle && (
<>
<h2>Viewing Session: ({userTitle}) {selected && <button onClick={setSelected.bind(null, null)}>(Stop Viewing)</button>}</h2>
{/*urls.map(url => (
<img width={`${imWidth}%`} src={url} style={{ float: "left" }} />
))*/}
<canvas ref={canvas} width="800" height="600"></canvas>
</>
)
}
</div>
);
}
export default App;
|
<reponame>ColFusion/PentahoKettle
package org.rzo.netty.ahessian.rpc.server;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.rzo.netty.ahessian.Constants;
import org.rzo.netty.ahessian.rpc.message.HessianRPCCallMessage;
import org.rzo.netty.ahessian.rpc.message.HessianRPCReplyMessage;
import org.rzo.netty.ahessian.session.Session;
/**
* Default implementation of a {@link Continuation}.
*/
class DefaultContinuation implements Continuation, Constants
{
/** The service. */
private ContinuationService _service;
/** The call request message. */
private HessianRPCCallMessage _message;
/** The headers for reply message. */
private Map _headers;
/** Indicates if the continuation has been completed. */
private boolean _completed = false;
/** Time to live. */
private Date _ttl;
private Session _session = null;
/**
* Instantiates a new default continuation.
*
* @param message the message
* @param service the service
*/
DefaultContinuation(HessianRPCCallMessage message, ContinuationService service, Session session)
{
_service = service;
_message = message;
_headers = _message.getHeaders();
if (_headers == null)
_headers = new HashMap();
Long ttl = (Long) _headers.get("TTL");
if (ttl == null)
_ttl = new Date(Long.MAX_VALUE);
else
_ttl = new Date(System.currentTimeMillis() + ttl.longValue());
_headers.put(COMPLETED_HEADER_KEY, Boolean.FALSE);
_session = session;
}
/* (non-Javadoc)
* @see org.rzo.netty.ahessian.rpc.server.Continuation#complete(java.lang.Object)
*/
public void complete(Object result)
{
checkCompleted();
_completed = true;
sendReply(result, null);
}
/* (non-Javadoc)
* @see org.rzo.netty.ahessian.rpc.server.Continuation#fault(java.lang.Throwable)
*/
public void fault(Throwable result)
{
checkCompleted();
_completed = true;
sendReply(null, result);
}
/* (non-Javadoc)
* @see org.rzo.netty.ahessian.rpc.server.Continuation#getTTL()
*/
public Date getTTL()
{
return _ttl;
}
/* (non-Javadoc)
* @see org.rzo.netty.ahessian.rpc.server.Continuation#send(java.lang.Object)
*/
public void send(Object result)
{
checkCompleted();
sendReply(result, null);
}
private void checkCompleted()
{
if (_completed )
throw new RuntimeException("Continuation already completed");
if (System.currentTimeMillis() > _ttl.getTime())
{
_completed = true;
throw new RuntimeException("Continuation already completed");
}
}
private void sendReply(Object result, Object fault)
{
if (_completed)
_headers.put(COMPLETED_HEADER_KEY, Boolean.TRUE);
//TODO set reply headers
_service.writeResult(new HessianRPCReplyMessage(result, fault, _message));
}
public Session getSession()
{
return _session;
}
}
|
#!/bin/bash
# setup ssh certificate
USSH=$HOME/.ssh
mkdir -p $USSH
ssh-keygen -t rsa -N '' -f $USSH/ci_id_rsa
cat >> $USSH/config <<EOF
Host localhost
StrictHostKeyChecking no
EOF
# Allow User CI key to login as root
sudo bash <<EOF
mkdir -p /root/.ssh
cat $USSH/ci_id_rsa.pub >> /root/.ssh/authorized_keys
chmod g-rw,o-rw /root/.ssh /root/.ssh/* $USSH/* $USSH
EOF
# make sure you have a profile is set correctly
minishift profile set keptn-dev
# minimum memory required for the minishift VM
minishift config set memory 4GB
# the minimum required vCpus for the minishift vm
minishift config set cpus 2
# Add new user called admin with password admin having role cluster-admin
minishift addons enable admin-user
# Allow the containers to be run with uid 0
minishift addons enable anyuid
minishift start --vm-driver=generic --remote-ipaddress 127.0.0.1 --remote-ssh-user root --remote-ssh-key $HOME/.ssh/ci_id_rsa
# Enable admission controller webhooks
# The configuration stanzas below look weird and are just to workaround for:
# https://bugzilla.redhat.com/show_bug.cgi?id=1635918
minishift openshift config set --target=kube --patch '{
"admissionConfig": {
"pluginConfig": {
"ValidatingAdmissionWebhook": {
"configuration": {
"apiVersion": "apiserver.config.k8s.io/v1alpha1",
"kind": "WebhookAdmission",
"kubeConfigFile": "/dev/null"
}
},
"MutatingAdmissionWebhook": {
"configuration": {
"apiVersion": "apiserver.config.k8s.io/v1alpha1",
"kind": "WebhookAdmission",
"kubeConfigFile": "/dev/null"
}
}
}
}
}'
# wait until the kube-apiserver is restarted
echo "Waiting for login ..."
until oc login -u admin -p admin; do sleep 5; done;
echo "Setting policies"
oc adm policy --as system:admin add-cluster-role-to-user cluster-admin admin
oc adm policy add-cluster-role-to-user cluster-admin system:serviceaccount:default:default
oc adm policy add-cluster-role-to-user cluster-admin system:serviceaccount:kube-system:default
# wait a little bit to ensure the cluster is ready
sleep 30
|
#!/bin/sh
set -e
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
# use filter instead of exclude so missing patterns dont' throw errors
echo "rsync --delete -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync --delete -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u && exit ${PIPESTATUS[0]})
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Copies the dSYM of a vendored framework
install_dsym() {
local source="$1"
if [ -r "$source" ]; then
echo "rsync --delete -av --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DWARF_DSYM_FOLDER_PATH}\""
rsync --delete -av --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DWARF_DSYM_FOLDER_PATH}"
fi
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY}" -a "${CODE_SIGNING_REQUIRED}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identitiy
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS} --preserve-metadata=identifier,entitlements '$1'"
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
code_sign_cmd="$code_sign_cmd &"
fi
echo "$code_sign_cmd"
eval "$code_sign_cmd"
fi
}
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
# Get architectures for current file
archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | rev)"
stripped=""
for arch in $archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary" || exit 1
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/Result-watchOS/Result.framework"
install_framework "${BUILT_PRODUCTS_DIR}/RxCocoa-watchOS/RxCocoa.framework"
install_framework "${BUILT_PRODUCTS_DIR}/RxSwift-watchOS/RxSwift.framework"
install_framework "${BUILT_PRODUCTS_DIR}/RxWatchConnectivity-watchOS/RxWatchConnectivity.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/Result-watchOS/Result.framework"
install_framework "${BUILT_PRODUCTS_DIR}/RxCocoa-watchOS/RxCocoa.framework"
install_framework "${BUILT_PRODUCTS_DIR}/RxSwift-watchOS/RxSwift.framework"
install_framework "${BUILT_PRODUCTS_DIR}/RxWatchConnectivity-watchOS/RxWatchConnectivity.framework"
fi
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
wait
fi
|
<gh_stars>0
package com.gmail.gustgamer29.util.expiring;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
/**
* Map with expiring entries. Following a configured amount of time after
* an entry has been inserted, the map will act as if the entry does not
* exist.
* <p>
* Time starts counting directly after insertion. Inserting a new entry with
* a key that already has a value will "reset" the expiration. Although the
* expiration can be redefined later on, only entries which are inserted
* afterwards will use the new expiration.
* <p>
* An expiration of {@code <= 0} will make the map expire all entries
* immediately after insertion. Note that the map does not remove expired
* entries automatically; this is only done when calling
* {@link #removeExpiredEntries()}.
*
* @param <K> the key type
* @param <V> the value type
*/
public class ExpiringMap<K, V> {
private final Map<K, ExpiringEntry<V>> entries = new ConcurrentHashMap<>();
private long expirationMillis;
/**
* Constructor.
*
* @param duration the duration of time after which entries expire
* @param unit the time unit in which {@code duration} is expressed
*/
public ExpiringMap(long duration, TimeUnit unit) {
setExpiration(duration, unit);
}
/**
* Returns the value associated with the given key,
* if available and not expired.
*
* @param key the key to look up
* @return the associated value, or {@code null} if not available
*/
public V get(K key) {
ExpiringEntry<V> value = entries.get(key);
if (value == null) {
return null;
} else if (System.currentTimeMillis() > value.getExpiration()) {
entries.remove(key);
return null;
}
return value.getValue();
}
/**
* Inserts a value for the given key. Overwrites a previous value
* for the key if it exists.
*
* @param key the key to insert a value for
* @param value the value to insert
*/
public void put(K key, V value) {
long expiration = System.currentTimeMillis() + expirationMillis;
entries.put(key, new ExpiringEntry<>(value, expiration));
}
/**
* Removes the value for the given key, if available.
*
* @param key the key to remove the value for
*/
public void remove(K key) {
entries.remove(key);
}
/**
* Removes all entries which have expired from the internal structure.
*/
public void removeExpiredEntries() {
entries.entrySet().removeIf(entry -> System.currentTimeMillis() > entry.getValue().getExpiration());
}
/**
* Sets a new expiration duration. Note that already present entries
* will still make use of the old expiration.
*
* @param duration the duration of time after which entries expire
* @param unit the time unit in which {@code duration} is expressed
*/
public void setExpiration(long duration, TimeUnit unit) {
this.expirationMillis = unit.toMillis(duration);
}
/**
* Returns whether this map is empty. This reflects the state of the
* internal map, which may contain expired entries only. The result
* may change after running {@link #removeExpiredEntries()}.
*
* @return true if map is really empty, false otherwise
*/
public boolean isEmpty() {
return entries.isEmpty();
}
/**
* @return the internal map
*/
protected Map<K, ExpiringEntry<V>> getEntries() {
return entries;
}
/**
* Class holding a value paired with an expiration timestamp.
*
* @param <V> the value type
*/
protected static final class ExpiringEntry<V> {
private final V value;
private final long expiration;
ExpiringEntry(V value, long expiration) {
this.value = value;
this.expiration = expiration;
}
V getValue() {
return value;
}
long getExpiration() {
return expiration;
}
}
}
|
import React from 'react';
class Game extends React.Component {
// initial state of the game
state = {
board: [],
score: 0
};
// define the size of the game board
boardSize = 9;
// generate a random game board
generateBoard() {
let board = [];
// generate a random board
while (board.length < this.boardSize) {
board.push(Math.floor(Math.random() * 2));
}
// set the state of the board
this.setState({board});
}
handleClick(index) {
// toggle the value of the board at the specified index
let board = this.state.board.slice();
board[index] = board[index] ? 0 : 1;
// update the board
this.setState({board});
// update the score
let score = 0;
board.forEach(val => {
if (val === 1) score += 1;
});
this.setState({score});
}
render() {
// generate a game board component
let board = this.state.board.map((val, index) => {
return (
<Tile
key={index}
val={val}
handleClick={() => this.handleClick(index)}
/>
);
});
return (
<div>
{board}
<div>
Score: {this.state.score}
</div>
</div>
);
}
}
class Tile extends React.Component {
render() {
return (
<div
className="tile"
onClick={this.props.handleClick}
>
{this.props.val === 1 ? 'X' : 'O'}
</div>
);
}
} |
import cv2
def process_image(im, args, im_size_max):
if not args.crop == "True":
# scale down if bigger than max size
re_scale = (float(args.max_edge) / float(im_size_max))
im = cv2.resize(im, None, None, fx=re_scale, fy=re_scale,
interpolation=cv2.INTER_LINEAR)
global_scale = re_scale
crop_box = [0, 0, im.shape[0], im.shape[1]]
else:
# Implement the alternative operation here
# For example:
# Perform a specific image processing operation when args.crop is "True"
global_scale = 1.0
crop_box = [0, 0, im.shape[0], im.shape[1]]
return im, global_scale, crop_box |
#!/bin/bash
stty erase ^H
export PS1='[\u@\h \W]\$'
export TMOUT=21600
export TIME_STYLE='+%y-%m-%d %H:%M'
export PATH=$PATH:$HOME/bin |
-- MySQL dump 10.16 Distrib 10.1.18-MariaDB, for Linux (x86_64)
--
-- Host: localhost Database: wallgreen4
-- ------------------------------------------------------
-- Server version 10.1.18-MariaDB
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `accesos`
--
DROP TABLE IF EXISTS `accesos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `accesos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`nombre_acceso` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_ubicacion` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `accesos_deleted_at_index` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `accesos`
--
LOCK TABLES `accesos` WRITE;
/*!40000 ALTER TABLE `accesos` DISABLE KEYS */;
INSERT INTO `accesos` VALUES (1,'Accesso01',2,'2017-09-27 00:18:13','2017-09-28 03:29:52',NULL),(2,'Acceso02',4,'2017-09-27 00:29:10','2017-09-28 03:29:31',NULL),(3,'Puerta Princial',3,'2017-09-27 07:01:22','2017-09-28 03:29:43',NULL);
/*!40000 ALTER TABLE `accesos` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `departamentos`
--
DROP TABLE IF EXISTS `departamentos`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `departamentos` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`departamento` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`descripcion` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `departamentos_deleted_at_index` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `departamentos`
--
LOCK TABLES `departamentos` WRITE;
/*!40000 ALTER TABLE `departamentos` DISABLE KEYS */;
INSERT INTO `departamentos` VALUES (1,'TI','Tecnología de información','2017-09-27 11:14:44','2017-09-27 11:14:44',NULL),(2,'RH','Recursos Humanos','2017-09-27 11:14:58','2017-09-27 11:14:58',NULL);
/*!40000 ALTER TABLE `departamentos` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `items`
--
DROP TABLE IF EXISTS `items`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `items` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`item_nombre` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`item_descripcion` text COLLATE utf8mb4_unicode_ci,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `items_deleted_at_index` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `items`
--
LOCK TABLES `items` WRITE;
/*!40000 ALTER TABLE `items` DISABLE KEYS */;
INSERT INTO `items` VALUES (1,'Proyecto MD200','Proyector VGA de 200 canales ....','2017-09-27 05:25:17','2017-09-27 05:25:17',NULL),(2,'Laptop','Laptop para proyectar Dell XPS 3514 salida HDMI','2017-09-27 05:28:54','2017-09-27 05:28:54',NULL),(3,'Pintarron Grande','Pintarron Grande 2.00 mts','2017-09-27 05:29:21','2017-09-27 05:29:21',NULL),(4,'Proyecto HP','Proyector hp de 3000 lumns','2017-09-27 07:02:28','2017-09-27 07:02:28',NULL);
/*!40000 ALTER TABLE `items` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `items_seccions`
--
DROP TABLE IF EXISTS `items_seccions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `items_seccions` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`id_seccions` int(11) NOT NULL,
`id_item` int(11) NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`status` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=33 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `items_seccions`
--
LOCK TABLES `items_seccions` WRITE;
/*!40000 ALTER TABLE `items_seccions` DISABLE KEYS */;
INSERT INTO `items_seccions` VALUES (1,12,1,'2017-09-27 03:36:11',NULL),(2,12,3,'2017-09-27 03:36:11',NULL),(3,13,1,'2017-09-27 03:47:13',NULL),(4,13,2,'2017-09-27 03:47:13',NULL),(18,14,1,'2017-09-28 03:12:26',NULL),(19,14,2,'2017-09-28 03:12:26',NULL),(20,14,3,'2017-09-28 03:12:26',NULL),(21,14,4,'2017-09-28 03:12:26',NULL),(32,15,1,'2017-09-28 03:35:53',NULL);
/*!40000 ALTER TABLE `items_seccions` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `migrations`
--
DROP TABLE IF EXISTS `migrations`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `migrations` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`migration` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`batch` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=18 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `migrations`
--
LOCK TABLES `migrations` WRITE;
/*!40000 ALTER TABLE `migrations` DISABLE KEYS */;
INSERT INTO `migrations` VALUES (1,'2014_10_12_100000_create_password_resets_table',1),(2,'2017_09_25_040737_create_1506301657_roles_table',1),(3,'2017_09_25_040740_create_1506301659_users_table',1),(4,'2017_09_25_040741_add_59c856dd0d225_relationships_to_user_table',1),(5,'2017_09_25_041648_create_1506302208_reservacions_table',1),(6,'2017_09_25_044419_update_1506303859_reservacions_table',1),(7,'2017_09_25_063435_update_1506310475_reservacions_table',1),(8,'2017_09_26_034411_create_1506386651_ubicaciones_table',1),(9,'2017_09_26_035236_create_1506387156_accesos_table',1),(10,'2017_09_26_040509_create_1506387909_seccions_table',1),(11,'2017_09_26_045342_update_1506390822_users_table',1),(12,'2017_09_26_045343_add_59c9b3277b07c_relationships_to_user_table',1),(13,'2017_09_26_052706_update_1506392826_reservacions_table',1),(14,'2017_09_26_054546_update_1506393946_reservacions_table',1),(15,'2017_09_27_025600_create_1506470160_items_table',2),(16,'2017_09_27_074401_update_1506487441_users_table',3),(17,'2017_09_27_090134_create_1506492094_departamentos_table',4);
/*!40000 ALTER TABLE `migrations` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `password_resets`
--
DROP TABLE IF EXISTS `password_resets`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `password_resets` (
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`token` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
KEY `password_resets_email_index` (`email`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `password_resets`
--
LOCK TABLES `password_resets` WRITE;
/*!40000 ALTER TABLE `password_resets` DISABLE KEYS */;
/*!40000 ALTER TABLE `password_resets` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `reservacions`
--
DROP TABLE IF EXISTS `reservacions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `reservacions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`nombre_de_reunion` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`sala_de_juntas` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`comentario` text COLLATE utf8mb4_unicode_ci,
`ubicacion` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`repeat` tinyint(4) DEFAULT '0',
`hora_duracion` int(11) DEFAULT NULL,
`minuto_duracion` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `reservacions_deleted_at_index` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `reservacions`
--
LOCK TABLES `reservacions` WRITE;
/*!40000 ALTER TABLE `reservacions` DISABLE KEYS */;
INSERT INTO `reservacions` VALUES (1,'2017-09-26 07:53:55','2017-09-26 07:53:55',NULL,'Reunion kickoff','imperial','porfavor vallan a la sala de juntas',NULL,0,NULL,NULL);
/*!40000 ALTER TABLE `reservacions` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `roles`
--
DROP TABLE IF EXISTS `roles`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `roles` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `roles`
--
LOCK TABLES `roles` WRITE;
/*!40000 ALTER TABLE `roles` DISABLE KEYS */;
INSERT INTO `roles` VALUES (1,'Administrator (can create other users)','2017-09-26 07:53:55','2017-09-26 07:53:55'),(2,'Simple user','2017-09-26 07:53:55','2017-09-26 07:53:55'),(3,'Usuario de Accesos','2017-09-27 07:10:35','2017-09-27 07:10:35');
/*!40000 ALTER TABLE `roles` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `seccions`
--
DROP TABLE IF EXISTS `seccions`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `seccions` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`id_ubicacion` int(11) DEFAULT NULL,
`nombre_seccion` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`id_atributos` int(11) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `seccions_deleted_at_index` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `seccions`
--
LOCK TABLES `seccions` WRITE;
/*!40000 ALTER TABLE `seccions` DISABLE KEYS */;
INSERT INTO `seccions` VALUES (1,1,'Sala Imperial',3,'2017-09-27 01:31:20','2017-09-27 01:31:20',NULL),(2,4,'Sala prinicipal',NULL,'2017-09-27 07:03:03','2017-09-27 07:03:03',NULL),(3,2,'ássas',2,'2017-09-27 08:10:44','2017-09-27 08:36:58','2017-09-27 08:36:58'),(4,4,'sala test',1,'2017-09-27 08:11:11','2017-09-27 08:11:11',NULL),(5,2,'last',1,'2017-09-27 08:15:03','2017-09-27 08:15:03',NULL),(6,2,'last',1,'2017-09-27 08:17:24','2017-09-27 08:36:58','2017-09-27 08:36:58'),(7,2,'sala demo',3,'2017-09-27 08:18:31','2017-09-27 08:18:31',NULL),(8,1,'sala demo 44',2,'2017-09-27 08:30:01','2017-09-27 08:30:01',NULL),(9,1,'sala demo 44',2,'2017-09-27 08:33:08','2017-09-27 08:36:58','2017-09-27 08:36:58'),(10,1,'sala demo 44',2,'2017-09-27 08:33:30','2017-09-27 08:36:58','2017-09-27 08:36:58'),(11,1,'sala demo 44',2,'2017-09-27 08:34:40','2017-09-27 08:36:58','2017-09-27 08:36:58'),(12,1,'sala demo 44',2,'2017-09-27 08:36:11','2017-09-27 08:36:58','2017-09-27 08:36:58'),(13,1,'<NAME>',2,'2017-09-27 08:47:13','2017-09-27 08:47:13',NULL),(14,1,'BIG',2,'2017-09-27 09:20:16','2017-09-27 09:20:16',NULL),(15,3,'SALA EXPERIMENTO',2,'2017-09-28 08:15:46','2017-09-28 08:15:46',NULL);
/*!40000 ALTER TABLE `seccions` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `ubicaciones`
--
DROP TABLE IF EXISTS `ubicaciones`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `ubicaciones` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`nombre` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`ciudad` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`estado` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `ubicaciones_deleted_at_index` (`deleted_at`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `ubicaciones`
--
LOCK TABLES `ubicaciones` WRITE;
/*!40000 ALTER TABLE `ubicaciones` DISABLE KEYS */;
INSERT INTO `ubicaciones` VALUES (1,'Corporativo MTY','MTY','Nuevo Leon','2017-09-26 07:53:55','2017-09-27 00:27:38',NULL),(2,'Corporativo GDL','GDL','Guadalajara','2017-09-26 07:53:55','2017-09-27 00:28:39',NULL),(3,'Corporativo CDMX','CDMX','CDMX','2017-09-26 07:53:55','2017-09-27 00:28:51',NULL),(4,'Ubicacion002','MTY','Nuevo Leon','2017-09-27 07:00:49','2017-09-27 07:00:49',NULL);
/*!40000 ALTER TABLE `ubicaciones` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `users`
--
DROP TABLE IF EXISTS `users`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `users` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`email` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`password` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`remember_token` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` timestamp NULL DEFAULT NULL,
`updated_at` timestamp NULL DEFAULT NULL,
`role_id` int(10) unsigned DEFAULT NULL,
`apellido_paterno` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`apellido_materno` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
`deleted_at` timestamp NULL DEFAULT NULL,
`ubicacion` int(11) DEFAULT NULL,
`departamento` int(11) DEFAULT NULL,
`extension` varchar(191) COLLATE utf8mb4_unicode_ci NOT NULL,
PRIMARY KEY (`id`),
KEY `76436_59c856dc03987` (`role_id`),
CONSTRAINT `76436_59c856dc03987` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `users`
--
LOCK TABLES `users` WRITE;
/*!40000 ALTER TABLE `users` DISABLE KEYS */;
INSERT INTO `users` VALUES (1,'Admin','admin<EMAIL>','$2y$10$XuPH4b3YFTONjfbKNUswZO4lxP7jQKLlKthn30uhfs6diiJdYUoX2','6iBPUHPAgEboaimR6fwDtlpiIPWUcFViFC13sh6lGL48C47iX6lYd3VBGuVA','2017-09-26 07:53:55','2017-09-27 10:14:54',1,'admin','aDMIN',NULL,1,1,'111'),(2,'user','<EMAIL>','$2y$10$NFtyGYjP9UZAKZfxYbhOQOLGQeqcGGDkVLuoorjUBS3R9T4jJ/YMa',NULL,'2017-09-26 07:53:55','2017-09-26 07:53:55',2,'user','user',NULL,NULL,NULL,''),(3,'sergio','<EMAIL>','$2y$10$LNlBAuSKaZMQn1zfl8SedeSAmXdrgH7E4YeeUftnUs6stagocmUPS',NULL,'2017-09-27 11:28:00','2017-09-27 11:28:00',2,'salinas','de la garza',NULL,1,1,'311'),(4,'alvero','<EMAIL>','$2y$10$9iPOeth1Q7A8UAgH3zhzE.q7JVDyI.AF4ruI07otU/HbZmHW531YS',NULL,'2017-09-27 11:28:50','2017-09-27 11:28:50',2,'perez','perez',NULL,3,2,'620');
/*!40000 ALTER TABLE `users` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2017-10-01 21:34:35
|
CC=/usr/local/musl/bin/musl-gcc CXX=x86_64-linux-musl-g++ GOARCH=amd64 GOOS=linux CGO_ENABLED=1 go build -o gofi_client-linux-amd64 -ldflags "-linkmode external -extldflags -static" main.go
|
echo "Restarting k8s services..."
bash StopServices.sh
bash StartServices.sh
|
interface Route {
path: string;
name: string;
useAsDefault?: boolean;
}
class RouteManager {
routes: Route[];
constructor(routes: Route[]) {
this.routes = routes;
}
redirectToDefault(): void {
const defaultRoute = this.routes.find(route => route.useAsDefault);
if (defaultRoute) {
window.location.href = `#${defaultRoute.path}`;
} else {
console.error("No default route specified");
}
}
}
// Example usage
const routes: Route[] = [
{ path: "/first-part-page/", name: "FirstPartFormViewModel", useAsDefault: true },
{ path: "/second-part-page/:parameter", name: "SecondPartFormViewModel" },
{ path: "/**", name: "NestedRouteMainFormViewModel" }
];
const routeManager = new RouteManager(routes);
routeManager.redirectToDefault(); |
#!/bin/bash
################################################################################
# Copyright (c) 2021 Vladislav Trifochkin
#
# Unified build script for Linux distributions
#
# Changelog:
# 2021.05.20 Initial version
################################################################################
CMAKE_OPTIONS=
if [ -z "$BUILD_GENERATOR" ] ; then
if command -v ninja > /dev/null ; then
BUILD_GENERATOR=Ninja
else
echo "WARN: Preferable build system 'ninja' not found, use default." >&2
BUILD_GENERATOR="Unix Makefiles"
fi
fi
if [ -n $BUILD_STRICT ] ; then
case $BUILD_STRICT in
[Oo][Nn])
BUILD_STRICT=ON
;;
*)
unset BUILD_STRICT
;;
esac
fi
if [ -n "$BUILD_STRICT" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DBUILD_STRICT=$BUILD_STRICT"
fi
if [ -n "$CXX_STANDARD" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DCMAKE_CXX_STANDARD=$CXX_STANDARD"
fi
if [ -n "$C_COMPILER" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DCMAKE_C_COMPILER=$C_COMPILER"
fi
if [ -n "$CXX_COMPILER" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DCMAKE_CXX_COMPILER=$CXX_COMPILER"
fi
if [ -z "$BUILD_TYPE" ] ; then
BUILD_TYPE=Debug
fi
CMAKE_OPTIONS="$CMAKE_OPTIONS -DCMAKE_BUILD_TYPE=$BUILD_TYPE"
if [ -n $BUILD_TESTS ] ; then
case $BUILD_TESTS in
[Oo][Nn])
BUILD_TESTS=ON
;;
*)
unset BUILD_TESTS
;;
esac
fi
if [ -n "$BUILD_TESTS" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DBUILD_TESTS=$BUILD_TESTS"
fi
if [ -n $BUILD_DEMO ] ; then
case $BUILD_DEMO in
[Oo][Nn])
BUILD_DEMO=ON
;;
*)
unset BUILD_DEMO
;;
esac
fi
if [ -n "$BUILD_DEMO" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DBUILD_DEMO=$BUILD_DEMO"
fi
if [ -n $ENABLE_COVERAGE ] ; then
case $ENABLE_COVERAGE in
[Oo][Nn])
ENABLE_COVERAGE=ON
;;
*)
unset ENABLE_COVERAGE
;;
esac
fi
if [ -n "$ENABLE_COVERAGE" ] ; then
CMAKE_OPTIONS="$CMAKE_OPTIONS -DENABLE_COVERAGE=$ENABLE_COVERAGE"
fi
BUILD_DIR=builds/${CXX_COMPILER:-default}.cxx${CXX_STANDARD:-}${ENABLE_COVERAGE:+.coverage}
# We are inside source directory
if [ -d .git ] ; then
if [ -z "$ENABLE_COVERAGE" ] ; then
SOURCE_DIR=`pwd`
fi
cd ..
fi
if [ -z "$SOURCE_DIR" ] ; then
if [ -d src/.git ] ; then
SOURCE_DIR=`pwd`/src
else
echo "ERROR: SOURCE_DIR must be specified" >&2
exit 1
fi
fi
mkdir -p ${BUILD_DIR} \
&& cd ${BUILD_DIR} \
&& cmake -G "${BUILD_GENERATOR}" $CMAKE_OPTIONS $SOURCE_DIR \
&& cmake --build . \
&& [ -n "$BUILD_TESTS" ] && ctest \
&& [ -n "$ENABLE_COVERAGE" ] && cmake --build . --target Coverage
|
export default function($stateProvider) {
'ngInject';
return $stateProvider.state('root', {
abstract: true,
views: {
'@': {
template: `<ion-side-menus enable-menu-with-back-views="true">
<ion-side-menu-content>
<ion-nav-bar class="bar-positive">
<ion-nav-back-button native-transitions native-transitions-options="{type: 'slide', direction:'right'}"></ion-nav-back-button>
<ion-nav-buttons side="left">
<button menu-toggle="left" class="button button-clear">
<i class="icon ion-navicon-round"></i>
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-nav-view name="content"></ion-nav-view>
</ion-side-menu-content>
<ion-side-menu side="left" ui-view="menu"></ion-side-menu>
</ion-side-menus>`
}
}
});
}
|
import { getSession } from "./neo4j";
export const createQuery = async (query: string, parameters = {}) => {
const session = getSession();
try {
const result = await session.run(query, parameters);
session.close();
return result.records;
} catch (err) {
session.close();
console.log("");
throw err;
}
};
|
#!/bin/bash
#====================================================
#
# FILE: Download-Bin.sh
#
# USAGE: ./Download-Bin.sh
#
# DESCRIPTION:
#
# OPTIONS: ---
# REQUIREMENTS: ---
# BUGS: ---
# NOTES: ---
# AUTHOR: Brett Salemink (BS), admin@roguedesigns.us
# ORGANIZATION: Rogue Designs
# CREATED: 08/26/2018 18:19
# REVISION: ---
#====================================================
set -o nounset # Treat unset variables as an error
#------------ SOURCED ----------------
#-------------------------------------
#---------- GLOBAL VARIABLES ---------
DOWNLOADDIR=$HOME
#-------------------------------------
function Main ()
{
sudo pacman -S Syu
wait
sudo pacman -S wget unzip
wait
cd $DOWNLOADDIR
wget https://github.com/stiles69/bin/archive/master.zip
wait
unzip $DOWNLOADDIR/master.zip
sudo chmod +x $DOWNLOADDIR/bin-master
sudo rm -r $DOWNLOADDIR/master.zip
cd $HOME/bin-master/files/manjaro/Install-Scripts
./*-Install-Raspberry-Pi.sh
wait
} # end Main
Main
#===EXIT===
exit 0
|
insert into table_A
select * from table_B;
|
(function () {
'use strict';
angular.module('mvMiPedido', [])
.component('mvMiPedido', mvMiPedido())
.service('mvMiPedidoService', mvMiPedidoService)
.service('ComandaService', ComandaService);
function mvMiPedido() {
return {
bindings: {
searchFunction: '&'
},
templateUrl: window.installPath + '/mv-angular-comandas/mv-mi-pedido.html',
controller: MvMiPedidoController
}
}
MvMiPedidoController.$inject = ['ComandasService', 'UserService', '$rootScope', 'ComandaService', 'MvUtils',
'EnviosService', '$interval'];
/**
* @param MvMiPedido
* @constructor
*/
function MvMiPedidoController(ComandasService, UserService, $rootScope, ComandaService, MvUtils,
EnviosService, $interval) {
var vm = this;
vm.comandas = [];
vm.comanda = {};
vm.comensales = 1;
vm.detalles = [];
vm.title = "Dónde vas a comer?";
vm.enableReserva = false;
vm.enableDelivery = false;
vm.fecha_reserva = new Date;
vm.hora_reserva = new Date;
vm.usuario = {};
//FUNCIONES
vm.quitar = quitar;
vm.saveReserva = saveReserva;
vm.saveDelivery = saveDelivery;
vm.showReserva = showReserva;
vm.showDelivery = showDelivery;
vm.limpiarVariables = limpiarVariables;
$interval(function () {
loadComandas();
}, 10000);
function loadComandas() {
ComandasService.getByMesa(UserService.getDataFromToken('mesa_id'), UserService.getDataFromToken('session_id')).then(
function (data) {
//console.log(data);
vm.comanda = data;
}
);
}
$rootScope.$on('miPedidoRefresh', function(){
loadComandas();
/*
ComandasService.getByMesa(UserService.getDataFromToken('mesa_id'), UserService.getDataFromToken('session_id')).then(
function (data) {
//console.log(data);
vm.comanda = data;
}
);
*/
});
ComandasService.getByMesa(UserService.getDataFromToken('mesa_id'), UserService.getDataFromToken('session_id')).then(
function (data) {
//console.log(data);
vm.comanda = data;
}
);
//console.log(UserService.getFromToken().data);
/*
function quitar(comanda_detalle_id) {
ComandasService.quitar(comanda_detalle_id).then(function (data) {
ComandasService.getByMesa(UserService.getDataFromToken('mesa_id'), UserService.getDataFromToken('session_id')).then(
function (data) {
console.log(data);
vm.comanda = data;
}
);
})
}
*/
function quitar(item) {
//console.log(item);
//console.log(vm.comanda[0]);
var total = vm.comanda[0].total - (item.cantidad * item.precio);
var comanda = {
comanda_id: vm.comanda[0].comanda_id,
usuario_id: UserService.getFromToken().data.id,
status: vm.comanda[0].status,
mesa_id: UserService.getDataFromToken('mesa_id'),
total: total,
origen_id: 1
};
//console.log(comanda);
ComandasService.quitar(item.comanda_detalle_id).then(function (data) {
ComandasService.updateComanda2(comanda).then(function(data){
//console.log(data);
vm.comanda[0].total = total;
ComandasService.getByMesa(UserService.getDataFromToken('mesa_id'), UserService.getDataFromToken('session_id')).then(
function (data) {
//console.log(data);
vm.comanda = data;
vm.comanda[0].usuario_id = comanda.usuario_id;
ComandaService.comanda = comanda;
ComandaService.broadcast();
}
);
}).catch(function(error){
console.log(error);
});
}).catch(function(error){
console.log(error);
});
}
function showReserva() {
vm.title = "Reserva";
vm.enableReserva = true;
vm.enableDelivery = false;
}
function showDelivery() {
vm.title = "Delivery";
vm.enableReserva = false;
vm.enableDelivery = true;
UserService.get('0,1,2,3').then(function(user){
console.log(vm.comanda[0]);
//var encontrado = false;
var usuarios = Object.getOwnPropertyNames(user);
usuarios.forEach(function (item, index, array) {
//console.log(user[item]);
//if(user[item].usuario_id == vm.comanda[0].usuario_id) {
if(user[item].usuario_id == UserService.getFromToken().data.id) {
vm.usuario = user[item];
console.log(vm.usuario);
//encontrado = true;
}
});
}).catch(function(error){
console.log(error);
});
console.log(vm.usuario);
}
function limpiarVariables() {
vm.comensales = 1;
vm.title = "Dónde vas a comer?";
vm.enableReserva = false;
vm.enableDelivery = false;
vm.fecha_reserva = new Date;
vm.hora_reserva = new Date;
}
function saveReserva() {
if(vm.comensales <= 0) {
MvUtils.showMessage('error', 'Los comensales no pueden ser menor a 0');
return;
}
console.log(vm.fecha_reserva);
console.log(vm.hora_reserva);
var reserva_fecha = new Date(vm.fecha_reserva.getFullYear(), vm.fecha_reserva.getMonth(), vm.fecha_reserva.getDate(), vm.hora_reserva.getHours(), vm.hora_reserva.getMinutes());
console.log(reserva_fecha);
var reserva = {
comanda_id: vm.comanda[0].comanda_id,
sucursal_id: 1,
comensales: vm.comensales,
fecha: reserva_fecha,
pagado: 0 //'0-No Pagada, 1-Pagada'
};
ComandasService.createReserva(reserva).then(function(data){
//console.log(data);
limpiarVariables();
MvUtils.showMessage('success', 'Su reserva ya fue guardado. Lo esperamos');
}).catch(function(error){
console.log(error);
});
}
function saveDelivery() {
console.log(vm.usuario);
if(vm.usuario == {}) {
MvUtils.showMessage('error', 'Cliente no encontrado');
} else {
vm.detalles = vm.comanda[0].detalles;
//Creo el envio
EnviosService.save(createEnvio(vm.usuario)).then(function (data) {
//console.log(data);
limpiarVariables();
MvUtils.showMessage('success', 'Su delivery ya fue guardado. Espere su pedido');
}).catch(function (data) {
console.log(data);
});
}
/*
//rol_id = 3 clientes
UserService.get('0,1,2,3').then(function(user){
//console.log(vm.comanda[0]);
var encontrado = false;
var usuario = {};
var usuarios = Object.getOwnPropertyNames(user);
usuarios.forEach(function (item, index, array) {
//console.log(user[item]);
if(user[item].usuario_id == vm.comanda[0].usuario_id) {
usuario = user[item];
encontrado = true;
}
});
//console.log(usuario);
if(encontrado) {
vm.detalles = vm.comanda[0].detalles;
//Creo el envio
EnviosService.save(createEnvio(usuario)).then(function (data) {
//console.log(data);
limpiarVariables();
MvUtils.showMessage('success', 'Su delivery ya fue guardado. Espere su pedido');
}).catch(function (data) {
console.log(data);
});
}
//EnviosService
}).catch(function(error){
console.log(error);
});
*/
}
function createEnvio(usuario) {
var envio = {
fecha_entrega: new Date(),
usuario_id: UserService.getFromToken().data.id,
cliente_id: usuario.usuario_id,
total: vm.comanda[0].total,
//calle: usuario.direcciones[0].calle,
//nro: usuario.direcciones[0].nro,
calle: '',
nro: '',
cp: '',
forma_pago: '01',
status: 0,
descuento: 0,
detalles: []
};
envio.detalles = createEnvioDetalle();
console.log(envio);
return envio;
}
function createEnvioDetalle() {
var envios = [];
console.log(vm.detalles);
var detalles = Object.getOwnPropertyNames(vm.detalles);
detalles.forEach(function (item, index, array) {
console.log(vm.detalles[item]);
var detalle = {};
detalle.envio_id = 0;
detalle.producto_id = vm.detalles[item].producto_id;
detalle.cantidad = vm.detalles[item].cantidad;
detalle.precio = vm.detalles[item].precio;
envios.push(detalle);
});
return envios;
}
}
mvMiPedidoService.$inject = ['$rootScope'];
function mvMiPedidoService($rootScope) {
var service = this;
service.refresh = refresh;
return service;
function refresh(){
$rootScope.$broadcast('miPedidoRefresh')
}
}
ComandaService.$inject = ['$rootScope'];
function ComandaService($rootScope){
this.broadcast = function () {
$rootScope.$broadcast("ComandaService")
};
this.listen = function (callback) {
$rootScope.$on("ComandaService", callback)
};
this.comanda = {};
}
})();
|
<gh_stars>1-10
package mindustry.ui.layout;
import arc.struct.*;
import arc.math.*;
public class RadialTreeLayout implements TreeLayout{
private static ObjectSet<TreeNode> visited = new ObjectSet<>();
private static Queue<TreeNode> queue = new Queue<>();
public float startRadius, delta;
@Override
public void layout(TreeNode root){
startRadius = root.height * 2.4f;
delta = root.height * 20.4f;
bfs(root, true);
ObjectSet<TreeNode> all = new ObjectSet<>(visited);
for(TreeNode node : all){
node.leaves = bfs(node, false);
}
radialize(root, startRadius, 0, 360);
}
void radialize(TreeNode root, float radius, float from, float to){
float angle = from;
for(TreeNode child : root.children){
float nextAngle = angle + ((float)child.leaves / root.leaves * (to - from));
float x = radius * Mathf.cos((angle + nextAngle) / 2f * Mathf.degRad);
float y = radius * Mathf.sin((angle + nextAngle) / 2f * Mathf.degRad);
child.x = x;
child.y = y;
if(child.children.length > 0) radialize(child, radius + delta, angle, nextAngle);
angle = nextAngle;
}
}
int bfs(TreeNode node, boolean assign){
visited.clear();
queue.clear();
if(assign) node.number = 0;
int leaves = 0;
visited.add(node);
queue.addFirst(node);
while(!queue.isEmpty()){
TreeNode current = queue.removeFirst();
if(current.children.length == 0) leaves++;
for(TreeNode child : current.children){
if(assign) child.number = current.number + 1;
if(visited.add(child)){
queue.addLast(child);
}
}
}
return leaves;
}
}
|
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn create_constants_file(directory_path: &str, constant_value: u32) -> std::io::Result<()> {
let dst = Path::new(directory_path);
let mut f = File::create(&dst.join("constants.rs"))?;
let content = format!("pub const RESULT: u32 = {};", constant_value);
f.write_all(content.as_bytes())?;
Ok(())
}
fn main() {
// Example usage
if let Err(err) = create_constants_file("/path/to/directory", 42) {
eprintln!("Error: {}", err);
} else {
println!("File created successfully!");
}
} |
export { default } from "./PaymentResponse";
|
<filename>src/features/messageCreate/spy.js
const icons = require('../../icons');
const {APIErrors} = require('discord.js').Constants;
exports.event = async (options, message) => {
if (!message.author.bot && message.content.includes(options.bot.user.id) || message.content.toLowerCase().includes(options.bot.user.username.toLowerCase())) {
try {
await message.react(icons.eyes);
}
catch (e) {
if (e.code !== APIErrors.UNKNOWN_MESSAGE) {
throw e;
}
}
}
};
|
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { map, catchError, tap } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class RestService {
constructor(private http: HttpClient) {
}
private extractData(res: Response) {
let body = res;
return body || {};
}
getEmployees(): Observable<any> {
return this.http.get(endpoint + 'employees').pipe(
map(this.extractData));
}
getEmployee(id): Observable<any> {
return this.http.get(endpoint + 'employees/' + id).pipe(
map(this.extractData));
}
addEmployee(employee): Observable<any> {
return this.http.post<any>(endpoint + 'employees', JSON.stringify(employee), httpOptions).pipe(
tap((employee) => console.log(`added employee w/ id=${employee.id}`)),
catchError(this.handleError<any>('addEmployee'))
);
}
updateEmployee(id, employee): Observable<any> {
const newEmployee = {
id: employee.id,
name: employee.name,
department: employee.department
}
return this.http.put(endpoint + 'employees/' + id, JSON.stringify(newEmployee), httpOptions).pipe(
tap(_ => console.log(`updated employee id=${id}`)),
catchError(this.handleError<any>('updateEmployee'))
);
}
deleteEmployee(id): Observable<any> {
return this.http.delete<any>(endpoint + 'employees/' + id, httpOptions).pipe(
tap(_ => console.log(`deleted employee id=${id}`)),
catchError(this.handleError<any>('deleteEmployee'))
);
}
private handleError<T>(operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
console.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
const endpoint = 'http://localhost:3000/api/';
const httpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
}; |
# if which cygpath >& /dev/null; then
# Starts the Atom editor. It assumes that Atom is in the path
#
# Note that to call this function for xargs, do the following:
#
# find -maxdepth 1 -type f | xargs zsh -lic "(){$functions[atom];}"' "$@"' zsh "$@" \;
#
atom() {
if ! which cygpath >& /dev/null; then
# Probably not running on Windows
atom "$@"
return
fi
# Separate flags from file arguments
while getopts ":?" opt; do
case $opt in
\?)
if [ -z $flags ]; then
local flags="-$OPTARG"
else
local flags="$flags -$OPTARG"
fi
;;
esac
done
shift $(($OPTIND - 1))
cygpath -a -w "$@" | tr -s '\n' '\0' | xargs --null "$LOCALAPPDATA/atom/bin/atom" "$flags"
}
|
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.naive_bayes import MultinomialNB
# Create a CountVectorizer and fit it to our data
vectorizer = CountVectorizer()
X = vectorizer.fit_transform(documents)
# Create a model and fit it to our data
model = MultinomialNB()
model.fit(X, labels) |
export type BackGroundColorType = "#932C16" | "#CE4B39" | "#EB6439"
| "#F1BD6A" | "#FFB500" | "#FFD80C"
| "#FFE199" | "#0B5A0E" | "#728F60"
| "#8EDA43" | "#99B6FF" | "#0048FF"
| "#ADA1F6" | "#502B8B" | "#99E0FF"
| "#F2B9D6" | "#E1C3BC" | "#E0E0E0"
| "#B4B4B4" | "#5F5F5F" | "#3A3A3A"
export const BackgroundColorListArray: BackGroundColorType[] = [
"#932C16", "#CE4B39", "#EB6439"
, "#F1BD6A", "#FFB500", "#FFD80C"
, "#FFE199", "#0B5A0E", "#728F60"
, "#8EDA43", "#99B6FF", "#0048FF"
, "#ADA1F6", "#502B8B", "#99E0FF"
, "#F2B9D6", "#E1C3BC", "#E0E0E0"
, "#B4B4B4", "#5F5F5F", "#3A3A3A"
]
export interface LinkListProps {
index: number;
isInput: boolean;
} |
#!/bin/sh
set -e
set -u
set -o pipefail
function on_error {
echo "$(realpath -mq "${0}"):$1: error: Unexpected failure"
}
trap 'on_error $LINENO' ERR
if [ -z ${FRAMEWORKS_FOLDER_PATH+x} ]; then
# If FRAMEWORKS_FOLDER_PATH is not set, then there's nowhere for us to copy
# frameworks to, so exit 0 (signalling the script phase was successful).
exit 0
fi
echo "mkdir -p ${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
mkdir -p "${CONFIGURATION_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
COCOAPODS_PARALLEL_CODE_SIGN="${COCOAPODS_PARALLEL_CODE_SIGN:-false}"
SWIFT_STDLIB_PATH="${DT_TOOLCHAIN_DIR}/usr/lib/swift/${PLATFORM_NAME}"
BCSYMBOLMAP_DIR="BCSymbolMaps"
# This protects against multiple targets copying the same framework dependency at the same time. The solution
# was originally proposed here: https://lists.samba.org/archive/rsync/2008-February/020158.html
RSYNC_PROTECT_TMP_FILES=(--filter "P .*.??????")
# Copies and strips a vendored framework
install_framework()
{
if [ -r "${BUILT_PRODUCTS_DIR}/$1" ]; then
local source="${BUILT_PRODUCTS_DIR}/$1"
elif [ -r "${BUILT_PRODUCTS_DIR}/$(basename "$1")" ]; then
local source="${BUILT_PRODUCTS_DIR}/$(basename "$1")"
elif [ -r "$1" ]; then
local source="$1"
fi
local destination="${TARGET_BUILD_DIR}/${FRAMEWORKS_FOLDER_PATH}"
if [ -L "${source}" ]; then
echo "Symlinked..."
source="$(readlink "${source}")"
fi
if [ -d "${source}/${BCSYMBOLMAP_DIR}" ]; then
# Locate and install any .bcsymbolmaps if present, and remove them from the .framework before the framework is copied
find "${source}/${BCSYMBOLMAP_DIR}" -name "*.bcsymbolmap"|while read f; do
echo "Installing $f"
install_bcsymbolmap "$f" "$destination"
rm "$f"
done
rmdir "${source}/${BCSYMBOLMAP_DIR}"
fi
# Use filter instead of exclude so missing patterns don't throw errors.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${destination}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${destination}"
local basename
basename="$(basename -s .framework "$1")"
binary="${destination}/${basename}.framework/${basename}"
if ! [ -r "$binary" ]; then
binary="${destination}/${basename}"
elif [ -L "${binary}" ]; then
echo "Destination binary is symlinked..."
dirname="$(dirname "${binary}")"
binary="${dirname}/$(readlink "${binary}")"
fi
# Strip invalid architectures so "fat" simulator / device frameworks work on device
if [[ "$(file "$binary")" == *"dynamically linked shared library"* ]]; then
strip_invalid_archs "$binary"
fi
# Resign the code if required by the build settings to avoid unstable apps
code_sign_if_enabled "${destination}/$(basename "$1")"
# Embed linked Swift runtime libraries. No longer necessary as of Xcode 7.
if [ "${XCODE_VERSION_MAJOR}" -lt 7 ]; then
local swift_runtime_libs
swift_runtime_libs=$(xcrun otool -LX "$binary" | grep --color=never @rpath/libswift | sed -E s/@rpath\\/\(.+dylib\).*/\\1/g | uniq -u)
for lib in $swift_runtime_libs; do
echo "rsync -auv \"${SWIFT_STDLIB_PATH}/${lib}\" \"${destination}\""
rsync -auv "${SWIFT_STDLIB_PATH}/${lib}" "${destination}"
code_sign_if_enabled "${destination}/${lib}"
done
fi
}
# Copies and strips a vendored dSYM
install_dsym() {
local source="$1"
warn_missing_arch=${2:-true}
if [ -r "$source" ]; then
# Copy the dSYM into the targets temp dir.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${source}\" \"${DERIVED_FILES_DIR}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${source}" "${DERIVED_FILES_DIR}"
local basename
basename="$(basename -s .dSYM "$source")"
binary_name="$(ls "$source/Contents/Resources/DWARF")"
binary="${DERIVED_FILES_DIR}/${basename}.dSYM/Contents/Resources/DWARF/${binary_name}"
# Strip invalid architectures from the dSYM.
if [[ "$(file "$binary")" == *"Mach-O "*"dSYM companion"* ]]; then
strip_invalid_archs "$binary" "$warn_missing_arch"
fi
if [[ $STRIP_BINARY_RETVAL == 0 ]]; then
# Move the stripped file into its final destination.
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter \"- CVS/\" --filter \"- .svn/\" --filter \"- .git/\" --filter \"- .hg/\" --filter \"- Headers\" --filter \"- PrivateHeaders\" --filter \"- Modules\" \"${DERIVED_FILES_DIR}/${basename}.framework.dSYM\" \"${DWARF_DSYM_FOLDER_PATH}\""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --links --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${DERIVED_FILES_DIR}/${basename}.dSYM" "${DWARF_DSYM_FOLDER_PATH}"
else
# The dSYM was not stripped at all, in this case touch a fake folder so the input/output paths from Xcode do not reexecute this script because the file is missing.
touch "${DWARF_DSYM_FOLDER_PATH}/${basename}.dSYM"
fi
fi
}
# Used as a return value for each invocation of `strip_invalid_archs` function.
STRIP_BINARY_RETVAL=0
# Strip invalid architectures
strip_invalid_archs() {
binary="$1"
warn_missing_arch=${2:-true}
# Get architectures for current target binary
binary_archs="$(lipo -info "$binary" | rev | cut -d ':' -f1 | awk '{$1=$1;print}' | rev)"
# Intersect them with the architectures we are building for
intersected_archs="$(echo ${ARCHS[@]} ${binary_archs[@]} | tr ' ' '\n' | sort | uniq -d)"
# If there are no archs supported by this binary then warn the user
if [[ -z "$intersected_archs" ]]; then
if [[ "$warn_missing_arch" == "true" ]]; then
echo "warning: [CP] Vendored binary '$binary' contains architectures ($binary_archs) none of which match the current build architectures ($ARCHS)."
fi
STRIP_BINARY_RETVAL=1
return
fi
stripped=""
for arch in $binary_archs; do
if ! [[ "${ARCHS}" == *"$arch"* ]]; then
# Strip non-valid architectures in-place
lipo -remove "$arch" -output "$binary" "$binary"
stripped="$stripped $arch"
fi
done
if [[ "$stripped" ]]; then
echo "Stripped $binary of architectures:$stripped"
fi
STRIP_BINARY_RETVAL=0
}
# Copies the bcsymbolmap files of a vendored framework
install_bcsymbolmap() {
local bcsymbolmap_path="$1"
local destination="${BUILT_PRODUCTS_DIR}"
echo "rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}""
rsync --delete -av "${RSYNC_PROTECT_TMP_FILES[@]}" --filter "- CVS/" --filter "- .svn/" --filter "- .git/" --filter "- .hg/" --filter "- Headers" --filter "- PrivateHeaders" --filter "- Modules" "${bcsymbolmap_path}" "${destination}"
}
# Signs a framework with the provided identity
code_sign_if_enabled() {
if [ -n "${EXPANDED_CODE_SIGN_IDENTITY:-}" -a "${CODE_SIGNING_REQUIRED:-}" != "NO" -a "${CODE_SIGNING_ALLOWED}" != "NO" ]; then
# Use the current code_sign_identity
echo "Code Signing $1 with Identity ${EXPANDED_CODE_SIGN_IDENTITY_NAME}"
local code_sign_cmd="/usr/bin/codesign --force --sign ${EXPANDED_CODE_SIGN_IDENTITY} ${OTHER_CODE_SIGN_FLAGS:-} --preserve-metadata=identifier,entitlements '$1'"
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
code_sign_cmd="$code_sign_cmd &"
fi
echo "$code_sign_cmd"
eval "$code_sign_cmd"
fi
}
if [[ "$CONFIGURATION" == "Debug" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/SwiftyGif/SwiftyGif.framework"
install_framework "${BUILT_PRODUCTS_DIR}/XYZPathKit/XYZPathKit.framework"
install_framework "${BUILT_PRODUCTS_DIR}/XYZTimeKit/XYZTimeKit.framework"
fi
if [[ "$CONFIGURATION" == "Release" ]]; then
install_framework "${BUILT_PRODUCTS_DIR}/SwiftyGif/SwiftyGif.framework"
install_framework "${BUILT_PRODUCTS_DIR}/XYZPathKit/XYZPathKit.framework"
install_framework "${BUILT_PRODUCTS_DIR}/XYZTimeKit/XYZTimeKit.framework"
fi
if [ "${COCOAPODS_PARALLEL_CODE_SIGN}" == "true" ]; then
wait
fi
|
<reponame>lostmsu/RoboZZle-Droid<gh_stars>1-10
/**
*
*/
package com.team242.robozzle;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import androidx.appcompat.widget.SearchView;
import androidx.appcompat.widget.Toolbar;
import android.text.InputType;
import android.view.*;
import android.view.MenuItem.OnMenuItemClickListener;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import com.team242.robozzle.achievements.Achievement;
import com.team242.robozzle.achievements.BraveHeartAchievement;
import com.team242.robozzle.achievements.CowardAchievement;
import com.team242.robozzle.model.Puzzle;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
/**
* @author lost
*
*/
public class UnsolvedPuzzles extends GenericPuzzleActivity {
private PuzzleAdapter adapter;
ListView puzzles;
@Override
protected void onDestroy() {
if (adapter != null)
adapter.cancel();
super.onDestroy();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.puzzles);
lowMemoryCheck();
puzzles = (ListView)findViewById(R.id.puzzles);
Toolbar toolbar = (Toolbar)findViewById(R.id.puzzlesToolbar);
this.setSupportActionBar(toolbar);
adapter = new PuzzleAdapter(this);
boolean showSolved = pref.getBoolean(RoboZZleSettings.SHOW_SOLVED, true);
boolean hideUnpopular = pref.getBoolean(RoboZZleSettings.HIDE_UNPOPULAR, true);
if (!pref.contains(RoboZZleSettings.ROB_AI_TELEMETRY_ENABLED)){
this.showResearchSuggestionDialog();
} else if (!loggedIn()){
Toast.makeText(this, R.string.must_sign_in, Toast.LENGTH_LONG).show();
this.showLoginDialog();
}
adapter.setShowSolved(showSolved);
adapter.setHideUnpopular(hideUnpopular);
try {
if (adapter.getTutorialCount() == 0)
adapter.createInitialPuzzles();
if (adapter.getCount() <= adapter.getTutorialCount()) {
adapter.updatePuzzles((LinearLayout)findViewById(R.id.syncPane), RobozzleWebClient.SortKind.POPULAR);
}
} catch (SQLException e) {
// TODO: report exception
throw new RuntimeException(e);
}
puzzles.setAdapter(adapter);
puzzles.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> view, View baseView, int itemIndex,
long itemID) {
openPuzzle((int) itemID);
}
});
}
private void showResearchSuggestionDialog() {
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.research_participation_dialog);
dialog.setTitle(R.string.researchDialogTitle);
View acceptButton = dialog.findViewById(R.id.accept);
View declineButton = dialog.findViewById(R.id.decline);
acceptButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Editor prefEditor = pref.edit();
prefEditor.putBoolean(RoboZZleSettings.ROB_AI_TELEMETRY_ENABLED, true);
prefEditor.putBoolean(RoboZZleSettings.AUTO_SOLUTION_SUBMIT, true);
prefEditor.commit();
if (!loggedIn())
showLoginDialog();
dialog.dismiss();
}
});
declineButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Editor prefEditor = pref.edit();
prefEditor.putBoolean(RoboZZleSettings.ROB_AI_TELEMETRY_ENABLED, false);
prefEditor.commit();
dialog.dismiss();
}
});
dialog.show();
}
private void showLoginDialog() {
LoginDialog loginDialog = new LoginDialog(this);
loginDialog.pref = this.pref;
loginDialog.show();
}
private static void preallocate(){
boolean oom = false;
int size = 128*1024;
while (!oom){
try{
byte[] block = new byte[size];
size *= 2;
block[0] = 1;
block[block.length - 1] = -1;
}catch (OutOfMemoryError error){
oom = true;
}
}
}
private void lowMemoryCheck() {
if (pref.contains(RoboZZleSettings.THUMBNAIL_MEMORY_USAGE)){
switch (Integer.parseInt(pref.getString(RoboZZleSettings.THUMBNAIL_MEMORY_USAGE, "0"))){
case 0:
thumbnailMemoryUsage = ThumbnailMemoryUsage.Normal;
break;
case 1:
thumbnailMemoryUsage = ThumbnailMemoryUsage.Limited;
break;
case -1:
thumbnailMemoryUsage = ThumbnailMemoryUsage.Disabled;
break;
}
} else {
preallocate();
Runtime runtime = Runtime.getRuntime();
Editor editor = pref.edit();
if (runtime.maxMemory() <= 16*1024*1024){
thumbnailMemoryUsage = ThumbnailMemoryUsage.Limited;
editor.putString(RoboZZleSettings.THUMBNAIL_MEMORY_USAGE, "1");
Toast.makeText(this, R.string.lowMemMode, Toast.LENGTH_LONG).show();
} else{
thumbnailMemoryUsage = ThumbnailMemoryUsage.Normal;
editor.putString(RoboZZleSettings.THUMBNAIL_MEMORY_USAGE, "0");
}
editor.commit();
}
}
private void openPuzzle(int puzzleID) {
openPuzzle(puzzleID, Solver.class);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (intent == null) return;
if (intent.hasExtra(Intents.PUZZLE_SOLVED)){
int puzzleID = intent.getIntExtra(Intents.PUZZLE_SOLVED, 0);
final Puzzle puzzle = refreshPuzzle(puzzleID);
checkAchievements();
if (puzzleID < 0) return;
if (!pref.getBoolean(RoboZZleSettings.AUTO_SOLUTION_SUBMIT, true)) return;
submitSolution(puzzle);
}
if (intent.hasExtra(Intents.PUZZLE_SCARY)) {
int puzzleID = intent.getIntExtra(Intents.PUZZLE_SCARY, 0);
refreshPuzzle(puzzleID);
checkAchievements(new Achievement[]{CowardAchievement.Instance, BraveHeartAchievement.Instance});
}
}
private Puzzle refreshPuzzle(int puzzleID){
int childCount = puzzles.getChildCount();
View view;
final Puzzle puzzle = getPuzzle(puzzleID);
for(int i = 0; i < childCount; i++){
view = puzzles.getChildAt(i);
if (view == null) continue;
Puzzle viewPuzzle = (Puzzle)view.getTag();
if (viewPuzzle.id == puzzleID) {
adapter.setPuzzle(view, puzzle);
adapter.refresh(puzzle);
break;
}
}
return puzzle;
}
private void submitSolution(final Puzzle puzzle) {
final String login = pref.getString(RoboZZleSettings.LOGIN, "");
final String password = pref.getString(RoboZZleSettings.PASSWORD, "");
if (login.equals("") || password.equals("")){
Toast.makeText(this, R.string.provideLogin, Toast.LENGTH_LONG);
return;
}
AsyncTask<Void, Void, Void> submitter = new AsyncTask<Void, Void, Void>() {
int message = R.string.solutionsSynchronized;
@Override
protected void onPostExecute(Void result) {
if (isCancelled()) return;
Toast.makeText(UnsolvedPuzzles.this, message, Toast.LENGTH_LONG).show();
}
@Override
protected Void doInBackground(Void... params) {
RobozzleWebClient webClient = new RobozzleWebClient();
try{
String solution = puzzle.getSolutionProgram().getProgram().replace("__", "");
String result = webClient.SubmitSolution(puzzle.id, login, password, solution);
if (result != null){
Exception error = new InvalidAlgorithmParameterException("Solution " + solution +
" does not fits puzzle " + puzzle.title + " according to RoboZZle.com");
// TODO: report exception
}
}catch (NoSuchAlgorithmException e) {
// TODO: report exception
message = R.string.loginHashNotSupported;
} catch (IOException e) {
message = R.string.robozzleComIOError;
} catch (XmlPullParserException e) {
message = R.string.loginCantParseServerResponse;
}
return null;
}
};
submitter.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.puzzle_list_menu, menu);
MenuItem update = menu.findItem(R.id.updatePuzzles);
update.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
updatePuzzles();
return true;
}
});
MenuItem share = menu.findItem(R.id.shareSolutions);
share.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
shareSolutions();
return true;
}
});
MenuItem showSolved = menu.findItem(R.id.filterSolved);
showSolved.setIcon(pref.getBoolean(RoboZZleSettings.SHOW_SOLVED, true)
? android.R.drawable.presence_online
: android.R.drawable.presence_invisible);
showSolved.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
boolean showSolved = pref.getBoolean(RoboZZleSettings.SHOW_SOLVED, true);
showSolved = !showSolved;
Editor edior = pref.edit();
edior.putBoolean(RoboZZleSettings.SHOW_SOLVED, showSolved);
item.setIcon(showSolved? android.R.drawable.presence_online: android.R.drawable.presence_invisible);
adapter.setShowSolved(showSolved);
edior.commit();
return true;
}
});
MenuItem hideUnpopular = menu.findItem(R.id.filterPopular);
hideUnpopular.setIcon(pref.getBoolean(RoboZZleSettings.HIDE_UNPOPULAR, true)
? android.R.drawable.star_on
: android.R.drawable.star_off);
hideUnpopular.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
boolean hideUnpopular = pref.getBoolean(RoboZZleSettings.HIDE_UNPOPULAR, true);
hideUnpopular = !hideUnpopular;
Editor editor = pref.edit();
editor.putBoolean(RoboZZleSettings.HIDE_UNPOPULAR, hideUnpopular);
item.setIcon(hideUnpopular? android.R.drawable.star_on: android.R.drawable.star_off);
adapter.setHideUnpopular(hideUnpopular);
editor.commit();
return true;
}
});
MenuItem showSettings = menu.findItem(R.id.showSettings);
showSettings.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
showSetting();
return true;
}
});
MenuItem jumpTo = menu.findItem(R.id.openCustomPuzzle);
jumpTo.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem menuItem) {
openCustomPuzzle();
return true;
}
});
MenuItem recheckAchievements = menu.findItem(R.id.checkAchievements);
recheckAchievements.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
openAchievements();
return true;
}
});
MenuItem about = menu.findItem(R.id.about);
about.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
showAbout();
return true;
}
});
MenuItem search = menu.findItem(R.id.action_search);
try {
SearchView searchView = (SearchView)search.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
adapter.setQueryString(query);
return true;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.setQueryString(newText);
return true;
}
});
searchView.setOnCloseListener(new SearchView.OnCloseListener() {
@Override
public boolean onClose() {
adapter.setQueryString(null);
return false;
}
});
}catch (NoSuchMethodError e){
search.setEnabled(false);
}
return true;
}
private void showAbout(){
Intent i = new Intent(UnsolvedPuzzles.this, AboutActivity.class);
startActivity(i);
}
private void showSetting() {
Intent i = new Intent(UnsolvedPuzzles.this, RoboZZleSettings.class);
startActivity(i);
}
private void shareSolutions() {
String login = pref.getString(RoboZZleSettings.LOGIN, "");
String password = pref.getString(RoboZZleSettings.PASSWORD, "");
if (login.length() == 0 || password.length() == 0) {
Toast.makeText(this, R.string.provideLogin, Toast.LENGTH_LONG).show();
this.showLoginDialog();
return;
}
if (adapter.isSynchronizing()){
Toast.makeText(this, R.string.alreadySynchronizing, Toast.LENGTH_SHORT).show();
return;
}
adapter.shareSolutions();
}
private void updatePuzzles() {
if (adapter.isSynchronizing()){
Toast.makeText(this, R.string.alreadySynchronizing, Toast.LENGTH_SHORT).show();
return;
}
View syncPane = findViewById(R.id.syncPane);
boolean hideUnpopular = pref.getBoolean(RoboZZleSettings.HIDE_UNPOPULAR, true);
RobozzleWebClient.SortKind sortKind = hideUnpopular
? RobozzleWebClient.SortKind.POPULAR
: RobozzleWebClient.SortKind.DESCENDING_ID;
adapter.updatePuzzles((LinearLayout)syncPane, sortKind);
}
private void openCustomPuzzle(){
final EditText alertInput = new EditText(this);
alertInput.setInputType(InputType.TYPE_CLASS_NUMBER);
AlertDialog.Builder alert =
new AlertDialog.Builder(this)
.setTitle(R.string.jump_to_puzzle)
.setMessage(R.string.prompt_puzzle_id)
.setView(alertInput)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
int puzzleID = Integer.parseInt(alertInput.getText().toString());
Puzzle puzzle = getHelper().getPuzzlesDAO().queryForId(puzzleID);
if (puzzle == null)
Toast.makeText(UnsolvedPuzzles.this,
R.string.invalidPuzzleID,
Toast.LENGTH_LONG).show();
else
openPuzzle(puzzleID);
} catch (NumberFormatException e) {
Toast.makeText(UnsolvedPuzzles.this, e.getLocalizedMessage(), Toast.LENGTH_LONG).show();
} catch (SQLException e){
e.printStackTrace();
throw new RuntimeException(e);
}
}
})
.setNegativeButton(R.string.cancel, null);
AlertDialog dialog = alert.create();
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.