text
stringlengths
1
1.05M
/* * Copyright 2017 Nafundi * * 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.odk.collect.android.fragments.dialogs; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.NumberPicker; import android.widget.TextView; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.DialogFragment; import androidx.lifecycle.ViewModelProvider; import org.joda.time.LocalDateTime; import org.odk.collect.android.R; import org.odk.collect.android.logic.DatePickerDetails; import org.odk.collect.android.utilities.DateTimeUtils; import org.odk.collect.android.widgets.utilities.DateTimeWidgetUtils; import org.odk.collect.android.widgets.viewmodels.DateTimeViewModel; /** * @author <NAME> (<EMAIL>) */ public abstract class CustomDatePickerDialog extends DialogFragment { private NumberPicker dayPicker; private NumberPicker monthPicker; private NumberPicker yearPicker; private TextView gregorianDateText; private DateTimeViewModel viewModel; private DateChangeListener dateChangeListener; public interface DateChangeListener { void onDateChanged(LocalDateTime selectedDate); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof DateChangeListener) { dateChangeListener = (DateChangeListener) context; } viewModel = new ViewModelProvider(this).get(DateTimeViewModel.class); if (viewModel.getLocalDateTime() == null) { viewModel.setLocalDateTime((LocalDateTime) getArguments().getSerializable(DateTimeWidgetUtils.DATE)); } viewModel.setDatePickerDetails((DatePickerDetails) getArguments().getSerializable(DateTimeWidgetUtils.DATE_PICKER_DETAILS)); viewModel.getSelectedDate().observe(this, localDateTime -> { if (localDateTime != null) { dateChangeListener.onDateChanged(localDateTime); } }); } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { return new AlertDialog.Builder(getActivity()) .setTitle(R.string.select_date) .setView(R.layout.custom_date_picker_dialog) .setPositiveButton(R.string.ok, (dialog, id) -> { LocalDateTime date = DateTimeUtils.getDateAsGregorian(getOriginalDate()); viewModel.setSelectedDate(date.getYear(), date.getMonthOfYear() - 1, date.getDayOfMonth()); dismiss(); }) .setNegativeButton(R.string.cancel, (dialog, id) -> dismiss()) .create(); } @Override public void onDestroyView() { viewModel.setLocalDateTime(DateTimeUtils.getDateAsGregorian(getOriginalDate())); super.onDestroyView(); } @Override public void onResume() { super.onResume(); gregorianDateText = getDialog().findViewById(R.id.date_gregorian); setUpPickers(); } private void setUpPickers() { dayPicker = getDialog().findViewById(R.id.day_picker); dayPicker.setOnValueChangedListener((picker, oldVal, newVal) -> updateGregorianDateLabel()); monthPicker = getDialog().findViewById(R.id.month_picker); monthPicker.setOnValueChangedListener((picker, oldVal, newVal) -> monthUpdated()); yearPicker = getDialog().findViewById(R.id.year_picker); yearPicker.setOnValueChangedListener((picker, oldVal, newVal) -> yearUpdated()); hidePickersIfNeeded(); } private void hidePickersIfNeeded() { if (viewModel.getDatePickerDetails().isMonthYearMode()) { dayPicker.setVisibility(View.GONE); } else if (viewModel.getDatePickerDetails().isYearMode()) { dayPicker.setVisibility(View.GONE); monthPicker.setVisibility(View.GONE); } } protected void updateGregorianDateLabel() { String label = DateTimeWidgetUtils.getDateTimeLabel(DateTimeUtils.getDateAsGregorian(getOriginalDate()).toDate(), viewModel.getDatePickerDetails(), false, getContext()); gregorianDateText.setText(label); } protected void setUpDayPicker(int dayOfMonth, int daysInMonth) { setUpDayPicker(1, dayOfMonth, daysInMonth); } protected void setUpDayPicker(int minDay, int dayOfMonth, int daysInMonth) { dayPicker.setMinValue(minDay); dayPicker.setMaxValue(daysInMonth); if (viewModel.getDatePickerDetails().isSpinnerMode()) { dayPicker.setValue(dayOfMonth); } } protected void setUpMonthPicker(int monthOfYear, String[] monthsArray) { // In Myanmar calendar we don't have specified amount of months, it's dynamic so clear // values first to avoid ArrayIndexOutOfBoundsException monthPicker.setDisplayedValues(null); monthPicker.setMaxValue(monthsArray.length - 1); monthPicker.setDisplayedValues(monthsArray); if (!viewModel.getDatePickerDetails().isYearMode()) { monthPicker.setValue(monthOfYear - 1); } } protected void setUpYearPicker(int year, int minSupportedYear, int maxSupportedYear) { yearPicker.setMinValue(minSupportedYear); yearPicker.setMaxValue(maxSupportedYear); yearPicker.setValue(year); } protected void monthUpdated() { updateDays(); updateGregorianDateLabel(); } protected void yearUpdated() { updateDays(); updateGregorianDateLabel(); } public int getDay() { return dayPicker.getValue(); } public String getMonth() { return monthPicker.getDisplayedValues()[monthPicker.getValue()]; } public int getMonthId() { return monthPicker.getValue(); } public int getYear() { return yearPicker.getValue(); } public LocalDateTime getDate() { return getDay() == 0 ? viewModel.getLocalDateTime() : getOriginalDate(); } protected abstract void updateDays(); protected abstract LocalDateTime getOriginalDate(); }
<reponame>lionelpa/openvalidation<filename>openvalidation-common/src/main/java/io/openvalidation/common/unittesting/astassertion/lists/OperandListAssertion.java /* * Copyright 2019 <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 io.openvalidation.common.unittesting.astassertion.lists; import io.openvalidation.common.ast.ASTModel; import io.openvalidation.common.ast.operand.ASTOperandBase; import io.openvalidation.common.unittesting.astassertion.ASTAssertionBase; import io.openvalidation.common.unittesting.astassertion.ASTListAssertionBase; import io.openvalidation.common.unittesting.astassertion.FunctionAssertion; import io.openvalidation.common.unittesting.astassertion.OperandAssertion; public class OperandListAssertion extends ASTListAssertionBase<ASTOperandBase, OperandAssertion, ASTAssertionBase> { public OperandListAssertion(String name, ASTModel ast, ASTAssertionBase parent) { super(name, ast, parent); } public FunctionAssertion parentFunction() { shouldBeInstanceOf(this.parent(), FunctionAssertion.class, "PARENT FUNCTION"); return (FunctionAssertion) this.parent(); } }
public class ExampleWhile { public static void main(String[] args) { int x = 5; while(x<=50) { System.out.println("X is equal to "+x); x += 5; } } }
//Morse Code encoding function function convertToMorse (text) { //object containing alphabets and their corresponding Morse representations const MorseCode = { 'A': '.-', 'B': '-...', 'C': '-.-.', 'D': '-..', 'E': '.', 'F': '..-.', 'G': '--.', 'H': '....', 'I': '..', 'J': '.---', 'K': '-.-', 'L': '.-..', 'M': '--', 'N': '-.', 'O': '---', 'P': '.--.', 'Q': '--.-', 'R': '.-.', 'S': '...', 'T': '-', 'U': '..-', 'V': '...-', 'W': '.--', 'X': '-..-', 'Y': '-.--', 'Z': '--..' }; let output = ''; //Loop through the text for (let i=0; i<text.length; i++) { //If the character is present in the MorseCode object if (MorseCode[text[i]] !== undefined) { // Add the corresponding Morse code for the character output += MorseCode[text[i]] + ' '; } } return output.trim(); } //Test let inputText = 'HELLO WORLD'; console.log(convertToMorse(inputText)); // .... . .-.. .-.. --- .-- --- .-. .-.. -..
<reponame>chipsi/GasMileage package net.alteridem.mileage.dialogs; import android.app.DialogFragment; import android.text.format.DateFormat; import android.view.KeyEvent; import android.view.View; import android.view.WindowManager; import android.view.inputmethod.EditorInfo; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import net.alteridem.mileage.IDateReceiver; import net.alteridem.mileage.MileageApplication; import net.alteridem.mileage.MileagePreferences_; import net.alteridem.mileage.R; import net.alteridem.mileage.adapters.VehicleSpinnerAdapter; import net.alteridem.mileage.data.Entry; import net.alteridem.mileage.data.Vehicle; import net.alteridem.mileage.fragments.DatePickerFragment; import net.alteridem.mileage.utilities.Convert; import org.androidannotations.annotations.AfterViews; import org.androidannotations.annotations.App; import org.androidannotations.annotations.Bean; import org.androidannotations.annotations.Click; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.EditorAction; import org.androidannotations.annotations.ViewById; import org.androidannotations.annotations.sharedpreferences.Pref; import java.text.Format; import java.util.Calendar; import java.util.Date; import java.util.List; @EFragment(R.layout.fragement_entry_dialog) public class EntryDialog extends DialogFragment implements IDateReceiver { public interface IEntryDialogListener { void onFinishEntryDialog(Vehicle vehicle); } @App MileageApplication _app; @Pref MileagePreferences_ _preferences; @Bean Convert _convert; List<Vehicle> _vehicleList; Vehicle _vehicle; // The current vehicle Entry _entry; // The current entry, this is null if new @ViewById(R.id.entry_dialog_vehicle) Spinner _vehicleSpinner; @ViewById(R.id.entry_dialog_kilometers) EditText _kilometers; @ViewById(R.id.entry_dialog_kilometers_unit) Spinner _kilometersUnit; @ViewById(R.id.entry_dialog_liters) EditText _liters; @ViewById(R.id.entry_dialog_liters_unit) Spinner _litersUnit; @ViewById(R.id.entry_dialog_date) TextView _datePicker; @ViewById(R.id.entry_dialog_note) TextView _note; int _year; int _month; int _day; public EntryDialog() { setDefaultDate(); } public void setVehicle(Vehicle vehicle) { _vehicle = vehicle; } public void setEntry(Entry entry) { _entry = entry; _year = entry.getFillup_date().getYear() + 1900; _month = entry.getFillup_date().getMonth(); _day = entry.getFillup_date().getDay() + 1; } @AfterViews void initialize() { _vehicleList = Vehicle.fetchAll(_app.getDbHelper().getWritableDatabase()); getDialog().setTitle(R.string.entry_dialog_title); ArrayAdapter adapter_veh = new VehicleSpinnerAdapter(getActivity(), _vehicleList); _vehicleSpinner.setAdapter(adapter_veh); ArrayAdapter adapter_km = ArrayAdapter.createFromResource(getActivity(), R.array.distance_units, android.R.layout.simple_spinner_item); adapter_km.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); _kilometersUnit.setAdapter(adapter_km); ArrayAdapter adapter_l = ArrayAdapter.createFromResource(getActivity(), R.array.volume_units, android.R.layout.simple_spinner_item); adapter_l.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); _litersUnit.setAdapter(adapter_l); setDate(); switchToVehicle(); setDefaultVolumeUnits(); setDefaultDistanceUnits(); // Show the soft keyboard automatically _kilometers.requestFocus(); getDialog().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE); // Set values when in edit mode if (_entry != null) { _liters.setText(String.valueOf(_convert.volume(_entry.getLitres()))); _kilometers.setText(String.valueOf(_convert.distance(_entry.getKilometers()))); _note.setText(_entry.getNote()); } } private void setDefaultVolumeUnits() { String units = _preferences.volume_units().get(); int pos = 0; if (units.equalsIgnoreCase("gal_us")) pos = 1; if (units.equalsIgnoreCase("gal_imp")) pos = 2; _litersUnit.setSelection(pos); } private void setDefaultDistanceUnits() { String units = _preferences.distance_units().get(); int pos = 0; if (units.equalsIgnoreCase("m")) pos = 1; _kilometersUnit.setSelection(pos); } private void switchToVehicle() { if (_vehicle == null) return; long id = _vehicle.getId(); Vehicle v = null; for (Vehicle veh : _vehicleList) { if (veh.getId() == id) { v = veh; break; } } int pos = _vehicleList.indexOf(v); if (pos >= 0) { _vehicleSpinner.setSelection(pos); } } private void setDefaultDate() { final Calendar c = Calendar.getInstance(); _year = c.get(Calendar.YEAR); _month = c.get(Calendar.MONTH); _day = c.get(Calendar.DAY_OF_MONTH); } @Click(R.id.entry_dialog_date) void showDatePickerDialog(View v) { DatePickerFragment newFragment = new DatePickerFragment(); newFragment.setReceiver(this); newFragment.show(getFragmentManager(), "datePicker"); } @EditorAction(R.id.entry_dialog_liters) void onEditorAction(TextView textView, int actionId, KeyEvent event) { if (EditorInfo.IME_ACTION_DONE == actionId) { closeDialog(); } } @Click(R.id.entry_dialog_ok) void closeDialog() { Vehicle v = (Vehicle) _vehicleSpinner.getSelectedItem(); double km = 0; try { km = Double.parseDouble(_kilometers.getText().toString()); if (_kilometersUnit.getSelectedItemPosition() == 1) { km = _convert.milesToKilometers(km); } } catch (NumberFormatException nfe) { } double l = 0; try { l = Double.parseDouble(_liters.getText().toString()); if (_litersUnit.getSelectedItemPosition() == 1) { l = _convert.gallonsToLiters(l, Convert.Gallons.US); } else if (_litersUnit.getSelectedItemPosition() == 2) { l = _convert.gallonsToLiters(l, Convert.Gallons.Imperial); } } catch (NumberFormatException nfe) { } if (km <= 0 || l <= 0) { if (km <= 0) { _kilometers.setError(getString(R.string.number_error)); } if (l <= 0) { _liters.setError(getString(R.string.number_error)); } return; } Date d = new Date(_year - 1900, _month, _day); String note = _note.getText().toString(); Entry entry = new Entry(v.getId(), d, km, l, note); if ( _entry != null ) { entry.setId(_entry.getId()); } entry.save(_app.getDbHelper().getWritableDatabase()); // Call back to the activity IEntryDialogListener activity = (IEntryDialogListener) getActivity(); activity.onFinishEntryDialog(v); this.dismiss(); } @Click(R.id.entry_dialog_cancel) void cancel() { dismiss(); } @Override public void setDate(int year, int month, int day) { _year = year; _month = month; _day = day; setDate(); } private void setDate() { // Use the user's default date format Format df = DateFormat.getLongDateFormat(getActivity()); Date d = new Date(_year - 1900, _month, _day); String dateStr = df.format(d); _datePicker.setText(dateStr); } }
import {connect} from 'react-redux' import Counter from '../components/counter' import {countDown, countUp} from '../actions' const mapStateToProps = (state) => { return { count: state.count.count } } const mapDispatchToProps = (dispatch) => { return { onClickCountUp: () => dispatch(countUp()), onClickCountDown: () => dispatch(countDown()) } } export default connect( mapStateToProps, mapDispatchToProps )(Counter)
<gh_stars>1-10 package sock import "syscall" func Control(network, address string, conn syscall.RawConn) error { return nil }
<reponame>Luxcium/iexjs "use strict"; /* *************************************************************************** * * Copyright (c) 2021, the iexjs authors. * * This file is part of the iexjs library, distributed under the terms of * the Apache License 2.0. The full license can be found in the LICENSE file. * */ Object.defineProperty(exports, "__esModule", { value: true }); exports.fortyF = exports.twentyF = exports.tenK = exports.tenQ = void 0; const client_1 = require("../client"); const common_1 = require("../common"); const timeseries_1 = require("../timeseries"); /** * Get company's 10-Q statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {object} standardOptions * @param {string} standardOptions.token Access token * @param {string} standardOptions.version API version * @param {string} standardOptions.filter https://iexcloud.io/docs/api/#filter-results * @param {string} standardOptions.format output format */ const tenQ = (options, { token, version, filter, format } = {}) => { const { symbol } = options; common_1._raiseIfNotStr(symbol); return timeseries_1.timeSeries(Object.assign({ id: "REPORTED_FINANCIALS", key: symbol, subkey: "10-Q" }, (options || {})), { token, version, filter, format }); }; exports.tenQ = tenQ; client_1.Client.prototype.tenQ = function (options, { filter, format } = {}) { return exports.tenQ(options, { token: this._token, version: this._version, filter, format, }); }; /** * Get company's 10-K statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {string} token Access token * @param {string} version API version * @param {string} filter https://iexcloud.io/docs/api/#filter-results * @param {string} format output format */ const tenK = (options, { token, version, filter, format } = {}) => { const { symbol } = options; common_1._raiseIfNotStr(symbol); return timeseries_1.timeSeries(Object.assign({ id: "REPORTED_FINANCIALS", key: symbol, subkey: "10-K" }, (options || {})), { token, version, filter, format }); }; exports.tenK = tenK; client_1.Client.prototype.tenK = function (options, { filter, format } = {}) { return exports.tenK(options, { token: this._token, version: this._version, filter, format, }); }; /** * Get company's 20-F statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {string} token Access token * @param {string} version API version * @param {string} filter https://iexcloud.io/docs/api/#filter-results * @param {string} format output format */ const twentyF = (options, { token, version, filter, format } = {}) => { const { symbol } = options; common_1._raiseIfNotStr(symbol); return timeseries_1.timeSeries(Object.assign({ id: "REPORTED_FINANCIALS", key: symbol, subkey: "20-F" }, (options || {})), { token, version, filter, format }); }; exports.twentyF = twentyF; client_1.Client.prototype.twentyF = function (options, { filter, format } = {}) { return exports.twentyF(options, { token: this._token, version: this._version, filter, format, }); }; /** * Get company's 40-F statement * * @param {object} options `timeseries` options * @param {string} options.symbol company symbol * @param {string} token Access token * @param {string} version API version * @param {string} filter https://iexcloud.io/docs/api/#filter-results * @param {string} format output format */ const fortyF = (options, { token, version, filter, format } = {}) => { const { symbol } = options; common_1._raiseIfNotStr(symbol); return timeseries_1.timeSeries(Object.assign({ id: "REPORTED_FINANCIALS", key: symbol, subkey: "40-F" }, (options || {})), { token, version, filter, format }); }; exports.fortyF = fortyF; client_1.Client.prototype.fortyF = function (options, { filter, format } = {}) { return exports.fortyF(options, { token: this._token, version: this._version, filter, format, }); };
<filename>sql/updates/Rel18/12654_01_mangos_command.sql<gh_stars>0 ALTER TABLE db_version CHANGE COLUMN required_c12631_02_mangos_gameobject required_m12654_command bit; update command set `name`='summon' where `name`='namego'; update command set `name`='appear' where `name`='goname';
<filename>test/bad-calls.test.js /** * @jest-environment node */ import { run, runIf, apply } from '..'; test('bad-calls', () => { const implementations = [run, runIf, apply]; implementations.forEach(implementation => expect(() => implementation('value', 'not-a-function')).toThrow('is not a function')); implementations.forEach(implementation => expect(() => implementation('value')).toThrow('is not a function')); implementations.forEach(implementation => expect(() => implementation('value', () => 'result', 'garbage')).toThrow('is not a function')); });
public class Triangle { public static boolean isTriangle (int a, int b, int c) { // The three lengths should not be negative if (a <= 0 || b <= 0 || c <= 0) return false; // Sum of any two sides should be larger than the third side if (a + b > c && a + c > b && b + c > a) return true; // If none of the above conditions is valid, then it is not a triangle return false; } // Driver code public static void main(String[] args){ int a = 3, b = 4, c = 5; System.out.println(isTriangle(a, b, c)); } }
#!/bin/bash . ./check-go.sh echo "-- Clear old plugchain testnet data and install plugchain and setup the node --" rm -rf ~/.plugchain YOUR_KEY_NAME=$1 YOUR_NAME=$2 DAEMON=plugchaind DENOM=line CHAIN_ID=plugchain-testnet-1 SEEDS="" APPNAME="~/.plugchain" echo "install plugchain" git clone https://github.com/oracleNetworkProtocol/plugchain $GOPATH/src/github.com/oracleNetworkProtocol/plugchain cd $GOPATH/src/github.com/oracleNetworkProtocol/plugchain git fetch git checkout v0.2.0 make install echo "Creating keys" $DAEMON keys add $YOUR_KEY_NAME echo "" echo "After you have copied the mnemonic phrase in a safe place," echo "press the space bar to continue." read -s -d ' ' echo "" echo "Setting up your validator" $DAEMON init --chain-id $CHAIN_ID $YOUR_NAME cp -f $GOPATH/src/github.com/oracleNetworkProtocol/plugchain/testnet/latest/genesis.json $APPNAME/config/ echo "----------Setting config for seed node---------" sed -i 's#tcp://127.0.0.1:26657#tcp://0.0.0.0:26657#g' $APPNAME/config/config.toml sed -i '/seeds =/c\seeds = "'"$SEEDS"'"' $APPNAME/config/config.toml DAEMON_PATH=$(which $DAEMON) # echo "Installing cosmovisor - an upgrade manager..." # rm -rf $GOPATH/src/github.com/cosmos/cosmos-sdk # git clone https://github.com/cosmos/cosmos-sdk $GOPATH/src/github.com/cosmos/cosmos-sdk # cd $GOPATH/src/github.com/cosmos/cosmos-sdk # git checkout v0.40.0 # cd cosmovisor # make cosmovisor # cp cosmovisor $GOBIN/cosmovisor # echo "Setting up cosmovisor directories" # mkdir -p $APPNAME/cosmovisor # mkdir -p $APPNAME/cosmovisor/genesis/bin # cp $GOBIN/plugchaind $APPNAME/cosmovisor/genesis/bin # echo "---------Creating system file---------" # echo "[Unit] # Description=Cosmovisor daemon # After=network-online.target # [Service] # Environment="DAEMON_NAME=plugchaind" # Environment="DAEMON_HOME=${HOME}/." # Environment="DAEMON_RESTART_AFTER_UPGRADE=on" # User=${USER} # ExecStart=${GOBIN}/cosmovisor start # Restart=always # RestartSec=3 # LimitNOFILE=4096 # [Install] # WantedBy=multi-user.target # " >cosmovisor.service # sudo mv cosmovisor.service /lib/systemd/system/cosmovisor.service # sudo -S systemctl daemon-reload # sudo -S systemctl start cosmovisor echo echo "Your account address is :" $DAEMON keys show $YOUR_KEY_NAME -a echo "Your node setup is done. You would need some tokens to start your validator. You can get some tokens from the faucet: http://www.plugchain.network/wallet/receive" echo echo # echo "After receiving tokens, you can create your validator by running" # echo "$DAEMON tx staking create-validator --amount 9000000000$DENOM --commission-max-change-rate \"0.1\" --commission-max-rate \"0.20\" --commission-rate \"0.1\" --details \"Some details about yourvalidator\" --from $YOUR_KEY_NAME --pubkey=\"$($DAEMON tendermint show-validator)\" --moniker $YOUR_NAME --min-self-delegation \"1000000\" --fees 5000$DENOM --chain-id $CHAIN_ID"
<filename>public/scripts/modules/sample-module/predix-asset-service.js define(['angular', './sample-module'], function(angular, module) { 'use strict'; /** * PredixAssetService is a sample service that integrates with Predix Asset Server API */ module.factory('PredixAssetService', ['$q', '$http', function($q, $http) { /** * Predix Asset server base url */ var baseUrl = '/sample-data'; /** * transform the asset entity into an object format consumable by px-context-browser item */ var transformChildren = function(entity) { // transform your entity to context browser entity format return { name: entity.assetId, // Displayed name in the context browser id: entity.uri, // Unique ID (could be a URI for example) parentId: entity.parent, // Parent ID. Used to place the children under the corresponding parent in the browser. classification: entity.classification, // Classification used for fetching the views. isOpenable: true }; }; /** * fetch the asset children by parentId */ var getEntityChildren = function(parentId, options) { var deferred = $q.defer(); var childrenUrl = baseUrl + '/sample-asset-'+parentId+'.json'; //'?pageSize=' + numberOfRecords + '&topLevelOnly=true&filter=parent=' + parentId; var childEntities = { meta: {link: ''}, data: [] }; if (options && options.hasOwnProperty('link')) { if (options.link === '') { deferred.resolve(childEntities); return deferred.promise; } else { //overwrite url if there is link childrenUrl = options.link; } } $http.get(childrenUrl) .success(function(data, status, headers) { var linkHeader = headers('Link'); var link = ''; if (data.length !== 0) { if (linkHeader && linkHeader !== '') { var posOfGt = linkHeader.indexOf('>'); if (posOfGt !== -1) { link = linkHeader.substring(1, posOfGt); } } } childEntities = { meta: {link: link, parentId: parentId}, data: data }; deferred.resolve(childEntities); }) .error(function() { deferred.reject('Error fetching asset with id ' + parentId); }); return deferred.promise; }; /** * get asset by parent id */ var getAssetsByParentId = function(parentId, options) { var deferred = $q.defer(); getEntityChildren(parentId, options).then(function(results) { var transformedChildren = []; for (var i = 0; i < results.data.length; i++) { transformedChildren.push(transformChildren(results.data[i])); } results.data = transformedChildren; deferred.resolve(results); }, function() { deferred.reject('Error fetching asset with id ' + parentId); }); return deferred.promise; }; return { getAssetsByParentId: getAssetsByParentId }; }]); });
/** * * MainPage * */ import React, { memo, useEffect } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Helmet } from 'react-helmet'; import { FormattedMessage } from 'react-intl'; import { createStructuredSelector } from 'reselect'; import { compose } from 'redux'; import { useInjectSaga } from 'utils/injectSaga'; import { useInjectReducer } from 'utils/injectReducer'; import { makeSelectList, makeSelectLoading, makeSelectError, } from 'containers/App/selectors'; import { loadList } from 'containers/App/actions'; import reducer from 'containers/App/reducer'; import makeSelectMainPage from './selectors'; import saga from './saga'; import messages from './messages'; import StringList from '../../components/StringList'; // key is for what context for the selector to get from the store const key = 'global'; export function MainPage({ loading, error, list, loadListDispatch }) { useInjectReducer({ key, reducer }); useInjectSaga({ key, saga }); const stringsListProps = { loading, error, list, }; useEffect(() => { // load strings on mount loadListDispatch(); }, []); return ( <div> <Helmet> <title>DMI Takehome - list</title> <meta name="description" content="List of strings" /> </Helmet> <h1> <FormattedMessage {...messages.header} /> </h1> <StringList {...stringsListProps} /> </div> ); } MainPage.propTypes = { loadListDispatch: PropTypes.func.isRequired, loading: PropTypes.bool, error: PropTypes.oneOfType([PropTypes.object, PropTypes.bool]), list: PropTypes.oneOfType([PropTypes.array, PropTypes.bool]), }; const mapStateToProps = createStructuredSelector({ mainPage: makeSelectMainPage(), list: makeSelectList(), error: makeSelectError(), loading: makeSelectLoading(), }); export function mapDispatchToProps(dispatch) { return { loadListDispatch: () => dispatch(loadList()), }; } const withConnect = connect( mapStateToProps, mapDispatchToProps, ); export default compose( withConnect, memo, )(MainPage);
<reponame>minuee/japan01<filename>assets/js/schedule.js $(function () { $(document).on("change", "#ScheduleTeam,#ProjectGroup", function () { $("#IsOnlyme").val(0); $('#calendar').fullCalendar('rerenderEvents'); }); $(document).on("click", "#btn_view_onlyme", function () { if ( $(this).hasClass("btn-default") ){ $("#IsOnlyme").val(1); $(this).removeClass("btn-default"); $(this).addClass("btn-primary"); $(this).text("전체보기"); }else{ $("#IsOnlyme").val(0); $(this).addClass("btn-default"); $(this).removeClass("btn-primary"); $(this).text("내 일정만 보기"); } $("#ScheduleTeam").find("option:eq(0)").prop("selected", true); $('#calendar').fullCalendar('rerenderEvents'); return false; }); }); function rgb2hex(rgb){ rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i); return (rgb && rgb.length === 4) ? "#" + ("0" + parseInt(rgb[1],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[2],10).toString(16)).slice(-2) + ("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : ''; } function pageprint(event) { html2canvas($('#calendar'), { logging: true, useCORS: true, background :'#FFFFFF', onrendered: function (canvas) { var imgData = canvas.toDataURL("image/jpeg"); var doc = new jsPDF(); doc.addImage(imgData, 'JPEG', 15, 40, 180, 160); download(doc.output(), "Schedule.pdf", "text/pdf"); } }) ; } function download(strData, strFileName, strMimeType) { var D = document, A = arguments, a = D.createElement("a"), d = A[0], n = A[1], t = A[2] || "text/plain"; //build download link: a.href = "data:" + strMimeType + "," + escape(strData); if (window.MSBlobBuilder) { var bb = new MSBlobBuilder(); bb.append(strData); return navigator.msSaveBlob(bb, strFileName); } /* end if(window.MSBlobBuilder) */ if ('download' in a) { a.setAttribute("download", n); a.innerHTML = "downloading..."; D.body.appendChild(a); setTimeout(function() { var e = D.createEvent("MouseEvents"); e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null); a.dispatchEvent(e); D.body.removeChild(a); }, 66); return true; } /* end if('download' in a) */ //do iframe dataURL download: var f = D.createElement("iframe"); D.body.appendChild(f); f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData); setTimeout(function() { D.body.removeChild(f); }, 333); return true; }
<reponame>paccojl/SD44-Deck-Copy-Tool<filename>src/Details.java import java.util.LinkedList; public class Details { String mapname; Integer gamemode; Integer maxPlayers; Integer ver; String duration; Integer victory; Integer score; LinkedList<Player> players; String servername; int startmoney; String income; String timelimit; int scorelimit; }
import { registerTheme } from '../../theme'; var BAR_ACTIVE_STYLE = function (style) { var opacity = style.opacity || 1; return { opacity: opacity * 0.5 }; }; var BAR_DISABLE_STYLE = function (style) { var opacity = style.opacity || 1; return { opacity: opacity * 0.5 }; }; export var DEFAULT_BAR_THEME = { label: { darkStyle: { fill: '#2c3542', stroke: '#ffffff', fillOpacity: 0.85, }, lightStyle: { fill: '#ffffff', stroke: '#ffffff', fillOpacity: 1, }, }, columnStyle: { normal: {}, active: BAR_ACTIVE_STYLE, disable: BAR_DISABLE_STYLE, selected: { lineWidth: 1, stroke: 'black' }, }, }; registerTheme('bar', DEFAULT_BAR_THEME); //# sourceMappingURL=theme.js.map
// sc: // https://ru.hexlet.io/courses/js-asynchronous-programming/lessons/event-loop/exercise_unit // Это задание напрямую не связано с теорией урока, но позволяет еще больше прокачаться в // работе с асинхронным кодом. // В библиотеке async есть функция waterfall, которая позволяет строить цепочки // асинхронных функций без необходимости вкладывать их друг в друга. Подробнее о том как // она работает, посмотрите в документации. Попробуйте решить данное упражнение с // применением этой функции. // file.js // Реализуйте и экспортируйте асинхронную функцию unionFiles, которую мы рассматривали в // предыдущих уроках. Вот её обычное решение на колбэках: // import fs from 'fs'; // const unionFiles = (inputPath1, inputPath2, outputPath, cb) => { // fs.readFile(inputPath1, 'utf-8', (error1, data1) => { // if (error1) { // cb(error1); // return; // } // fs.readFile(inputPath2, 'utf-8', (error2, data2) => { // if (error2) { // cb(error2); // return; // } // fs.writeFile(outputPath, `${data1}${data2}`, (error3) => { // if (error3) { // cb(error3); // return; // } // cb(null); // не забываем последний успешный вызов // }); // }); // }); // } // Попробуйте написать её, используя указанную выше функцию waterfall. /* eslint-disable import/prefer-default-export */ import fs from 'fs'; import { waterfall } from 'async'; // BEGIN (write your solution here) export const unionFiles = (inputPath1, inputPath2, outputPath, callback) => { waterfall( [ (cb) => fs.readFile(inputPath1, cb), (data1, cb) => fs.readFile(inputPath2, (err, data2) => cb(err, data1, data2)), (data1, data2, cb) => fs.writeFile(outputPath, `${data1}${data2}`, cb), ], callback ); }; // END
import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense, Conv2D, Flatten, Dropout, MaxPooling2D # Create the model model = Sequential([ Conv2D(16, 3, padding='same', activation='relu', input_shape=(28, 28 ,1)), MaxPooling2D(), Dropout(0.5), Conv2D(32, 3, padding='same', activation='relu'), MaxPooling2D(), Conv2D(64, 3, padding='same', activation='relu'), MaxPooling2D(), Flatten(), Dense(128, activation='relu'), Dropout(0.5), Dense(10, activation='softmax') ]) # Compile the model model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
#!/bin/bash # Copyright © 2020 Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-3-Clause set -e DIR=$1 MQTT=$2 CONFIDENCE=$3 SKUS=$4 source /opt/intel/openvino_2021/bin/setupvars.sh /go/src/ds-cv-inference/ds-cv-inference -dir $DIR -mqtt $MQTT -skuMapping $SKUS -model /go/src/ds-cv-inference/product-detection-0001/FP32/product-detection-0001.bin -config /go/src/ds-cv-inference/product-detection-0001/FP32/product-detection-0001.xml -confidence $CONFIDENCE
#! /bin/sh # Copyright (C) 2012-2017 Free Software Foundation, Inc. # # 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 2, 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 this program. If not, see <http://www.gnu.org/licenses/>. # Option 'serial-tests'. am_create_testdir=empty . test-init.sh hasnt_parallel_tests () { $EGREP 'TEST_SUITE_LOG|TEST_LOGS|\.log.*:' $1 && exit 1 grep 'recheck.*:' $1 && exit 1 grep '^check-TESTS: \$(TESTS)$' $1 } has_parallel_tests () { $EGREP '(^| )check-TESTS.*:' $1 $EGREP '(^| )recheck.*:' $1 grep '^\$(TEST_SUITE_LOG): \$(TEST_LOGS)$' $1 grep '^\.test\.log:$' $1 } mkdir one two cat > one/configure.ac <<END AC_INIT([$me], [1.0]) AM_INIT_AUTOMAKE([serial-tests]) AC_CONFIG_FILES([Makefile]) END echo 'TESTS = foo.test bar.test' > one/Makefile.am cat > two/configure.ac <<END AC_INIT([$me], [2.0]) AC_CONFIG_AUX_DIR([config]) AM_INIT_AUTOMAKE([parallel-tests]) AC_CONFIG_FILES([aMakefile bMakefile]) END cp one/Makefile.am two/aMakefile.am cat - one/Makefile.am > two/bMakefile.am <<END AUTOMAKE_OPTIONS = serial-tests END cd one touch missing install-sh $ACLOCAL $AUTOMAKE grep TEST Makefile.in # For debugging. hasnt_parallel_tests Makefile.in test ! -e test-driver cd .. cd two mkdir config $ACLOCAL $AUTOMAKE --add-missing grep TEST [ab]Makefile.in # For debugging. has_parallel_tests aMakefile.in hasnt_parallel_tests bMakefile.in mv aMakefile.in aMakefile.sav mv bMakefile.in bMakefile.sav test ! -e test-driver test -f config/test-driver $AUTOMAKE diff aMakefile.sav aMakefile.in diff bMakefile.sav bMakefile.in cd .. :
<reponame>harry-xiaomi/SREWorks package com.alibaba.sreworks.job.worker.taskscene.risk; import java.net.http.HttpResponse; import java.util.List; import com.alibaba.fastjson.JSONObject; import com.alibaba.sreworks.job.taskinstance.ElasticTaskInstanceWithBlobs; import com.alibaba.sreworks.job.taskinstance.ElasticTaskInstanceWithBlobsRepository; import com.alibaba.sreworks.job.utils.Requests; import com.alibaba.sreworks.job.worker.taskscene.AbstractTaskScene; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @EqualsAndHashCode(callSuper = true) @Data @Service @Slf4j public class RiskTaskScene extends AbstractTaskScene<RiskTaskSceneConf> { @Autowired ElasticTaskInstanceWithBlobsRepository taskInstanceRepository; public String type = "risk"; @Override public Class<RiskTaskSceneConf> getConfClass() { return RiskTaskSceneConf.class; } @Override public void toSuccess(String taskInstanceId) throws Exception { ElasticTaskInstanceWithBlobs taskInstance = taskInstanceRepository.findFirstById(taskInstanceId); RiskTaskSceneConf taskSceneConf = getConf(taskInstance); String stdout = getStdout(taskInstance.getStdout()); String url = "http://prod-health-health.sreworks.svc.cluster.local" + "/risk_instance/pushRisks?defId=" + taskSceneConf.getModelId(); HttpResponse<String> response = Requests.post(url, null, null, parseOutputToArrayString(stdout)); Requests.checkResponseStatus(response); } }
import { vtkAlgorithm, vtkObject } from "../../../interfaces"; interface IDracoReaderOptions { binary?: boolean; compression?: string; progressCallback?: any; } /** * */ export interface IDracoReaderInitialValues { } type vtkDracoReaderBase = vtkObject & Omit<vtkAlgorithm, | 'getInputData' | 'setInputData' | 'setInputConnection' | 'getInputConnection' | 'addInputConnection' | 'addInputData'>; export interface vtkDracoReader extends vtkDracoReaderBase { /** * */ getBaseURL(): string; /** * */ getDataAccessHelper(): any; /** * Get the url of the object to load. */ getUrl(): string; /** * Load the object data. * @param {IDracoReaderOptions} [options] */ loadData(options?: IDracoReaderOptions): Promise<any>; /** * Parse data. * @param {String | ArrayBuffer} content The content to parse. */ parse(content: string | ArrayBuffer): void; /** * Parse data as ArrayBuffer. * @param {ArrayBuffer} content The content to parse. */ parseAsArrayBuffer(content: ArrayBuffer): void; /** * Parse data as text. * @param {String} content The content to parse. */ parseAsText(content: string): void; /** * * @param inData * @param outData */ requestData(inData: any, outData: any): void; /** * Set the url of the object to load. * @param {String} url the url of the object to load. * @param {IDracoReaderOptions} [option] The Draco reader options. */ setUrl(url: string, option?: IDracoReaderOptions): boolean; /** * * @param dataAccessHelper */ setDataAccessHelper(dataAccessHelper: any): boolean; } /** * Method used to decorate a given object (publicAPI+model) with vtkDracoReader characteristics. * * @param publicAPI object on which methods will be bounds (public) * @param model object on which data structure will be bounds (protected) * @param {IDracoReaderInitialValues} [initialValues] (default: {}) */ export function extend(publicAPI: object, model: object, initialValues?: IDracoReaderInitialValues): void; /** * Method used to create a new instance of vtkDracoReader * @param {IDracoReaderInitialValues} [initialValues] for pre-setting some of its content */ export function newInstance(initialValues?: IDracoReaderInitialValues): vtkDracoReader; /** * */ export function getDracoDecoder(): any; /** * * @param createDracoModule */ export function setDracoDecoder(createDracoModule: any): void; /** * Load the WASM decoder from url and set the decoderModule * @param url * @param binaryName */ export function setWasmBinary(url: string, binaryName: string): Promise<boolean>; /** * vtkDracoReader is a source object that reads a geometry compressed with the * Draco library. */ export declare const vtkDracoReader: { newInstance: typeof newInstance; extend: typeof extend; getDracoDecoder: typeof getDracoDecoder; setDracoDecoder: typeof setDracoDecoder; setWasmBinary: typeof setWasmBinary; } export default vtkDracoReader;
<filename>router_test.go package ogen import ( "fmt" "net/http" "testing" "github.com/stretchr/testify/require" api "github.com/ogen-go/ogen/internal/sample_api" ) func TestRouter(t *testing.T) { s := api.NewServer(&sampleAPIServer{}) type testCase struct { Method string Path string Operation string Args []string } test := func(m, p, op string, args ...string) testCase { if len(args) == 0 { args = []string{} } return testCase{ Method: m, Path: p, Operation: op, Args: args, } } get := func(p, op string, args ...string) testCase { return test(http.MethodGet, p, op, args...) } post := func(p, op string, args ...string) testCase { return test(http.MethodPost, p, op, args...) } put := func(p, op string, args ...string) testCase { return test(http.MethodPut, p, op, args...) } for i, tc := range []testCase{ get("/pet/name/10", "PetNameByID", "10"), get("/pet/friendNames/10", "PetFriendsNamesByID", "10"), get("/pet", "PetGet"), get("/pet/avatar", "PetGetAvatarByID"), post("/pet/avatar", "PetUploadAvatarByID"), get("/pet/aboba", "PetGetByName", "aboba"), get("/foobar", "FoobarGet"), post("/foobar", "FoobarPost"), put("/foobar", "FoobarPut"), get("/error", "ErrorGet"), get("/test/header", "GetHeader"), // "/name/{id}/{foo}1234{bar}-{baz}!{kek}" get("/name/10/foobar1234barh-buzz!-kek", "DataGetFormat", "10", "foobar", "barh", "buzz", "-kek"), } { tc := tc t.Run(fmt.Sprintf("Test%d", i), func(t *testing.T) { a := require.New(t) r, ok := s.FindRoute(tc.Method, tc.Path) if tc.Operation == "" { a.False(ok) return } a.True(ok) a.Equal(tc.Operation, r.OperationID()) a.Equal(tc.Args, r.Args()) }) } }
#include "stdafx.h" std::tuple<int32_t, int32_t> GetDesktopRes() { HMONITOR monitor = MonitorFromWindow(GetDesktopWindow(), MONITOR_DEFAULTTONEAREST); MONITORINFO info = {}; info.cbSize = sizeof(MONITORINFO); GetMonitorInfo(monitor, &info); int32_t DesktopResW = info.rcMonitor.right - info.rcMonitor.left; int32_t DesktopResH = info.rcMonitor.bottom - info.rcMonitor.top; return std::make_tuple(DesktopResW, DesktopResH); } std::string format(const char *fmt, ...) { va_list args; va_start(args, fmt); std::vector<char> v(1024); while (true) { va_list args2; va_copy(args2, args); int res = vsnprintf(v.data(), v.size(), fmt, args2); if ((res >= 0) && (res < static_cast<int>(v.size()))) { va_end(args); va_end(args2); return std::string(v.data()); } size_t size; if (res < 0) size = v.size() * 2; else size = static_cast<size_t>(res) + 1; v.clear(); v.resize(size); va_end(args2); } }
<gh_stars>10-100 package chylex.hee.world.feature.stronghold.rooms.loot; import java.util.Arrays; import java.util.Random; import net.minecraft.init.Blocks; import chylex.hee.init.BlockList; import chylex.hee.system.abstractions.Meta; import chylex.hee.system.abstractions.Pos; import chylex.hee.system.abstractions.Pos.PosMutable; import chylex.hee.system.abstractions.facing.Facing4; import chylex.hee.world.structure.StructureWorld; import chylex.hee.world.structure.dungeon.StructureDungeonPieceInst; import chylex.hee.world.structure.util.IBlockPicker; import chylex.hee.world.util.Size; public class StrongholdRoomRelicFountains extends StrongholdRoomRelic{ public static StrongholdRoomRelicFountains[] generateRelicRooms(){ return Arrays.stream(Facing4.list).map(facing -> new StrongholdRoomRelicFountains(facing)).toArray(StrongholdRoomRelicFountains[]::new); } private final Facing4 entranceFrom; public StrongholdRoomRelicFountains(Facing4 entranceFrom){ super(new Size(entranceFrom.getX() != 0 ? 19 : 13, 12, entranceFrom.getZ() != 0 ? 19 : 13), null); this.entranceFrom = entranceFrom; if (entranceFrom == Facing4.SOUTH_POSZ)addConnection(Facing4.NORTH_NEGZ, maxX/2, 1, 0, fromRoom); else if (entranceFrom == Facing4.NORTH_NEGZ)addConnection(Facing4.SOUTH_POSZ, maxX/2, 1, maxZ, fromRoom); else if (entranceFrom == Facing4.WEST_NEGX)addConnection(Facing4.EAST_POSX, maxX, 1, maxZ/2, fromRoom); else if (entranceFrom == Facing4.EAST_POSX)addConnection(Facing4.WEST_NEGX, 0, 1, maxZ/2, fromRoom); } @Override public void generate(StructureDungeonPieceInst inst, StructureWorld world, Random rand, int x, int y, int z){ super.generate(inst, world, rand, x, y, z); Facing4 left = entranceFrom.rotateLeft(), right = entranceFrom.rotateRight(); Connection connection = connections.get(0); PosMutable mpos = new PosMutable(); Pos point1, point2; // water mpos.set(x+connection.offsetX, 0, z+connection.offsetZ).move(entranceFrom); for(int side = 0; side < 2; side++){ Facing4 sideFacing = side == 0 ? left : right; point1 = Pos.at(mpos).offset(sideFacing, 2); point2 = Pos.at(point1).offset(sideFacing, 3).offset(entranceFrom, 16); placeCube(world, rand, placeWater, point1.getX(), y+1, point1.getZ(), point2.getX(), y+1, point2.getZ()); } // road point1 = Pos.at(mpos).offset(left); point2 = Pos.at(mpos).offset(right).offset(entranceFrom, 16); placeCube(world, rand, placeStoneBrick, point1.getX(), y+1, point1.getZ(), point2.getX(), y+1, point2.getZ()); // water streams for(int side = 0; side < 2; side++){ Facing4 sideFacing = side == 0 ? left : right; for(int stream = 0; stream < 3; stream++){ mpos.set(x+connection.offsetX, 0, z+connection.offsetZ).move(sideFacing, 5).move(entranceFrom, 4+5*stream); placeBlock(world, rand, placeStoneBrickStairs(sideFacing, true), mpos.x, y+5, mpos.z); // bottom lower stair placeBlock(world, rand, placeStoneBrickStairs(sideFacing, true), mpos.x, y+6, mpos.z); // bottom upper stair placeBlock(world, rand, placeStoneBrickStairs(sideFacing, false), mpos.x-sideFacing.getX(), y+6, mpos.z-sideFacing.getZ()); // front stair placeBlock(world, rand, placeWater, mpos.x, y+7, mpos.z); // water // side stairs mpos.move(entranceFrom.opposite()); placeBlock(world, rand, placeStoneBrickStairs(entranceFrom, true), mpos.x, y+7, mpos.z); placeBlock(world, rand, placeStoneBrickStairs(sideFacing, true), mpos.x-sideFacing.getX(), y+7, mpos.z-sideFacing.getZ()); mpos.move(entranceFrom); placeBlock(world, rand, placeEtherealLantern, mpos.x+sideFacing.getX(), y+7, mpos.z+sideFacing.getZ()); mpos.move(entranceFrom); placeBlock(world, rand, placeStoneBrickStairs(entranceFrom.opposite(), true), mpos.x, y+7, mpos.z); placeBlock(world, rand, placeStoneBrickStairs(sideFacing, true), mpos.x-sideFacing.getX(), y+7, mpos.z-sideFacing.getZ()); } } // wall outlines placeOutline(world, rand, placeStoneBrickWall, x+1, y+maxY-1, z+1, x+maxX-1, y+maxY-1, z+maxZ-1, 1); mpos.set(x+connection.offsetX, 0, z+connection.offsetZ).move(entranceFrom); placeBlock(world, rand, placeStoneBrickWall, mpos.x, y+5, mpos.z); for(int side = 0; side < 2; side++){ Facing4 sideFacing = side == 0 ? left : right; mpos.set(x+connection.offsetX, 0, z+connection.offsetZ).move(entranceFrom).move(sideFacing); placeBlock(world, rand, placeStoneBrickWall, mpos.x, y+5, mpos.z); mpos.move(sideFacing); placeLine(world, rand, placeStoneBrickWall, mpos.x, y+5, mpos.z, mpos.x, y+2, mpos.z); mpos.move(sideFacing); placeLine(world, rand, placeStoneBrickWall, mpos.x, y+2, mpos.z, mpos.x+sideFacing.getX(), y+2, mpos.z+sideFacing.getZ()); mpos.move(sideFacing, 2); placeLine(world, rand, placeStoneBrickWall, mpos.x, y+2, mpos.z, mpos.x+16*entranceFrom.getX(), y+2, mpos.z+16*entranceFrom.getZ()); mpos.move(entranceFrom, 16).move(sideFacing.opposite()); placeLine(world, rand, placeStoneBrickWall, mpos.x, y+2, mpos.z, mpos.x-2*sideFacing.getX(), y+2, mpos.z-2*sideFacing.getZ()); } // chest mpos.set(x+connection.offsetX, 0, z+connection.offsetZ).move(entranceFrom, 17); placeBlock(world, rand, placeStoneBrickPlain, mpos.x, y+2, mpos.z); placeBlock(world, rand, IBlockPicker.basic(Blocks.stone_brick_stairs, Meta.getStairs(entranceFrom, true)), mpos.x+left.getX(), y+2, mpos.z+left.getZ()); placeBlock(world, rand, IBlockPicker.basic(Blocks.stone_brick_stairs, Meta.getStairs(entranceFrom, true)), mpos.x+right.getX(), y+2, mpos.z+right.getZ()); placeBlock(world, rand, IBlockPicker.basic(BlockList.loot_chest), mpos.x, y+3, mpos.z); world.setTileEntity(mpos.x, y+3, mpos.z, Meta.generateChest(entranceFrom.opposite(), getRelicGenerator())); } }
<filename>datapipe/store/milvus.py import pandas as pd from typing import Dict, List, Optional from pymilvus import connections, utility, CollectionSchema, Collection, FieldSchema, SearchResult from datapipe.types import DataSchema, MetaSchema, IndexDF, DataDF, data_to_index from datapipe.store.table_store import TableStore class MilvusStore(TableStore): def __init__( self, name: str, schema: List[FieldSchema], primary_db_schema: DataSchema, index_params: Dict, pk_field: str, embedding_field: str, connection_details: Dict ): super().__init__() self.name = name self.schema = schema self.primary_db_schema = primary_db_schema self.index_params = index_params self.pk_field = pk_field self.embedding_field = embedding_field self.connection_details = connection_details self._collection_loaded = False connections.connect(**connection_details) schema_milvus = CollectionSchema(schema, "MilvusStore") self.collection = Collection(name, schema_milvus) if not utility.has_collection(name): self.collection.create_index(embedding_field, index_params) def get_primary_schema(self) -> DataSchema: return self.primary_db_schema def get_meta_schema(self) -> MetaSchema: return [] def pk_expr(self, idx: IndexDF) -> str: if isinstance(idx[self.pk_field].values[0], str): values = idx[self.pk_field].apply(lambda val: f"'{val}'") else: values = idx[self.pk_field].apply(str) return ", ".join(values) def delete_rows(self, idx: IndexDF) -> None: if len(idx) == 0: return ids_joined = self.pk_expr(idx) self.collection.delete(expr=f"{self.pk_field} in [{ids_joined}]") if self._collection_loaded: self.collection.release() self._collection_loaded = False def insert_rows(self, df: DataDF) -> None: if len(df) == 0: return values = [df[field.name].tolist() for field in self.schema] self.collection.insert(values) if self._collection_loaded: self.collection.release() self._collection_loaded = False def update_rows(self, df: DataDF) -> None: self.delete_rows(data_to_index(df, [self.pk_field])) self.insert_rows(df) def read_rows(self, idx: Optional[IndexDF] = None) -> DataDF: if not idx: raise Exception("Milvus doesn't support full store reading") ids_joined = self.pk_expr(idx) names = [field.name for field in self.schema] result = self.query_search(f"{self.pk_field} in [{ids_joined}]", names) return pd.DataFrame.from_records(result) def vector_search( self, embeddings: List, query_params: Dict, expr: str, limit: int ) -> SearchResult: if not self._collection_loaded: self.collection.load() self._collection_loaded = True return self.collection.search( data=embeddings, anns_field=self.embedding_field, param={"params": query_params}, limit=limit, expr=expr, consistency_level="Strong", ) def query_search(self, expr: str, output_fields: List) -> List: if not self._collection_loaded: self.collection.load() self._collection_loaded = True return self.collection.query( expr=expr, output_fields=output_fields )
<filename>wit/src/StCons.h //============================================================================== // WIT // // Based On: //============================================================================== // Constrained Materials Management and Production Planning Tool // // (C) Copyright IBM Corp. 1993, 2020 All Rights Reserved //============================================================================== #ifndef StConsH #define StConsH //------------------------------------------------------------------------------ // Header file: "StCons.h" // // Contains the declaration the following classes: // // StResCon // StSubCon // StShipCon // StSlbCon //------------------------------------------------------------------------------ #include <StochCon.h> //------------------------------------------------------------------------------ // class StResCon // // "Stochastic Resource Constraint" // A resource constraint in a stochastic implosion optimization problem. // // Class hierarchy: // // OptVC // OptVar // StochCon // StResCon // // Implemented in StCons.C. //------------------------------------------------------------------------------ class WitStResCon: public WitStochCon { public: //----------------------------------------------------------------------- // Constructor functions. //----------------------------------------------------------------------- WitStResCon (WitPart *, WitStochLoc *); //----------------------------------------------------------------------- // Destructor function. //----------------------------------------------------------------------- virtual ~WitStResCon (); //----------------------------------------------------------------------- // Overriding public virtual member functions. //----------------------------------------------------------------------- virtual void generateCoeffs (); private: //----------------------------------------------------------------------- // Private member functions. //----------------------------------------------------------------------- //----------------------------------------------------------------------- // Overriding private virtual member functions. //----------------------------------------------------------------------- virtual double upperBoundVal (); virtual double lowerBoundVal (); virtual const char * classText (); virtual void printItem (); //----------------------------------------------------------------------- // Other private member functions. //----------------------------------------------------------------------- void genPartCoeffs (); void genMatCoeffs (); void genDemandCoeffs (); void genBomEntCoeffs (); void genSubCoeffs (); void genBopEntCoeffs (); // // Generates the Coeffs of this StResCon associated with: // myPart_ // myPart_ as a Material, if it is one // The Demands for myPart_ // The consuming BOM entries of myPart_ // The consuming substitutes of myPart_ // The producing BOP entries of myPart_ void getExecPerRange ( WitBillEntry * theBillEnt, WitPeriod & execPerF, WitPeriod & execPerL); // // Sets execPerF and execPerL to be the first and last execution // periods, execPer, for which // theBillEnt->impactPeriod ()[execPer] == myPer (). noCopyCtorAssign (WitStResCon); //----------------------------------------------------------------------- // Private member data. //----------------------------------------------------------------------- WitPart * const myPart_; // // The Part for this StResCon. }; //------------------------------------------------------------------------------ // class StSubCon // // "Stochastic Substitution Constraint" // A substituion constraint in a stochastic implosion optimization problem. // // Class hierarchy: // // OptVC // OptVar // StochCon // StSubCon // // Implemented in StCons.C. //------------------------------------------------------------------------------ class WitStSubCon: public WitStochCon { public: //----------------------------------------------------------------------- // Constructor functions. //----------------------------------------------------------------------- WitStSubCon (WitBomEntry *, WitStochLoc *); //----------------------------------------------------------------------- // Destructor function. //----------------------------------------------------------------------- virtual ~WitStSubCon (); //----------------------------------------------------------------------- // Overriding public virtual member functions. //----------------------------------------------------------------------- virtual void generateCoeffs (); private: //----------------------------------------------------------------------- // Private member functions. //----------------------------------------------------------------------- //----------------------------------------------------------------------- // Overriding private virtual member functions. //----------------------------------------------------------------------- virtual double upperBoundVal (); virtual double lowerBoundVal (); virtual const char * classText (); virtual void printItem (); //----------------------------------------------------------------------- // Other private member functions. //----------------------------------------------------------------------- noCopyCtorAssign (WitStSubCon); //----------------------------------------------------------------------- // Private member data. //----------------------------------------------------------------------- WitBomEntry * const myBomEnt_; // // The BomEntry for this StSubCon. }; //------------------------------------------------------------------------------ // class StShipCon // // "Stochastic Shipment Constraint" // A shipment constraint in a stochastic implosion optimization problem. // // Class hierarchy: // // OptVC // OptVar // StochCon // StShipCon // // Implemented in StCons.C. //------------------------------------------------------------------------------ class WitStShipCon: public WitStochCon { public: //----------------------------------------------------------------------- // Constructor functions. //----------------------------------------------------------------------- WitStShipCon (WitDemand *, WitStochLoc *); //----------------------------------------------------------------------- // Destructor function. //----------------------------------------------------------------------- virtual ~WitStShipCon (); //----------------------------------------------------------------------- // Overriding public virtual member functions. //----------------------------------------------------------------------- virtual void generateCoeffs (); private: //----------------------------------------------------------------------- // Private member functions. //----------------------------------------------------------------------- //----------------------------------------------------------------------- // Overriding private virtual member functions. //----------------------------------------------------------------------- virtual double upperBoundVal (); virtual double lowerBoundVal (); virtual const char * classText (); virtual void printItem (); //----------------------------------------------------------------------- // Other private member functions. //----------------------------------------------------------------------- noCopyCtorAssign (WitStShipCon); //----------------------------------------------------------------------- // Private member data. //----------------------------------------------------------------------- WitDemand * const myDemand_; // // The Demand for this StShipCon. }; //------------------------------------------------------------------------------ // class StSlbCon // // "Stochastic Soft Lower Bound Constraint" // A soft lower bound constraint in a stochastic implosion optimization problem. // // Class hierarchy: // // OptVC // OptVar // StochCon // StSlbCon // // Implemented in StCons.C. //------------------------------------------------------------------------------ class WitStSlbCon: public WitStochCon { public: //----------------------------------------------------------------------- // Constructor functions. //----------------------------------------------------------------------- WitStSlbCon (WitStSlbvVar *); //----------------------------------------------------------------------- // Destructor function. //----------------------------------------------------------------------- virtual ~WitStSlbCon (); //----------------------------------------------------------------------- // Overriding public virtual member functions. //----------------------------------------------------------------------- virtual void generateCoeffs (); private: //----------------------------------------------------------------------- // Private member functions. //----------------------------------------------------------------------- //----------------------------------------------------------------------- // Overriding private virtual member functions. //----------------------------------------------------------------------- virtual double upperBoundVal (); virtual double lowerBoundVal (); virtual const char * classText (); virtual void printItem (); //----------------------------------------------------------------------- // Other private member functions. //----------------------------------------------------------------------- WitStBddVar * myBddVar (); noCopyCtorAssign (WitStSlbCon); //----------------------------------------------------------------------- // Private member data. //----------------------------------------------------------------------- WitStSlbvVar * const mySlbvVar_; // // The StSlbvVar for this StSblCon. }; #endif
require 'yaml' module Termup class Base def initialize(project) @handler = Termup::Handler.new config = YAML.load(File.read("#{TERMUP_DIR}/#{project}.yml")) @tabs = config['tabs'] # Config file compatibility checking if @tabs.is_a?(Array) and @tabs.first.is_a?(Hash) abort 'YAML syntax for config has been changed. See https://github.com/kenn/termup for details.' end @options = config['options'] || {} @iterm_options = @options['iterm'] # Split panes for iTerm 2 split_panes if @handler.iterm? and @iterm_options # Setting up tabs / panes @tabs.each_with_index do |(tabname, values), index| # Set tab title @handler.set_property(:name, tabname) # Run commands (advanced_iterm? ? values['commands'] : values).each do |command| @handler.run command end # Layout if advanced_iterm? values['properties'].each do |key, value| @handler.set_property(key, value) end if values['properties'] values['layout'].each do |command| layout command end if values['layout'] else # Move to next if @iterm_options layout :goto_next_pane else if index < @tabs.size - 1 layout :new_tab sleep 0.01 # Allow some time to complete opening a new tab else layout :goto_next_tab # Back home end end end end end def split_panes width, height = @iterm_options['width'], @iterm_options['height'] return unless width and height (width - 1).times do layout :split_vertically end layout :goto_next_pane # Back home width.times do (height - 1).times do layout :split_horizontally end layout :goto_next_pane # Move to next, or back home end end def advanced_iterm? unless defined?(@advanced_iterm) @advanced_iterm = case @tabs.values.first when Hash then true when Array then false else abort 'invalid YAML format' end abort 'advanced config only supported for iTerm' if @advanced_iterm and !@handler.iterm? end @advanced_iterm end def layout(command) @handler.layout(command) end end end
#!/usr/bin/env bash name=$1 ass=$2 file=$3 # adjust the next line for class and semester curl -F student=$name -F assignment="CS472 F16 Assignment $ass" -F "submittedfile=@$file" "http://ec2-52-89-93-46.us-west-2.compute.amazonaws.com/cgi-bin/fileCapture.py"
import React, { useEffect } from 'react' import { makeStyles, useTheme } from '@material-ui/core/styles' import Input from '@material-ui/core/Input' import MenuItem from '@material-ui/core/MenuItem' import FormControl from '@material-ui/core/FormControl' import Select from '@material-ui/core/Select' import axios from 'axios' import CenteredCircularProgress from '../../Utilities/CenteredCircularProgress' const useStyles = makeStyles(theme => ({ formControl: { margin: theme.spacing(0), minWidth: 200, maxWidth: 500 }, chips: { display: 'flex', flexWrap: 'wrap' }, chip: { margin: 2 }, noLabel: { marginTop: theme.spacing(3) } })) const ITEM_HEIGHT = 48 const ITEM_PADDING_TOP = 8 const MenuProps = { PaperProps: { style: { maxHeight: ITEM_HEIGHT * 9 + ITEM_PADDING_TOP, width: 350 } } } // Parameters: none // Return: list of Representatives objects async function fetchAllRepresentatives () { let representatives = [] await axios .get('/api/representatives/getAllRepresentatives') .then(res => { if (res.data.success) { representatives = res.data.data } }) .catch(err => console.error(err)) return representatives } // Parameters: list of representatives objects // Return: list of ridings export function getAllRidings (representatives) { return representatives .map(rep => { return rep.riding.replace(/\u2013|\u2014/g, '-') }) .sort() } // Parameters: email of user, new riding for that user. // Return: none export async function updateUserRiding (email, newRiding) { const updateObject = { email: email, riding: newRiding } axios.put('/api/users/updateUserRiding', updateObject) } function getStyles (name, personName, theme) { return { fontWeight: personName.indexOf(name) === -1 ? theme.typography.fontWeightRegular : theme.typography.fontWeightMedium } } export default function RidingSwitcher (props) { const classes = useStyles() const theme = useTheme() const [representatives, setRepresentatives] = React.useState(null) useEffect(() => { async function getData () { if (!representatives) { const reps = await fetchAllRepresentatives() setRepresentatives(reps) } } getData() }, [representatives]) const [ridings, setRidings] = React.useState(null) useEffect(() => { if (representatives && !ridings) { const allRidings = getAllRidings(representatives) setRidings(allRidings) } }, [representatives, ridings]) const handleChange = event => { updateUserRiding(props.user.email, event.target.value) .then((resp) => { props.onChange(event.target.value) }) } return ( <div> {props.riding && ridings ? ( <FormControl className={classes.formControl}> <Select value={props.riding} onChange={handleChange} input={<Input />} MenuProps={MenuProps} > {ridings.map(riding => ( <MenuItem key={riding} value={riding} style={getStyles(riding, riding, theme)} > {riding} </MenuItem> ))} </Select> </FormControl> ) : (<CenteredCircularProgress />)} </div> ) }
#IMAGE=supervisely/base-py #docker pull $IMAGE && \ #docker build --build-arg IMAGE=$IMAGE -t $IMAGE"-debug" . && \ #docker run --rm -it -p 7777:22 --shm-size='1G' -e PYTHONUNBUFFERED='1' $IMAGE"-debug" # -v ~/max:/workdir cp /root/.ssh/authorized_keys . && \ docker-compose up -d && \ docker-compose ps
/** * OLAT - Online Learning and Training<br> * http://www.olat.org * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Copyright (c) since 2004 at Multimedia- & E-Learning Services (MELS),<br> * University of Zurich, Switzerland. * <hr> * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * This file has been modified by the OpenOLAT community. Changes are licensed * under the Apache 2.0 license as the original file. */ package org.olat.modules.wiki; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.Event; import org.olat.core.gui.control.WindowControl; import org.olat.core.util.StringHelper; /** * Description:<br> * Provides a search text input field * * <P> * Initial Date: 07.02.2008 <br> * @author guido */ public class WikiArticleSearchForm extends FormBasicController { private TextElement searchQuery; public WikiArticleSearchForm(UserRequest ureq, WindowControl control) { super(ureq, control, "articleSearch"); initForm(ureq); } @Override protected void formOK(UserRequest ureq) { fireEvent(ureq, Event.DONE_EVENT); } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { searchQuery = uifactory.addTextElement("search", null, 250, null, formLayout); searchQuery.setDisplaySize(40); uifactory.addFormSubmitButton("subm", "navigation.create.article", formLayout); } @Override protected boolean validateFormLogic(UserRequest ureq) { boolean allOk = super.validateFormLogic(ureq); String val = searchQuery.getValue(); searchQuery.clearError(); if(!StringHelper.containsNonWhitespace(val)) { searchQuery.setErrorKey("form.legende.mandatory", null); allOk &= false; } else if(StringHelper.xssScanForErrors(val)) { searchQuery.setErrorKey("form.legende.mandatory", null); searchQuery.setValue(""); allOk &= false; } return allOk; } public String getQuery() { return searchQuery.getValue(); } }
set -e if [ ! -f /usr/local/bin/windres ]; then ln -s /usr/bin/x86_64-w64-mingw32-windres /usr/local/bin/windres fi cd /deps/openssl CC=x86_64-w64-mingw32-gcc HOST=x86_64-w64-mingw32 INCLUDE=/usr/x86_64-w64-mingw32/include LIB=/usr/x86_64-w64-mingw32/lib ./Configure --prefix=/usr/x86_64-w64-mingw32 mingw64 threads no-shared make make install cd /deps/libgit2 mkdir -p build/windows cd build/windows # Need this fix http://www.cmake.org/gitweb?p=cmake.git;a=commitdiff;h=c5d9a8283cfac15b4a5a07f18d5eb10c1f388505 #sed -i 's/REGEX "^#define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")/REGEX "^# *define[\t ]+OPENSSL_VERSION_NUMBER[\t ]+0x([0-9a-fA-F])+.*")/g' sed -i 's/REGEX "^#define\[\\t ]+OPENSSL_VERSION_NUMBER\[\\t ]+0x(\[0-9a-fA-F])+\.\*")/REGEX "^# *define[\\t ]+OPENSSL_VERSION_NUMBER[\\t ]+0x([0-9a-fA-F])+.*")/' /usr/share/cmake-3.5/Modules/FindOpenSSL.cmake VERBOSE=1 cmake ../.. -DBUILD_SHARED_LIBS=OFF -DCMAKE_BUILD_TYPE=Release -DBUILD_CLAR=OFF -DTHREADSAFE=ON \ -DCMAKE_TOOLCHAIN_FILE=/scripts/toolchains/windows/windows.cmake -DCMAKE_INSTALL_PREFIX=/usr/local/windows \ -DCMAKE_VERBOSE_MAKEFILE=ON cmake --build . --target install FLAGS=$(x86_64-w64-mingw32-pkg-config --static --libs /usr/local/windows/lib/pkgconfig/libgit2.pc) export CGO_CFLAGS="-I/usr/local/windows/include -I/usr/x86_64-w64-mingw32/include" export CGO_LDFLAGS="/usr/local/windows/lib/libgit2.a -L/usr/local/windows/lib -L/usr/x86_64-w64-mingw32/lib ${FLAGS}" export PKG_CONFIG_PATH=/usr/local/windows/lib/pkgconfig:/usr/x86_64-w64-mingw32/lib/pkgconfig
#!/bin/bash if [[ "$1" == "" ]]; then echo "" echo "usage: random_sampler.bash FACTOR" echo "" echo "prints to STDOUT approximately 1/FACTOR of the lines passed to STDIN" echo "" exit fi awk -v SEED=$RANDOM -v FACTOR=$1 'BEGIN{srand(SEED)} {if( rand() < 1/FACTOR) print $0}' <&0
def last_n_elements(arr, n): """Returns an array containing the last n elements from the original array""" return arr[-n:]
using System; public class Program { public static void Main() { int[] intList = {1,2,3,4,5}; foreach (int num in intList) { Console.WriteLine(num); } } }
for port in `seq 7001 7006`; do \ mkdir -p ./${port}/conf \ && PORT=${port} envsubst < redis-cluster.tmpl > ./${port}/conf/redis.conf \ && mkdir -p ./${port}/data; \ done
from wtforms import StringField, SubmitField from flask import Flask, render_template, redirect, url_for from flask_wtf import FlaskForm from wtforms.validators import InputRequired import possible_cards app = Flask(__name__) app.config["SECRET_KEY"] = "testkey" class OpponentForm(FlaskForm): card1 = StringField('Card 1', validators=[InputRequired()]) card2 = StringField('Card 2', validators=[InputRequired()]) card3 = StringField('Card 3', validators=[InputRequired()]) submit = SubmitField('Submit') @app.route('/select_cards', methods=['GET', 'POST']) def select_cards(): form = OpponentForm() if form.validate_on_submit(): # Process the selected cards selected_cards = [form.card1.data, form.card2.data, form.card3.data] # Perform game logic with the selected cards # Redirect to a new page or perform further actions return redirect(url_for('success')) return render_template('select_cards.html', form=form) @app.route('/success') def success(): return "Cards successfully selected!" if __name__ == '__main__': app.run(debug=True)
<gh_stars>100-1000 # -*- encoding: utf-8 -*- # this is required because of the use of eval interacting badly with require_relative require 'razor/acceptance/utils' confine :except, :roles => %w{master dashboard database frictionless} test_name 'Remove policy tag with nonexistent tag' step 'https://testrail.ops.puppetlabs.net/index.php?/cases/view/780' reset_database results = create_policy agents razor agents, "remove-policy-tag --name #{results[:policy][:name]} --tag does-not-exist" do |agent, output| assert_match /Tag does-not-exist was not on policy #{results[:policy][:name]}/, output end
package fr.unice.polytech.si3.qgl.soyouz.classes.objectives.root.regatta; import fr.unice.polytech.si3.qgl.soyouz.classes.actions.GameAction; import fr.unice.polytech.si3.qgl.soyouz.classes.gameflow.GameState; import fr.unice.polytech.si3.qgl.soyouz.classes.gameflow.goals.RegattaGoal; import fr.unice.polytech.si3.qgl.soyouz.classes.objectives.root.RootObjective; import fr.unice.polytech.si3.qgl.soyouz.classes.objectives.sailor.helper.OnBoardDataHelper; import fr.unice.polytech.si3.qgl.soyouz.classes.objectives.sailor.helper.SeaDataHelper; import fr.unice.polytech.si3.qgl.soyouz.classes.objectives.sailor.movement.initialisation.InitSailorPositionObjective; import fr.unice.polytech.si3.qgl.soyouz.classes.parameters.InitGameParameters; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import static fr.unice.polytech.si3.qgl.soyouz.Cockpit.trace; /** * Race type objective. */ public class RegattaObjective implements RootObjective { private static final Logger logger = Logger.getLogger(RegattaObjective.class.getSimpleName()); private final RegattaGoal goalData; private final InitSailorPositionObjective initialisationObjective; private int numCheckpoint = 0; private CheckpointObjective currentCheckpoint; private OnBoardDataHelper onBoardDataHelper; private SeaDataHelper seaDataHelper; /** * Constructor. * * @param goalData The data of the race. */ public RegattaObjective(RegattaGoal goalData, InitGameParameters ip) { this.goalData = goalData; currentCheckpoint = null; onBoardDataHelper = null; seaDataHelper = null; initialisationObjective = new InitSailorPositionObjective(ip.getShip(), new ArrayList<>(Arrays.asList(ip.getSailors()))); } public CheckpointObjective getCurrentCheckpoint() { return currentCheckpoint; } /** * Update the current checkpoint to reach. * * @param state of the game */ private void update(GameState state) { trace(); if (initialisationObjective.isValidated()) { updateHelpers(state); updateCheckpoint(state); } } /** * Update all helpers. * * @param state The curent game state. */ private void updateHelpers(GameState state) { trace(); if (onBoardDataHelper == null) { onBoardDataHelper = new OnBoardDataHelper(state.getIp().getShip(), new ArrayList<>(Arrays.asList(state.getIp().getSailors()))); } if (seaDataHelper == null) { seaDataHelper = new SeaDataHelper(state.getNp().getShip(), state.getNp().getWind()); } else { seaDataHelper.update(state); } } /** * Update the current checkpoint. * * @param state The game state. */ private void updateCheckpoint(GameState state) { trace(); if (currentCheckpoint == null) { currentCheckpoint = new CheckpointObjective(goalData.getCheckpoints()[numCheckpoint], onBoardDataHelper, seaDataHelper); } if (currentCheckpoint.isValidated(state)) { if (goalData.getCheckpoints().length - 1 > numCheckpoint) { logger.log(Level.INFO, "Checkpoint " + numCheckpoint + " reached"); numCheckpoint++; } else { logger.log(Level.INFO, "Regatta ended"); numCheckpoint = 0; } currentCheckpoint = new CheckpointObjective(goalData.getCheckpoints()[numCheckpoint], onBoardDataHelper, seaDataHelper); } } /** * Determine if the goal is reached. * * @param state of the game * @return true if this objective is validated */ @Override public boolean isValidated(GameState state) { return numCheckpoint == ((RegattaGoal) state.getIp().getGoal()).getCheckpoints().length - 1; } /** * Defines actions to perform in order to reach the next checkpoint. * * @param state of the game * @return a list of all actions to send to JSON */ @Override public List<GameAction> resolve(GameState state) { trace(); update(state); if (initialisationObjective.isValidated()) { return currentCheckpoint.resolve(state); } else { List<GameAction> ga = initialisationObjective.resolve(); if (initialisationObjective.isValidated()) { update(state); if (onBoardDataHelper.getMutableRowers().isEmpty()) { ga.addAll(currentCheckpoint.resolve(state)); } } return ga; } } }
#! /bin/bash # Exit when any command fails set -e echo "Stopping all services" python3.7 deploy_aws.py --target=flask --state=down python3.7 deploy_aws.py --target=test_metric_producer --state=down --start_cluster_id=0 python3.7 deploy_aws.py --target=test_metric_reader --state=down python3.7 deploy_aws.py --target=metric_consumer --state=down
public class MultiplicationTable { public static void main(String[] args) { int n = Integer.parseInt(args[0]); for (int i = 1; i <= n; i++) { for (int j = 1; j <= n; j++) { System.out.print(String.format("%4d", i * j)); } System.out.println(); } } }
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package org.apache.tapestry5.func; /** * Used when filtering a collection of objects of a given type; the predicate is passed * each object in turn, and returns true to include the object in the result collection. * * The {@link F} class includes a number of Predicate factory methods. * * This was converted from a abstract base class to an interface in 5.3. * * @since 5.2.0 * @see Flow#filter(Predicate) * @see Flow#remove(Predicate) */ public interface Predicate<T> { /** * This method is overridden in subclasses to define which objects the Predicate will accept * and which it will reject. * * @param element * the element from the flow to be evaluated by the Predicate */ boolean accept(T element); }
def find_max_sum_subarray(arr): max_sum = 0 temp_sum = 0 start = 0 end = 0 for i in range(0, len(arr)): temp_sum = temp_sum + arr[i] if temp_sum < 0: temp_sum = 0 start = i + 1 else: if temp_sum > max_sum: max_sum = temp_sum end = i return [start, end], max_sum res = find_max_sum_subarray(arr) print("Subarray between indices", res[0], "having maximum sum", res[1])
<reponame>Michael-Jalloh/serial-link from serial_link import Link def run(port="/dev/ttyUSB0"): l = Link(port) while 1: l.read() if l.new_data: data = l.get_data().split(";") print(f"SW: {data[0]}") print(f"X: {data[1]}") print(f"Y: {data[2]}") print("==========================*==========================") if __name__ == "__main__": port =input("Please Enter port: ") run(port)
#!/usr/bin/env bash # # The Alluxio Open Foundation licenses this work under the Apache License, version 2.0 # (the "License"). You may not use this work except in compliance with the License, which is # available at www.apache.org/licenses/LICENSE-2.0 # # This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied, as more fully set forth in the License. # # See the NOTICE file distributed with this work for information regarding copyright ownership. # DISK=$(ls / | grep '^disk') TIERED_PATH="" TIERED_QUOTA="" for disk in ${DISK}; do TIERED_PATH=/${disk},${TIERED_PATH} quota=$(df -h | grep "/${disk}" | awk '{print $2}') TIERED_QUOTA=${quota}B,${TIERED_QUOTA} done [[ "$TIERED_PATH" == "" ]] && exit 0 sed -i "s/alluxio.worker.tieredstore.levels=1/alluxio.worker.tieredstore.levels=2/g " /alluxio/conf/alluxio-env.sh sed -i "/export ALLUXIO_JAVA_OPTS+=\"/ a\ -Dalluxio.worker.tieredstore.level1.dirs.quota=$TIERED_QUOTA " /alluxio/conf/alluxio-env.sh sed -i "/export ALLUXIO_JAVA_OPTS+=\"/ a\ -Dalluxio.worker.tieredstore.level1.dirs.path=$TIERED_PATH " /alluxio/conf/alluxio-env.sh sed -i "/export ALLUXIO_JAVA_OPTS+=\"/ a\ -Dalluxio.worker.tieredstore.level1.alias=SSD " /alluxio/conf/alluxio-env.sh
rm -rf temp/data/integration-test-wallet mkdir -p temp/data/integration-test-wallet export TARI_BASE_NODE__NETWORK=localnet export TARI_BASE_NODE__LOCALNET__DATA_DIR=localnet export TARI_BASE_NODE__LOCALNET__DB_TYPE=lmdb export TARI_BASE_NODE__LOCALNET__ORPHAN_STORAGE_CAPACITY=10 export TARI_BASE_NODE__LOCALNET__PRUNING_HORIZON=0 export TARI_BASE_NODE__LOCALNET__PRUNED_MODE_CLEANUP_INTERVAL=10000 export TARI_BASE_NODE__LOCALNET__CORE_THREADS=10 export TARI_BASE_NODE__LOCALNET__MAX_THREADS=512 export TARI_BASE_NODE__LOCALNET__ENABLE_WALLET=true export TARI_BASE_NODE__LOCALNET__IDENTITY_FILE=nodeid.json export TARI_BASE_NODE__LOCALNET__TOR_IDENTITY_FILE=node_tor_id.json export TARI_BASE_NODE__LOCALNET__WALLET_IDENTITY_FILE=walletid.json export TARI_BASE_NODE__LOCALNET__WALLET_TOR_IDENTITY_FILE=wallet_tor_id.json export TARI_BASE_NODE__LOCALNET__TRANSPORT=tcp export TARI_BASE_NODE__LOCALNET__TCP_LISTENER_ADDRESS=/ip4/0.0.0.0/tcp/18190 export TARI_BASE_NODE__LOCALNET__PUBLIC_ADDRESS=/ip4/0.0.0.0/tcp/18190 #export TARI_BASE_NODE__LOCALNET__TOR_CONTROL_ADDRESS=/ip4/127.0.0.1/tcp/9051 #export TARI_BASE_NODE__LOCALNET__TOR_CONTROL_AUTH=none #export TARI_BASE_NODE__LOCALNET__TOR_FORWARD_ADDRESS=/ip4/127.0.0.1/tcp/0 #export TARI_BASE_NODE__LOCALNET__TOR_ONION_PORT=18999 #export TARI_BASE_NODE__LOCALNET__PUBLIC_ADDRESS= export TARI_BASE_NODE__LOCALNET__GRPC_ENABLED=true export TARI_BASE_NODE__LOCALNET__GRPC_ADDRESS=127.0.0.1:9999 export TARI_BASE_NODE__LOCALNET__BLOCK_SYNC_STRATEGY=ViaBestChainMetadata export TARI_BASE_NODE__LOCALNET__ENABLE_MINING=false export TARI_BASE_NODE__LOCALNET__NUM_MINING_THREADS=1 export TARI_BASE_NODE__LOCALNET__ORPHAN_DB_CLEAN_OUT_THRESHOLD=0 # not used export TARI_BASE_NODE__LOCALNET__GRPC_WALLET_ADDRESS=127.0.0.1:50061 export TARI_MERGE_MINING_PROXY__LOCALNET__MONEROD_URL=aasdf export TARI_MERGE_MINING_PROXY__LOCALNET__MONEROD_USE_AUTH=false export TARI_MERGE_MINING_PROXY__LOCALNET__MONEROD_USERNAME=asdf export TARI_MERGE_MINING_PROXY__LOCALNET__MONEROD_PASSWORD=asdf export TARI_MERGE_MINING_PROXY__LOCALNET__PROXY_HOST_ADDRESS=127.0.0.1:9999 cd temp/data/integration-test-wallet cargo run --release --bin tari_console_wallet -- --base-path . --create-id --init cargo run --release --bin tari_console_wallet -- --base-path . -d
<filename>src/main/java/com/threathunter/bordercollie/slot/compute/graph/nodegenerator/FilterVariableNodeGenerator.java package com.threathunter.bordercollie.slot.compute.graph.nodegenerator; import com.threathunter.bordercollie.slot.compute.graph.node.FilterVariableNode; import com.threathunter.bordercollie.slot.compute.graph.node.VariableNode; import com.threathunter.bordercollie.slot.compute.graph.node.propertyhandler.condition.PropertyConditionHandlerGenerator; import com.threathunter.bordercollie.slot.compute.graph.node.propertyhandler.mapping.PropertyMappingHandler; import com.threathunter.bordercollie.slot.compute.graph.node.propertyhandler.mapping.PropertyMappingHandlerGenerator; import com.threathunter.common.Identifier; import com.threathunter.model.Property; import com.threathunter.model.PropertyCondition; import com.threathunter.model.PropertyMapping; import com.threathunter.variable.meta.FilterVariableMeta; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * */ public class FilterVariableNodeGenerator extends VariableNodeGenerator<FilterVariableMeta> { private static final Logger LOGGER = LoggerFactory.getLogger("bordercollie"); @Override public List<VariableNode> genVariableNodes() { FilterVariableNode node = new FilterVariableNode(); FilterVariableMeta meta = getVariableMeta(); node.setPriority(meta.getPriority()); node.setMeta(meta); node.setSrcIdentifiers(meta.getSrcVariableMetasID()); node.setIdentifier(Identifier.fromKeys(meta.getApp(), meta.getName())); PropertyCondition condition = meta.getPropertyCondition(); if (condition != null) { List<Property> srcProperty = condition.getSrcProperties(); if (srcProperty != null && srcProperty.get(0).getIdentifier() != null) { node.setConditionBefore(true); } else { node.setConditionBefore(false); } node.setConditionHandler(PropertyConditionHandlerGenerator.generateConditionHandler(meta.getPropertyCondition())); } List<PropertyMapping> mappings = meta.getPropertyMappings(); if (mappings != null && mappings.size() > 0) { List<PropertyMappingHandler> mappingHandlers = new ArrayList<>(); mappings.forEach(mapping -> mappingHandlers.add( PropertyMappingHandlerGenerator.generateMappingHandler(mapping) )); node.setMappingHandlers(mappingHandlers); } LOGGER.warn("TopVariableNodeGenerator , meta:{}",meta.to_json_object()); return Arrays.asList(node); } }
<reponame>Ravi9562/Sample #!/usr/bin/python from collections import defaultdict import requests import argparse parser = argparse.ArgumentParser(description="Run SQLI Tests") parser.add_argument("-hn", "--hostname", help="Hostname", required=True) parser.add_argument("-p", "--port", help="Port", required=True) parser.add_argument("-f", "--file", help="Data file", required=True) parser.add_argument("-d", "--debug", action="store_true") args = parser.parse_args() input_file = open(args.file) expected_dict = defaultdict(list) actual_dict = defaultdict(list) url = "http://{0}:{1}".format(args.hostname, args.port) for entry in input_file: parts = entry.strip().split("<split>") if parts[0] in expected_dict: expected_dict[parts[0]].append((parts[1], parts[2])) else: expected_dict[parts[0]] = [] expected_dict[parts[0]].append((parts[1], parts[2])) for key in expected_dict.keys(): actual_dict[key] = [] for key in expected_dict.keys(): for entry in expected_dict[key]: r = requests.get("{0}{1}{2}" .format(url, key, entry[0])) if args.debug: print r.url, r.status_code actual_dict[key].append((entry[0], r.status_code)) successful_tests = 0 log = open("results.csv", "a+") for key in actual_dict.keys(): counter = len(actual_dict[key]) for x in range(0, counter): if str(expected_dict[key][x][1]) == str(actual_dict[key][x][1]): successful_tests += 1 log.write("{0}{1},{2},{3}\n".format(url, key, expected_dict[key][x][1], actual_dict[key][x][1])) print("Servlet {0} had {1} tests. Pass: {2} Fail {3}" .format(key, counter, successful_tests, counter - successful_tests)) successful_tests = 0 log.close()
#! /bin/bash # [Topcoder] # This script consists of Test-case from 7 to 11 #exec >> automated_test2.log # Enable set -e to stop script in case of exception #set -e # http://stackoverflow.com/questions/59895/can-a-bash-script-tell-what-directory-its-stored-in?page=1&tab=votes#tab-top SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SOURCE="$(readlink "$SOURCE")" [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" #INSTALL_PATH="/Users/yyu/Documents/GitHub/OpenWARP/source" INSTALL_PATH=$NEMOHPATH ROOT="$DIR" echo $NEMOHPATH export LD_LIBRARY_PATH="$INSTALL_PATH/openwarpgui/bundled/simulation/libs:$LD_LIBRARY_PATH" export LDFLAGS="-L$INSTALL_PATH/openwarpgui/bundled/simulation/libs" export PYTOHNPATH="$INSTALL_PATH" export OMP_NUM_THREADS=1 mkdir -p ~/OpenWarpFiles/temp mkdir -p ~/OpenWarpFiles/user_data echo "------------------------" echo "-->Starting Nemoh Runs-" echo "------------------------" rm db.hdf5 rm -rf results #cd "$INSTALL_PATH" python "$INSTALL_PATH/openwarpgui/mesh/GDFtoDAT.py" "$DIR/mesh/flap.gdf" [0,0,-3.9] python "$INSTALL_PATH/openwarpgui/mesh/GDFtoDAT.py" "$DIR/mesh/base.gdf" [0,0,-10.9] ## python "$INSTALL_PATH/openwarpgui/openwarp_cli.py" "$DIR/Nemoh.json" echo "--> Nemoh run finished successfully"
import { MutationResult, useMutation } from "@apollo/client"; import { apolloCacheUpdateQuery } from "../../lib/apollo-immer"; import { PostFragment, PostVotersDocument, UserDetailsDocument, VoteDocument } from "../generated"; import { useSessionQuery } from "../queries/Session"; export type VoteFunction = (post: PostFragment, value: 0 | -1 | 1) => void; export function useVoteMutation(): [VoteFunction, MutationResult] { const { user } = useSessionQuery(); const [mutationFunction, mutationResult] = useMutation(VoteDocument); const voteFunction: VoteFunction = (post, value) => { const previousValue = (post.my_vote_value ?? 0) as 0 | 1 | -1; mutationFunction({ variables: { post_id: post.id, value }, optimisticResponse: { vote: { __typename: "VoteOutput", vote: { __typename: "votes", post: { __typename: "posts", id: post.id, vote_total: (post.vote_total ?? 0) + (value - previousValue), my_vote_value: value, }, }, }, }, update: (cache, { data }) => { if (!user || !data) return; // update list of post voters apolloCacheUpdateQuery(cache, { query: PostVotersDocument, variables: { postId: post.id }, update(query) { for (const which of ["upvotes", "downvotes"] as const) { query.posts_by_pk![which] = query.posts_by_pk![which].filter( (vote) => vote.user.id !== user.id, ); } if (value !== 0) { query.posts_by_pk![value === 1 ? "upvotes" : "downvotes"].push({ user }); } }, }); // update user details -> "upvotes given" & "downvotes given" apolloCacheUpdateQuery(cache, { query: UserDetailsDocument, variables: { id: user.id }, update(query) { const getAggregateForValue = (value: 1 | -1) => (value > 0 ? query.users_by_pk!.upvotes_aggregate : query.users_by_pk!.downvotes_aggregate ).aggregate!; if (previousValue) { getAggregateForValue(previousValue).count!--; } if (value) { getAggregateForValue(value).count!++; } }, }); }, }); }; return [voteFunction, mutationResult]; }
<filename>src/app/accounts/index.ts import { hashApiKey } from "@domain/accounts" import { ValidationError } from "@domain/errors" import { AccountApiKeysRepository, AccountsRepository, WalletsRepository, } from "@services/mongoose" export * from "./add-api-key-for-account" export * from "./get-api-keys-for-account" export * from "./disable-api-key-for-account" export const getAccount = async (accountId: AccountId) => { const accounts = AccountsRepository() return accounts.findById(accountId) } export const getAccountByApiKey = async ( key: string, secret: string, ): Promise<Account | ApplicationError> => { const hashedKey = await hashApiKey({ key, secret }) if (hashedKey instanceof Error) return hashedKey const accountApiKeysRepository = AccountApiKeysRepository() const accountApiKey = await accountApiKeysRepository.findByHashedKey(hashedKey) if (accountApiKey instanceof Error) return accountApiKey const accountRepo = AccountsRepository() return accountRepo.findById(accountApiKey.accountId) } export const hasPermissions = async ( userId: UserId, walletPublicId: WalletPublicId, ): Promise<boolean | ApplicationError> => { const accounts = AccountsRepository() const userAccounts = await accounts.listByUserId(userId) if (userAccounts instanceof Error) return userAccounts const walletAccount = await accounts.findByWalletPublicId(walletPublicId) if (walletAccount instanceof Error) return walletAccount return userAccounts.some((a) => a.id === walletAccount.id) } export const getBusinessMapMarkers = async () => { const accounts = AccountsRepository() return accounts.listBusinessesForMap() } export const toWalletIds = async ({ account, walletPublicIds, }: { account: Account walletPublicIds: WalletPublicId[] }): Promise<WalletId[] | ApplicationError> => { const wallets = WalletsRepository() const walletIds: WalletId[] = [] for (const walletPublicId of walletPublicIds) { const wallet = await wallets.findByPublicId(walletPublicId) if (wallet instanceof Error) { return wallet } if (!account.walletIds.includes(wallet.id)) { return new ValidationError() } walletIds.push(wallet.id) } return walletIds }
#!/bin/sh echo tutu echo "### nova boot " nova boot --flavor t1.cw.tiny --image "CentOS 6.5" --key-name KP_BadCops-Dev_GLL --security-groups SSH_Only,SGrpAdmin --user_data user_data_file.yaml IN-BAD-DEV1-GLL-01 echo "### sleep " sleep 30 echo "### nova floating-ip-associate " nova floating-ip-associate IN-BAD-DEV1-GLL-01 84.39.35.168 echo "### nova show " nova show IN-BAD-DEV1-GLL-01 sleep 10 echo "### nova floating-ip-associate " nova floating-ip-associate IN-BAD-DEV1-GLL-01 84.39.35.168 echo "### nova show " nova show IN-BAD-DEV1-GLL-01 echo titi
package redi import ( "github.com/gomodule/redigo/redis" "time" "github.com/name5566/leaf/log" ) var rediPool * redis.Pool func newPool(addr string, pwd string) *redis.Pool { if addr == "" || pwd == "" { return nil } return &redis.Pool{ MaxIdle: 3, IdleTimeout: 240 * time.Second, Dial: func () (redis.Conn, error) { c, err := redis.Dial("tcp", addr) if err != nil { return nil, err } if _, err := c.Do("AUTH", pwd); err != nil { c.Close() return nil, err } return c, nil }, } } //var ( // pool *redis.Pool // redisServer = flag.String("redisServer", ":6379", "") //) //func main() { // flag.Parse() // pool = newPool(*redisServer) // //} func RedisInit(url string, pwd string) *redis.Pool{ rediPool := newPool(url, pwd) if rediPool == nil { log.Fatal("rdisInit fail") } con, err := rediPool.Dial() if con == nil { log.Fatal("rediPool dial error-%v", err) } return rediPool //c := rediPool.Get() //defer c.Close() // //if _, err := c.Do("AUTH", conf.Server.RedisPwdLogin); err != nil { // log.Fatal("redis AUTH failed pd:b840fc02d524045429941cc15f59e41cb7be6c5288") //} // // ////c.Do("hgetall, "myname", "superL") //table, err := c.Do("hget", "client1", "name") //if err != nil { // log.Debug("redis get failed", err) //} else { // t2 := table.([]byte) // userName := string(t2) // log.Debug("t2", userName) // //var t1 = table.([]interface{}) // //for index, data := range t1 { // // log.Debug("get mykey:%v%v\n", index, string(data.([]byte))) // //} // //} //string(table[0]) //username, err := redis.String(c.Do("Get", "mykey")) //if err != nil { // log.Debug("redis get failed", err) //} else { // log.Debug("get mykey:%v\n", username) //} }
<gh_stars>1-10 package fetch import ( "fmt" "os" "testing" ) func TestGetMaxWidth(t *testing.T) { os.Setenv("VIP_MAX_WIDTH", "500") if width := getMaxWidth(); width != 500 { t.Fail() } os.Setenv("VIP_MAX_WIDTH", "1024") if width := getMaxWidth(); width != 1024 { t.Fail() } // Test default value os.Setenv("VIP_MAX_WIDTH", "") if width := getMaxWidth(); width != 720 { t.Fail() } } func TestNeedsRotation(t *testing.T) { for i := 1; i <= 8; i++ { filename := fmt.Sprintf("f%d-exif.jpg", i) f, err := os.Open(fmt.Sprintf("../test/%s", filename)) if err != nil { t.Errorf("Could not open %s.", filename) } angle := needsRotation(f) switch i { case 6: if angle != 270 { t.Errorf("Expected 270; got %d", angle) } case 3: if angle != 180 { t.Errorf("Expected 180; got %d", angle) } case 8: if angle != 90 { t.Errorf("Expected 90; got %d", angle) } default: if angle != 0 { t.Errorf("Expected 0; got %d", angle) } } } } func TestNeedsRotationAltFiles(t *testing.T) { filenames := map[int]string{ 1: "awesome.jpeg", 2: "exif_test_img.jpg", } for key, filename := range filenames { f, err := os.Open(fmt.Sprintf("../test/%s", filename)) if err != nil { t.Errorf("Could not open %s.", filename) } angle := needsRotation(f) switch key { case 1: if angle != 0 { t.Errorf("Expected 0; got %d", angle) } case 2: if angle != 270 { t.Errorf("Expected 270; got %d", angle) } } } }
/* * Copyright 2011-2021 Branimir Karadzic. All rights reserved. * License: https://github.com/bkaradzic/bgfx#license-bsd-2-clause */ #ifndef __SHADERLIB_SH__ #define __SHADERLIB_SH__ vec4 encodeRE8(float _r) { float exponent = ceil(log2(_r) ); return vec4(_r / exp2(exponent) , 0.0 , 0.0 , (exponent + 128.0) / 255.0 ); } float decodeRE8(vec4 _re8) { float exponent = _re8.w * 255.0 - 128.0; return _re8.x * exp2(exponent); } vec4 encodeRGBE8(vec3 _rgb) { vec4 rgbe8; float maxComponent = max(max(_rgb.x, _rgb.y), _rgb.z); float exponent = ceil(log2(maxComponent) ); rgbe8.xyz = _rgb / exp2(exponent); rgbe8.w = (exponent + 128.0) / 255.0; return rgbe8; } vec3 decodeRGBE8(vec4 _rgbe8) { float exponent = _rgbe8.w * 255.0 - 128.0; vec3 rgb = _rgbe8.xyz * exp2(exponent); return rgb; } vec3 encodeNormalUint(vec3 _normal) { return _normal * 0.5 + 0.5; } vec3 decodeNormalUint(vec3 _encodedNormal) { return _encodedNormal * 2.0 - 1.0; } vec2 encodeNormalSphereMap(vec3 _normal) { return normalize(_normal.xy) * sqrt(_normal.z * 0.5 + 0.5); } vec3 decodeNormalSphereMap(vec2 _encodedNormal) { float zz = dot(_encodedNormal, _encodedNormal) * 2.0 - 1.0; return vec3(normalize(_encodedNormal.xy) * sqrt(1.0 - zz*zz), zz); } vec2 octahedronWrap(vec2 _val) { // Reference(s): // - Octahedron normal vector encoding // https://web.archive.org/web/20191027010600/https://knarkowicz.wordpress.com/2014/04/16/octahedron-normal-vector-encoding/comment-page-1/ return (1.0 - abs(_val.yx) ) * mix(vec2_splat(-1.0), vec2_splat(1.0), vec2(greaterThanEqual(_val.xy, vec2_splat(0.0) ) ) ); } vec2 encodeNormalOctahedron(vec3 _normal) { _normal /= abs(_normal.x) + abs(_normal.y) + abs(_normal.z); _normal.xy = _normal.z >= 0.0 ? _normal.xy : octahedronWrap(_normal.xy); _normal.xy = _normal.xy * 0.5 + 0.5; return _normal.xy; } vec3 decodeNormalOctahedron(vec2 _encodedNormal) { _encodedNormal = _encodedNormal * 2.0 - 1.0; vec3 normal; normal.z = 1.0 - abs(_encodedNormal.x) - abs(_encodedNormal.y); normal.xy = normal.z >= 0.0 ? _encodedNormal.xy : octahedronWrap(_encodedNormal.xy); return normalize(normal); } vec3 convertRGB2XYZ(vec3 _rgb) { // Reference(s): // - RGB/XYZ Matrices // https://web.archive.org/web/20191027010220/http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html vec3 xyz; xyz.x = dot(vec3(0.4124564, 0.3575761, 0.1804375), _rgb); xyz.y = dot(vec3(0.2126729, 0.7151522, 0.0721750), _rgb); xyz.z = dot(vec3(0.0193339, 0.1191920, 0.9503041), _rgb); return xyz; } vec3 convertXYZ2RGB(vec3 _xyz) { vec3 rgb; rgb.x = dot(vec3( 3.2404542, -1.5371385, -0.4985314), _xyz); rgb.y = dot(vec3(-0.9692660, 1.8760108, 0.0415560), _xyz); rgb.z = dot(vec3( 0.0556434, -0.2040259, 1.0572252), _xyz); return rgb; } vec3 convertXYZ2Yxy(vec3 _xyz) { // Reference(s): // - XYZ to xyY // https://web.archive.org/web/20191027010144/http://www.brucelindbloom.com/index.html?Eqn_XYZ_to_xyY.html float inv = 1.0/dot(_xyz, vec3(1.0, 1.0, 1.0) ); return vec3(_xyz.y, _xyz.x*inv, _xyz.y*inv); } vec3 convertYxy2XYZ(vec3 _Yxy) { // Reference(s): // - xyY to XYZ // https://web.archive.org/web/20191027010036/http://www.brucelindbloom.com/index.html?Eqn_xyY_to_XYZ.html vec3 xyz; xyz.x = _Yxy.x*_Yxy.y/_Yxy.z; xyz.y = _Yxy.x; xyz.z = _Yxy.x*(1.0 - _Yxy.y - _Yxy.z)/_Yxy.z; return xyz; } vec3 convertRGB2Yxy(vec3 _rgb) { return convertXYZ2Yxy(convertRGB2XYZ(_rgb) ); } vec3 convertYxy2RGB(vec3 _Yxy) { return convertXYZ2RGB(convertYxy2XYZ(_Yxy) ); } vec3 convertRGB2Yuv(vec3 _rgb) { vec3 yuv; yuv.x = dot(_rgb, vec3(0.299, 0.587, 0.114) ); yuv.y = (_rgb.x - yuv.x)*0.713 + 0.5; yuv.z = (_rgb.z - yuv.x)*0.564 + 0.5; return yuv; } vec3 convertYuv2RGB(vec3 _yuv) { vec3 rgb; rgb.x = _yuv.x + 1.403*(_yuv.y-0.5); rgb.y = _yuv.x - 0.344*(_yuv.y-0.5) - 0.714*(_yuv.z-0.5); rgb.z = _yuv.x + 1.773*(_yuv.z-0.5); return rgb; } vec3 convertRGB2YIQ(vec3 _rgb) { vec3 yiq; yiq.x = dot(vec3(0.299, 0.587, 0.114 ), _rgb); yiq.y = dot(vec3(0.595716, -0.274453, -0.321263), _rgb); yiq.z = dot(vec3(0.211456, -0.522591, 0.311135), _rgb); return yiq; } vec3 convertYIQ2RGB(vec3 _yiq) { vec3 rgb; rgb.x = dot(vec3(1.0, 0.9563, 0.6210), _yiq); rgb.y = dot(vec3(1.0, -0.2721, -0.6474), _yiq); rgb.z = dot(vec3(1.0, -1.1070, 1.7046), _yiq); return rgb; } vec3 toLinear(vec3 _rgb) { return pow(abs(_rgb), vec3_splat(2.2) ); } vec4 toLinear(vec4 _rgba) { return vec4(toLinear(_rgba.xyz), _rgba.w); } vec3 toLinearAccurate(vec3 _rgb) { vec3 lo = _rgb / 12.92; vec3 hi = pow( (_rgb + 0.055) / 1.055, vec3_splat(2.4) ); vec3 rgb = mix(hi, lo, vec3(lessThanEqual(_rgb, vec3_splat(0.04045) ) ) ); return rgb; } vec4 toLinearAccurate(vec4 _rgba) { return vec4(toLinearAccurate(_rgba.xyz), _rgba.w); } float toGamma(float _r) { return pow(abs(_r), 1.0/2.2); } vec3 toGamma(vec3 _rgb) { return pow(abs(_rgb), vec3_splat(1.0/2.2) ); } vec4 toGamma(vec4 _rgba) { return vec4(toGamma(_rgba.xyz), _rgba.w); } vec3 toGammaAccurate(vec3 _rgb) { vec3 lo = _rgb * 12.92; vec3 hi = pow(abs(_rgb), vec3_splat(1.0/2.4) ) * 1.055 - 0.055; vec3 rgb = mix(hi, lo, vec3(lessThanEqual(_rgb, vec3_splat(0.0031308) ) ) ); return rgb; } vec4 toGammaAccurate(vec4 _rgba) { return vec4(toGammaAccurate(_rgba.xyz), _rgba.w); } vec3 toReinhard(vec3 _rgb) { return toGamma(_rgb/(_rgb+vec3_splat(1.0) ) ); } vec4 toReinhard(vec4 _rgba) { return vec4(toReinhard(_rgba.xyz), _rgba.w); } vec3 toFilmic(vec3 _rgb) { _rgb = max(vec3_splat(0.0), _rgb - 0.004); _rgb = (_rgb*(6.2*_rgb + 0.5) ) / (_rgb*(6.2*_rgb + 1.7) + 0.06); return _rgb; } vec4 toFilmic(vec4 _rgba) { return vec4(toFilmic(_rgba.xyz), _rgba.w); } vec3 toAcesFilmic(vec3 _rgb) { // Reference(s): // - ACES Filmic Tone Mapping Curve // https://web.archive.org/web/20191027010704/https://knarkowicz.wordpress.com/2016/01/06/aces-filmic-tone-mapping-curve/ float aa = 2.51f; float bb = 0.03f; float cc = 2.43f; float dd = 0.59f; float ee = 0.14f; return saturate( (_rgb*(aa*_rgb + bb) )/(_rgb*(cc*_rgb + dd) + ee) ); } vec4 toAcesFilmic(vec4 _rgba) { return vec4(toAcesFilmic(_rgba.xyz), _rgba.w); } vec3 luma(vec3 _rgb) { float yy = dot(vec3(0.2126729, 0.7151522, 0.0721750), _rgb); return vec3_splat(yy); } vec4 luma(vec4 _rgba) { return vec4(luma(_rgba.xyz), _rgba.w); } vec3 conSatBri(vec3 _rgb, vec3 _csb) { vec3 rgb = _rgb * _csb.z; rgb = mix(luma(rgb), rgb, _csb.y); rgb = mix(vec3_splat(0.5), rgb, _csb.x); return rgb; } vec4 conSatBri(vec4 _rgba, vec3 _csb) { return vec4(conSatBri(_rgba.xyz, _csb), _rgba.w); } vec3 posterize(vec3 _rgb, float _numColors) { return floor(_rgb*_numColors) / _numColors; } vec4 posterize(vec4 _rgba, float _numColors) { return vec4(posterize(_rgba.xyz, _numColors), _rgba.w); } vec3 sepia(vec3 _rgb) { vec3 color; color.x = dot(_rgb, vec3(0.393, 0.769, 0.189) ); color.y = dot(_rgb, vec3(0.349, 0.686, 0.168) ); color.z = dot(_rgb, vec3(0.272, 0.534, 0.131) ); return color; } vec4 sepia(vec4 _rgba) { return vec4(sepia(_rgba.xyz), _rgba.w); } vec3 blendOverlay(vec3 _base, vec3 _blend) { vec3 lt = 2.0 * _base * _blend; vec3 gte = 1.0 - 2.0 * (1.0 - _base) * (1.0 - _blend); return mix(lt, gte, step(vec3_splat(0.5), _base) ); } vec4 blendOverlay(vec4 _base, vec4 _blend) { return vec4(blendOverlay(_base.xyz, _blend.xyz), _base.w); } vec3 adjustHue(vec3 _rgb, float _hue) { vec3 yiq = convertRGB2YIQ(_rgb); float angle = _hue + atan2(yiq.z, yiq.y); float len = length(yiq.yz); return convertYIQ2RGB(vec3(yiq.x, len*cos(angle), len*sin(angle) ) ); } vec4 packFloatToRgba(float _value) { const vec4 shift = vec4(256 * 256 * 256, 256 * 256, 256, 1.0); const vec4 mask = vec4(0, 1.0 / 256.0, 1.0 / 256.0, 1.0 / 256.0); vec4 comp = fract(_value * shift); comp -= comp.xxyz * mask; return comp; } float unpackRgbaToFloat(vec4 _rgba) { const vec4 shift = vec4(1.0 / (256.0 * 256.0 * 256.0), 1.0 / (256.0 * 256.0), 1.0 / 256.0, 1.0); return dot(_rgba, shift); } vec2 packHalfFloat(float _value) { const vec2 shift = vec2(256, 1.0); const vec2 mask = vec2(0, 1.0 / 256.0); vec2 comp = fract(_value * shift); comp -= comp.xx * mask; return comp; } float unpackHalfFloat(vec2 _rg) { const vec2 shift = vec2(1.0 / 256.0, 1.0); return dot(_rg, shift); } float random(vec2 _uv) { return fract(sin(dot(_uv.xy, vec2(12.9898, 78.233) ) ) * 43758.5453); } vec3 fixCubeLookup(vec3 _v, float _lod, float _topLevelCubeSize) { // Reference(s): // - Seamless cube-map filtering // https://web.archive.org/web/20190411181934/http://the-witness.net/news/2012/02/seamless-cube-map-filtering/ float ax = abs(_v.x); float ay = abs(_v.y); float az = abs(_v.z); float vmax = max(max(ax, ay), az); float scale = 1.0 - exp2(_lod) / _topLevelCubeSize; if (ax != vmax) { _v.x *= scale; } if (ay != vmax) { _v.y *= scale; } if (az != vmax) { _v.z *= scale; } return _v; } vec2 texture2DBc5(sampler2D _sampler, vec2 _uv) { #if BGFX_SHADER_LANGUAGE_HLSL && BGFX_SHADER_LANGUAGE_HLSL <= 300 return texture2D(_sampler, _uv).yx; #else return texture2D(_sampler, _uv).xy; #endif } mat3 cofactor(mat4 _m) { // Reference: // Cofactor of matrix. Use to transform normals. The code assumes the last column of _m is [0,0,0,1]. // https://www.shadertoy.com/view/3s33zj // https://github.com/graphitemaster/normals_revisited return mat3( _m[1][1]*_m[2][2]-_m[1][2]*_m[2][1], _m[1][2]*_m[2][0]-_m[1][0]*_m[2][2], _m[1][0]*_m[2][1]-_m[1][1]*_m[2][0], _m[0][2]*_m[2][1]-_m[0][1]*_m[2][2], _m[0][0]*_m[2][2]-_m[0][2]*_m[2][0], _m[0][1]*_m[2][0]-_m[0][0]*_m[2][1], _m[0][1]*_m[1][2]-_m[0][2]*_m[1][1], _m[0][2]*_m[1][0]-_m[0][0]*_m[1][2], _m[0][0]*_m[1][1]-_m[0][1]*_m[1][0] ); } #endif // __SHADERLIB_SH__
'use strict'; // ***************************************************** // API // ***************************************************** function ResultSet() { this.loaded = false; this.loading = true; } ResultSet.prototype.set = function(error, value) { this.loaded = true; this.loading = false; this.error = error; this.affix = value; this.value = (this.value instanceof Array && value instanceof Array) ? this.value.concat(value) : value; }; module.factory('$RAW', ['$http', function($http) { return { call: function(m, f, d, c) { var now = new Date(); return $http.post('/api/' + m + '/' + f, d) .success(function(res) { // parse result (again) try { res = JSON.parse(res); } catch (ex) {} // yield result c(null, res, new Date() - now); }) .error(function(res) { c(res, null, new Date() - now); }); } }; } ]); module.factory('$RPC', ['$RAW', '$log', function($RAW, $log) { return { call: function(m, f, d, c) { var res = new ResultSet(); $RAW.call(m, f, d, function(error, value) { res.set(error, value); $log.debug('$RPC', m, f, d, res, res.error); if (typeof c === 'function') { c(res.error, res); } }); return res; } }; } ]); module.factory('$RPCService', ['$q', '$RPC', function($q, $RPC) { return { call: function(o, f, d, c) { var deferred = $q.defer(); $RPC.call(o, f, d, function(err, obj) { if (typeof c === 'function') { c(err, obj); } if(!err) { deferred.resolve(obj); } return deferred.reject(); }); return deferred.promise; } }; } ]);
package ctag.tags; import ctag.Binary; import ctag.CTagInput; import ctag.exception.EndException; import ctag.exception.NegativeLengthException; import java.io.IOException; /** * The tag that represents a signed 32bit integer array. * <br/><br/> * <table> * <tr> * <td><b>Binary prefix: </b></td> * <td><code>00001110 - 0E</code></td> * </tr> * <tr> * <td><b>Minimal payload: </b></td> * <td>2 bytes</td> * </tr> * <tr> * <td><b>Maximal payload: </b></td> * <td>262146 bytes</td> * </tr> * </table> * The integer array binary starts with two bytes holding the length, followed * by a series of 4-byte strings holding the values respectively. * <br/> * <pre> * Prefix Length Value 1 ... * 00001110 0000000000000001 00000000000000000000000000001001 * INTEGER_ARRAY length = 1 = 9 * </pre> * @since 1.0 */ public class TagIntegerArray implements ITag<int[]> { private int[] array; public TagIntegerArray( int... ints ) { array = ints; } @Override public Binary encode() { Binary.Builder builder = new Binary.Builder(); builder.append( new TagShort( ( short ) array.length ).encode() ); for( int s : array ) { builder.append( new TagInteger( s ).encode() ); } return builder.build(); } @Override public int[] getValue() { return array; } @Override public void setValue( int[] value ) { array = value; } @Override public Binary getPrefixByte() { return new Binary( ( byte ) 0b1110 ); } /** * Parses a CTag code as an integer array. * @param input The {@link CTagInput} stream that possibly begins with this * integer array data. * @return The parsed {@link TagIntegerArray} if parsed with success. * @exception IOException If the {@link CTagInput}'s underlying stream * throws an IOException. * @since 1.0 */ public static TagIntegerArray parse( CTagInput input ) throws IOException, EndException, NegativeLengthException { short len = TagShort.parse( input ).getValue(); if( len < 0 ) throw new NegativeLengthException( "Found array with negative length" ); int[] ints = new int[ len ]; for( int i = 0; i < len; i++ ) { ints[ i ] = TagInteger.parse( input ).getValue(); } return new TagIntegerArray( ints ); } public String toString() { StringBuilder builder = new StringBuilder( "INTEGER_ARRAY [\n" ); int i = 0; for( int b : array ) { builder.append( " " ); builder.append( i ); builder.append( ": " ); builder.append( b ); builder.append( "\n" ); i++; } builder.append( "]" ); return builder.toString(); } }
function sendEmail() { var address = "example@example.com"; var subject = "Automatic Message"; var message = "Hello!"; MailApp.sendEmail(address, subject, message); }
./yaml2latex mv xvi-wiek.tex ../tufte-latex/ cd ../tufte-latex/ pdflatex xvi-wiek.tex pdflatex xvi-wiek.tex texindy xvi-wiek.idx -L polish -C utf8 pdflatex xvi-wiek.tex cp xvi-wiek.pdf ../xvi-wiek/ui/static/pdf/
class User: def __init__(self, name): self.name = name def update_name(self, new_name): self.name = new_name
#!/bin/bash urdfFile=`rospack find $1`/$1.urdf echo link,mass,ixx,iyy,izz,ixy,ixz,iyz for suffix in \ `xmlstarlet sel -t -v '//link/@name' $urdfFile | \ grep '^r_' | sed -e 's@^r@@'` do xmlstarlet sel -t -o "r$suffix," \ -t -v "//link[@name='r$suffix']/inertial/mass/@value" -t -o ',' \ -t -v "//link[@name='r$suffix']/inertial/inertia/@ixx" -t -o ',' \ -t -v "//link[@name='r$suffix']/inertial/inertia/@iyy" -t -o ',' \ -t -v "//link[@name='r$suffix']/inertial/inertia/@izz" -t -o ',' \ -t -v "//link[@name='r$suffix']/inertial/inertia/@ixy" -t -o ',' \ -t -v "//link[@name='r$suffix']/inertial/inertia/@ixz" -t -o ',' \ -t -v "//link[@name='r$suffix']/inertial/inertia/@iyz" $urdfFile xmlstarlet sel -t -o "l$suffix," \ -t -v "//link[@name='l$suffix']/inertial/mass/@value" -t -o ',' \ -t -v "//link[@name='l$suffix']/inertial/inertia/@ixx" -t -o ',' \ -t -v "//link[@name='l$suffix']/inertial/inertia/@iyy" -t -o ',' \ -t -v "//link[@name='l$suffix']/inertial/inertia/@izz" -t -o ',' \ -t -v "//link[@name='l$suffix']/inertial/inertia/@ixy" -t -o ',' \ -t -v "//link[@name='l$suffix']/inertial/inertia/@ixz" -t -o ',' \ -t -v "//link[@name='l$suffix']/inertial/inertia/@iyz" $urdfFile done
#!/bin/bash set -o errexit -o nounset rev=$(git rev-parse --short HEAD) ldoc -d $CIRCLE_ARTIFACTS/docs . cd $CIRCLE_ARTIFACTS/docs git init git config user.name "Kyle McLamb" git config user.email "kjmclamb@gmail.com" git remote add upstream "https://$GH_API@github.com/Alloyed/ltrie.git" git fetch upstream git reset upstream/gh-pages git add -A . git commit -m "rebuild pages at ${rev}" git push -q upstream HEAD:gh-pages rm -rf .git
#!/bin/bash set -e -u MAKE="make $1" PLATFORM=`gcc -dumpmachine` UNAME=`uname` MACHINE=`uname -m` echo $UNAME echo $MACHINE function contains () { # helper function to determine whether a bash array contains a certain element # http://stackoverflow.com/questions/3685970/bash-check-if-an-array-contains-a-value local n=$# local value=${!n} for ((i=1;i < $#;i++)) { if [ "${!i}" == "${value}" ]; then echo "y" return 0 fi } echo "n" return 1 } if [ "$UNAME" = "Linux" ]; then if [ "$MACHINE" = "armv6l" ]; then BLACKLIST=(amp audio biosemi ctf emotiv neuralynx neuromag siemens tmsi tobi) else BLACKLIST=(audio emotiv neuralynx siemens tmsi tobi) fi fi if [ "$UNAME" = "Darwin" ]; then BLACKLIST=(audio emotiv neuralynx siemens neuromag tmsi tobi ctf) fi echo Building buffer and ODM... (cd buffer/src && $MAKE) (cd buffer/cpp && $MAKE) echo Building acquisition... for ac in `ls -d acquisition/*/`; do SHORTNAME=`basename $ac` echo $SHORTNAME if [ $(contains ${BLACKLIST[@]} ${SHORTNAME}) == "y" ] ; then echo \'$SHORTNAME\' is blacklisted for this platform. else echo Building \'$ac\'... (cd $ac && $MAKE) fi done echo Building utilities... for ac in `ls -d utilities/*/`; do SHORTNAME=`basename $ac` echo $SHORTNAME if [ $(contains ${BLACKLIST[@]} ${SHORTNAME}) == "y" ] ; then echo \'$SHORTNAME\' is blacklisted for this platform. else echo Building \'$ac\'... (cd $ac && $MAKE) fi done
#!/usr/bin/env sh CONFIG_PATH=/config TEMPLATES="http.conf.template mail.conf.template nginx.conf.template proxy.conf.template tls.conf.template" function render_template() { eval "echo \"$(cat $1)\"" } function generate_configs() { for item in ${TEMPLATES}; do render_template ${CONFIG_PATH}/${item} > ${CONFIG_PATH}/${item%.template} rm ${CONFIG_PATH}/${item} done } if [[ "${DOMAIN?}" -a "${SERVER_NAMES?}" ]]; then generate_configs mkdir /etc/ssl/${DOMAIN} mkdir /var/log/nginx/${DOMAIN} cp ${CONFIG_PATH}/http.conf /etc/nginx/conf.d/default.conf cp ${CONFIG_PATH}/mail.conf /etc/nginx/conf.d/ cp ${CONFIG_PATH}/nginx.conf /etc/nginx/ cp ${CONFIG_PATH}/proxy.conf /etc/nginx/ cp ${CONFIG_PATH}/tls.conf /etc/nginx/ fi exec "$@"
import java.util.Random; public class Program { public static void main(String[] args){ String password = generatePassword("alice"); System.out.println(password); } public static String generatePassword(String str) { String numbers = "0123456789"; String lower_case = "abcdefghijklmnopqrstuvwxyz"; String upper_case = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; String password = ""; SecureRandom random = new SecureRandom(); while (password.length() < 3) { int rnd = random.nextInt(3); if (rnd == 0){ int index = random.nextInt(numbers.length()); char ch = numbers.charAt(index); password += ch; } else if (rnd == 1) { int index = random.nextInt(lower_case.length()); char ch = lower_case.charAt(index); password += ch; } else if (rnd == 2) { int index = random.nextInt(upper_case.length()); char ch = upper_case.charAt(index); password += ch; } } password += str.charAt(random.nextInt(str.length())); return password; } } // Output: A3ic3
""" Enhance the existing code such that it can process multi-dimensional lists recursively. """ def sum_list(in_list): if not isinstance(in_list, list): return print("Error: input must be a list") total = 0 for item in in_list: if isinstance(item, list): total += sum_list(item) else: total += item return total
<filename>src/app/shared/models/table/column.ts export class Column<T> { public readonly columnDef: string; public readonly key: string; public readonly cell: (element: T) => string; constructor(columnDef: string, key: string, cell: (element: T) => string) { this.columnDef = columnDef; this.key = key; this.cell = cell; } }
# Imports from flask import Flask, render_template, request from sklearn.externals import joblib # App app = Flask(__name__) # Load the model model = joblib.load(Python Machine Learning model file) # Routes @app.route('/', methods=['GET', 'POST']) def predict(): # Get the data from the POST request. data = request.form # Make prediction using the model. prediction = model.predict(data) # Render template return render_template('index.html', prediction=prediction) # Run App if __name__ == '__main__': app.run(debug=True)
<reponame>ideacrew/pa_edidb class UpdatePersonAddress def initialize(person_repo, address_changer, change_address_request_factory) @person_repo = person_repo @address_changer = address_changer @change_address_request_factory = change_address_request_factory end def validate(request, listener) fail = false person = @person_repo.find_by_id(request[:person_id]) if(missing_home_address?(request)) listener.home_address_not_present fail = true end type_count_map = {} request[:addresses].each do |address| type_count_map[address[:address_type]] ||= 0 type_count_map[address[:address_type]] += 1 end type_count_map.each_pair do |type, count| max = 1 if(count > max) listener.too_many_addresses_of_type({address_type: type, max: max}) fail = true end end addresses_valid = true request[:addresses].each_with_index do |address, idx| listener.set_current_address(idx) change_address_request = @change_address_request_factory.from_person_update_request(address, { :person_id => request[:person_id], :current_user => request[:current_user] }) addresses_valid = addresses_valid && @address_changer.validate(change_address_request, listener) end if listener.has_errors? fail = true end unless addresses_valid fail = true end !fail end def execute(request, listener) if validate(request, listener) commit(request) listener.success else listener.fail end end def commit(request) person = @person_repo.find_by_id(request[:person_id]) address_deleter = DeleteAddress.new(NullPolicyMaintenance.new, @person_repo) Address::TYPES.each do |t| request_address = request[:addresses].detect { |a| a[:address_type] == t } if (request_address.nil?) address_deleter.commit({ :person_id => request[:person_id], :type => t, :current_user => request[:current_user] } ) else change_address_request = @change_address_request_factory.from_person_update_request(request_address, { :person_id => request[:person_id], :current_user => request[:current_user] }) @address_changer.commit(change_address_request) end end person.updated_by = request[:current_user] person.save! end protected def missing_home_address?(request) request[:addresses].detect { |a| a[:address_type] == 'home' }.nil? end end
<reponame>chylex/Hardcore-Ender-Expansion package chylex.hee.entity.mob.ai.target; import net.minecraft.entity.EntityCreature; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import chylex.hee.entity.mob.ai.base.EntityAIAbstractTarget; import chylex.hee.system.abstractions.Vec; import chylex.hee.system.abstractions.entity.EntitySelector; import chylex.hee.system.util.MathUtil; public class EntityAIDirectLookTarget extends EntityAIAbstractTarget{ private final ITargetOnDirectLook lookHandler; private double maxDistance = 32D; private int tickLimiter, lookTimer; public EntityAIDirectLookTarget(EntityCreature owner, ITargetOnDirectLook lookHandler){ super(owner, true, false); this.lookHandler = lookHandler; } public EntityAIDirectLookTarget setMaxDistance(double maxDistance){ this.maxDistance = maxDistance; return this; } @Override protected EntityLivingBase findNewTarget(){ if (++tickLimiter < 2)return null; tickLimiter = 0; for(EntityPlayer player:EntitySelector.players(taskOwner.worldObj, taskOwner.boundingBox.expand(maxDistance, maxDistance, maxDistance))){ double dist = MathUtil.distance(player.posX-taskOwner.posX, player.posY-taskOwner.posY, player.posZ-taskOwner.posZ); if (dist <= maxDistance && isPlayerLookingIntoEyes(player) && lookHandler.canTargetOnDirectLook(player, dist)){ if (++lookTimer == 4){ lookTimer = 0; return player; } else return null; } } lookTimer = 0; return null; } private boolean isPlayerLookingIntoEyes(EntityPlayer target){ ItemStack headIS = target.inventory.armorInventory[3]; if (headIS != null && headIS.getItem() == Item.getItemFromBlock(Blocks.pumpkin))return false; Vec posDiff = Vec.between(target, taskOwner); posDiff.y += taskOwner.height*0.9D-target.getEyeHeight(); double dist = posDiff.length(); double dot = Vec.xyzLook(target).dotProduct(posDiff.normalized()); return Math.abs(dot-1D) < 0.05D/MathUtil.square(dist) && target.canEntityBeSeen(taskOwner); } @FunctionalInterface public static interface ITargetOnDirectLook{ boolean canTargetOnDirectLook(EntityPlayer target, double distance); } }
#!/bin/bash # Script Path SCRIPT="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" # Go to root path of application cd $SCRIPT && cd .. echo "===========================================" echo "==== Reset node_modules and components ====" echo "===========================================" echo "" echo "=== Delete node_modules" rm package-lock.json rm -r ./node_modules echo "=== finished" echo "" echo "=== Delete components" rm -r ./app/components echo "=== finished" echo "" echo "=== Clean cache npm" npm cache clean --force echo "=== finished" echo "" echo "=== Install node_modules" npm install echo "=== finished" echo ""
termux_step_install_license() { [ "$TERMUX_PKG_METAPACKAGE" = "true" ] && return mkdir -p "$TERMUX_PREFIX/share/doc/$TERMUX_PKG_NAME" local LICENSE local COUNTER=0 if [ ! "${TERMUX_PKG_LICENSE_FILE}" = "" ]; then INSTALLED_LICENSES=() COUNTER=1 while read -r LICENSE; do if [ ! -f "$TERMUX_PKG_SRCDIR/$LICENSE" ]; then termux_error_exit "$TERMUX_PKG_SRCDIR/$LICENSE does not exist" fi if [[ " ${INSTALLED_LICENSES[@]} " =~ " $(basename $LICENSE) " ]]; then # We have already installed a license file named $(basename $LICENSE) so add a suffix to it TARGET="$TERMUX_PREFIX/share/doc/${TERMUX_PKG_NAME}/$(basename $LICENSE).$COUNTER" COUNTER=$((COUNTER + 1)) else TARGET="$TERMUX_PREFIX/share/doc/${TERMUX_PKG_NAME}/$(basename $LICENSE)" INSTALLED_LICENSES+=("$(basename $LICENSE)") fi cp -f "${TERMUX_PKG_SRCDIR}/${LICENSE}" "$TARGET" done < <(echo "$TERMUX_PKG_LICENSE_FILE" | sed "s/,/\n/g") else while read -r LICENSE; do # These licenses contain copyright information, so # we cannot use a generic license file if [ "$LICENSE" == "MIT" ] || \ [ "$LICENSE" == "ISC" ] || \ [ "$LICENSE" == "PythonPL" ] || \ [ "$LICENSE" == "Openfont-1.1" ] || \ [ "$LICENSE" == "ZLIB" ] || \ [ "$LICENSE" == "Libpng" ] || \ [ "$LICENSE" == "BSD" ] || \ [ "$LICENSE" == "BSD 2-Clause" ] || \ [ "$LICENSE" == "BSD 3-Clause" ]; then for FILE in LICENSE \ LICENSE.md \ LICENSE.txt \ LICENSE.TXT \ COPYING \ COPYRIGHT \ Copyright.txt \ Copyright \ LICENCE \ License \ license \ license.md \ License.txt \ license.txt \ licence; do if [ -f "$TERMUX_PKG_SRCDIR/$FILE" ]; then if [[ $COUNTER -gt 0 ]]; then cp -f "${TERMUX_PKG_SRCDIR}/$FILE" "${TERMUX_PREFIX}/share/doc/${TERMUX_PKG_NAME}/LICENSE.${COUNTER}" else cp -f "${TERMUX_PKG_SRCDIR}/$FILE" "${TERMUX_PREFIX}/share/doc/${TERMUX_PKG_NAME}/LICENSE" fi COUNTER=$((COUNTER + 1)) fi done elif [ -f "$TERMUX_SCRIPTDIR/packages/termux-licenses/LICENSES/${LICENSE}.txt" ]; then if [[ $COUNTER -gt 0 ]]; then ln -sf "../../LICENSES/${LICENSE}.txt" "$TERMUX_PREFIX/share/doc/$TERMUX_PKG_NAME/LICENSE.${COUNTER}" else ln -sf "../../LICENSES/${LICENSE}.txt" "$TERMUX_PREFIX/share/doc/$TERMUX_PKG_NAME/LICENSE" fi COUNTER=$((COUNTER + 1)) fi done < <(echo "$TERMUX_PKG_LICENSE" | sed "s/,/\n/g") for LICENSE in "$TERMUX_PREFIX/share/doc/$TERMUX_PKG_NAME"/LICENSE*; do if [ "$LICENSE" = "$TERMUX_PREFIX/share/doc/$TERMUX_PKG_NAME/LICENSE*" ]; then termux_error_exit "No LICENSE file was installed for $TERMUX_PKG_NAME" fi done fi }
package com.cumbari.dps.config; import junit.framework.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = "classpath:/META-INF/spring/applicationContext.xml") public class ServerConfigTest { @Autowired private ServerConfiguration serverConfig; @Test public void testProps() { Assert.assertEquals(5, serverConfig.getAppendGoogleCouponsWhenLessThan()); Assert.assertTrue( serverConfig.getDefaultNoCouponsInBatch() > 10); Assert.assertEquals(500, serverConfig.getDefaultSearchRadius()); Assert.assertTrue(serverConfig.getMaxNoCouponsInBatch() > 20); Assert.assertEquals(2, serverConfig.getMaxNoSponsoredFirst()); Assert.assertTrue(serverConfig.isAllowGoogleCoupons()); Assert.assertTrue(serverConfig.isAllowTestDataCreation()); Assert.assertTrue(serverConfig.isLogPerformaceStatisics()); Assert.assertTrue(serverConfig.isUseInternalCashe()); Assert.assertTrue(serverConfig.isValidSecretToken("cum<PASSWORD>".toCharArray())); Assert.assertTrue(serverConfig.isValidSecretToken("cum<PASSWORD>".toCharArray())); Assert.assertFalse(serverConfig.isValidSecretToken("Invalid".toCharArray())); } }
/** * This class was created by <ArekkuusuJerii>. It's distributed as * part of Stratoprism. Get the Source Code in github: * https://github.com/ArekkuusuJerii/Stratoprism * * Stratoprism is Open Source and distributed under the * MIT Licence: https://github.com/ArekkuusuJerii/Stratoprism/blob/master/LICENSE */ package arekkuusu.stratoprism.api.item.capability; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; public class VastatioCapabilityStorage implements Capability.IStorage<IVastatioCapability>{ public static final VastatioCapabilityStorage cap = new VastatioCapabilityStorage(); @Override public NBTBase writeNBT(Capability<IVastatioCapability> capability, IVastatioCapability instance, EnumFacing side) { NBTTagCompound nbt= new NBTTagCompound(); nbt.setFloat("vastatio", ((DefaultVastatioCapability)instance).vastatio); nbt.setFloat("max_vastatio", ((DefaultVastatioCapability)instance).maxVastatio); return nbt; } @Override public void readNBT(Capability<IVastatioCapability> capability, IVastatioCapability instance, EnumFacing side,NBTBase nbt) { NBTTagCompound tag = (NBTTagCompound) nbt; ((DefaultVastatioCapability)instance).vastatio = tag.getFloat("vastatio"); ((DefaultVastatioCapability)instance).maxVastatio = tag.getFloat("max_vastatio"); } }
package gex.newsml.g2; import lombok.ToString; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyAttribute; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlID; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import javax.xml.namespace.QName; import org.w3c.dom.Element; /** * The type for a set of properties directly associated with the item (Type * defined in this XML Schema only) * * <p> * Java class for ItemMetadataType complex type. * * <p> * The following schema fragment specifies the expected content contained within * this class. * * <pre> * &lt;complexType name="ItemMetadataType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;group ref="{http://iptc.org/std/nar/2006-10-01/}ItemManagementGroup"/> * &lt;element ref="{http://iptc.org/std/nar/2006-10-01/}link" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="itemMetaExtProperty" type="{http://iptc.org/std/nar/2006-10-01/}Flex2ExtPropType" maxOccurs="unbounded" minOccurs="0"/> * &lt;any processContents='lax' namespace='##other' maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attGroup ref="{http://iptc.org/std/nar/2006-10-01/}commonPowerAttributes"/> * &lt;attGroup ref="{http://iptc.org/std/nar/2006-10-01/}i18nAttributes"/> * &lt;anyAttribute processContents='lax' namespace='##other'/> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ItemMetadataType", propOrder = { "itemClass", "provider", "versionCreated", "firstCreated", "embargoed", "pubStatus", "role", "fileName", "generator", "profile", "service", "title", "edNote", "memberOf", "instanceOf", "signal", "altRep", "deliverableOf", "hash", "expires", "origRep", "incomingFeedId", "link", "itemMetaExtProperty", "any" }) @ToString public class ItemMetadataType { @XmlElement(required = true) protected QualPropType itemClass; @XmlElement(required = true) protected FlexPartyPropType provider; @XmlElement(required = true) protected DateTimePropType versionCreated; protected DateTimePropType firstCreated; protected DateTimeOrNullPropType embargoed; protected QualPropType pubStatus; protected QualPropType role; protected FileName fileName; protected List<Generator> generator; protected VersionedStringType profile; protected List<QualPropType> service; protected List<Label1Type> title; protected List<BlockType> edNote; protected List<Flex1PropType> memberOf; protected List<Flex1PropType> instanceOf; protected List<Signal> signal; protected List<AltRep> altRep; protected List<Link1Type> deliverableOf; protected List<Hash> hash; protected List<DateOptTimePropType> expires; protected List<OrigRep> origRep; protected List<IncomingFeedId> incomingFeedId; protected List<Link1Type> link; protected List<Flex2ExtPropType> itemMetaExtProperty; @XmlAnyElement(lax = true) protected List<Object> any; @XmlAttribute(name = "id") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlID @XmlSchemaType(name = "ID") protected String id; @XmlAttribute(name = "creator") protected String creator; @XmlAttribute(name = "creatoruri") protected String creatoruri; @XmlAttribute(name = "modified") protected String modified; @XmlAttribute(name = "custom") protected Boolean custom; @XmlAttribute(name = "how") protected String how; @XmlAttribute(name = "howuri") protected String howuri; @XmlAttribute(name = "why") protected String why; @XmlAttribute(name = "whyuri") protected String whyuri; @XmlAttribute(name = "pubconstraint") protected List<String> pubconstraint; @XmlAttribute(name = "pubconstrainturi") protected List<String> pubconstrainturi; @XmlAttribute(name = "lang", namespace = "http://www.w3.org/XML/1998/namespace") protected String lang; @XmlAttribute(name = "dir") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) protected String dir; @XmlAnyAttribute private Map<QName, String> otherAttributes = new HashMap<QName, String>(); /** * Gets the value of the itemClass property. * * @return possible object is {@link QualPropType } * */ public QualPropType getItemClass() { return itemClass; } /** * Sets the value of the itemClass property. * * @param value * allowed object is {@link QualPropType } * */ public void setItemClass(QualPropType value) { this.itemClass = value; } /** * Gets the value of the provider property. * * @return possible object is {@link FlexPartyPropType } * */ public FlexPartyPropType getProvider() { return provider; } /** * Sets the value of the provider property. * * @param value * allowed object is {@link FlexPartyPropType } * */ public void setProvider(FlexPartyPropType value) { this.provider = value; } /** * Gets the value of the versionCreated property. * * @return possible object is {@link DateTimePropType } * */ public DateTimePropType getVersionCreated() { return versionCreated; } /** * Sets the value of the versionCreated property. * * @param value * allowed object is {@link DateTimePropType } * */ public void setVersionCreated(DateTimePropType value) { this.versionCreated = value; } /** * Gets the value of the firstCreated property. * * @return possible object is {@link DateTimePropType } * */ public DateTimePropType getFirstCreated() { return firstCreated; } /** * Sets the value of the firstCreated property. * * @param value * allowed object is {@link DateTimePropType } * */ public void setFirstCreated(DateTimePropType value) { this.firstCreated = value; } /** * Gets the value of the embargoed property. * * @return possible object is {@link DateTimeOrNullPropType } * */ public DateTimeOrNullPropType getEmbargoed() { return embargoed; } /** * Sets the value of the embargoed property. * * @param value * allowed object is {@link DateTimeOrNullPropType } * */ public void setEmbargoed(DateTimeOrNullPropType value) { this.embargoed = value; } /** * Gets the value of the pubStatus property. * * @return possible object is {@link QualPropType } * */ public QualPropType getPubStatus() { return pubStatus; } /** * Sets the value of the pubStatus property. * * @param value * allowed object is {@link QualPropType } * */ public void setPubStatus(QualPropType value) { this.pubStatus = value; } /** * Gets the value of the role property. * * @return possible object is {@link QualPropType } * */ public QualPropType getRole() { return role; } /** * Sets the value of the role property. * * @param value * allowed object is {@link QualPropType } * */ public void setRole(QualPropType value) { this.role = value; } /** * Gets the value of the fileName property. * * @return possible object is {@link FileName } * */ public FileName getFileName() { return fileName; } /** * Sets the value of the fileName property. * * @param value * allowed object is {@link FileName } * */ public void setFileName(FileName value) { this.fileName = value; } /** * Gets the value of the generator property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the generator property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getGenerator().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Generator * } * * */ public List<Generator> getGenerator() { if (generator == null) { generator = new ArrayList<Generator>(); } return this.generator; } /** * Gets the value of the profile property. * * @return possible object is {@link VersionedStringType } * */ public VersionedStringType getProfile() { return profile; } /** * Sets the value of the profile property. * * @param value * allowed object is {@link VersionedStringType } * */ public void setProfile(VersionedStringType value) { this.profile = value; } /** * Gets the value of the service property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the service property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getService().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link QualPropType } * * */ public List<QualPropType> getService() { if (service == null) { service = new ArrayList<QualPropType>(); } return this.service; } /** * A short natural language name for the Item.Gets the value of the title * property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the title property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getTitle().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Label1Type } * * */ public List<Label1Type> getTitle() { if (title == null) { title = new ArrayList<Label1Type>(); } return this.title; } /** * Gets the value of the edNote property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the edNote property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getEdNote().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link BlockType * } * * */ public List<BlockType> getEdNote() { if (edNote == null) { edNote = new ArrayList<BlockType>(); } return this.edNote; } /** * Gets the value of the memberOf property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the memberOf property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getMemberOf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Flex1PropType } * * */ public List<Flex1PropType> getMemberOf() { if (memberOf == null) { memberOf = new ArrayList<Flex1PropType>(); } return this.memberOf; } /** * Gets the value of the instanceOf property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the instanceOf property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getInstanceOf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Flex1PropType } * * */ public List<Flex1PropType> getInstanceOf() { if (instanceOf == null) { instanceOf = new ArrayList<Flex1PropType>(); } return this.instanceOf; } /** * Gets the value of the signal property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the signal property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getSignal().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Signal } * * */ public List<Signal> getSignal() { if (signal == null) { signal = new ArrayList<Signal>(); } return this.signal; } /** * Gets the value of the altRep property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the altRep property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getAltRep().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link AltRep } * * */ public List<AltRep> getAltRep() { if (altRep == null) { altRep = new ArrayList<AltRep>(); } return this.altRep; } /** * Gets the value of the deliverableOf property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the deliverableOf property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getDeliverableOf().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Link1Type * } * * */ public List<Link1Type> getDeliverableOf() { if (deliverableOf == null) { deliverableOf = new ArrayList<Link1Type>(); } return this.deliverableOf; } /** * Gets the value of the hash property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the hash property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getHash().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Hash } * * */ public List<Hash> getHash() { if (hash == null) { hash = new ArrayList<Hash>(); } return this.hash; } /** * Gets the value of the expires property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the expires property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getExpires().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DateOptTimePropType } * * */ public List<DateOptTimePropType> getExpires() { if (expires == null) { expires = new ArrayList<DateOptTimePropType>(); } return this.expires; } /** * Gets the value of the origRep property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the origRep property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getOrigRep().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link OrigRep } * * */ public List<OrigRep> getOrigRep() { if (origRep == null) { origRep = new ArrayList<OrigRep>(); } return this.origRep; } /** * Gets the value of the incomingFeedId property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the incomingFeedId property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getIncomingFeedId().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link IncomingFeedId } * * */ public List<IncomingFeedId> getIncomingFeedId() { if (incomingFeedId == null) { incomingFeedId = new ArrayList<IncomingFeedId>(); } return this.incomingFeedId; } /** * Gets the value of the link property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the link property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getLink().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Link1Type * } * * */ public List<Link1Type> getLink() { if (link == null) { link = new ArrayList<Link1Type>(); } return this.link; } /** * Gets the value of the itemMetaExtProperty property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the itemMetaExtProperty property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getItemMetaExtProperty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Flex2ExtPropType } * * */ public List<Flex2ExtPropType> getItemMetaExtProperty() { if (itemMetaExtProperty == null) { itemMetaExtProperty = new ArrayList<Flex2ExtPropType>(); } return this.itemMetaExtProperty; } /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link Object } * {@link Element } * * */ public List<Object> getAny() { if (any == null) { any = new ArrayList<Object>(); } return this.any; } /** * Gets the value of the id property. * * @return possible object is {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is {@link String } * */ public void setId(String value) { this.id = value; } /** * Gets the value of the creator property. * * @return possible object is {@link String } * */ public String getCreator() { return creator; } /** * Sets the value of the creator property. * * @param value * allowed object is {@link String } * */ public void setCreator(String value) { this.creator = value; } /** * Gets the value of the creatoruri property. * * @return possible object is {@link String } * */ public String getCreatoruri() { return creatoruri; } /** * Sets the value of the creatoruri property. * * @param value * allowed object is {@link String } * */ public void setCreatoruri(String value) { this.creatoruri = value; } /** * Gets the value of the modified property. * * @return possible object is {@link String } * */ public String getModified() { return modified; } /** * Sets the value of the modified property. * * @param value * allowed object is {@link String } * */ public void setModified(String value) { this.modified = value; } /** * Gets the value of the custom property. * * @return possible object is {@link Boolean } * */ public Boolean isCustom() { return custom; } /** * Sets the value of the custom property. * * @param value * allowed object is {@link Boolean } * */ public void setCustom(Boolean value) { this.custom = value; } /** * Gets the value of the how property. * * @return possible object is {@link String } * */ public String getHow() { return how; } /** * Sets the value of the how property. * * @param value * allowed object is {@link String } * */ public void setHow(String value) { this.how = value; } /** * Gets the value of the howuri property. * * @return possible object is {@link String } * */ public String getHowuri() { return howuri; } /** * Sets the value of the howuri property. * * @param value * allowed object is {@link String } * */ public void setHowuri(String value) { this.howuri = value; } /** * Gets the value of the why property. * * @return possible object is {@link String } * */ public String getWhy() { return why; } /** * Sets the value of the why property. * * @param value * allowed object is {@link String } * */ public void setWhy(String value) { this.why = value; } /** * Gets the value of the whyuri property. * * @return possible object is {@link String } * */ public String getWhyuri() { return whyuri; } /** * Sets the value of the whyuri property. * * @param value * allowed object is {@link String } * */ public void setWhyuri(String value) { this.whyuri = value; } /** * Gets the value of the pubconstraint property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the pubconstraint property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getPubconstraint().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link String } * * */ public List<String> getPubconstraint() { if (pubconstraint == null) { pubconstraint = new ArrayList<String>(); } return this.pubconstraint; } /** * Gets the value of the pubconstrainturi property. * * <p> * This accessor method returns a reference to the live list, not a * snapshot. Therefore any modification you make to the returned list will * be present inside the JAXB object. This is why there is not a * <CODE>set</CODE> method for the pubconstrainturi property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getPubconstrainturi().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list {@link String } * * */ public List<String> getPubconstrainturi() { if (pubconstrainturi == null) { pubconstrainturi = new ArrayList<String>(); } return this.pubconstrainturi; } /** * Specifies the language of this property and potentially all descendant * properties. xml:lang values of descendant properties override this value. * Values are determined by Internet BCP 47. * * @return possible object is {@link String } * */ public String getLang() { return lang; } /** * Sets the value of the lang property. * * @param value * allowed object is {@link String } * */ public void setLang(String value) { this.lang = value; } /** * Gets the value of the dir property. * * @return possible object is {@link String } * */ public String getDir() { return dir; } /** * Sets the value of the dir property. * * @param value * allowed object is {@link String } * */ public void setDir(String value) { this.dir = value; } /** * Gets a map that contains attributes that aren't bound to any typed * property on this class. * * <p> * the map is keyed by the name of the attribute and the value is the string * value of the attribute. * * the map returned by this method is live, and you can add new attribute by * updating the map directly. Because of this design, there's no setter. * * * @return always non-null */ public Map<QName, String> getOtherAttributes() { return otherAttributes; } }
# This works for AKS... # Can also just use az aks get-credentials... cat <<EOF | cfssl genkey - | cfssljson -bare james { "CN": "james", "key": { "algo": "rsa", "size": 4096 } } EOF cat <<EOF | kubectl apply -f - apiVersion: certificates.k8s.io/v1beta1 kind: CertificateSigningRequest metadata: name: james spec: request: $(cat james.csr | base64 | tr -d '\n') usages: - digital signature - key encipherment - client auth EOF kubectl certificate james approve kubectl get csr james-o jsonpath='{.status.certificate}' | base64 -d > james.pem # kubectl config set-credentials kubeuser/foo.kubernetes.com --username=kubeuser --password=kubepassword kubectl config set-credentials james \ --client-certificate=james.pem \ --client-key=james.pem kubectl config set-context james-context \ --cluster=kubernetes --user=james-context
#!/bin/bash sudo dpkg-reconfigure keyboard-configuration
#!/bin/bash print_usage() { cat <<EOF USAGE: install-ssl-certificate.sh [-h] install-ssl-certificate.sh [-v version] [-C certificatefile] [-P password] install-ssl-certificate.sh [-a appliance] [-t accesstoken] [-v version] [-C certificatefile] [-P password] -h Show help and exit -a Network address of the appliance -v Web API Version: 3 is default -t Safeguard access token -C File containing certificate (PKCS#12 format, ie p12 or pfx file) -P Password to decrypt the certificate (otherwise you will be prompted) Upload a certificate file to Safeguard for use as an SSL certificate. This script will upload the certificate to the cluster and immediately configure it for use with this appliance. EOF exit 0 } ScriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" if [ -z "$(which jq 2> /dev/null)" ]; then >&2 echo "This script requires jq for parsing between requests." exit 1 fi Appliance= AccessToken= Version=3 SSLCertificateFile= SSLCertificatePassword= . "$ScriptDir/utils/loginfile.sh" require_args() { require_login_args if [ -z "$SSLCertificateFile" ]; then read -p "Certificate file: " SSLCertificateFile fi if [ -z "$SSLCertificatePassword" ]; then read -s -p "Certificate file password: " SSLCertificatePassword >&2 echo fi if [ ! -r "$SSLCertificateFile" ]; then >&2 echo "Unable to read certificate file '$SSLCertificateFile'" exit 1 fi } while getopts ":t:a:v:C:P:h" opt; do case $opt in t) AccessToken=$OPTARG ;; a) Appliance=$OPTARG ;; v) Version=$OPTARG ;; C) SSLCertificateFile=$OPTARG ;; P) SSLCertificatePassword=$OPTARG ;; h) print_usage ;; esac done require_args echo "Uploading '$SSLCertificateFile'..." Response=$($ScriptDir/invoke-safeguard-method.sh -a "$Appliance" -T -v $Version -s core -m POST -U SslCertificates -N -b "{ \"Base64CertificateData\": \"$(base64 $SSLCertificateFile)\", \"Passphrase\": \"$SSLCertificatePassword\" }" <<<$AccessToken) echo $Response | jq . if [ -z "$Response" ]; then >&2 echo "Invalid response while trying to upload certificate file" exit 1 fi Thumbprint=$(echo $Response | jq -r .Thumbprint) ApplianceId=$($ScriptDir/get-appliance-status.sh -a "$Appliance" | jq .ApplianceId) if [ -z "$ApplianceId" ]; then >&2 echo "Unable to determine appliance ID from notification service" exit 1 fi echo "Setting '$Thumbprint' as SSL certificate for '$Appliance', ID='$ApplianceId'..." $ScriptDir/invoke-safeguard-method.sh -a "$Appliance" -T -s core -m PUT -U "SslCertificates/$Thumbprint/Appliances" -N -b "[ { \"Id\": $ApplianceId } ]" <<<$AccessToken
word = input('Enter word: ') if word.lower() == 'super': print('Object found')
<gh_stars>10-100 package infoblox import ( "encoding/json" "fmt" "log" "net/url" ) //Resource represents a WAPI object type Object struct { Ref string `json:"_ref"` r *Resource } func (o Object) Get(opts *Options) (map[string]interface{}, error) { resp, err := o.get(opts) if err != nil { return nil, err } var out map[string]interface{} err = resp.Parse(&out) if err != nil { return nil, fmt.Errorf("%+v\n", err) } return out, nil } func (o Object) get(opts *Options) (*APIResponse, error) { q := o.r.getQuery(opts, []Condition{}, url.Values{}) resp, err := o.r.conn.SendRequest("GET", o.objectURI()+"?"+q.Encode(), "", nil) if err != nil { return nil, fmt.Errorf("Error sending request: %v\n", err) } return resp, nil } func (o Object) Update(data url.Values, opts *Options, body interface{}) (string, error) { q := o.r.getQuery(opts, []Condition{}, data) q.Set("_return_fields", "") //Force object response var err error head := make(map[string]string) var bodyStr, urlStr string if body == nil { // Send URL-encoded data in the request body urlStr = o.objectURI() bodyStr = q.Encode() head["Content-Type"] = "application/x-www-form-urlencoded" } else { // Put url-encoded data in the URL and send the body parameter as a JSON body. bodyJSON, err := json.Marshal(body) if err != nil { return "", fmt.Errorf("Error creating request: %v\n", err) } log.Printf("PUT body: %s\n", bodyJSON) urlStr = o.objectURI() + "?" + q.Encode() bodyStr = string(bodyJSON) head["Content-Type"] = "application/json" } resp, err := o.r.conn.SendRequest("PUT", urlStr, bodyStr, head) if err != nil { return "", fmt.Errorf("Error sending request: %v\n", err) } //fmt.Printf("%v", resp.ReadBody()) var responseData interface{} var ret string if err := resp.Parse(&responseData); err != nil { return "", fmt.Errorf("%+v\n", err) } switch s := responseData.(type) { case string: ret = s case map[string]interface{}: ret = s["_ref"].(string) default: return "", fmt.Errorf("Invalid return type %T", s) } return ret, nil } func (o Object) Delete(opts *Options) error { q := o.r.getQuery(opts, []Condition{}, url.Values{}) resp, err := o.r.conn.SendRequest("DELETE", o.objectURI()+"?"+q.Encode(), "", nil) if err != nil { return fmt.Errorf("Error sending request: %v\n", err) } //fmt.Printf("%v", resp.ReadBody()) var out interface{} err = resp.Parse(&out) if err != nil { return fmt.Errorf("%+v\n", err) } return nil } func (o Object) FunctionCall(functionName string, jsonBody interface{}) (map[string]interface{}, error) { data, err := json.Marshal(jsonBody) if err != nil { return nil, fmt.Errorf("Error sending request: %v\n", err) } resp, err := o.r.conn.SendRequest("POST", fmt.Sprintf("%s?_function=%s", o.objectURI(), functionName), string(data), map[string]string{"Content-Type": "application/json"}) if err != nil { return nil, fmt.Errorf("Error sending request: %v\n", err) } //fmt.Printf("%v", resp.ReadBody()) var out map[string]interface{} err = resp.Parse(&out) if err != nil { return nil, fmt.Errorf("%+v\n", err) } return out, nil } func (o Object) objectURI() string { return BASE_PATH + o.Ref }
package org.jooby.issues; import com.typesafe.config.ConfigFactory; import com.typesafe.config.ConfigValueFactory; import org.flywaydb.core.Flyway; import org.jooby.flyway.Flywaydb; import org.jooby.test.ServerFeature; import org.junit.Test; import java.util.Arrays; public class Issue623 extends ServerFeature { { use(ConfigFactory.empty() .withValue("flyway.db1.url", ConfigValueFactory.fromAnyRef("jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1")) .withValue("flyway.db1.locations", ConfigValueFactory .fromAnyRef(Arrays.asList("i623/fway1"))) .withValue("flyway.db2.url", ConfigValueFactory.fromAnyRef("jdbc:h2:mem:db2;DB_CLOSE_DELAY=-1")) .withValue("flyway.db2.locations", ConfigValueFactory .fromAnyRef(Arrays.asList("i623/fway2")))); use(new Flywaydb("flyway.db1")); use(new Flywaydb("flyway.db2")); get("/623", req -> req.require(req.param("name").value(), Flyway.class).info().current() .getDescription()); } @Test public void bootstratp2dbs() throws Exception { request() .get("/623?name=flyway.db1") .expect("fway1"); request() .get("/623?name=flyway.db2") .expect("fway2"); } }
<gh_stars>0 import {loadSchedule, loadSession} from '../actions'; export default () => ({ title: 'CodeMash', loadSchedule, loadSession, days: ['2019-01-08', '2019-01-09', '2019-01-10', '2019-01-11'], tags: ['codemash'], location: 'Sandusky, OH', site: 'http://www.codemash.org/', image: 'https://pbs.twimg.com/profile_images/575897195/CodeMashLogoSquare_400x400.png', });
<filename>pkg/inmemory-mvcc/transaction_test.go package inmemory_mvcc import ( "fmt" "sync" "testing" "github.com/dr0pdb/icecanedb/pkg/storage" "github.com/dr0pdb/icecanedb/test" "github.com/stretchr/testify/assert" ) var ( mvcc *MVCC ) // create a snapshot with the given seq number. set seq to 0, for the default one. func newTestSnapshot(storage *storage.Storage, seq uint64) *storage.Snapshot { snap := storage.GetSnapshot() if seq != 0 { snap.SeqNum = seq } return snap } func newTestTransaction(storage *storage.Storage, id, seq uint64) *Transaction { return newTransaction(id, mvcc, storage, newTestSnapshot(storage, seq), make([]*Transaction, 0)) } func setupStorage() (*storage.Storage, error) { options := &storage.Options{ CreateIfNotExist: true, } s, err := storage.NewStorage(test.TestDirectory, test.TestDbName, options) if err != nil { return nil, err } err = s.Open() mvcc = newTestMVCC(s) return s, err } func addDataBeforeSnapshot(storage *storage.Storage) error { for i := range test.TestKeys { err := storage.Set(test.TestKeys[i], test.TestValues[i], nil) if err != nil { return err } } return nil } func TestSingleGetSetDelete(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) txn := newTestTransaction(s, 1, 0) // seq 0 means the current one. for i := range test.TestKeys { val, err := txn.Get(test.TestKeys[i], nil) assert.Nil(t, err) assert.Equal(t, test.TestValues[i], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", i, test.TestValues[i], val)) } for i := range test.TestKeys { err := txn.Set(test.TestKeys[i], test.TestUpdatedValues[i], nil) assert.Nil(t, err, fmt.Sprintf("Unexpected error in setting value for key%d.", i)) } // should get new updated values. for i := range test.TestKeys { val, err := txn.Get(test.TestKeys[i], nil) assert.Nil(t, err) assert.Equal(t, test.TestUpdatedValues[i], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", i, test.TestUpdatedValues[i], val)) } for i := range test.TestKeys { err := txn.Delete(test.TestKeys[i], nil) assert.Nil(t, err, fmt.Sprintf("Unexpected error in deleting value for key%d.", i)) } // should get a not found error for i := range test.TestKeys { val, err := txn.Get(test.TestKeys[i], nil) assert.NotNil(t, err, fmt.Sprintf("Unexpected value for key%d. Expected not found error, found %v", i, val)) } } func TestOperationOnAbortedTxn(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) txn := newTestTransaction(s, 1, 0) // seq 0 means the current one. err = txn.Rollback() assert.Nil(t, err, fmt.Sprintf("Unexpected error in rolling back txn.")) val, err := txn.Get(test.TestKeys[0], nil) assert.NotNil(t, err, fmt.Sprintf("Unexpected value for key%d. Expected error due to aborted txn, found %v", 0, val)) } func TestValidateInvariant(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) txn := newTestTransaction(s, 1, 0) // seq 0 means the current one. txn.sets[string(test.TestKeys[0])] = string(test.TestValues[0]) txn.sets[string(test.TestKeys[1])] = string(test.TestValues[1]) assert.True(t, txn.validateInvariants(), fmt.Sprintf("Validate invariant error; expected true, got false")) txn.deletes[string(test.TestKeys[1])] = true assert.False(t, txn.validateInvariants(), fmt.Sprintf("Validate invariant error; expected false, got true")) } func TestAbortedTxnNoSideEffect(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) txn := newTestTransaction(s, 0, 0) // seq 0 means the current one. txn.Set(test.TestKeys[0], test.TestUpdatedValues[0], nil) err = txn.Rollback() assert.Nil(t, err) val, err := s.Get(test.TestKeys[0], nil) assert.Nil(t, err) assert.Equal(t, test.TestValues[0], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", 0, test.TestValues[0], val)) } func TestBasicMultipleTxn(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) txn := newTestTransaction(s, 1, 0) // seq 0 means the current one. txn2 := newTestTransaction(s, 2, 0) // txn updates 0 and txn2 updates 1. txn.Set(test.TestKeys[0], test.TestUpdatedValues[0], nil) txn2.Set(test.TestKeys[1], test.TestUpdatedValues[1], nil) // txn shouldn't see the update on key1. val, err := txn.Get(test.TestKeys[1], nil) assert.Nil(t, err) assert.Equal(t, test.TestValues[1], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", 1, test.TestValues[1], val)) // txn2 shouldn't see the update on key0. val, err = txn2.Get(test.TestKeys[0], nil) assert.Nil(t, err) assert.Equal(t, test.TestValues[0], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", 0, test.TestValues[0], val)) err = txn.Commit() assert.Nil(t, err) // committing of txn shouldn't affect txn2 val, err = txn2.Get(test.TestKeys[0], nil) assert.Nil(t, err) assert.Equal(t, test.TestValues[0], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", 0, test.TestValues[0], val)) err = txn2.Commit() assert.Nil(t, err) val, err = s.Get(test.TestKeys[0], nil) assert.Nil(t, err) assert.Equal(t, test.TestUpdatedValues[0], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", 0, test.TestUpdatedValues[0], val)) val, err = s.Get(test.TestKeys[1], nil) assert.Nil(t, err) assert.Equal(t, test.TestUpdatedValues[1], val, fmt.Sprintf("Unexpected value for key%d. Expected %v, found %v", 1, test.TestUpdatedValues[1], val)) } func TestShouldAbortConflictingTxn(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) txn := newTestTransaction(s, 1, 0) // seq 0 means the current one. txn2 := newTestTransaction(s, 2, 0) // txn updates 0 and txn2 updates 0 and 1. // txn will commit first and then txn2 shouldn't be allowed to commit. txn.Set(test.TestKeys[0], test.TestUpdatedValues[0], nil) txn2.Set(test.TestKeys[0], test.TestUpdatedValues[0], nil) txn2.Set(test.TestKeys[1], test.TestUpdatedValues[1], nil) err = txn.Commit() assert.Nil(t, err, fmt.Sprintf("Unexpected error in committing txn%d", 0)) err = txn2.Commit() assert.NotNil(t, err, fmt.Sprintf("Unexpected success in committing txn%d, expected failure, got success", 1)) } func TestShouldAllowNonConflictingTxn(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) wg := &sync.WaitGroup{} wg.Add(5) // ith txn will only update ith key, so they all should commit for i := uint64(0); i < 5; i++ { go func(t *testing.T, i uint64) { defer wg.Done() txn := newTestTransaction(s, i, 0) err := txn.Set(test.TestKeys[i], test.TestUpdatedValues[i], nil) assert.Nil(t, err, fmt.Sprintf("Unexpected error in setting key%d for txn%d", i, i)) err = txn.Commit() assert.Nil(t, err, fmt.Sprintf("Unexpected error in committing txn%d", i)) }(t, i) } wg.Wait() } func TestMultipleConflictingTxnConcurrent(t *testing.T) { test.CreateTestDirectory(test.TestDirectory) defer test.CleanupTestDirectory(test.TestDirectory) s, err := setupStorage() assert.Nil(t, err, "Unexpected error in creating new storage") addDataBeforeSnapshot(s) success := 0 tot := 0 ch := make(chan int, 5) var txns [5]*Transaction for i := uint64(0); i < 5; i++ { txns[i] = newTestTransaction(s, i, 0) } // spawn 5 go routines, each one will update key 0. only one should succeed and rest 4 should fail. for i := uint64(0); i < 5; i++ { go func(t *testing.T, i uint64, ch chan int) { err := txns[i].Set(test.TestKeys[0], test.TestUpdatedValues[0], nil) assert.Nil(t, err, fmt.Sprintf("Unexpected error in setting key%d for txn%d", 0, i)) err = txns[i].Commit() if err == nil { // success ch <- 1 } else { ch <- 0 } }(t, i, ch) } // not proud of this but works for now. for { msg := <-ch if msg == 1 { success++ tot++ } else { tot++ } if tot == 5 { break } } assert.Equal(t, 1, success, fmt.Sprintf("Unexpected value of success. Expected one txn to succeed, found %d", success)) }
import React, {useState, useEffect} from 'react'; import axios from 'axios'; const App = () => { const [query, setQuery] = useState(''); const [cities, setCities] = useState([]); useEffect(() => { axios .get(`https://api.openweathermap.org/data/2.5/weather?q=${query}&appid=<API-KEY>`) .then(data => setCities(data.list)) .catch(error => console.log(error)) }, [query]); const onChange = (e) => { setQuery(e.target.value); }; return ( <div className="App"> <input type="text" onChange={onChange} /> <ul> {cities.map((city, index) => ( <li key={index}>{city.name}</li> ))} </ul> </div> ); }; export default App;
#!/bin/bash ## Enable Docker systemctl daemon-reload systemctl restart docker systemctl enable docker ## Pull Docker images docker pull registry.gitlab.com/analythium/shinyproxy-hello/hello:latest docker pull analythium/shinyproxy-demo:latest ## Onstall ShinyProxy export VERSION="2.5.0" wget https://www.shinyproxy.io/downloads/shinyproxy_${VERSION}_amd64.deb apt install ./shinyproxy_${VERSION}_amd64.deb rm shinyproxy_${VERSION}_amd64.deb ## Restart ShinyProxy service shinyproxy restart ## Restart Nginx service nginx restart # Setting firewall rules ufw default deny incoming ufw default allow outgoing ufw allow ssh ufw allow http #ufw allow https ufw --force enable echo =============================== echo Version info: echo echo ------------------------------- echo ShinyProxy $VERSION echo ------------------------------- java -version echo ------------------------------- docker -v echo ------------------------------- docker-compose -v echo ------------------------------- nginx -v echo ------------------------------- ufw version echo ===============================
<gh_stars>1-10 import { CoreElement } from './enum'; export const CoreOption = Object.freeze([ { label: '火', value: CoreElement.火, }, { label: '水', value: CoreElement.水, }, { label: '地', value: CoreElement.地, }, { label: '风', value: CoreElement.风, }, { label: '光', value: CoreElement.光, }, { label: '暗', value: CoreElement.暗, }, ]); /** * 暴击倍率:有利属性为0.5,其他属性为0.25 */ export const CriRatio = { up: 1.5, noraml: 1.25, down: 1.25 }; export const AtkRatio = { up: 1.25, normal: 1, down: 0.75 } export const DaTaRatio = { da : 1.5, ta: 2 } export const Limit = { /** 伤害上限 */ saDamage: 4e5, daDamage: 6e5, taDamage: 8e5, skillDamage: 6e5, ubDamage: 28e5, // 单独hp区间下限 hp: -0.7, // 综合hp下限 totalHp: -9.99999, // 连击概率上限 combo: 0.75, /** 单独UB上限 */ ubBonus: 0.5, sklBonus: 0.5, }
#!/bin/bash -f #********************************************************************************************************* # Vivado (TM) v2019.1 (64-bit) # # Filename : DM.sh # Simulator : Xilinx Vivado Simulator # Description : Simulation script for compiling, elaborating and verifying the project source files. # The script will automatically create the design libraries sub-directories in the run # directory, add the library logical mappings in the simulator setup file, create default # 'do/prj' file, execute compilation, elaboration and simulation steps. # # Generated by Vivado on Sun May 10 21:04:10 +0800 2020 # SW Build 2552052 on Fri May 24 14:49:42 MDT 2019 # # Copyright 1986-2019 Xilinx, Inc. All Rights Reserved. # # usage: DM.sh [-help] # usage: DM.sh [-lib_map_path] # usage: DM.sh [-noclean_files] # usage: DM.sh [-reset_run] # #********************************************************************************************************* # Command line options xv_boost_lib_path=C:/Xilinx/Vivado/2019.1/tps/boost_1_64_0 xvlog_opts="--relax" # Script info echo -e "DM.sh - Script generated by export_simulation (Vivado v2019.1 (64-bit)-id)\n" # Main steps run() { check_args $# $1 setup $1 $2 compile elaborate simulate } # RUN_STEP: <compile> compile() { # Compile design files xvlog $xvlog_opts -prj vlog.prj 2>&1 | tee compile.log } # RUN_STEP: <elaborate> elaborate() { xelab --relax --debug typical --mt auto -L dist_mem_gen_v8_0_13 -L xil_defaultlib -L unisims_ver -L unimacro_ver -L secureip -L xpm --snapshot DM xil_defaultlib.DM xil_defaultlib.glbl -log elaborate.log } # RUN_STEP: <simulate> simulate() { xsim DM -key {Behavioral:sim_1:Functional:DM} -tclbatch cmd.tcl -log simulate.log } # STEP: setup setup() { case $1 in "-lib_map_path" ) if [[ ($2 == "") ]]; then echo -e "ERROR: Simulation library directory path not specified (type \"./DM.sh -help\" for more information)\n" exit 1 fi copy_setup_file $2 ;; "-reset_run" ) reset_run echo -e "INFO: Simulation run files deleted.\n" exit 0 ;; "-noclean_files" ) # do not remove previous data ;; * ) copy_setup_file $2 esac # Add any setup/initialization commands here:- # <user specific commands> } # Copy xsim.ini file copy_setup_file() { file="xsim.ini" lib_map_path="C:/Xilinx/Vivado/2019.1/data/xsim" if [[ ($1 != "") ]]; then lib_map_path="$1" fi if [[ ($lib_map_path != "") ]]; then src_file="$lib_map_path/$file" if [[ -e $src_file ]]; then cp $src_file . fi # Map local design libraries to xsim.ini map_local_libs fi } # Map local design libraries map_local_libs() { updated_mappings=() local_mappings=() # Local design libraries local_libs=() if [[ 0 == ${#local_libs[@]} ]]; then return fi file="xsim.ini" file_backup="xsim.ini.bak" if [[ -e $file ]]; then rm -f $file_backup # Create a backup copy of the xsim.ini file cp $file $file_backup # Read libraries from backup file and search in local library collection while read -r line do IN=$line # Split mapping entry with '=' delimiter to fetch library name and mapping read lib_name mapping <<<$(IFS="="; echo $IN) # If local library found, then construct the local mapping and add to local mapping collection if `echo ${local_libs[@]} | grep -wq $lib_name` ; then line="$lib_name=xsim.dir/$lib_name" local_mappings+=("$lib_name") fi # Add to updated library mapping collection updated_mappings+=("$line") done < "$file_backup" # Append local libraries not found originally from xsim.ini for (( i=0; i<${#local_libs[*]}; i++ )); do lib_name="${local_libs[i]}" if `echo ${local_mappings[@]} | grep -wvq $lib_name` ; then line="$lib_name=xsim.dir/$lib_name" updated_mappings+=("$line") fi done # Write updated mappings in xsim.ini rm -f $file for (( i=0; i<${#updated_mappings[*]}; i++ )); do lib_name="${updated_mappings[i]}" echo $lib_name >> $file done else for (( i=0; i<${#local_libs[*]}; i++ )); do lib_name="${local_libs[i]}" mapping="$lib_name=xsim.dir/$lib_name" echo $mapping >> $file done fi } # Delete generated data from the previous run reset_run() { files_to_remove=(xelab.pb xsim.jou xvhdl.log xvlog.log compile.log elaborate.log simulate.log xelab.log xsim.log run.log xvhdl.pb xvlog.pb DM.wdb xsim.dir) for (( i=0; i<${#files_to_remove[*]}; i++ )); do file="${files_to_remove[i]}" if [[ -e $file ]]; then rm -rf $file fi done } # Check command line arguments check_args() { if [[ ($1 == 1 ) && ($2 != "-lib_map_path" && $2 != "-noclean_files" && $2 != "-reset_run" && $2 != "-help" && $2 != "-h") ]]; then echo -e "ERROR: Unknown option specified '$2' (type \"./DM.sh -help\" for more information)\n" exit 1 fi if [[ ($2 == "-help" || $2 == "-h") ]]; then usage fi } # Script usage usage() { msg="Usage: DM.sh [-help]\n\ Usage: DM.sh [-lib_map_path]\n\ Usage: DM.sh [-reset_run]\n\ Usage: DM.sh [-noclean_files]\n\n\ [-help] -- Print help information for this script\n\n\ [-lib_map_path <path>] -- Compiled simulation library directory path. The simulation library is compiled\n\ using the compile_simlib tcl command. Please see 'compile_simlib -help' for more information.\n\n\ [-reset_run] -- Recreate simulator setup files and library mappings for a clean run. The generated files\n\ from the previous run will be removed. If you don't want to remove the simulator generated files, use the\n\ -noclean_files switch.\n\n\ [-noclean_files] -- Reset previous run, but do not remove simulator generated files from the previous run.\n\n" echo -e $msg exit 1 } # Launch script run $1 $2
<reponame>Kam-M/english-irregular-verbs package englishVerbs; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.Writer; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Set; import java.util.TreeSet; import java.util.stream.Collectors; import java.util.stream.Stream; class FileHandler implements DaoI { // paths when exporting .jar // private String filePathMainCollection = new File("").getAbsolutePath() + File.separator + "English-Irregular-Verbs" + File.separator + "irregular-verbs.txt"; // private String filePathLearntVerbs = new File("").getAbsolutePath() + File.separator + "English-Irregular-Verbs" + File.separator + "learnt-verbs.txt"; // file paths for testing private String filePathMainCollection = new File("").getAbsolutePath() + File.separator + "irregular-verbs.txt"; private String filePathLearntVerbs = new File("").getAbsolutePath() + File.separator + "learnt-verbs.txt"; private VerbsCollection mainCollection; private VerbsCollection learntCollection; public FileHandler(VerbsCollection mainCollection, VerbsCollection learntCollection) { this.mainCollection = mainCollection; this.learntCollection = learntCollection; } @Override public Set<Verb> readMainCollectionFromSource() { Set<Verb> verbsCollection = null; try (Stream<String> s = Files.lines(Paths.get(filePathMainCollection.toString()), StandardCharsets.UTF_8)) { verbsCollection = s.map(streamString -> streamString.strip()).map(oneLineString -> oneLineString.split(",")) .map(arrayWithVerb -> new Verb(arrayWithVerb[0], arrayWithVerb[1], arrayWithVerb[2], arrayWithVerb[3])) .collect(Collectors.toCollection(TreeSet::new)); } catch (IOException e) { System.out.println( "\nCannot load verbs from source file -> check file \"irregular-verbs.txt\" in the app directory." + "\n\nShutting down..."); System.exit(-1); } return verbsCollection; } @Override public Set<Verb> readLearntCollectionFromSource() { Set<Verb> verbsCollection = null; try (Stream<String> s = Files.lines(Paths.get(filePathLearntVerbs.toString()), StandardCharsets.UTF_8)) { verbsCollection = s.map(streamString -> streamString.strip()).map(oneLineString -> oneLineString.split(",")) .map(arrayWithVerb -> new Verb(arrayWithVerb[0], arrayWithVerb[1], arrayWithVerb[2], arrayWithVerb[3])) .collect(Collectors.toCollection(TreeSet::new)); } catch (IOException e) { System.out.println( "\nCannot load verbs from source file -> check file \"learnt-verbs.txt\" in the app directory." + "\n\nShutting down..."); System.exit(-1); } return verbsCollection; } @Override public void saveMainCollection() { try (Writer output = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(filePathMainCollection), Charset.forName("UTF8")))) { for (var verb : this.mainCollection.getVerbsSortedByTranslation()) { output.write(verb.getVerbFormsAsOneSqueezedString() + System.lineSeparator()); } } catch (IOException e) { System.out.println( "\nSomething gone wrong while updating file -> check file \"irregular-verbs.txt\" in the app directory." + "\n\nShutting down..."); System.exit(-1); } } @Override public void saveLearnCollection() { try (Writer output = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(filePathLearntVerbs), Charset.forName("UTF8")))) { for (var verb : learntCollection.getVerbsSortedByTranslation()) { output.write(verb.getVerbFormsAsOneSqueezedString() + System.lineSeparator()); } } catch (IOException e) { System.out.println( "\nSomething gone wrong while updating file -> check file \"learnt-verbs.txt\" in the app directory." + "\n\nShutting down..."); System.exit(-1); } } }
#!/bin/bash LC_ALL=C tensorboard --logdir="/work/log" --port=6006 & jupyter lab --ip=0.0.0.0 --allow-root --port=8888 \ --NotebookApp.token='token' \ --NotebookApp.terminado_settings='{"shell_command": ["/bin/bash"]}'
#!/bin/bash if [ $# -ne 1 ]; then echo "usage: ./publish.sh \"commit message\"" exit 1; fi sculpin generate --env=prod git stash git checkout master cp -R output_prod/* . rm -rf output_* objects refs source git add * git commit -m "$1" git push origin --all git checkout drafts git stash pop
#!/bin/bash curl https://dot.net/v1/dotnet-install.sh -o dotnet-install.sh chmod +x dotnet-install.sh ./dotnet-install.sh --channel $1 --verbose
package xtest_test import ( xtest "github.com/goclub/test" "github.com/stretchr/testify/assert" "regexp" "strconv" "testing" ) func TestUUID(t *testing.T) { testRun(100, func(i int) (_break bool) { assert.Equal(t,len(xtest.UUID()), 36) assert.True(t,testMustBool(regexp.MatchString("[a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}", xtest.UUID()))) return }) countMap := map[string]int{} testRun(100, func(i int) (_break bool) { countMap[xtest.UUID()] = countMap[xtest.UUID()] +1 if countMap[xtest.UUID()] >1 { t.Log("uuid repeat!") t.Fail() } return }) } func TestIncrID(t *testing.T) { userIncrID := xtest.IncrID() userStringID := xtest.IncrID() testRun(100, func(i int) (_break bool) { id := i+1 assert.Equal(t,id, userIncrID.Int()) return }) testRun(100, func(i int) (_break bool) { id := i+1 assert.Equal(t,strconv.Itoa(id), userStringID.String()) return }) } func TestNameIncrID(t *testing.T) { testRun(100, func(i int) (_break bool) { id := strconv.Itoa(i+1) assert.Equal(t,id, xtest.NameIncrID("34gv43g43gv")) return }) }
// Basic imports import '../assets/main.css'; import { Component } from 'react'; import autoBind from 'react-autobind'; import Footer from '../components/footer'; import Header from '../components/header'; import { Button, Card, CardBody, CardImg, CardSubtitle, CardText, CardTitle, Col, Input, ListGroup, ListGroupItem, Row } from 'reactstrap'; import { abi } from '../contracts/nftContract'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome' import thetaIcon from '../assets/theta-token.svg'; import { FaFileInvoiceDollar, FaImage, FaPalette, FaUpload } from 'react-icons/fa'; const Web3 = require('web3') const dataweb3 = new Web3("https://eth-rpc-api-testnet.thetatoken.org/rpc"); function shuffle(inArray) { let tempArray = inArray; for (let i = tempArray.length - 1; i > 0; i--) { let j = Math.floor(Math.random() * (i + 1)); let temp = tempArray[i]; tempArray[i] = tempArray[j]; tempArray[j] = temp; } return tempArray; } function searchInJSON(json, searchTerm) { let result = []; let avoid = []; for (let i = 0; i < json.length; i++) { if (JSON.parse(json[i].Data).name.toLowerCase().includes(searchTerm.toLowerCase())) { avoid.push(i); result.push(json[i]); } } for (let i = 0; i < json.length; i++) { if (JSON.parse(json[i].Data).attributes[0].game.toLowerCase().includes(searchTerm.toLowerCase()) && avoid.indexOf(i) === -1) { result.push(json[i]); } } return result; } class Main extends Component { constructor(props) { super(props); this.state = { elements: [], artist: {}, prices: [], status: [], search: "", searchElements: [], searchResults: [], } autoBind(this); this.unirest = require('unirest'); } async componentDidMount() { this.unirest('GET', 'https://XXXXXXXXXX.execute-api.us-east-1.amazonaws.com/arcade-FullDB') .end((res) => { if (res.error) throw new Error(res.error); if (res.body.length > 0) { let temp = this.state.artist; let temp2 = res.body; let temp3 = [] let temp4 = [] for (let i = 0; i < res.body.length; i++) { if (temp[res.body[i]["PubKey"]] === undefined) { temp[res.body[i]["PubKey"]] = 0; } else { temp[res.body[i]["PubKey"]]++; } temp2[i]["Counter"] = temp[res.body[i]["PubKey"]] temp3.push("0") temp4.push(res.body[i]) temp2[i]["index"] = i } this.setState({ elements: shuffle(temp2), prices: temp3, searchElements: temp4, }, () => { for (let i = 0; i < res.body.length; i++) { this.updatePrice(res.body[i]["Contract"], i) } }); } }); } updatePrice(contract, id) { const mint_contract = new dataweb3.eth.Contract(abi(), contract); mint_contract.methods.flag().call().then(status => { let temp = this.state.status; temp[id] = status; this.setState({ status: temp }); }); mint_contract.methods.price().call().then(price => { let temp = this.state.prices; temp[id] = price; this.setState({ prices: temp }); }); } render() { return ( <div className="App" style={{ overflowX: "hidden" }}> <Header /> <div className="body-style" id="body-style" style={{ overflowX: "hidden", overflowY: "hidden" }}> <div> <Row style={{ paddingBottom: "13vh" }}> <Col style={{ paddingTop: "14vh", paddingLeft: "12vw" }}> <h1 style={{ fontWeight: "bold", fontSize: "4rem" }}>OWN<p /> streaming’s BEST <p /> moments</h1> <h5> <p />Collect and trade great moments <p />from your favourite creators. </h5> <br /> <Row> <Col> <div style={{ width: "90%", paddingLeft: "5%" }} className="flexbox-style"> <Input onClick={()=>{ this.setState({ searchResults:[], }) }} onChange={(event) => { this.setState({ search: event.target.value }); }} style={{ borderRadius: "25px 0px 0px 25px", fontSize: "1.5rem" }} type="text" placeholder=" Search Creator or Content" /> <Button onClick={() => { console.log(searchInJSON(this.state.searchElements, this.state.search)) this.setState({ searchResults: searchInJSON(this.state.searchElements, this.state.search) }); }} style={{ width: "200px", borderRadius: "0px 25px 25px 0px", fontSize: "1.5rem", background: `#d209c3` }}>Search</Button> </div> <div style={{height:"20px"}}> { this.state.searchResults.length > 0 && <ListGroup style={{paddingLeft:"8%",overflowY:"scroll",height:"18vh",width:"67%"}}> { this.state.searchResults.map((element) => { return ( <ListGroupItem style={{textAlign:"justify"}}> <a className="nostyle" href={`/nft/${element.PubKey}?id=${element.Counter}`}> { "NFT: " + JSON.parse(element.Data).name + ", Game: "+ JSON.parse(element.Data).attributes[0].game } </a> </ListGroupItem> ) }) } </ListGroup> } </div> </Col> </Row> </Col> <Col> <div className="background-images"/> </Col> </Row> <br /> <div className="myhr2" /> <div style={{ paddingTop: "4vh" }}> <h1> Exclusives from Theta Clips </h1> </div> <br /> <div className="flexbox-style"> { this.state.elements.map((item, index) => { if (index < 3) { return ( <div key={"element" + index} style={{ margin: "10px", height: "74vh" }}> <Card id={"cards" + index} style={{ width: "20vw", height: "74vh", backgroundColor:"#00c6c6" }}> <div style={{ opacity: "100%", textAlign: "center", paddingTop: "10px" }} > <video width= "250px" src={item.Url} /> </div> <br /> <CardBody style={{WebkitTextStroke:"0.2px black"}}> <CardTitle tag="h5">{JSON.parse(item.Data).attributes[0].artist}</CardTitle> <br /> <CardSubtitle tag="h3" className="mb-2 text-muted"> <div className="flexbox-style" style={{color:"white"}}> <div> {"Price:"} <>&nbsp;</> </div> <div> { this.state.prices[index] === "0" ? "....." : dataweb3.utils.fromWei(this.state.prices[index], 'ether') } </div> <>&nbsp;</> <img src={thetaIcon} style={{width:"24px", border:"1px solid black"}} /> { !this.state.status[index] && <div style={{ color: "red" }}> <>&nbsp;</> Sold </div> } </div> </CardSubtitle> <br /> <div style={{ overflowY: "hidden", height: "100%", fontSize:"1.3rem" }}> <CardText > { JSON.parse(item.Data).description.length > 150 ? JSON.parse(item.Data).description.substring(0, 150) + "..." : JSON.parse(item.Data).description } </CardText> </div> <br /> <div className="flexbox-style"> <div style={{ position: "absolute", bottom: "2vh" }}> <Button style={{ width: "200px", borderRadius: "25px", fontSize: "1.3rem", background: ` #d209c3` }} onClick={() => { window.open(`/nft/${item.PubKey}?id=${item.Counter}`, "_blank"); }}>Open NFT</Button> </div> </div> </CardBody> </Card> </div> ) } else { return null } }) } </div> <br /> <br /> <div className="myhr2" /> <div style={{ paddingTop: "4vh" }}> <div> <h1> Create and sell your NFTs </h1> </div> <Row style={{ padding: "10vh 4vh 4vh 4vh" }}> <Col> <div> <FaImage className="fa-gradient1" /> </div> <div style={{ fontSize: "1.5rem", fontWeight: "bolder", paddingTop: "2vh", paddingBottom: "2vh" }}> Connect to your wallet </div> <div style={{ padding: "0px 20px 0px 20px" }}> Set up your wallet of choice. Link your NFT profile by clicking the wallet icon on the top right corner. Learn more in the wallets section. </div> </Col> <Col> <div> <FaUpload className="fa-gradient3" /> </div> <div style={{ fontSize: "1.5rem", fontWeight: "bolder", paddingTop: "2vh", paddingBottom: "2vh" }}> Upload your content </div> <div style={{ padding: "0px 20px 0px 20px" }}> Create your creator profile, Upload your descriptions, upload content you use to work with. </div> </Col> <Col> <div> <FaFileInvoiceDollar className="fa-gradient4" /> </div> <div style={{ fontSize: "1.5rem", fontWeight: "bolder", paddingTop: "2vh", paddingBottom: "2vh" }}> Sell your Content </div> <div style={{ padding: "0px 20px 0px 20px" }}> Sell and trade 15 second videos of your favourite moments. You choose how you want to sell your NFTs. </div> </Col> </Row> </div> </div> <div className="myhr2" /> </div> <Footer /> </div> ); } } export default Main;
import chai from "chai"; import { beforeEach, afterEach } from "mocha"; import chaiHttp from "chai-http"; import server from "../../index"; import Article from "../../models/Article"; const { expect } = chai; chai.use(chaiHttp); const getArticles = () => { beforeEach(async () => { await Article.deleteMany({}); }); afterEach(async () => { await Article.deleteMany({}); }); it("shoult return 200 status if article fetched successfully ", (done) => { Article.collection.insertMany([ { title: "first title", subtitle: "first subtitle ever", image: "images/og-default.jpg", content: "this is content for testing article api", author: "gilbert", }, { title: "second title", subtitle: "second subtitle ever", image: "images/og-default.jpg", content: "this is content for testing article api", author: "elnino", }, ]); chai .request(server) .get("/api/articles") .end((err, res) => { expect(err).to.be.null; expect(res).to.have.status(200); expect(res.body).to.have.property( "message", "post fetched successfully" ); expect(res.body).to.have.property("data"); done(); }); }); }; export default getArticles;
<filename>node_modules/ts-toolbelt/out/List/NullableKeys.d.ts<gh_stars>1-10 import { NullableKeys as ONullableKeys } from '../Object/NullableKeys'; import { ObjectOf } from './ObjectOf'; import { List } from './List'; /** * Get the keys of `L` that are nullable * @param L * @returns [[Key]] * @example * ```ts * ``` */ export declare type NullableKeys<L extends List> = ONullableKeys<ObjectOf<L>>;
#!/bin/bash set -e if [ "$1" = "run" ]; then cd /app/configuration exec tas-cli server fi exec "$@"
#!/usr/bin/env bash function describe_actions() { echo " 📦 Install the latest keybase package from Homebrew" } function install() { install_homebrew_package "keybase" }
<reponame>ymx0627/HMap<gh_stars>10-100 /** * Created by FDD on 2017/2/24. * @desc 原作者 Wandergis <https://github.com/wandergis/coordtransform> * 在此基础上添加优化和处理,并改写为es6 */ const PI = Math.PI; // PI const X_PI = PI * 3000.0 / 180.0; const a = 6378245.0; // 北京54坐标系长半轴a=6378245m const ee = 0.00669342162296594323; /** * 转换纬度 * @param lng * @param lat * @returns {number} */ const transformlat = (lng, lat) => { let ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lat * PI) + 40.0 * Math.sin(lat / 3.0 * PI)) * 2.0 / 3.0; ret += (160.0 * Math.sin(lat / 12.0 * PI) + 320 * Math.sin(lat * PI / 30.0)) * 2.0 / 3.0; return ret; }; /** * 转换经度 * @param lng * @param lat * @returns {number} */ const transformlng = (lng, lat) => { let ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng)); ret += (20.0 * Math.sin(6.0 * lng * PI) + 20.0 * Math.sin(2.0 * lng * PI)) * 2.0 / 3.0; ret += (20.0 * Math.sin(lng * PI) + 40.0 * Math.sin(lng / 3.0 * PI)) * 2.0 / 3.0; ret += (150.0 * Math.sin(lng / 12.0 * PI) + 300.0 * Math.sin(lng / 30.0 * PI)) * 2.0 / 3.0; return ret; }; /** * 判断坐标是否在国内(国外坐标不需转换) * @param lng * @param lat * @returns {boolean} */ const outOfChina = (lng, lat) => { // 纬度3.86~53.55,经度73.66~135.05 return !(lng > 73.66 && lng < 135.05 && lat > 3.86 && lat < 53.55); }; /** * 国测局J02(火星坐标系 (GCJ-02))坐标转WGS84 * @param lng * @param lat * @returns {[*,*]} */ const gcj02towgs84 = (lng, lat) => { if (outOfChina(lng, lat)) { return [lng, lat]; } else { let dlat = transformlat(lng - 105.0, lat - 35.0); let dlng = transformlng(lng - 105.0, lat - 35.0); let radlat = lat / 180.0 * PI; let magic = Math.sin(radlat); magic = 1 - ee * magic * magic; let sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI); let mglat = lat + dlat; let mglng = lng + dlng; return [lng * 2 - mglng, lat * 2 - mglat]; } }; /** * WGS84转国测局J02(火星坐标系 (GCJ-02)) * @param lng * @param lat * @returns {[*,*]} */ const wgs84togcj02 = (lng, lat) => { if (outOfChina(lng, lat)) { return [lng, lat]; } else { let dlat = transformlat(lng - 105.0, lat - 35.0); let dlng = transformlng(lng - 105.0, lat - 35.0); let radlat = lat / 180.0 * PI; let magic = Math.sin(radlat); magic = 1 - ee * magic * magic; let sqrtmagic = Math.sqrt(magic); dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * PI); dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * PI); let mglat = lat + dlat; let mglng = lng + dlng; return [mglng, mglat]; } }; /** * 国测局J02(火星坐标系 (GCJ-02))转百度坐标系 * @param lng * @param lat * @returns {[*,*]} */ const gcj02tobd = (lng, lat) => { let z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * X_PI); let theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * X_PI); let bdLng = z * Math.cos(theta) + 0.0065; let bdLat = z * Math.sin(theta) + 0.006; return [bdLng, bdLat]; }; /** * 百度坐标系转国测局J02(火星坐标系 (GCJ-02)) * @param lon * @param lat * @returns {[*,*]} */ const bdtogcj02 = (lon, lat) => { let x = lon - 0.0065; let y = lat - 0.006; let z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * X_PI); let theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * X_PI); let ggLng = z * Math.cos(theta); let ggLat = z * Math.sin(theta); return [ggLng, ggLat]; }; /** * 经纬度转Mercator * @param lontitude * @param latitude * @returns {[*,*]} */ const lonLatToMercator = (lontitude, latitude) => { let x = lontitude * 20037508.34 / 180; let y = Math.log(Math.tan((90 + latitude) * Math.PI / 360)) / (Math.PI / 180); y = y * 20037508.34 / 180; return [x, y]; }; /** * Mercator转经纬度 * @param x * @param y * @returns {[*,*]} * @constructor */ const MercatorTolonLat = (x, y) => { let longtitude = x / 20037508.34 * 180; let latitude = y / 20037508.34 * 180; latitude = 180 / Math.PI * (2 * Math.atan(Math.exp(latitude * Math.PI / 180)) - Math.PI / 2); return [longtitude, latitude]; }; export { transformlat, transformlng, outOfChina, gcj02towgs84, wgs84togcj02, gcj02tobd, bdtogcj02, lonLatToMercator, MercatorTolonLat };