text
stringlengths
1
1.05M
/* * Copyright (c) 2015. Seagate Technology PLC. All rights reserved. */ package com.seagate.alto.provider.example; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.suitebuilder.annotation.LargeTest; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.matcher.ViewMatchers.withId; @RunWith(AndroidJUnit4.class) @LargeTest public class ProviderAppTest { @Rule public ActivityTestRule<ProviderUserActivity> mActivityRule = new ActivityTestRule<>(ProviderUserActivity.class); @Test public void showPhotos() { onView(withId(R.id.provider_files_button)).perform(click()); // onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); // onView(withId(R.id.editText)).perform(typeText(STRING_TO_BE_TYPED), closeSoftKeyboard()); // onView(withText("Say hello!")).perform(click()); //line 2 // String expectedText = "Hello, " + STRING_TO_BE_TYPED + "!"; // onView(withId(R.id.textView)).check(matches(withText(expectedText))); //line 3 } }
<gh_stars>1-10 /* jshint expr: true */ var chai = require('chai'); var adt = require('../index'); chai.should(); describe('adt-linked-list', function () { var ll; beforeEach(function () { ll = adt.createLinkedList(); }); it('should instantiate an empty list', function() { ll.isEmpty().should.be.true; }); it('should not be empty if at least 1 item is in the list', function() { ll.add(0, {item: 1}); ll.isEmpty().should.be.false; }); it('should add an item to an empty list and have size 1', function() { ll.add(0, {item: 1}); ll.size().should.equal(1); }); it('should leave the list empty when an item is added and then removed from an empty list', function () { ll.add(0, {item: 1}); ll.remove(0); ll.isEmpty().should.be.true; }); describe('operations on non-empty lists', function () { beforeEach(function () { // create a list containing 10 items for (var i = 0; i < 10 ; i++) { var item = {}; item['item-' + i] = i; ll.add(i, item); } }); it('should add an item to a list of size \'n\' and have size \'n + 1\'', function() { // get the size of the list var n = ll.size(); // now add a new item to the list ll.add(n, {"item-n": n}); ll.size().should.equal(n + 1); }); it('should add an item to the correct position in the list', function() { var newItem = { newItem: 'new'}; var pos = Math.floor(ll.size() / 2); ll.add(pos, newItem); ll.get(pos).should.deep.equal(newItem); }); it('should thow an error if asked to remove an item that does not exist', function() { (function() { ll.remove(100); }).should.throw(Error); }); it('should have the correct size after a remove opertion', function () { var size = ll.size(); var pos = Math.floor(ll.size() / 2); ll.remove(pos); ll.size().should.equal(size - 1); }); it('should leave the list empty after all items have been removed', function () { var size = ll.size(); for (var i = 0; i < size; i++) { ll.remove(0); } ll.isEmpty().should.be.true; ll.size().should.equal(0); }); it('should return the correct item when get() is called with an index that exists', function() { var pos = Math.floor(ll.size() / 2); var item = ll.get(pos); item.hasOwnProperty('item-' + pos).should.be.true; }); it('should throw an error when get() is called with an index that does not exist', function() { var index = ll.size() * 2; (function() { ll.get(index); }).should.throw(Error); }); it('should return the correct size of the list', function() { ll.size().should.equal(10); }); }); });
function gcd(a, b) { if (a === 0 || b === 0) { return 0; } if (a === b) { return a; } if (a > b) { return gcd(a - b, b); } return gcd(a, b - a); }
<reponame>lgoldstein/communitychest package net.community.chest.net.proto.text.imap4; /** * <P>Copyright 2008 as per GPLv2</P> * * <P>Uses a tags generator that starts at a certain value and increments by * 1 at each call (wraps around if negative)</P> * * @author <NAME>. * @since Mar 27, 2008 9:23:43 AM */ public class IncrementalIMAP4TagsGenerator implements IMAP4TagsGenerator { /** * Last returned value - next one will be +1 (wrapped around if negative) */ private int _curTag /* =0 */; /** * Initialized constructor * @param startTag value to start from - if negative then its * <U>absolute</U> value will be used */ public IncrementalIMAP4TagsGenerator (int startTag) { // need to do this because Math.abs(Integer.MIN_VALUE) => Integer.MIN_VALUE if ((_curTag=Math.abs(startTag)) < 0) _curTag = 0; } /** * Default constructor - starts from {@link System#currentTimeMillis()} */ public IncrementalIMAP4TagsGenerator () { this((int) System.currentTimeMillis()); } /* NOTE !!! not synchronized * @see net.community.chest.net.proto.text.imap4.IMAP4TagsGenerator#getNextTag() */ @Override public int getNextTag () { _curTag++; if (_curTag < 0) _curTag = 0; return _curTag; } }
/*============================================================================= Boost.Wave: A Standard compliant C++ preprocessor library Definition of the preprocessor context http://www.boost.org/ Copyright (c) 2001-2005 <NAME>. Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(CPP_CONTEXT_HPP_907485E2_6649_4A87_911B_7F7225F3E5B8_INCLUDED) #define CPP_CONTEXT_HPP_907485E2_6649_4A87_911B_7F7225F3E5B8_INCLUDED #include <string> #include <vector> #include <stack> #include <boost/concept_check.hpp> #include <boost/wave/wave_config.hpp> #include <boost/wave/token_ids.hpp> #include <boost/wave/util/unput_queue_iterator.hpp> #include <boost/wave/util/cpp_ifblock.hpp> #include <boost/wave/util/cpp_include_paths.hpp> #include <boost/wave/util/iteration_context.hpp> #include <boost/wave/util/cpp_iterator.hpp> #include <boost/wave/util/cpp_macromap.hpp> #include <boost/wave/preprocessing_hooks.hpp> #include <boost/wave/cpp_iteration_context.hpp> #include <boost/wave/language_support.hpp> /////////////////////////////////////////////////////////////////////////////// namespace boost { namespace wave { /////////////////////////////////////////////////////////////////////////////// // // The C preprocessor context template class // // The boost::wave::context template is the main interface class to // control the behaviour of the preprocessing engine. // // The following template parameters has to be supplied: // // IteratorT The iterator type of the underlying input stream // LexIteratorT The lexer iterator type to use as the token factory // InputPolicyT The input policy type to use for loading the files // to be included. This template parameter is optional and // defaults to the // iteration_context_policies::load_file_to_string // type // TraceT The trace policy to use for trace and include file // notification callback. // /////////////////////////////////////////////////////////////////////////////// template < typename IteratorT, typename LexIteratorT, typename InputPolicyT = iteration_context_policies::load_file_to_string, typename TraceT = context_policies::default_preprocessing_hooks > class context { public: // concept checks // the given iterator shall be at least a forward iterator type BOOST_CLASS_REQUIRE(IteratorT, boost, ForwardIteratorConcept); // public typedefs typedef typename LexIteratorT::token_type token_type; typedef context<IteratorT, LexIteratorT, InputPolicyT, TraceT> self_type; typedef IteratorT target_iterator_type; typedef LexIteratorT lexer_type; typedef pp_iterator<self_type> iterator_type; typedef InputPolicyT input_policy_type; typedef typename token_type::position_type position_type; // type of a token sequence typedef std::list<token_type, boost::fast_pool_allocator<token_type> > token_sequence_type; // types of the policies typedef TraceT trace_policy_type; private: // stack of shared_ptr's to the pending iteration contexts typedef boost::shared_ptr<base_iteration_context<lexer_type> > iteration_ptr_type; typedef boost::wave::util::iteration_context_stack<iteration_ptr_type> iteration_context_stack_type; typedef typename iteration_context_stack_type::size_type iter_size_type; // the context object should not be copied around context(context const& rhs); context& operator= (context const& rhs); public: context(target_iterator_type const &first_, target_iterator_type const &last_, char const *fname = "<Unknown>", TraceT const &trace_ = TraceT()) : first(first_), last(last_), filename(fname) #if BOOST_WAVE_SUPPORT_PRAGMA_ONCE != 0 , current_filename(fname) #endif , macros(*this), language(boost::wave::support_cpp), trace(trace_) { macros.init_predefined_macros(fname); includes.init_initial_path(); } // iterator interface iterator_type begin() { includes.set_current_directory(filename.c_str()); return iterator_type(*this, first, last, position_type(filename.c_str()), get_language()); } iterator_type end() const { return iterator_type(); } // maintain include paths bool add_include_path(char const *path_) { return includes.add_include_path(path_, false);} bool add_sysinclude_path(char const *path_) { return includes.add_include_path(path_, true);} void set_sysinclude_delimiter() { includes.set_sys_include_delimiter(); } typename iteration_context_stack_type::size_type get_iteration_depth() const { return iter_ctxs.size(); } // maintain defined macros #if BOOST_WAVE_ENABLE_COMMANDLINE_MACROS != 0 bool add_macro_definition(std::string macrostring, bool is_predefined = false) { return boost::wave::util::add_macro_definition(*this, macrostring, is_predefined, get_language()); } #endif bool add_macro_definition(token_type const &name, bool has_params, std::vector<token_type> &parameters, token_sequence_type &definition, bool is_predefined = false) { return macros.add_macro(name, has_params, parameters, definition, is_predefined); } template <typename IteratorT2> bool is_defined_macro(IteratorT2 const &begin, IteratorT2 const &end) { return macros.is_defined(begin, end); } bool remove_macro_definition(typename token_type::string_type const &name, bool even_predefined = false) { return macros.remove_macro( token_type(T_IDENTIFIER, name, macros.get_main_pos()), even_predefined); } bool remove_macro_definition(token_type const &token, bool even_predefined = false) { return macros.remove_macro(token, even_predefined); } void reset_macro_definitions() { macros.reset_macromap(); macros.init_predefined_macros(); } // get the pp-iterator version information static std::string get_version() { return boost::wave::util::predefined_macros::get_fullversion(false); } static std::string get_version_string() { return boost::wave::util::predefined_macros::get_versionstr(false); } void set_language(boost::wave::language_support language_) { language = language_; reset_macro_definitions(); } boost::wave::language_support get_language() const { return language; } // change and ask for maximal possible include nesting depth void set_max_include_nesting_depth(iter_size_type new_depth) { iter_ctxs.set_max_include_nesting_depth(new_depth); } iter_size_type get_max_include_nesting_depth() const { return iter_ctxs.get_max_include_nesting_depth(); } // access the trace policy trace_policy_type &get_trace_policy() { return trace; } #if !defined(BOOST_NO_MEMBER_TEMPLATE_FRIENDS) protected: friend class boost::wave::pp_iterator< boost::wave::context<IteratorT, lexer_type, InputPolicyT, TraceT> >; friend class boost::wave::impl::pp_iterator_functor< boost::wave::context<IteratorT, lexer_type, InputPolicyT, TraceT> >; #endif // maintain include paths (helper functions) bool find_include_file (std::string &s, std::string &d, bool is_system, char const *current_file) const { return includes.find_include_file(s, d, is_system, current_file); } void set_current_directory(char const *path_) { includes.set_current_directory(path_); } // conditional compilation contexts bool get_if_block_status() const { return ifblocks.get_status(); } void enter_if_block(bool new_status) { ifblocks.enter_if_block(new_status); } bool enter_elif_block(bool new_status) { return ifblocks.enter_elif_block(new_status); } bool enter_else_block() { return ifblocks.enter_else_block(); } bool exit_if_block() { return ifblocks.exit_if_block(); } typename boost::wave::util::if_block_stack::size_type get_if_block_depth() const { return ifblocks.get_if_block_depth(); } // stack of iteration contexts iteration_ptr_type pop_iteration_context() { iteration_ptr_type top = iter_ctxs.top(); iter_ctxs.pop(); return top; } void push_iteration_context(position_type const &act_pos, iteration_ptr_type iter_ctx) { iter_ctxs.push(act_pos, iter_ctx); } position_type &get_main_pos() { return macros.get_main_pos(); } /////////////////////////////////////////////////////////////////////////////// // // expand_tokensequence(): // expands all macros contained in a given token sequence, handles '##' // and '#' pp operators and re-scans the resulting sequence // (essentially preprocesses the token sequence). // // The expand_undefined parameter is true during macro expansion inside // a C++ expression given for a #if or #elif statement. // /////////////////////////////////////////////////////////////////////////////// template <typename IteratorT2> token_type expand_tokensequence(IteratorT2 &first, IteratorT2 const &last, token_sequence_type &pending, token_sequence_type &expanded, bool expand_undefined = false) { return macros.expand_tokensequence(first, last, pending, expanded, expand_undefined); } template <typename IteratorT2> void expand_whole_tokensequence(IteratorT2 &first, IteratorT2 const &last, token_sequence_type &expanded, bool expand_undefined = true) { macros.expand_whole_tokensequence(expanded, first, last, expand_undefined); // remove any contained placeholder boost::wave::util::impl::remove_placeholders(expanded); } public: #if BOOST_WAVE_SUPPORT_PRAGMA_ONCE != 0 // support for #pragma once // maintain the real name of the current preprocessed file void set_current_filename(char const *real_name) { current_filename = real_name; } std::string const &get_current_filename() const { return current_filename; } // maintain the list of known headers containing #pragma once bool has_pragma_once(std::string const &filename) { return includes.has_pragma_once(filename); } bool add_pragma_once_header(std::string const &filename) { return includes.add_pragma_once_header(filename); } #endif // forwarding functions for the context policy hooks template <typename ContainerT> bool interpret_pragma(ContainerT &pending, token_type const &option, ContainerT const &values, token_type const &act_token) { return trace.interpret_pragma(*this, pending, option, values, act_token); } template <typename ParametersT, typename DefinitionT> void defined_macro(token_type const &name, bool is_functionlike, ParametersT const &parameters, DefinitionT const &definition, bool is_predefined) { trace.defined_macro(name, is_functionlike, parameters, definition, is_predefined); } void undefined_macro(token_type const &token) { trace.undefined_macro(token); } private: // the main input stream target_iterator_type first; // underlying input stream target_iterator_type last; std::string filename; // associated main filename #if BOOST_WAVE_SUPPORT_PRAGMA_ONCE != 0 std::string current_filename; // real name of current preprocessed file #endif boost::wave::util::if_block_stack ifblocks; // conditional compilation contexts boost::wave::util::include_paths includes; // lists of include directories to search iteration_context_stack_type iter_ctxs; // iteration contexts boost::wave::util::macromap<self_type> macros; // map of defined macros boost::wave::language_support language; // supported language/extensions trace_policy_type trace; // trace policy instance }; /////////////////////////////////////////////////////////////////////////////// } // namespace wave } // namespace boost #endif // !defined(CPP_CONTEXT_HPP_907485E2_6649_4A87_911B_7F7225F3E5B8_INCLUDED)
<filename>apps/system/js/sim_lock.js /* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- / /* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */ 'use strict'; var SimLock = { init: function sl_init() { // Do not do anything if we can't have access to MobileConnection API var conn = window.navigator.mozMobileConnection; if (!conn) return; this.onClose = this.onClose.bind(this); // Watch for apps that need a mobile connection window.addEventListener('appwillopen', this); // Display the dialog only after lockscreen is unlocked // To prevent keyboard being displayed behind it. window.addEventListener('unlock', this); // always monitor card state change conn.addEventListener('cardstatechange', this.showIfLocked.bind(this)); }, handleEvent: function sl_handleEvent(evt) { switch (evt.type) { case 'unlock': this.showIfLocked(); break; case 'appwillopen': // If an app needs 'telephony' or 'sms' permissions (i.e. mobile // connection) and the SIM card is locked, the SIM PIN unlock screen // should be launched var app = Applications.getByManifestURL( evt.target.getAttribute('mozapp')); if (!app || !app.manifest.permissions) return; // Ignore first time usage (FTU) app which already asks for the PIN code // XXX: We should have a better way to detect this app is FTU or not. if (evt.target.dataset.frameOrigin == FtuLauncher.getFtuOrigin()) return; // Ignore apps that don't require a mobile connection if (!('telephony' in app.manifest.permissions || 'sms' in app.manifest.permissions)) return; // Ignore second 'appwillopen' event when showIfLocked eventually opens // the app on valid PIN code var origin = evt.target.dataset.frameOrigin; if (origin == this._lastOrigin) { delete this._lastOrigin; return; } this._lastOrigin = origin; // If SIM is locked, cancel app opening in order to display // it after the SIM PIN dialog is shown if (this.showIfLocked()) evt.preventDefault(); break; } }, showIfLocked: function sl_showIfLocked() { var conn = window.navigator.mozMobileConnection; if (!conn) return false; if (LockScreen.locked) return false; // FTU has its specific SIM PIN UI if (FtuLauncher.isFtuRunning()) return false; switch (conn.cardState) { // do nothing in either absent, unknown or null card states case null: case 'absent': case 'unknown': break; case 'pukRequired': case 'pinRequired': SimPinDialog.show('unlock', this.onClose); return true; case 'networkLocked': // XXXX: After unlocking the SIM the cardState is // 'networkLocked' but it changes inmediately to 'ready' // if the phone is not SIM-locked. If the cardState // is still 'networkLocked' after 20 seconds we unlock // the network control key lock (network personalization). setTimeout(function checkState() { if (conn.cardState == 'networkLocked') { SimPinDialog.show('unlock', SimLock.onClose); } }, 20000); break; } return false; }, onClose: function sl_onClose(reason) { // Display the app only when PIN code is valid and when we click // on `X` button if (this._lastOrigin && (reason == 'success' || reason == 'skip')) WindowManager.setDisplayedApp(this._lastOrigin); delete this._lastOrigin; } }; SimLock.init();
#!/bin/bash # Copyright 2011-2019 The OTP authors # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in all # copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # Create a gradle configuration file to use a local maven repository if [[ ! -z "${MAVEN_REPOSITORY_URL}" ]]; then echo "The local maven repository will be configured in ~/.gradle/init.d/repo.gradle" mkdir -p ~/.gradle/init.d/ ( cat << EOF settingsEvaluated { settings -> settings.pluginManagement { repositories { maven { url '${MAVEN_REPOSITORY_URL}' } } } } allprojects { repositories { maven { url '${MAVEN_REPOSITORY_URL}' } } buildscript.repositories { maven { url '${MAVEN_REPOSITORY_URL}' } } } EOF ) > ~/.gradle/init.d/repo.gradle else echo "The local maven repository won't be configured in ~/.gradle/init.d/repo.gradle" fi
#!/bin/bash echo "Waiting 5 seconds before staring container monitor" sleep 5s echo "Starting docker container monitor" /opt/monitor/scripts/monitor.sh
import React from "react"; import { Box } from "@material-ui/core"; import { useIntl } from "react-intl"; import useStoreViewsSelector from "../../../hooks/useStoreViewsSelector"; import { Helmet } from "react-helmet"; import Analytics from "../../../components/Provider/Analytics"; const CopyTradersAnalytics = () => { const storeViews = useStoreViewsSelector(); const intl = useIntl(); return ( <Box className="profileAnalyticsPage"> <Helmet> <title> {`${storeViews.provider.name} - ${intl.formatMessage({ id: "srv.analytics", })} | ${intl.formatMessage({ id: "product" })}`} </title> </Helmet> <Analytics provider={storeViews.provider} /> </Box> ); }; export default CopyTradersAnalytics;
<reponame>astrangeguy/libx11-debian-mirror /* * Copyright 1992 Oracle and/or its affiliates. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. */ /****************************************************************** Copyright 1992, 1993, 1994 by FUJITSU LIMITED Permission to use, copy, modify, distribute, and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name of FUJITSU LIMITED not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. FUJITSU LIMITED makes no representations about the suitability of this software for any purpose. It is provided "as is" without express or implied warranty. FUJITSU LIMITED DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL FUJITSU LIMITED BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. Author: <NAME> (<EMAIL>) Sun Microsystems, Inc. <NAME> FUJITSU LIMITED <EMAIL> ******************************************************************/ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <string.h> #include <X11/Xatom.h> #include "Xlibint.h" #include "Xlcint.h" #include "Ximint.h" #include "XimTrInt.h" #include "XimTrX.h" Private Bool _XimXRegisterDispatcher( Xim im, Bool (*callback)( Xim, INT16, XPointer, XPointer ), XPointer call_data) { XIntrCallbackPtr rec; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; if (!(rec = (XIntrCallbackPtr)Xmalloc(sizeof(XIntrCallbackRec)))) return False; rec->func = callback; rec->call_data = call_data; rec->next = spec->intr_cb; spec->intr_cb = rec; return True; } Private void _XimXFreeIntrCallback( Xim im) { XSpecRec *spec = (XSpecRec *)im->private.proto.spec; register XIntrCallbackPtr rec, next; for (rec = spec->intr_cb; rec;) { next = rec->next; Xfree(rec); rec = next; } return; } Private Bool _XimXCallDispatcher(Xim im, INT16 len, XPointer data) { register XIntrCallbackRec *rec; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; for (rec = spec->intr_cb; rec; rec = rec->next) { if ((*rec->func)(im, len, data, rec->call_data)) return True; } return False; } Private Bool _XimXFilterWaitEvent( Display *d, Window w, XEvent *ev, XPointer arg) { Xim im = (Xim)arg; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; Bool ret; spec->ev = (XPointer)ev; ret = _XimFilterWaitEvent(im); /* * If ev is a pointer to a stack variable, there could be * a coredump later on if the pointer is dereferenced. * Therefore, reset to NULL to force reinitialization in * _XimXRead(). * * Keep in mind _XimXRead may be called again when the stack * is very different. */ spec->ev = (XPointer)NULL; return ret; } Private Bool _CheckConnect( Display *display, XEvent *event, XPointer xim) { Xim im = (Xim)xim; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; if ((event->type == ClientMessage) && (event->xclient.message_type == spec->imconnectid)) { return True; } return False; } Private Bool _XimXConnect(Xim im) { XEvent event; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; CARD32 major_code; CARD32 minor_code; if (!(spec->lib_connect_wid = XCreateSimpleWindow(im->core.display, DefaultRootWindow(im->core.display), 0, 0, 1, 1, 1, 0, 0))) { return False; } event.xclient.type = ClientMessage; event.xclient.display = im->core.display; event.xclient.window = im->private.proto.im_window; event.xclient.message_type = spec->imconnectid; event.xclient.format = 32; event.xclient.data.l[0] = (CARD32)spec->lib_connect_wid; event.xclient.data.l[1] = spec->major_code; event.xclient.data.l[2] = spec->minor_code; event.xclient.data.l[3] = 0; event.xclient.data.l[4] = 0; if(event.xclient.data.l[1] == 1 || event.xclient.data.l[1] == 2) { XWindowAttributes atr; long event_mask; XGetWindowAttributes(im->core.display, spec->lib_connect_wid, &atr); event_mask = atr.your_event_mask | PropertyChangeMask; XSelectInput(im->core.display, spec->lib_connect_wid, event_mask); _XRegisterFilterByType(im->core.display, spec->lib_connect_wid, PropertyNotify, PropertyNotify, _XimXFilterWaitEvent, (XPointer)im); } XSendEvent(im->core.display, im->private.proto.im_window, False, NoEventMask, &event); XFlush(im->core.display); for (;;) { XIfEvent(im->core.display, &event, _CheckConnect, (XPointer)im); if (event.xclient.type != ClientMessage) { return False; } if (event.xclient.message_type == spec->imconnectid) break; } spec->ims_connect_wid = (Window)event.xclient.data.l[0]; major_code = (CARD32)event.xclient.data.l[1]; minor_code = (CARD32)event.xclient.data.l[2]; if (((major_code == 0) && (minor_code <= 2)) || ((major_code == 1) && (minor_code == 0)) || ((major_code == 2) && (minor_code <= 1))) { spec->major_code = major_code; spec->minor_code = minor_code; } if (((major_code == 0) && (minor_code == 2)) || ((major_code == 2) && (minor_code == 1))) { spec->BoundarySize = (CARD32)event.xclient.data.l[3]; } /* ClientMessage Event Filter */ _XRegisterFilterByType(im->core.display, spec->lib_connect_wid, ClientMessage, ClientMessage, _XimXFilterWaitEvent, (XPointer)im); return True; } Private Bool _XimXShutdown(Xim im) { XSpecRec *spec = (XSpecRec *)im->private.proto.spec; if (!spec) return True; /* ClientMessage Event Filter */ _XUnregisterFilter(im->core.display, ((XSpecRec *)im->private.proto.spec)->lib_connect_wid, _XimXFilterWaitEvent, (XPointer)im); XDestroyWindow(im->core.display, ((XSpecRec *)im->private.proto.spec)->lib_connect_wid); _XimXFreeIntrCallback(im); Xfree(spec); im->private.proto.spec = 0; return True; } Private char * _NewAtom( char *atomName) { static int sequence = 0; (void)sprintf(atomName, "_client%d", sequence); sequence = ((sequence < 20) ? sequence + 1 : 0); return atomName; } Private Bool _XimXWrite(Xim im, INT16 len, XPointer data) { Atom atom; char atomName[16]; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; XEvent event; CARD8 *p; CARD32 major_code = spec->major_code; CARD32 minor_code = spec->minor_code; int BoundSize; bzero(&event,sizeof(XEvent)); event.xclient.type = ClientMessage; event.xclient.display = im->core.display; event.xclient.window = spec->ims_connect_wid; if(major_code == 1 && minor_code == 0) { BoundSize = 0; } else if((major_code == 0 && minor_code == 2) || (major_code == 2 && minor_code == 1)) { BoundSize = spec->BoundarySize; } else if(major_code == 0 && minor_code == 1) { BoundSize = len; } else { BoundSize = XIM_CM_DATA_SIZE; } if (len > BoundSize) { event.xclient.message_type = spec->improtocolid; atom = XInternAtom(im->core.display, _NewAtom(atomName), False); XChangeProperty(im->core.display, spec->ims_connect_wid, atom, XA_STRING, 8, PropModeAppend, (unsigned char *)data, len); if(major_code == 0) { event.xclient.format = 32; event.xclient.data.l[0] = (long)len; event.xclient.data.l[1] = (long)atom; XSendEvent(im->core.display, spec->ims_connect_wid, False, NoEventMask, &event); } } else { int length; event.xclient.format = 8; for(length = 0 ; length < len ; length += XIM_CM_DATA_SIZE) { p = (CARD8 *)&event.xclient.data.b[0]; if((length + XIM_CM_DATA_SIZE) >= len) { event.xclient.message_type = spec->improtocolid; bzero(p, XIM_CM_DATA_SIZE); memcpy((char *)p, (data + length), (len - length)); } else { event.xclient.message_type = spec->immoredataid; memcpy((char *)p, (data + length), XIM_CM_DATA_SIZE); } XSendEvent(im->core.display, spec->ims_connect_wid, False, NoEventMask, &event); } } return True; } Private Bool _XimXGetReadData( Xim im, char *buf, int buf_len, int *ret_len, XEvent *event) { char *data; int len; char tmp_buf[XIM_CM_DATA_SIZE]; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; unsigned long length; Atom prop; int return_code; Atom type_ret; int format_ret; unsigned long nitems; unsigned long bytes_after_ret; unsigned char *prop_ret; if ((event->type == ClientMessage) && !((event->xclient.message_type == spec->improtocolid) || (event->xclient.message_type == spec->immoredataid))) { /* This event has nothing to do with us, * FIXME should not have gotten here then... */ return False; } else if ((event->type == ClientMessage) && (event->xclient.format == 8)) { data = event->xclient.data.b; if (buf_len >= XIM_CM_DATA_SIZE) { (void)memcpy(buf, data, XIM_CM_DATA_SIZE); *ret_len = XIM_CM_DATA_SIZE; } else { (void)memcpy(buf, data, buf_len); len = XIM_CM_DATA_SIZE - buf_len; (void)memcpy(tmp_buf, &data[buf_len], len); bzero(data, XIM_CM_DATA_SIZE); (void)memcpy(data, tmp_buf, len); XPutBackEvent(im->core.display, event); *ret_len = buf_len; } } else if ((event->type == ClientMessage) && (event->xclient.format == 32)) { length = (unsigned long)event->xclient.data.l[0]; prop = (Atom)event->xclient.data.l[1]; return_code = XGetWindowProperty(im->core.display, spec->lib_connect_wid, prop, 0L, (long)((length + 3)/ 4), True, AnyPropertyType, &type_ret, &format_ret, &nitems, &bytes_after_ret, &prop_ret); if (return_code != Success || format_ret == 0 || nitems == 0) { if (return_code == Success) XFree(prop_ret); return False; } if (buf_len >= length) { (void)memcpy(buf, prop_ret, (int)nitems); *ret_len = (int)nitems; if (bytes_after_ret > 0) { XFree(prop_ret); if (XGetWindowProperty(im->core.display, spec->lib_connect_wid, prop, 0L, ((length + bytes_after_ret + 3)/ 4), True, AnyPropertyType, &type_ret, &format_ret, &nitems, &bytes_after_ret, &prop_ret) == Success) { XChangeProperty(im->core.display, spec->lib_connect_wid, prop, XA_STRING, 8, PropModePrepend, &prop_ret[length], (nitems - length)); } else { return False; } } } else { (void)memcpy(buf, prop_ret, buf_len); *ret_len = buf_len; len = nitems - buf_len; if (bytes_after_ret > 0) { XFree(prop_ret); if (XGetWindowProperty(im->core.display, spec->lib_connect_wid, prop, 0L, ((length + bytes_after_ret + 3)/ 4), True, AnyPropertyType, &type_ret, &format_ret, &nitems, &bytes_after_ret, &prop_ret) != Success) { return False; } } XChangeProperty(im->core.display, spec->lib_connect_wid, prop, XA_STRING, 8, PropModePrepend, &prop_ret[buf_len], len); event->xclient.data.l[0] = (long)len; event->xclient.data.l[1] = (long)prop; XPutBackEvent(im->core.display, event); } XFree(prop_ret); } else if (event->type == PropertyNotify) { prop = event->xproperty.atom; return_code = XGetWindowProperty(im->core.display, spec->lib_connect_wid, prop, 0L, 1000000L, True, AnyPropertyType, &type_ret, &format_ret, &nitems, &bytes_after_ret, &prop_ret); if (return_code != Success || format_ret == 0 || nitems == 0) { if (return_code == Success) XFree(prop_ret); return False; } if (buf_len >= nitems) { (void)memcpy(buf, prop_ret, (int)nitems); *ret_len = (int)nitems; } else { (void)memcpy(buf, prop_ret, buf_len); *ret_len = buf_len; len = nitems - buf_len; XChangeProperty(im->core.display, spec->lib_connect_wid, prop, XA_STRING, 8, PropModePrepend, &prop_ret[buf_len], len); } XFree(prop_ret); } return True; } Private Bool _CheckCMEvent( Display *display, XEvent *event, XPointer xim) { Xim im = (Xim)xim; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; CARD32 major_code = spec->major_code; if ((event->type == ClientMessage) &&((event->xclient.message_type == spec->improtocolid) || (event->xclient.message_type == spec->immoredataid))) return True; if((major_code == 1 || major_code == 2) && (event->type == PropertyNotify) && (event->xproperty.state == PropertyNewValue)) return True; return False; } Private Bool _XimXRead(Xim im, XPointer recv_buf, int buf_len, int *ret_len) { XEvent *ev; XEvent event; int len = 0; XSpecRec *spec = (XSpecRec *)im->private.proto.spec; XPointer arg = spec->ev; if (!arg) { bzero(&event, sizeof(XEvent)); ev = &event; XIfEvent(im->core.display, ev, _CheckCMEvent, (XPointer)im); } else { ev = (XEvent *)arg; spec->ev = (XPointer)NULL; } if (!(_XimXGetReadData(im, recv_buf, buf_len, &len, ev))) return False; *ret_len = len; return True; } Private void _XimXFlush(Xim im) { XFlush(im->core.display); return; } Public Bool _XimXConf(Xim im, char *address) { XSpecRec *spec; if (!(spec = Xcalloc(1, sizeof(XSpecRec)))) return False; spec->improtocolid = XInternAtom(im->core.display, _XIM_PROTOCOL, False); spec->imconnectid = XInternAtom(im->core.display, _XIM_XCONNECT, False); spec->immoredataid = XInternAtom(im->core.display, _XIM_MOREDATA, False); spec->major_code = MAJOR_TRANSPORT_VERSION; spec->minor_code = MINOR_TRANSPORT_VERSION; im->private.proto.spec = (XPointer)spec; im->private.proto.connect = _XimXConnect; im->private.proto.shutdown = _XimXShutdown; im->private.proto.write = _XimXWrite; im->private.proto.read = _XimXRead; im->private.proto.flush = _XimXFlush; im->private.proto.register_dispatcher = _XimXRegisterDispatcher; im->private.proto.call_dispatcher = _XimXCallDispatcher; return True; }
<reponame>caHarkness/android-dl package com.caharkness.support.fragments; import android.os.Environment; import android.view.View; import com.caharkness.support.R; import com.caharkness.support.SupportApplication; import com.caharkness.support.models.SupportBundle; import com.caharkness.support.utilities.SupportFiles; import com.caharkness.support.utilities.SupportColors; import com.caharkness.support.views.SupportMenuItemView; import com.caharkness.support.views.SupportMenuView; import java.io.File; import java.util.ArrayList; import java.util.List; public class SupportFileBrowserFragment extends SupportAsyncFragment { File file; SupportMenuView list_view; public SupportFileBrowserFragment() { super(); } public File getHome() { return Environment.getExternalStorageDirectory(); } public File getFile() { if (file == null) { file = getHome(); String path = getData().getString("path", ""); if (path.length() > 0) file = new File(path); } return file; } public SupportMenuView getListView() { return list_view; } // // // // Area: Behavior flags // // // public boolean getNavigationEnabled() { return true; } public boolean getShowParentDirectory() { return true; } public boolean getViewFileDetailsBeforeSelecting() { return false; } public boolean getRootBrowsingEnabled() { return false; } public boolean getShowHiddenFilesEnabled() { return false; } public boolean getSelectingEnabled() { return false; } public boolean isAtRoot() { if (getFile().getAbsolutePath().length() < 2) return true; if (!getRootBrowsingEnabled()) { String current_path = getFile().getAbsolutePath(); String external_storage_path = Environment.getExternalStorageDirectory().getAbsolutePath(); if (current_path.equals(external_storage_path)) return true; } return false; } // // // // Area: Navigation // // // public void navigateTo(File file) { try { if (getMode() != Mode.BROWSING) return; replaceWith( getClass() .newInstance() .slideInRight() .setData( new SupportBundle() .set("path", file.getAbsolutePath()) .getBundle())); } catch (Exception x) { throw new RuntimeException(x.getMessage()); } } public void navigateBackTo(File file) { try { if (getMode() != Mode.BROWSING) return; replaceWith( getClass() .newInstance() .slideInLeft() .setData( new SupportBundle() .set("path", file.getAbsolutePath()) .getBundle())); } catch (Exception x) { throw new RuntimeException(x.getMessage()); } } public void navigateUp() { if (getMode() != Mode.BROWSING) return; navigateBackTo(getFile().getParentFile()); } // // // // // // // public Runnable getFolderAction(final File file, SupportMenuItemView view) { return new Runnable() { @Override public void run() { if (getSelectingEnabled()) if (getMode() == Mode.SELECTING) { if (getSelection().contains(file)) deselect(file); else select(file); return; } if (getNavigationEnabled()) navigateTo(file); } }; } public Runnable getFolderAlternateAction(final File file, SupportMenuItemView view) { return new Runnable() { @Override public void run() { if (getSelectingEnabled()) select(file); } }; } public Runnable getFileAction(final File file, SupportMenuItemView view) { return new Runnable() { @Override public void run() { if (getSelectingEnabled()) if (getMode() == Mode.SELECTING) { if (getSelection().contains(file)) deselect(file); else select(file); return; } if (getViewFileDetailsBeforeSelecting()) { if (getNavigationEnabled()) navigateTo(file); } else onFileChosen(file); } }; } public Runnable getFileAlternateAction(final File file, SupportMenuItemView view) { return new Runnable() { @Override public void run() { if (getSelectingEnabled()) select(file); } }; } public SupportMenuItemView getParentDirectoryListItemView() { return new SupportMenuItemView(getContext()) .setLeftIcon(R.drawable.ic_reply) .setTitle("Parent directory") .setAction(new Runnable() { @Override public void run() { if (getNavigationEnabled()) navigateUp(); } }); } public SupportMenuItemView getFileListItemView(final File file) { final SupportMenuItemView item = new SupportMenuItemView(getContext()); if (file.isDirectory()) { item.setLeftIcon( R.drawable.ic_folder, SupportColors.getAccentColor(getContext())); item.setAction( getFolderAction( file, item)); item.setAlternateAction( getFolderAlternateAction( file, item)); item.addTag("folder"); item.addTag("directory"); item.addTag("selectable"); item.putMetadata("folder_path", file.getAbsolutePath()); item.putMetadata("path", file.getAbsolutePath()); item.putMetadata("kind", "folder"); item.putMetadata("type", "folder"); } else { item.setLeftIcon( R.drawable.ic_insert_drive_file, SupportColors.getForegroundColor(getContext())); item.setAction( getFileAction( file, item)); item.setAlternateAction( getFileAlternateAction( file, item)); item.addTag("file"); item.addTag("selectable"); item.putMetadata("file_path", file.getAbsolutePath()); item.putMetadata("path", file.getAbsolutePath()); item.putMetadata("kind", "file"); item.putMetadata("type", "file"); } item.setTitle(file.getName()); return item; } public List<SupportMenuItemView> getFileActionListItemViews(final File file) { ArrayList<SupportMenuItemView> items = new ArrayList<>(); items.add( new SupportMenuItemView(getContext()) .setTitle("Select") .setAction(new Runnable() { @Override public void run() { onFileChosen(file); } })); return items; } public SupportMenuItemView getListItemViewFromFile(File file) { for (SupportMenuItemView v : getListView().getItemsContainingMetadata("path")) if (v.getMetadata("path").equals(file.getAbsolutePath())) return v; return null; } // // // // Area: Events // // // public void onFileChosen(File file) { } public void onFileSelected(File file) { if (!getSelectingEnabled()) return; if (getSelection().contains(file)) return; getSelection().add(file); SupportMenuItemView view = getListItemViewFromFile(file); view.addTag("selected"); view.setRightIcon( R.drawable.ic_check, SupportColors.getAccentColor(getContext())); setMode(Mode.SELECTING); onSelectionChanged(); } public void onFileDeselected(File file) { getSelection().remove(file); SupportMenuItemView view = getListItemViewFromFile(file); view.removeTag("selected"); view.setRightIcon(null); onSelectionChanged(); } public void onSelectionChanged() { if (getSelection().size() < 1) setMode(Mode.BROWSING); } public void onViewDirectory() { } public void onViewFile() { } public void onView() { } public void chooseFileByName() { getSupportActivity().showInputDialog( "File Name", new Runnable() { @Override public void run() { onFileChosen( new File( getFile().getAbsolutePath() + "/" + SupportApplication.getString("_input"))); } }); } // // // // Area: File selection // // // public enum Mode { BROWSING, SELECTING } private Mode mode; private ArrayList<File> selection; public Mode getMode() { if (mode == null) mode = Mode.BROWSING; return mode; } public void setMode(Mode m) { mode = m; } public ArrayList<File> getSelection() { if (selection == null) selection = new ArrayList<>(); return selection; } public void selectAll() { for (SupportMenuItemView view : getListView().getItemsContainingMetadata("path")) select(new File(view.getMetadata("path"))); } public void select(File file) { onFileSelected(file); } public void deselect(File file) { onFileDeselected(file); } public void deselectAll() { while (getSelection().size() > 0) deselect(getSelection().get(0)); } // // // // Area: View Creation // // // @Override public View onCreateView() { list_view = new SupportMenuView(getContext()); // // // if (getFile().isDirectory()) { // // // // Area: Directory view populating // // // if (!isAtRoot()) if (getShowParentDirectory()) list_view.addItem(getParentDirectoryListItemView()); List<File> files = SupportFiles.directory(file); for (File file : files) { // // If there's a search filter applied and the file name doesn't match it, // Skip listing this file entirely. // if (getData().getString("search", "").length() > 0) if (!file.getName().contains(getData().getString("search", ""))) continue; if (file.getName().startsWith(".")) if (!getShowHiddenFilesEnabled()) continue; list_view.addItem(getFileListItemView(file)); } onViewDirectory(); onView(); } else { // // // // Area: File view populating // // // list_view.addItem( new SupportMenuItemView(getContext()) .setLeftIcon(R.drawable.ic_insert_drive_file) .setTitle(getFile().getName())); /*.setTable( new String[][] { {"Size", getFile().length() + " bytes"}, {"Path", getFile().getAbsolutePath()}, }, SupportColors.getAccentColor(getContext())));*/ list_view.addItem( new SupportMenuItemView(getContext()) .setLabel("Actions")); for (SupportMenuItemView item : getFileActionListItemViews(getFile())) list_view.addItem(item); onViewFile(); onView(); } // // // int refresh_color = getSupportActivity() .getToolbar() .getToolbarBackgroundColor(); if (SupportColors.isLight(refresh_color)) refresh_color = SupportColors.getAccentColor(getContext()); if (SupportColors.isLight(refresh_color)) refresh_color = SupportColors.get("black"); return list_view .getAsSwipeRefreshLayout( new Runnable() { @Override public void run() { if (getNavigationEnabled()) recreate(); } }); } }
<reponame>devosoft/empirical-prefab-demo #pragma once #include <string> #include "emp/prefab/Card.hpp" #include "emp/prefab/CodeBlock.hpp" #include "emp/prefab/FontAwesomeIcon.hpp" #include "emp/prefab/LoadingModal.hpp" #include "emp/web/Document.hpp" #include "emp/web/Div.hpp" void loading_modal_example( emp::web::Document& doc ) { // ------ Loading Modal Example ------ emp::prefab::Card loading_modal_ex("INIT_CLOSED"); doc << loading_modal_ex; loading_modal_ex.AddHeaderContent("<h3>Loading Modal</h3>"); loading_modal_ex << "<h3>Live Demo:</h3><hr>"; loading_modal_ex << "<p>Click button to show loading modal. It will close automatically after a few seconds.</p>"; emp::web::Button loading_modal_demo([](){emscripten_run_script("DemoLoadingModal();");}, "Show Loading Modal"); loading_modal_ex << loading_modal_demo; loading_modal_demo.SetAttr( "class", "btn btn-info" ); loading_modal_ex << "<br><br><br><h3>Code:</h3><hr>"; const std::string loading_modal_code = R"( #include "emp/prefab/LoadingModal.hpp" #include "emp/web/web.hpp" emp::web::Document doc("emp_base"); int main(){ // Code that takes a while to render on web page emp::prefab::CloseLoadingModal(); } )"; emp::prefab::CodeBlock loading_modal_code_block(loading_modal_code, "c++"); loading_modal_ex << loading_modal_code_block; loading_modal_ex << "<p>Add Loading Modal script at the top of the body section of your HTML file.</p>"; const std::string loading_modal_html = R"( <html> <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"> <script src="jquery-1.11.2.min.js></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/gh/devosoft/Empirical/source/prefab/DefaultConfigPanelStyle.css"> </head> <body> <script src="https://cdn.jsdelivr.net/gh/devosoft/Empirical/source/prefab/LoadingModal.js"></script> <!-- Rest of web page --> </body> </html> )"; emp::prefab::CodeBlock loading_modal_code_block_html(loading_modal_html, "html"); loading_modal_ex << loading_modal_code_block_html; }
<gh_stars>100-1000 #ifndef _EN_EX_ITEM_H_ #define _EN_EX_ITEM_H_ #include "z3D/z3D.h" #include "z3D/actors/z_en_ex_item.h" void EnExItem_rInit(Actor* thisx, GlobalContext* globalCtx); void EnExItem_rDestroy(Actor* thisx, GlobalContext* globalCtx); #endif //_EN_EX_ITEM_H_
void calculateComplement() { int num_bits = sizeof(complement_mask_) * 8; // Assuming 32-bit integer complement_mask_ = ~complement_mask_; // Calculate the bitwise complement // Apply a mask to keep only the relevant bits int mask = (1 << num_bits) - 1; complement_mask_ &= mask; }
class HikingTrail: def __init__(self, locations, difficulty): self.locations = locations self.difficulty = difficulty @property def location_list_short(self): return [l.name_short for l in self.locations.all()] @property def difficulty_index(self): return constants.DIFFICULTY_CHOICES.index_of(self.difficulty) def filter_tags(self, tags): filtered_locations = [] for location in self.locations: if any(tag in location.tags for tag in tags): filtered_locations.append(location) return filtered_locations
<reponame>chec/headlesscommerce.org<gh_stars>10-100 import { useReducer } from "react"; const SUBMIT_SUCCESS = "SUBMIT_SUCCESS"; const SUBMIT_ERROR = "SUBMIT_ERROR"; function reducer(state, action) { const { type, message }: { type: string; message?: string } = action; switch (type) { case SUBMIT_ERROR: return { ...state, error: message, submitted: false, }; case SUBMIT_SUCCESS: return { ...state, error: null, submitted: true, }; default: return { ...state, }; } } function useSendData(endpoint: string) { const [state, dispatch] = useReducer(reducer, { error: null, submitted: null, }); async function sendData(body) { try { const response = await fetch(endpoint, { method: "POST", body: JSON.stringify(body), }); if (!response.ok) throw new Error("There was a problem"); dispatch({ type: SUBMIT_SUCCESS }); } catch ({ message }) { dispatch({ type: SUBMIT_ERROR, message }); } } return { sendData, ...state }; } export default useSendData;
package com.jeeneee.realworld.comment.controller; import static com.jeeneee.realworld.fixture.ArticleFixture.ARTICLE1; import static com.jeeneee.realworld.fixture.CommentFixture.COMMENT1; import static com.jeeneee.realworld.fixture.CommentFixture.COMMENT2; import static com.jeeneee.realworld.fixture.CommentFixture.CREATE_REQUEST; import static com.jeeneee.realworld.fixture.UserFixture.USER1; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doNothing; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.payload.PayloadDocumentation.fieldWithPath; import static org.springframework.restdocs.payload.PayloadDocumentation.requestFields; import static org.springframework.restdocs.payload.PayloadDocumentation.responseFields; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.jeeneee.realworld.ControllerTest; import com.jeeneee.realworld.comment.domain.Comment; import com.jeeneee.realworld.comment.dto.CommentCreateRequest; import com.jeeneee.realworld.comment.dto.MultipleCommentResponse; import com.jeeneee.realworld.comment.dto.SingleCommentResponse; import com.jeeneee.realworld.comment.service.CommentService; import com.jeeneee.realworld.descriptor.CommentFieldDescriptor; import com.jeeneee.realworld.descriptor.ProfileFieldDescriptor; import com.jeeneee.realworld.user.domain.User; import java.util.List; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.restdocs.payload.JsonFieldType; import org.springframework.test.web.servlet.ResultActions; @WebMvcTest(CommentController.class) class CommentControllerTest extends ControllerTest { @MockBean private CommentService commentService; @DisplayName("댓글 생성") @Test void create() throws Exception { String request = objectMapper.writeValueAsString(CREATE_REQUEST); SingleCommentResponse response = SingleCommentResponse.of(COMMENT1, USER1); given(commentService.create(any(), any(CommentCreateRequest.class), any(User.class))) .willReturn(response); ResultActions result = mockMvc.perform( post("/api/articles/{slug}/comments", ARTICLE1.getSlugValue()) .accept(APPLICATION_JSON_VALUE) .contentType(APPLICATION_JSON_VALUE) .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_VALUE) .content(request) ); result.andExpect(status().isCreated()) .andDo( document("comment/create", requestHeaders( headerWithName(AUTHORIZATION_HEADER_NAME).description("토큰") ), requestFields( fieldWithPath("comment.body").type(JsonFieldType.STRING).description("내용") ), responseFields( fieldWithPath("comment").type(JsonFieldType.OBJECT).description("댓글") ).andWithPrefix("comment.", CommentFieldDescriptor.comment) .andWithPrefix("comment.author.", ProfileFieldDescriptor.profile) ) ); } @DisplayName("댓글 삭제") @Test void deleteComment() throws Exception { doNothing().when(commentService).delete(anyLong(), any(User.class)); ResultActions result = mockMvc.perform( delete("/api/articles/{slug}/comments/{id}", ARTICLE1.getSlugValue(), COMMENT1.getId()) .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_VALUE) ); result.andExpect(status().isNoContent()) .andDo( document("comment/delete", requestHeaders( headerWithName(AUTHORIZATION_HEADER_NAME).description("토큰") ) ) ); } @DisplayName("댓글 전체 조회") @Test void findAll() throws Exception { List<Comment> list = List.of(COMMENT1, COMMENT2); MultipleCommentResponse response = MultipleCommentResponse.of(list, USER1); given(commentService.findAll(any(), any(User.class))).willReturn(response); ResultActions result = mockMvc.perform( get("/api/articles/{slug}/comments", ARTICLE1.getSlugValue()) .header(AUTHORIZATION_HEADER_NAME, AUTHORIZATION_HEADER_VALUE) ); result.andExpect(status().isOk()) .andDo( document("comment/find-all", requestHeaders( headerWithName(AUTHORIZATION_HEADER_NAME).description("토큰").optional() ), responseFields( fieldWithPath("comments").type(JsonFieldType.ARRAY).description("댓글 목록") ).andWithPrefix("comments[].", CommentFieldDescriptor.comment) .andWithPrefix("comments[].author.", ProfileFieldDescriptor.profile) ) ); } }
<filename>assets/js/index.js import setup from './setup-ractive'; import App from './app'; // As of 0.7 default for debug is true // Ractive.defaults.debug = false; new App({ el: document.body });
package seedu.address.logic.commands; import static java.util.Objects.requireNonNull; import static seedu.address.logic.parser.CliSyntax.PREFIX_COMMUTER; import static seedu.address.logic.parser.CliSyntax.PREFIX_NAME; import static seedu.address.logic.parser.CliSyntax.PREFIX_PHONE; import static seedu.address.logic.parser.CliSyntax.PREFIX_TAG; import static seedu.address.logic.parser.CliSyntax.PREFIX_TRIPDAY; import static seedu.address.logic.parser.CliSyntax.PREFIX_TRIPTIME; import static seedu.address.model.Model.PREDICATE_SHOW_ALL_POOLS; import java.util.ArrayList; import java.util.List; import java.util.Set; import seedu.address.commons.core.Messages; import seedu.address.commons.core.index.Index; import seedu.address.logic.commands.exceptions.CommandException; import seedu.address.model.Model; import seedu.address.model.TripDay; import seedu.address.model.TripTime; import seedu.address.model.person.driver.Driver; import seedu.address.model.person.passenger.Passenger; import seedu.address.model.pool.Pool; import seedu.address.model.tag.Tag; /** * Associates a Driver with the selected Passengers. */ public class PoolCommand extends Command { public static final String COMMAND_WORD = "pool"; public static final long MAX_TIME_DIFFERENCE = 15; public static final String MESSAGE_USAGE = COMMAND_WORD + ": Pools commuters together with a driver. " + "Parameters: " + PREFIX_NAME + "DRIVER NAME " + PREFIX_PHONE + "DRIVER PHONE " + PREFIX_TRIPDAY + "TRIP DAY " + PREFIX_TRIPTIME + "TRIP TIME " + PREFIX_COMMUTER + "COMMUTER " + "[" + PREFIX_COMMUTER + "COMMUTER]... " + "[" + PREFIX_TAG + "TAG]...\n" + "Example: " + COMMAND_WORD + " " + PREFIX_NAME + "<NAME> " + PREFIX_PHONE + "98765432 " + PREFIX_TRIPDAY + "monday " + PREFIX_TRIPTIME + "1930 " + PREFIX_COMMUTER + "1 " + PREFIX_COMMUTER + "4 " + PREFIX_TAG + "female"; public static final String MESSAGE_NO_COMMUTERS = "No commuters were selected."; public static final String MESSAGE_POOL_SUCCESS = "Successfully created pool: %s, %s"; public static final String MESSAGE_POOL_SUCCESS_WITH_WARNING = "Successfully created pool: %s, %s. \nNOTE: " + "There are passengers with time differences of more than 15 minutes with the pool time."; public static final String MESSAGE_DUPLICATE_POOL = "This pool already exists in the GME Terminal."; public static final String MESSAGE_POOLS_CONTAIN_PERSON = "One or more passengers specified are already assigned " + "to a pool."; public static final String MESSAGE_TRIPDAY_MISMATCH = "One or more of the passengers specified " + "have a trip day that does not match this pool driver's trip day."; private final Driver driver; private final TripDay tripDay; private final TripTime tripTime; private final Set<Index> indexes; private final Set<Tag> tags; /** * Creates a PoolCommand that adds a pool specified by {@code driver}, {@code tripDay}, {@code tripTime}, * {@code tags}, and with passengers specified by {@code indexes}. * * @param driver Driver of the pool added. * @param indexes Indexes of the passengers to be added to the pool. * @param tripDay Trip day of the pool added. * @param tripTime Trip time of the pool added. * @param tags Tags associated with the pool added. */ public PoolCommand(Driver driver, Set<Index> indexes, TripDay tripDay, TripTime tripTime, Set<Tag> tags) { requireNonNull(driver); requireNonNull(indexes); requireNonNull(tripDay); requireNonNull(tripTime); this.driver = driver; this.indexes = indexes; this.tripDay = tripDay; this.tripTime = tripTime; this.tags = tags; } private boolean checkTimeDifference(List<Passenger> passengers) { return passengers.stream() .anyMatch(x -> x.getTripTime().compareMinutes(this.tripTime) > MAX_TIME_DIFFERENCE); } private List<Passenger> getPassengersFromIndexes(Set<Index> indexes, Model model) throws CommandException { List<Passenger> lastShownList = List.copyOf(model.getFilteredPassengerList()); List<Passenger> passengers = new ArrayList<>(); for (Index idx : indexes) { if (idx.getZeroBased() >= lastShownList.size()) { throw new CommandException(Messages.MESSAGE_INVALID_PASSENGER_DISPLAYED_INDEX); } Passenger passenger = lastShownList.get(idx.getZeroBased()); assert passenger != null : "passenger should not be null"; boolean isTripDayMismatch = !passenger.getTripDay().equals(tripDay); if (isTripDayMismatch) { throw new CommandException(MESSAGE_TRIPDAY_MISMATCH); } passengers.add(passenger); } return passengers; } @Override public CommandResult execute(Model model) throws CommandException { requireNonNull(model); if (indexes.size() == 0) { throw new CommandException(MESSAGE_NO_COMMUTERS); } List<Passenger> passengers = getPassengersFromIndexes(indexes, model); if (passengers.stream().anyMatch(model::hasPoolWithPassenger)) { throw new CommandException(MESSAGE_POOLS_CONTAIN_PERSON); } boolean shouldWarn = checkTimeDifference(passengers); Pool toAdd = new Pool(driver, tripDay, tripTime, passengers, tags); if (model.hasPool(toAdd)) { throw new CommandException(MESSAGE_DUPLICATE_POOL); } model.addPool(toAdd); model.updateFilteredPoolList(PREDICATE_SHOW_ALL_POOLS); String outputMessage = shouldWarn ? MESSAGE_POOL_SUCCESS_WITH_WARNING : MESSAGE_POOL_SUCCESS; return new CommandResult(String.format(outputMessage, toAdd.getDriverAsStr(), toAdd.getPassengerNames())); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof PoolCommand // instanceof handles nulls && (driver.equals(((PoolCommand) other).driver) && indexes.equals(((PoolCommand) other).indexes))); } }
from typing import Dict, List, Tuple from bs4 import BeautifulSoup def parse_footer_links(html_code: str) -> Dict[str, List[Tuple[str, str]]]: footer_links = {} soup = BeautifulSoup(html_code, 'html.parser') footer_sections = soup.find_all('div', class_='ft__list') for section in footer_sections: heading = section.find('div', class_='ft__heading').text links = section.find_all('a', class_='ft__link') footer_links[heading] = [(link.text, link['href']) for link in links] return footer_links
<gh_stars>10-100 import { DeployKeyTypeInterface } from '../type/deploy-key-type.interface'; import { DeployKeyRepository } from '../../persistence/repository/deploy-key.repository'; import { ResolverPaginationArgumentsInterface } from '../pagination-argument/resolver-pagination-arguments.interface'; import { ResolverDeployKeyFilterArgumentsInterface } from '../filter-argument/resolver-deploy-key-filter-arguments.interface'; import { RegenerateDeployKeyInputTypeInterface } from '../input-type/regenerate-deploy-key-input-type.interface'; import { RemoveDeployKeyInputTypeInterface } from '../input-type/remove-deploy-key-input-type.interface'; import { DefinitionRepository } from '../../persistence/repository/definition.repository'; import { SourceTypeInterface } from '../type/nested/definition-recipe/source-type.interface'; import { DeployKeyHelperComponent } from '../../helper/deploy-key-helper.component'; import { Args, Mutation, Query, Resolver } from '@nestjs/graphql'; import { DeployKeyLister } from '../lister/deploy-key-lister.component'; import { DeployKeyModelToTypeMapper } from '../model-to-type-mapper/deploy-key-model-to-type-mapper.service'; import { unlinkSync } from 'fs'; import * as _ from 'lodash'; import { DefinitionRecipeMapper } from '../../instantiation/definition-recipe-mapper.component'; @Resolver('DeployKey') export class DeployKeyResolver { constructor( private readonly deployKeyRepository: DeployKeyRepository, private readonly definitionRepository: DefinitionRepository, private readonly deployKeyHelper: DeployKeyHelperComponent, private readonly deployKeyLister: DeployKeyLister, private readonly deployKeyModelToTypeMapper: DeployKeyModelToTypeMapper, private readonly definitionRecipeMapper: DefinitionRecipeMapper, ) {} @Query('deployKeys') async getAll(@Args() args: any): Promise<DeployKeyTypeInterface[]> { const resolverListOptions = args as ResolverPaginationArgumentsInterface; const criteria = this.applyFilterArgumentToCriteria( {}, args as ResolverDeployKeyFilterArgumentsInterface, ); const deployKeys = await this.deployKeyLister.getList( criteria, args as ResolverPaginationArgumentsInterface, ); return this.deployKeyModelToTypeMapper.mapMany(deployKeys); } @Query('deployKey') async getOne(@Args('id') id: string): Promise<DeployKeyTypeInterface> { const deployKey = await this.deployKeyRepository.findOneById(id); return this.deployKeyModelToTypeMapper.mapOne(deployKey); } @Mutation('regenerateDeployKey') async regenerateOne( @Args() regenerateDeployKeyInput: RegenerateDeployKeyInputTypeInterface, ): Promise<DeployKeyTypeInterface> { // TODO Extract somewhere else. const deployKey = await this.deployKeyRepository.create( regenerateDeployKeyInput.cloneUrl, true, ); return this.deployKeyModelToTypeMapper.mapOne(deployKey); } @Mutation('generateMissingDeployKeys') async generateAllMissing(): Promise<object> { // TODO Extract somewhere else. const definitions = await this.definitionRepository.find({}, 0, 99999); const referencedCloneUrls = []; for (const definition of definitions) { const definitionRecipe = this.definitionRecipeMapper.map( definition.recipeAsYaml, ); for (const source of definitionRecipe.sources) { const cloneUrl = (source as SourceTypeInterface).cloneUrl; if ((source as SourceTypeInterface).useDeployKey) { referencedCloneUrls.push(cloneUrl); } } } const deployKeys = await this.deployKeyRepository.find({}, 0, 99999); const existingDeployKeyCloneUrls = []; for (const deployKey of deployKeys) { existingDeployKeyCloneUrls.push(deployKey.cloneUrl); } const missingReferencedCloneUrls = _.difference( _.uniq(referencedCloneUrls), existingDeployKeyCloneUrls, ); const createPromises = []; for (const missingReferencedCloneUrl of missingReferencedCloneUrls) { createPromises.push( this.deployKeyRepository.create(missingReferencedCloneUrl), ); } await Promise.all(createPromises); return { generated: true }; } @Mutation('removeUnusedDeployKeys') async removeAllUnused(): Promise<object> { // TODO Extract somewhere else. const deployKeys = await this.deployKeyRepository.find({}, 0, 99999); const definitions = await this.definitionRepository.find({}, 0, 99999); const cloneUrls = []; for (const deployKey of deployKeys) { cloneUrls.push(deployKey.cloneUrl); } const referencedCloneUrls = []; for (const definition of definitions) { const definitionRecipe = this.definitionRecipeMapper.map( definition.recipeAsYaml, ); for (const source of definitionRecipe.sources) { const cloneUrl = (source as SourceTypeInterface).cloneUrl; if ((source as SourceTypeInterface).useDeployKey) { referencedCloneUrls.push(cloneUrl); } } } const unreferencedCloneUrls = _.difference( cloneUrls, referencedCloneUrls, ); const removePromises = []; for (const unreferencedCloneUrl of unreferencedCloneUrls) { removePromises.push( this.deployKeyRepository.remove(unreferencedCloneUrl), ); unlinkSync( this.deployKeyHelper.getIdentityFileAbsoluteGuestPath( unreferencedCloneUrl, ), ); } await Promise.all(removePromises); return { removed: true }; } @Mutation('removeDeployKey') async removeOne( @Args() removeDeployKeyInput: RemoveDeployKeyInputTypeInterface, ): Promise<object> { await this.deployKeyRepository.remove(removeDeployKeyInput.cloneUrl); unlinkSync( this.deployKeyHelper.getIdentityFileAbsoluteGuestPath( removeDeployKeyInput.cloneUrl, ), ); return { removed: true }; } // TODO Move somewhere else. protected applyFilterArgumentToCriteria( criteria: any, args: ResolverDeployKeyFilterArgumentsInterface, ): any { return criteria; } }
#!/bin/bash cd /home/factory/Avalon-extras/scripts/factory make isedir=/home/factory/Xilinx/14.6/ISE_DS reflash MM_PLATFORM=$1 [ -z "$BAR" ] && BAR="+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n$1 Burn Complete\n+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++" echo -e $BAR
<filename>TestDoubleMatrix.java<gh_stars>0 import java.io.IOException; import java.io.BufferedWriter; import java.nio.file.Paths; import java.nio.file.Files; // Usage: java -ea TestDoubleMatrix public class TestDoubleMatrix { public static void writeToFile(String filename, String str)throws IOException { try(BufferedWriter file = Files.newBufferedWriter(Paths.get(filename))) { file.write(str, 0, str.length()); file.flush(); } catch(IOException ioe) { throw ioe; } } public static void main(String[] args) { { // 引数の配列が不正な場合を確認 try { DoubleMatrix a = new DoubleMatrix(new double[][]{{0}, {1, 2}}); } catch(IllegalArgumentException iae) { System.err.println(iae); } try { DoubleMatrix a = new DoubleMatrix(new double[][]{{0, 1}, {1, 2}, {1, 2, 3}, {4, 5}}); } catch(IllegalArgumentException iae) { System.err.println(iae); } } // end of block { // rows, columns, sizeが正しく設定されているかを確認 DoubleMatrix a = new DoubleMatrix(new double[][]{{0, 0, 0}}); assert a.rows == 1; assert a.columns == 3; assert a.size == 3; DoubleMatrix b = new DoubleMatrix( new double[][]{ {0}, {0}, {0}, {0}, } ); assert b.rows == 4; assert b.columns == 1; assert b.size == 4; DoubleMatrix c = new DoubleMatrix( new double[][]{ {0, 1, 5}, {0, 2, 4}, {0, 3, 3}, {0, 4, 2}, {0, 5, 1}, } ); assert c.rows == 5; assert c.columns == 3; assert c.size == 15; } // end of block { // get(), set()の動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, } ); assert a.get(1, 1) == 4; assert a.get(2, 2) == 8; a.set(1, 1, -90); a.set(2, 2, 256); assert a.get(1, 1) == -90; assert a.get(2, 2) == 256; } // end of block { // 行列の元となった配列の値の変更の影響を受けないことを確認 double[][] val = { {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, }; DoubleMatrix a = new DoubleMatrix(val); for(int i = 0; i < val.length; i++) { for(int j = 0; j < val[i].length; j++) { val[i][j] = 42; } } for(int i = 0; i < val.length; i++) { for(int j = 0; j < val[i].length; j++) { assert a.get(i, j) == a.rows * i + j; } } } // end of block { // isEqual() の動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}, } ); DoubleMatrix b = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, } ); DoubleMatrix c = new DoubleMatrix( new double[][]{ {0, 1}, {3, 4}, {6, 7}, {9, 10}, } ); DoubleMatrix d = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, 11}, } ); DoubleMatrix e = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, {9, 10, -11}, } ); // 実引数がnullなら例外 try { a.isEqual(null); } catch(NullPointerException npe) { System.err.println("a.isEqual(null) => " + npe); } assert a.isEqual(a); // 行数が異なる場合 assert !a.isEqual(b); assert !b.isEqual(a); // 列数が異なる場合 assert !a.isEqual(c); assert !c.isEqual(a); // 同じ場合 assert a.isEqual(d); assert d.isEqual(a); // 型は等しいが,成分の値が一部異っている場合 assert !a.isEqual(e); assert !e.isEqual(a); } // end of block if(false) { // toString() の呼び出し DoubleMatrix a = new DoubleMatrix(new double[][]{{0, 1, 2}}); System.out.println(a); System.out.println(a.toString(",")); DoubleMatrix b = new DoubleMatrix( new double[][]{ {0}, {1}, {2}, } ); System.out.println(b); System.out.println(b.toString(";")); DoubleMatrix c = new DoubleMatrix( new double[][]{ {0, 3, 6, 9}, {1, 4, 7, 10}, {2, 5, 8, 11}, } ); System.out.print(c); System.out.print(c.toString(" | ")); } // end of block { // add() の動作確認 DoubleMatrix a = new DoubleMatrix(new double[][]{{1, 2, 3}}); DoubleMatrix b = new DoubleMatrix( new double[][]{ {1, 4, 5}, {2, 5, 6}, {3, 6, 7}, } ); DoubleMatrix c = new DoubleMatrix( new double[][]{ {1, 4}, {2, 5}, {3, 6}, } ); DoubleMatrix d = new DoubleMatrix( new double[][]{ {1, 4}, {2, 5}, {3, 6}, } ); DoubleMatrix e = new DoubleMatrix( new double[][]{ {-1, 4}, {-2, 5}, {-3, 6}, } ); DoubleMatrix f = new DoubleMatrix( new double[][]{ {0, 8}, {0, 10}, {0, 12}, } ); // 実引数がnullなら例外 try { a.add(null); } catch(NullPointerException npe) { System.err.println("a.add(null) => " + npe); } // 行数が異なる場合 assert a.add(b) == null; assert b.add(a) == null; // 列数が異なる場合 assert b.add(c) == null; assert c.add(b) == null; // 加算結果が正しいかどうか assert d.add(e).isEqual(f); assert e.add(d).isEqual(f); } // end of block { // sub() の動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {1, 4, 7, 10}, {2, 5, 8, 11}, {3, 6, 9, 12}, } ); DoubleMatrix b = new DoubleMatrix( new double[][]{ { 1, 1, 1, 1}, {-1, -1, -1, -1}, { 2, 2, 2, 2}, } ); DoubleMatrix c = new DoubleMatrix( new double[][]{ {0, 3, 6, 9}, {3, 6, 9, 12}, {1, 4, 7, 10}, } ); assert a.sub(b).isEqual(c); } // end of block { // 行列の定数倍の動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {-9, -3, 6}, { 4, 5, 6}, { 1, 2, 3}, } ); DoubleMatrix b = new DoubleMatrix( new double[][]{ {-18, -6, 12}, { 8, 10, 12}, { 2, 4, 6}, } ); DoubleMatrix z = new DoubleMatrix( new double[][]{ {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, } ); assert a.mul(2).isEqual(b); assert b.mul(0.5).isEqual(a); // 0A = O assert a.mul(0).isEqual(z); // 1A = A assert a.mul(1).isEqual(a); // kO = O assert z.mul(12).isEqual(z); } // end of block { // 行列同士の掛け算の動作確認 DoubleMatrix a = new DoubleMatrix(new double[][]{{1, 2, 3, 4, 5}}); DoubleMatrix b = new DoubleMatrix( new double[][]{ {1}, {1}, {1}, {1}, {1}, } ); DoubleMatrix c = new DoubleMatrix( new double[][]{ {1}, {2}, {3}, {4}, {5}, } ); DoubleMatrix d = new DoubleMatrix(new double[][]{{1, 1, 1, 1, 1}}); DoubleMatrix e = new DoubleMatrix(new double[][]{{15}}); DoubleMatrix f = new DoubleMatrix( new double[][]{ {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5}, } ); DoubleMatrix g = new DoubleMatrix( new double[][]{ {1, 1, 1, 1, 1}, {2, 2, 2, 2, 2}, {3, 3, 3, 3, 3}, {4, 4, 4, 4, 4}, {5, 5, 5, 5, 5}, } ); assert a.mul(b).isEqual(e); assert d.mul(c).isEqual(e); assert b.mul(a).isEqual(f); assert c.mul(d).isEqual(g); } // end of block { // createDiagonalMatrix() の動作確認 DoubleMatrix a = DoubleMatrix.createDiagonalMatrix(1, 2, 3); DoubleMatrix b = new DoubleMatrix( new double[][]{ {1, 0, 0}, {0, 2, 0}, {0, 0, 3}, } ); DoubleMatrix c = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, } ); DoubleMatrix d = DoubleMatrix.createDiagonalMatrix(2, 3, 4); DoubleMatrix e = new DoubleMatrix( new double[][]{ { 0, 3, 8}, { 6, 12, 20}, {12, 21, 32}, } ); DoubleMatrix f = DoubleMatrix.createDiagonalMatrix(2, 1); DoubleMatrix g = new DoubleMatrix( new double[][]{ {1, 2, 3}, {4, 5, 6}, } ); DoubleMatrix h = new DoubleMatrix( new double[][]{ {2, 4, 6}, {4, 5, 6}, } ); DoubleMatrix z = new DoubleMatrix( new double[][]{ {0, 0, 0}, {0, 0, 0}, {0, 0, 0}, } ); assert a.isEqual(b); assert c.mul(d).isEqual(e); assert f.mul(g).isEqual(h); assert z.isEqual(DoubleMatrix.createDiagonalMatrix(new double[]{0, 0, 0})); assert z.isEqual(DoubleMatrix.createDiagonalMatrix(0, 0, 0)); } // end of block { // createIdentityMatrix() の動作確認 DoubleMatrix a = DoubleMatrix.createIdentityMatrix(5); DoubleMatrix b = new DoubleMatrix( new double[][]{ {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 1}, } ); assert a.isEqual(b); } // end of block { // 行列の転置の動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {1, 2, 3}, {4, 5, 6}, } ); DoubleMatrix b = new DoubleMatrix( new double[][]{ {1, 4}, {2, 5}, {3, 6}, } ); DoubleMatrix c = new DoubleMatrix(new double[][]{{1, 2, 3}}); DoubleMatrix d = new DoubleMatrix( new double[][]{ {1}, {2}, {3}, } ); DoubleMatrix e = DoubleMatrix.createDiagonalMatrix(1, 2, 3); assert a.trs().isEqual(b); assert a.trs().trs().isEqual(a); assert c.trs().isEqual(d); assert e.trs().isEqual(e); } // end of block { // isSymmetricMatrix() の動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {1, 7, 3}, {7, 4, -5}, {3, -5, 6}, } ); assert DoubleMatrix.isSymmetricMatrix(a); a.set(0, 1, 1); assert !DoubleMatrix.isSymmetricMatrix(a); } // end of block { // 行列同士の型の比較の動作確認 DoubleMatrix a = new DoubleMatrix(new double[][]{{1, 2, 3}}); DoubleMatrix b = new DoubleMatrix(new double[][]{{0, 0, 0}}); DoubleMatrix c = new DoubleMatrix( new double[][]{ {1, 2, 3}, {1, 2, 3}, {1, 2, 3}, } ); DoubleMatrix d = new DoubleMatrix( new double[][]{ {1, 2, 3}, {1, 2, 3}, {1, 0, 3}, } ); assert !a.isEqual(b); assert !b.isEqual(a); assert a.isTypeEqual(b); assert b.isTypeEqual(a); assert !c.isEqual(d); assert !d.isEqual(c); assert c.isTypeEqual(d); assert d.isTypeEqual(c); } // end of block { // 行と列の交換の動作確認 double[][] val = { {1, 1, 1, 1}, {2, 2, 2, 2}, {3, 3, 3, 3}, {4, 4, 4, 4}, {5, 5, 5, 5}, }; DoubleMatrix a = new DoubleMatrix(val); DoubleMatrix b = new DoubleMatrix(val); DoubleMatrix c = new DoubleMatrix( new double[][]{ {0, 0, 0, 1, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {1, 0, 0, 0, 0}, {0, 0, 0, 0, 1}, } ); double[][] val2 = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}, {3, 2, 1}, }; DoubleMatrix d = new DoubleMatrix(val2); DoubleMatrix e = new DoubleMatrix(val2); DoubleMatrix f = new DoubleMatrix( new double[][]{ {0, 0, 1}, {0, 1, 0}, {1, 0, 0}, } ); try { a.swapRows(-1, -1); } catch(ArrayIndexOutOfBoundsException aioobe) { System.out.println("a.swapRows(-1, -1) => " + aioobe); } try { a.swapRows(100, 100); } catch(ArrayIndexOutOfBoundsException aioobe) { System.out.println("a.swapRows(100, 100) => " + aioobe); } try { a.swapColumns(-1, -1); } catch(ArrayIndexOutOfBoundsException aioobe) { System.out.println("a.swapColumns(-1, -1) => " + aioobe); } try { a.swapColumns(100, 100); } catch(ArrayIndexOutOfBoundsException aioobe) { System.out.println("a.swapColumns(100, 100) => " + aioobe); } assert a.isEqual(b); assert b.isEqual(a); a.swapRows(0, 3); assert a.isEqual(c.mul(b)); assert d.isEqual(e); assert e.isEqual(d); d.swapColumns(0, 2); assert d.isEqual(e.mul(f)); } // end of block { // 自分自身に対する加算と減算の動作確認 double[][] val = { {1, 2, 3}, {4, 5, 6}, }; DoubleMatrix a = new DoubleMatrix(val); DoubleMatrix b = new DoubleMatrix(val); DoubleMatrix c = new DoubleMatrix( new double[][]{ {2, 2, 2}, {2, 2, 2}, } ); DoubleMatrix d = new DoubleMatrix( new double[][]{ {3, 4, 5}, {6, 7, 8}, } ); assert !a.isEqual(d); a.addeq(c); assert a.isEqual(d); a.subeq(c); assert !a.isEqual(d); assert a.isEqual(b); } // end of block { // 自分自身の定数倍の動作確認 DoubleMatrix a = new DoubleMatrix(new double[][]{{1, 2, 3}}); DoubleMatrix b = new DoubleMatrix(new double[][]{{12, 24, 36}}); assert !a.isEqual(b); a.muleq(12); assert a.isEqual(b); } // end of block { // ファイル入出力の動作確認 DoubleMatrix a = new DoubleMatrix(new double[][]{{1, 2, 3}}); DoubleMatrix b = new DoubleMatrix( new double[][]{ {-1}, {-2}, {-3}, } ); DoubleMatrix c = new DoubleMatrix( new double[][]{ {-1, -4}, {-2, -5}, {-3, -6}, } ); try { DoubleMatrix.writeToFile(a, "tmp1.dat"); DoubleMatrix.writeToFile(b, "tmp2.dat"); DoubleMatrix.writeToFile(c, "tmp3.dat", ","); } catch(IOException ioe) { ioe.printStackTrace(); System.exit(1); } DoubleMatrix d, e, f; d = e = f = null; try { d = DoubleMatrix.readFromFile("tmp1.dat"); e = DoubleMatrix.readFromFile("tmp2.dat"); f = DoubleMatrix.readFromFile("tmp3.dat", ","); } catch(IOException ioe) { ioe.printStackTrace(); System.exit(1); } assert a.isEqual(d); assert b.isEqual(e); assert c.isEqual(f); } // end of block { // DoubleMatrix(int, int), DoubleMatrix(int, int, double...) の動作確認 DoubleMatrix a = new DoubleMatrix(5, 1); DoubleMatrix b = new DoubleMatrix( new double[][]{ {0}, {0}, {0}, {0}, {0}, } ); DoubleMatrix c = new DoubleMatrix(4, 5); DoubleMatrix d = new DoubleMatrix( new double[][]{ {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, {0, 0, 0, 0, 0}, } ); DoubleMatrix e = new DoubleMatrix(2, 2, 1, 2, 3, 4); DoubleMatrix f = new DoubleMatrix( new double[][]{ {1, 2}, {3, 4}, } ); try { DoubleMatrix g = new DoubleMatrix(2, 2, 1, 2, 3); } catch(IllegalArgumentException iae) { System.out.println("new DoubleMatrix(2, 2, 1, 2, 3) => " + iae); } try { DoubleMatrix g = new DoubleMatrix(2, 2, 1, 2, 3, 4, 5); } catch(IllegalArgumentException iae) { System.out.println("new DoubleMatrix(2, 2, 1, 2, 3, 4, 5) => " + iae); } assert a.isEqual(b); assert c.isEqual(d); assert e.isEqual(f); } // end of block { // createRowVector(), createColumnVector() の動作確認 DoubleMatrix a = DoubleMatrix.createRowVector(-3, -2, -1, 0); DoubleMatrix b = new DoubleMatrix(new double[][]{{-3, -2, -1, 0}}); DoubleMatrix c = DoubleMatrix.createColumnVector(4, 5, 6, -9); DoubleMatrix d = new DoubleMatrix( new double[][]{ {4}, {5}, {6}, {-9}, } ); assert a.isEqual(b); assert c.isEqual(d); } // end of block { // 行列の水平方向,垂直方向への結合の動作確認 DoubleMatrix a = DoubleMatrix.createColumnVector(-1, 2, 3); DoubleMatrix b = DoubleMatrix.createColumnVector(1, -2, 3); DoubleMatrix c = DoubleMatrix.createColumnVector(1, 2, -3); DoubleMatrix d = new DoubleMatrix( new double[][]{ {-1, 1, 1}, {2, -2, 2}, {3, 3, -3}, } ); DoubleMatrix e = new DoubleMatrix( new double[][]{ {1, 2, 3}, {4, 5, 6}, } ); DoubleMatrix f = new DoubleMatrix( new double[][]{ {1, 2, 3, 1, 2, 3}, {4, 5, 6, 4, 5, 6}, } ); DoubleMatrix g = new DoubleMatrix( new double[][]{ {1, 2, 3, 1, 2, 3}, {4, 5, 6, 4, 5, 6}, {1, 2, 3, 1, 2, 3}, {4, 5, 6, 4, 5, 6}, {1, 2, 3, 1, 2, 3}, {4, 5, 6, 4, 5, 6}, } ); try { DoubleMatrix h = DoubleMatrix.combineHorizontally(f, g); } catch(IllegalArgumentException iae) { System.err.println("DoubleMatrix.combineHorizontally(f, g) => " + iae); } try { DoubleMatrix h = DoubleMatrix.combineVertically(e, f, e); } catch(IllegalArgumentException iae) { System.err.println("DoubleMatrix.combineVertically(e, f, e) => " + iae); } assert d.isEqual(DoubleMatrix.combineHorizontally(a, b, c)); assert d.trs().isEqual(DoubleMatrix.combineVertically(a.trs(), b.trs(), c.trs())); assert f.isEqual(DoubleMatrix.combineHorizontally(e, e)); assert g.isEqual(DoubleMatrix.combineVertically(f, f, f)); } // end of block { // ファイルの形式に誤りがあった場合の例外を確認 try { writeToFile("tmpe1.dat", "2 3 4\n6 u 9\n"); DoubleMatrix a = DoubleMatrix.readFromFile("tmpe1.dat"); } catch(IOException ioe) { System.err.print("DoubleMatrix.readFromFile(\"tmpe1.dat\") => "); ioe.printStackTrace(); } } // end of block { // コピーコンストラクタの動作確認 DoubleMatrix a = new DoubleMatrix( new double[][]{ {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, } ); DoubleMatrix b = new DoubleMatrix(a); // aの内容でbを作成 assert a.isEqual(b); a.set(1, 1, -9); assert !a.isEqual(b); } // end of block System.err.println(); System.err.println("テスト完了"); } // end of main() } // end of class TestDoubleMatrix
use std::io::{Read, Write}; impl EntityBig { fn serialize(&self) -> Vec<u8> { // Serialize the fields of EntityBig into a byte array // Example: let mut buffer = Vec::with_capacity(size_of_entity); // Write the fields into the buffer using the `write` method from the `Write` trait // Return the buffer unimplemented!() } fn deserialize(data: &[u8]) -> Result<EntityBig, std::io::Error> { // Create a cursor from the input data using `std::io::Cursor` // Read the fields from the cursor using the `read` method from the `Read` trait // Return the deserialized EntityBig instance or an error if deserialization fails unimplemented!() } }
import numpy as np import cv2 from sklearn.svm import SVC from sklearn.model_selection import train_test_split # load the sequence of frames from the video frames = np.load('video_frames.npy') # extract the features from each frame features = extractFeatures(frames) # split the data into training and testing sets X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=0) # train the SVM model clf = SVC() clf.fit(X_train, y_train) # make predictions on the test set predictions = clf.predict(X_test) # evaluate the model accuracy = accuracy_score(y_test, predictions)
#!/bin/bash echo "Starting bob agent on port: 8090" dlv debug ../cmd/elesto-agent/main.go -- start \ --api-host localhost:8090 \ --inbound-host ws@localhost:8092 \ --inbound-host-external ws@ws://localhost:8092 \ --outbound-transport ws \ --webhook-url http://localhost:7082/wh/bob \ --auto-accept true \ --transport-return-route all \ --agent-default-label BobAgent \ --database-type mem \ --database-prefix bob \ --log-level DEBUG \ --http-resolver-url cosmos@https://resolver-driver.cosmos-cash.app.beta.starport.cloud/identifier/aries/
import React from 'react'; export default () => ( <svg version="1.1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 140"> <rect x="10" y="43.91" fill="#43BDD7" width="120" height="52.17" /> <rect x="10" y="70" fill="#39A1B7" width="120" height="26.09" /> <polygon fill="#43BDD7" points="10,96.09 0,100 0,40 10,43.91 " /> <polygon fill="#39A1B7" points="10,96.09 0,100 0,70 10,70 " /> <polygon fill="#43BDD7" points="130,96.09 140,100 140,40 130,43.91 " /> <polygon fill="#39A1B7" points="130,96.09 140,100 140,70 130,70 " /> <rect x="10" y="43.91" fill="#FFCD00" width="10" height="52.17" /> <rect x="10" y="70" fill="#EDAB07" width="10" height="26.09" /> <rect x="120" y="43.91" fill="#FFCD00" width="10" height="52.17" /> <rect x="120" y="70" fill="#EDAB07" width="10" height="26.09" /> </svg> );
python transformers/examples/language-modeling/run_language_modeling.py --model_name_or_path train-outputs/1024+0+512-SS-N/7-model --tokenizer_name model-configs/1536-config --eval_data_file ../data/wikitext-103-raw/wiki.valid.raw --output_dir eval-outputs/1024+0+512-SS-N/7-1024+0+512-SWS-first-256 --do_eval --per_device_eval_batch_size 1 --dataloader_drop_last --augmented --augmentation_function shuffle_within_sentences_first_two_thirds_sixth --eval_function penultimate_sixth_eval
import java.util.HashMap; import java.util.Map; public class ValueFactoryMappingDefaultsForGroup extends ValueFactoryMappingDefault { private final Group groupSelected; private Map<String, Object> defaultValues; ValueFactoryMappingDefaultsForGroup(String mappingResource, Group groupSelector) { super(mappingResource); this.groupSelected = groupSelector; this.defaultValues = new HashMap<>(); // Load default values for the specified group from the mapping resource loadDefaultValues(); } // Method to load default values for the specified group from the mapping resource private void loadDefaultValues() { // Implement logic to load default values for the specified group from the mapping resource // and populate the defaultValues map } // Method to retrieve the default value for a specific key public Object getDefaultValue(String key) { return defaultValues.get(key); } // Method to update the default value for a specific key public void updateDefaultValue(String key, Object value) { defaultValues.put(key, value); // Implement logic to update the default value for the specified key in the mapping resource } // Additional methods for managing default values as needed }
({ success:function(){ var is=(function(){ return { whiteSpace:(function() { var cs=[' ','\r','\n','\t']; return function(c) { return has(cs,c) }; })() }; })(); var parse_until=function(txt,flag,end){ var start=flag; var nobreak=true; while(flag<txt.length && nobreak){ var c=txt[flag]; if (c==end) { nobreak=false; }else{ if (c=='\\') { flag++; } flag++; } } return flag; }; return function(txt){ var flag=0; while(flag<txt.length){ var c=txt[flag]; if (is.whiteSpace(c)) { flag++; }else{ if (c=='"') { var index=flag; flag++; var end=parse_until(txt,flag,'"'); if (end<txt.length) { var str=txt.substr(index,end+1-index); flag=index+str.length; tokens=lib.s.extend({type:"string",begin:index,value:str},tokens); }else{ } }else if(c=='`'){ }else if(c=='('){ }else if(c==')'){ }else{ } } } }; } })
// Copyright © 2019 <NAME> – This file is part of GoatCounter and // published under the terms of a slightly modified EUPL v1.2 license, which can // be found in the LICENSE file or at https://license.goatcounter.com package goatcounter import ( "context" "database/sql/driver" "fmt" "sort" "strconv" "strings" "unicode" "zgo.at/json" "zgo.at/tz" "zgo.at/z18n" "zgo.at/zstd/zint" "zgo.at/zstd/zjson" "zgo.at/zvalidate" ) // Settings.Collect values (bitmask) // // DO NOT change the values of these constants; they're stored in the database. // // Note: also update CollectFlags() method below. // // Nothing is 1 and 0 is "unset". This is so we can distinguish between "this // field was never sent in the form" vs. "user unchecked all boxes". const ( CollectNothing zint.Bitflag16 = 1 << iota CollectReferrer // 2 CollectUserAgent // 4 CollectScreenSize // 8 CollectLocation // 16 CollectLocationRegion // 32 CollectLanguage // 64 CollectSession // 128 ) // UserSettings.EmailReport values. const ( EmailReportNever = iota // Email once after 2 weeks; for new sites. EmailReportDaily EmailReportWeekly EmailReportBiWeekly EmailReportMonthly ) var EmailReports = []int{EmailReportNever, EmailReportDaily, EmailReportWeekly, EmailReportBiWeekly, EmailReportMonthly} type ( // SiteSettings contains all the user-configurable settings for a site, with // the exception of the domain and billing settings. // // This is stored as JSON in the database. SiteSettings struct { Public string `json:"public"` Secret string `json:"secret"` AllowCounter bool `json:"allow_counter"` AllowBosmang bool `json:"allow_bosmang"` DataRetention int `json:"data_retention"` Campaigns Strings `json:"campaigns"` IgnoreIPs Strings `json:"ignore_ips"` Collect zint.Bitflag16 `json:"collect"` CollectRegions Strings `json:"collect_regions"` } // UserSettings are all user preferences. UserSettings struct { TwentyFourHours bool `json:"twenty_four_hours"` SundayStartsWeek bool `json:"sunday_starts_week"` Language string `json:"language"` DateFormat string `json:"date_format"` NumberFormat rune `json:"number_format"` Timezone *tz.Zone `json:"timezone"` Widgets Widgets `json:"widgets"` Views Views `json:"views"` EmailReports zint.Int `json:"email_reports"` } // Widgets is a list of widgets to be printed, in order. Widgets []Widget Widget map[string]interface{} WidgetSettings map[string]WidgetSetting WidgetSetting struct { Type string Hidden bool Label string Help string Options [][2]string OptionsFunc func(context.Context) [][2]string Validate func(*zvalidate.Validator, interface{}) Value interface{} } // Views for the dashboard; these settings apply to all widget and are // configurable in the yellow box at the top. Views []View View struct { Name string `json:"name"` Filter string `json:"filter"` Daily bool `json:"daily"` Period string `json:"period"` // "week", "week-cur", or n days: "8" } ) // Default widgets for new sites. // // This *must* return a list of all configurable widgets; even if it's off by // default. // // As a function to ensure a global map isn't accidentally modified. func defaultWidgets(ctx context.Context) Widgets { s := defaultWidgetSettings(ctx) w := Widgets{} for _, n := range []string{"pages", "totalpages", "toprefs", "browsers", "systems", "sizes", "locations", "languages"} { w = append(w, map[string]interface{}{"n": n, "s": s[n].getMap()}) } return w } // List of all settings for widgets with some data. func defaultWidgetSettings(ctx context.Context) map[string]WidgetSettings { return map[string]WidgetSettings{ "pages": map[string]WidgetSetting{ "limit_pages": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/page-size|Page size"), Help: z18n.T(ctx, "widget-setting/help/page-size|Number of pages to load"), Value: float64(10), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit_pages", int64(val.(float64)), 1, 100) }, }, "limit_refs": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/ref-page-size|Referrers page size"), Help: z18n.T(ctx, "widget-setting/help/ref-page-size|Number of referrers to load when clicking on a path"), Value: float64(10), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit_pages", int64(val.(float64)), 1, 100) }, }, "style": WidgetSetting{ Type: "select", Label: z18n.T(ctx, "widget-setting/label/chart-style|Chart style"), Help: z18n.T(ctx, "widget-setting/help/chart-style|How to draw the charts"), Value: "line", Options: [][2]string{ [2]string{"line", z18n.T(ctx, "widget-settings/line-chart|Line chart")}, [2]string{"bar", z18n.T(ctx, "widget-settings/bar-chart|Bar chart")}, [2]string{"text", z18n.T(ctx, "widget-settings/text-chart|Text table")}, }, Validate: func(v *zvalidate.Validator, val interface{}) { v.Include("style", val.(string), []string{"line", "bar", "text"}) }, }, }, "totalpages": map[string]WidgetSetting{ "align": WidgetSetting{ Type: "checkbox", Label: z18n.T(ctx, "widget-setting/label/align|Align with pages"), Help: z18n.T(ctx, "widget-setting/help/align|Add margin to the left so it aligns with pages charts"), Value: false, }, "no-events": WidgetSetting{ Type: "checkbox", Label: z18n.T(ctx, "widget-setting/label/no-events|Exclude events"), Help: z18n.T(ctx, "widget-setting/help/no-events|Don't include events in the Totals overview"), Value: false, }, "style": WidgetSetting{ Type: "select", Label: z18n.T(ctx, "widget-setting/label/chart-style|Chart style"), Help: z18n.T(ctx, "widget-setting/help/chart-style|How to draw the charts"), Value: "line", Options: [][2]string{ [2]string{"line", z18n.T(ctx, "widget-settings/line-chart|Line chart")}, [2]string{"bar", z18n.T(ctx, "widget-settings/bar-chart|Bar chart")}, }, Validate: func(v *zvalidate.Validator, val interface{}) { v.Include("style", val.(string), []string{"line", "bar"}) }, }, }, "toprefs": map[string]WidgetSetting{ "limit": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/page-size|Page size"), Help: z18n.T(ctx, "widget-setting/help/page-size|Number of pages to load"), Value: float64(6), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit", int64(val.(float64)), 1, 20) }, }, "key": WidgetSetting{Hidden: true}, }, "browsers": map[string]WidgetSetting{ "limit": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/page-size|Page size"), Help: z18n.T(ctx, "widget-setting/help/page-size|Number of pages to load"), Value: float64(6), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit", int64(val.(float64)), 1, 20) }, }, "key": WidgetSetting{Hidden: true}, }, "systems": map[string]WidgetSetting{ "limit": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/page-size|Page size"), Help: z18n.T(ctx, "widget-setting/help/page-size|Number of pages to load"), Value: float64(6), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit", int64(val.(float64)), 1, 20) }, }, "key": WidgetSetting{Hidden: true}, }, "sizes": map[string]WidgetSetting{ "key": WidgetSetting{Hidden: true}, }, "locations": map[string]WidgetSetting{ "limit": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/page-size|Page size"), Help: z18n.T(ctx, "widget-setting/help/page-size|Number of pages to load"), Value: float64(6), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit", int64(val.(float64)), 1, 20) }, }, "key": WidgetSetting{ Type: "select", Label: z18n.T(ctx, "widget-setting/label/regions|Show regions"), Help: z18n.T(ctx, "widget-setting/help/regions|Show regions for this country instead of a country list"), Value: "", OptionsFunc: func(ctx context.Context) [][2]string { var l Locations err := l.ListCountries(ctx) if err != nil { panic(err) } countries := make([][2]string, 0, len(l)+1) countries = append(countries, [2]string{"", ""}) for _, ll := range l { countries = append(countries, [2]string{ll.Country, ll.CountryName}) } return countries }, }, }, "languages": map[string]WidgetSetting{ "limit": WidgetSetting{ Type: "number", Label: z18n.T(ctx, "widget-setting/label/page-size|Page size"), Help: z18n.T(ctx, "widget-setting/help/page-size|Number of pages to load"), Value: float64(6), Validate: func(v *zvalidate.Validator, val interface{}) { v.Range("limit", int64(val.(float64)), 1, 20) }, }, }, } } func (ss SiteSettings) String() string { return string(zjson.MustMarshal(ss)) } func (ss SiteSettings) Value() (driver.Value, error) { return json.Marshal(ss) } func (ss *SiteSettings) Scan(v interface{}) error { switch vv := v.(type) { case []byte: return json.Unmarshal(vv, ss) case string: return json.Unmarshal([]byte(vv), ss) default: return fmt.Errorf("SiteSettings.Scan: unsupported type: %T", v) } } func (ss UserSettings) String() string { return string(zjson.MustMarshal(ss)) } func (ss UserSettings) Value() (driver.Value, error) { return json.Marshal(ss) } func (ss *UserSettings) Scan(v interface{}) error { switch vv := v.(type) { case []byte: return json.Unmarshal(vv, ss) case string: return json.Unmarshal([]byte(vv), ss) default: return fmt.Errorf("UserSettings.Scan: unsupported type: %T", v) } } func (ss *SiteSettings) Defaults(ctx context.Context) { if ss.Campaigns == nil { ss.Campaigns = []string{"utm_campaign", "utm_source", "ref"} } if ss.Public == "" { ss.Public = "private" } if ss.Collect == 0 { ss.Collect = CollectReferrer | CollectUserAgent | CollectScreenSize | CollectLocation | CollectLocationRegion | CollectSession } if ss.Collect.Has(CollectLocationRegion) { // Collecting region without country makes no sense. ss.Collect |= CollectLocation } if ss.CollectRegions == nil { ss.CollectRegions = []string{"US", "RU", "CH"} } } func (ss *SiteSettings) Validate(ctx context.Context) error { v := NewValidate(ctx) v.Include("public", ss.Public, []string{"private", "secret", "public"}) if ss.Public == "secret" { v.Len("secret", ss.Secret, 8, 40) v.Contains("secret", ss.Secret, []*unicode.RangeTable{zvalidate.AlphaNumeric}, nil) } if ss.DataRetention > 0 { v.Range("data_retention", int64(ss.DataRetention), 31, 0) } if len(ss.IgnoreIPs) > 0 { for _, ip := range ss.IgnoreIPs { v.IP("ignore_ips", ip) } } return v.ErrorOrNil() } func (ss SiteSettings) CanView(token string) bool { return ss.Public == "public" || (ss.Public == "secret" && token == ss.Secret) } func (ss SiteSettings) IsPublic() bool { return ss.Public == "public" } type CollectFlag struct { Label, Help string Flag zint.Bitflag16 } // CollectFlags returns a list of all flags we know for the Collect settings. func (ss SiteSettings) CollectFlags(ctx context.Context) []CollectFlag { return []CollectFlag{ { Label: z18n.T(ctx, "data-collect/label/sessions|Sessions"), Help: z18n.T(ctx, "data-collect/help/sessions|Track unique visitors for up to 8 hours; if you disable this then someone pressing e.g. F5 to reload the page will just show as 2 pageviews instead of 1"), Flag: CollectSession, }, { Label: z18n.T(ctx, "data-collect/label/referrer|Referrer"), Help: z18n.T(ctx, "data-collect/help/referrer|Referer header and campaign parameters."), Flag: CollectReferrer, }, { Label: z18n.T(ctx, "data-collect/label/user-agent|User-Agent"), Help: z18n.T(ctx, "data-collect/help/user-agent|User-Agent header to get the browser and system name and version."), Flag: CollectUserAgent, }, { Label: z18n.T(ctx, "data-collect/label/size|Size"), Help: z18n.T(ctx, "data-collect/help/size|Screen size."), Flag: CollectScreenSize, }, { Label: z18n.T(ctx, "data-collect/label/country|Country"), Help: z18n.T(ctx, "data-collect/help/country|Country name, for example Belgium, Indonesia, etc."), Flag: CollectLocation, }, { Label: z18n.T(ctx, "data-collect/label/region|Region"), Help: z18n.T(ctx, "data-collect/help/region|Region, for example Texas, Bali, etc. The details for this differ per country."), Flag: CollectLocationRegion, }, { Label: z18n.T(ctx, "data-collect/label/language|Language"), Help: z18n.T(ctx, "data-collect/help/language|Supported languages from Accept-Language"), Flag: CollectLanguage, }, } } func (s *WidgetSettings) Set(k string, v interface{}) { ss := *s m := ss[k] m.Value = v ss[k] = m } func (s WidgetSettings) getMap() map[string]interface{} { m := make(map[string]interface{}) for k, v := range s { m[k] = v.Value } return m } // HasSettings reports if there are any non-hidden settings. func (s WidgetSettings) HasSettings() bool { for _, ss := range s { if !ss.Hidden { return true } } return false } // Display all values that are different from the default. func (s WidgetSettings) Display(ctx context.Context, wname string) string { defaults := defaultWidgetSettings(ctx)[wname] order := make([]string, 0, len(s)) for k := range s { order = append(order, k) } sort.Strings(order) str := make([]string, 0, len(s)) for _, k := range order { ss := s[k] if ss.Hidden { continue } if ss.Value == defaults[k].Value { continue } l := strings.ToLower(ss.Label) if ss.Type == "checkbox" { str = append(str, l) } else { str = append(str, fmt.Sprintf("%s: %v", l, ss.Value)) } } return strings.Join(str, ", ") } func NewWidget(name string) Widget { return Widget{"n": name} } // SetSettings set the setting "setting" for widget "widget" to "value". // // The value is converted to the correct type for this setting. func (w Widget) SetSetting(ctx context.Context, widget, setting, value string) error { defW, ok := defaultWidgetSettings(ctx)[widget] if !ok { return fmt.Errorf("Widget.SetSetting: no such widget %q", widget) } def, ok := defW[setting] if !ok { return fmt.Errorf("Widget.SetSetting: no such setting %q for widget %q", setting, widget) } s, ok := w["s"].(map[string]interface{}) if !ok { s = make(map[string]interface{}) } switch def.Type { case "number": n, err := strconv.Atoi(value) if err != nil { return fmt.Errorf("Widget.SetSetting: setting %q for widget %q: %w", setting, widget, err) } s[setting] = float64(n) case "checkbox": s[setting] = value == "on" case "text", "select": s[setting] = value } w["s"] = s return nil } // Name gets this widget's name. func (w Widget) Name() string { return w["n"].(string) } func (w Widget) GetSetting(ctx context.Context, n string) interface{} { for k, v := range w.GetSettings(ctx) { if k == n { return v.Value } } return nil } // GetSettings gets all setting for this widget. func (w Widget) GetSettings(ctx context.Context) WidgetSettings { def := defaultWidgetSettings(ctx)[w.Name()] s, ok := w["s"] if ok { for k, v := range s.(map[string]interface{}) { if v != nil { d := def[k] d.Value = v def[k] = d } } } return def } // Get all widget from the list by name. func (w Widgets) Get(name string) Widgets { var r Widgets for _, v := range w { if v["n"] == name { r = append(r, v) } } return r } // ByID gets this widget by the position/ID. func (w Widgets) ByID(id int) Widget { return w[id] } // Get a view for this site by name and returns the view and index. // Returns -1 if this view doesn't exist. func (v Views) Get(name string) (View, int) { for i, vv := range v { if strings.EqualFold(vv.Name, name) { return vv, i } } return View{}, -1 } func (ss *UserSettings) Defaults(ctx context.Context) { if ss.Language == "" { ss.Language = "en-GB" } if ss.DateFormat == "" { ss.DateFormat = "2 Jan ’06" } if ss.NumberFormat == 0 { ss.NumberFormat = 0x202f } if ss.Timezone == nil { ss.Timezone = tz.UTC } if len(ss.Widgets) == 0 { ss.Widgets = defaultWidgets(ctx) } if len(ss.Views) == 0 { ss.Views = Views{{Name: "default", Period: "week"}} } } func (ss *UserSettings) Validate(ctx context.Context) error { v := NewValidate(ctx) for i, w := range ss.Widgets { for _, s := range w.GetSettings(ctx) { if s.Validate == nil { continue } vv := NewValidate(ctx) s.Validate(&vv, s.Value) v.Sub("widgets", strconv.Itoa(i), vv) } } if _, i := ss.Views.Get("default"); i == -1 || len(ss.Views) != 1 { v.Append("views", z18n.T(ctx, "view not set")) } if !zint.Contains(EmailReports, ss.EmailReports.Int()) { v.Append("email_reports", "invalid value") } return v.ErrorOrNil() }
<filename>toy/src/culling_util.cpp #include "culling_util.h" glm::vec4 normalize_plane(glm::vec4 plane) { glm::vec3 normal(plane); return plane * (1.0f / glm::length(normal)); } bool plane_intersect_point(glm::vec4 plane, glm::vec3 point) { float dot = glm::dot(plane, glm::vec4(point, 1.0f)); return dot > 0; } bool plane_intersect_sphere(glm::vec4 plane, glm::vec3 sphere_position, float sphere_radius) { float dot = glm::dot(plane, glm::vec4(sphere_position, 1.0f)); return dot > -sphere_radius; } bool plane_intersect_aabb(glm::vec4 plane, AABB aabb) { float dot = glm::dot(plane, glm::vec4(aabb.center, 1.0f)); float effective_radius = glm::dot(aabb.extents, glm::abs(glm::vec3(plane))); return dot > -effective_radius; } bool plane_intersect_obb(glm::vec4 plane, OBB obb) { float dot = glm::dot(plane, glm::vec4(obb.center, 1.0f)); glm::vec3 normal(plane); glm::vec3 normal_dot_axes = normal * obb.axes; float effective_radius = glm::dot(obb.extents, glm::abs(normal_dot_axes)); return dot > -effective_radius; } bool planes_intersect_point(std::span<glm::vec4> planes, glm::vec3 point) { for (auto plane : planes) { if (!plane_intersect_point(plane, point)) { return false; } } return true; } bool planes_intersect_sphere(std::span<glm::vec4> planes, glm::vec3 sphere_position, float sphere_radius) { for (auto plane : planes) { if (!plane_intersect_sphere(plane, sphere_position, sphere_radius)) { return false; } } return true; } bool planes_intersect_aabb(std::span<glm::vec4> planes, AABB aabb) { for (auto plane : planes) { if (!plane_intersect_aabb(plane, aabb)) { return false; } } return true; } bool planes_intersect_obb(std::span<glm::vec4> planes, OBB obb) { for (auto plane : planes) { if (!plane_intersect_obb(plane, obb)) { return false; } } return true; } std::vector<glm::vec4> view_projection_planes(glm::mat4 matrix) { glm::mat4 m = glm::transpose(matrix); glm::vec4 row0 = m[0]; glm::vec4 row1 = m[1]; glm::vec4 row2 = m[2]; glm::vec4 row3 = m[3]; glm::vec4 left = row0 + row3; glm::vec4 right = -row0 + row3; glm::vec4 bottom = row1 + row3; glm::vec4 top = -row1 + row3; glm::vec4 z_near = row2; glm::vec4 z_far = -row2 + row3; return std::vector<glm::vec4>{ normalize_plane(left), normalize_plane(right), normalize_plane(bottom), normalize_plane(top), normalize_plane(z_near), normalize_plane(z_far) }; } // f' = f * inverse(M) glm::vec4 transform_plane(glm::mat4 matrix, glm::vec4 plane) { glm::mat4 matrix_inverse = glm::inverse(matrix); return normalize_plane(plane * matrix_inverse); } // f' = f * inverse(M), so f = f' * M glm::vec4 inverse_transform_plane(glm::mat4 matrix, glm::vec4 plane) { return normalize_plane(plane * matrix); } std::vector<glm::vec4> clip_planes() { return std::vector<glm::vec4>{ glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), // left plane glm::vec4(-1.0f, 0.0f, 0.0f, 1.0f), // right plane glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), // bottom plane glm::vec4(0.0f, -1.0f, 0.0f, 1.0f), // top plane glm::vec4(0.0f, 0.0f, 1.0f, 0.0f), // near plane glm::vec4(0.0f, 0.0f, -1.0f, 1.0f) // far plane }; }
#!/bin/sh # Copyright 2019 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eux command -v virtualenv >/dev/null workdir="$(mktemp -d)" cd "${workdir}" cleanup() { rm -r "${workdir}" } trap cleanup EXIT cp -LR "${TEST_SRCDIR}/org_tensorflow_tensorboard/tensorboard/examples/plugins/example_basic/" \ ./example-plugin/ mkdir tensorboard-wheels tar xzvf \ "${TEST_SRCDIR}/org_tensorflow_tensorboard/tensorboard/pip_package/pip_packages.tar.gz" \ -C ./tensorboard-wheels/ virtualenv venv export VIRTUAL_ENV=venv export PATH="${PWD}/venv/bin:${PATH}" unset PYTHON_HOME # Require wheel for bdist_wheel command, and setuptools 36.2.0+ so that # env markers are handled (https://github.com/pypa/setuptools/pull/1081) pip install -qU wheel 'setuptools>=36.2.0' (cd ./example-plugin && python setup.py bdist_wheel) [ -f ./example-plugin/dist/*.whl ] # just one wheel py_major_version="$(python -c 'import sys; print(sys.version_info[0])')" pip install tf-nightly-2.0-preview # TODO(@wchargin): Other versions, too? pip uninstall -y tensorboard tb-nightly # drop conflicting packages pip install ./tensorboard-wheels/*py"${py_major_version}"*.whl pip install ./example-plugin/dist/*.whl python -m tensorboard_plugin_example.demo # Test tensorboard + tensorboard_plugin_example integration. mkfifo pipe tensorboard \ --logdir=. \ --port=0 \ --reload_interval=0 \ --reload_task=blocking \ 2>pipe & perl -ne 'print STDERR;/http:.*:(\d+)/ and print $1.v10 and exit 0' <pipe >port port="$(cat port)" curl -fs "http://localhost:${port}/data/plugin/example_basic/index.js" >index.js diff -u example-plugin/tensorboard_plugin_example/static/index.js index.js curl -fs "http://localhost:${port}/data/plugins_listing" >plugins_listing cat plugins_listing; printf '\n' perl -nle 'print if m{"example_basic":(?:(?!"enabled").)*+"enabled": *true}' plugins_listing grep -qF '"/data/plugin/example_basic/index.js"' plugins_listing curl -fs "http://localhost:${port}/data/plugin/example_basic/tags" >tags <<EOF tr -d '\n' | diff -u - tags {"demo_logs": {"guestbook": {"description": "Sign your name!"}, "more_names": {"description": ""}}} EOF kill $!
<filename>lib/cassandra_audits/sweeper.rb<gh_stars>0 require 'cassandra_audits/adapters/active_record/user_info.rb' module CassandraAudits class PartitionKeyNotSpecified < ::Exception; end class Sweeper < ActiveModel::Observer # observe CassandraAudits.audit_class # observe CassandraAudits::Adapters::ActiveRecord::StudyPlanAudit # observe CassandraAudits::Adapters::ActiveRecord::UserAudit observe CassandraAudits::Adapters::ActiveRecord::UserInfo def around(controller) begin self.controller = controller yield ensure self.controller = nil end end def before_create(audit) audit.audit_data ||= OpenStruct.new if controller.present? audit.audit_data.user_id ||= current_user.try(:id) || 0 if superior_user.present? audit.audit_data.superior_id ||= superior_user.id if controller.respond_to?(:superior_user_data) audit.audit_data.superior_data ||= controller.superior_user_data.to_json end end audit.audit_data.remote_address = controller.try(:request).try(:ip) || "" end end [:current_user, :superior_user].each do |method_name| define_method method_name do if controller.respond_to?(CassandraAudits.send("#{method_name}_method")) controller.send(CassandraAudits.send("#{method_name}_method")) end end end def add_observer!(klass) super define_callback(klass) end def define_callback(klass) observer = self callback_meth = :"_notify_audited_sweeper" klass.send(:define_method, callback_meth) do observer.update(:before_create, self) end klass.send(:before_create, callback_meth) end def controller ::CassandraAudits.store[:current_controller] end def controller=(value) ::CassandraAudits.store[:current_controller] = value end end end if defined?(ActionController) and defined?(ActionController::Base) ActionController::Base.class_eval do around_filter CassandraAudits::Sweeper.instance end end
from typing import List, Tuple def find_problematic_positions(edges: List[Tuple[int, int]], last_pos: List[int]) -> List[int]: problematic_positions = [] for i in range(len(last_pos)): count = 0 for edge in edges: if edge[0] == last_pos[i]: count += 1 if count != 1: problematic_positions.append(i+1) return problematic_positions
#!/bin/bash #------------------------------------------------------------------------------- # This script is used to create lcd service that starts at boot. # It also enables the user to select screens and currency to be used. #------------------------------------------------------------------------------- # Display the screen selection menu echo "==============================================================================================" echo " SCREEN SELECTION MENU" echo "==============================================================================================" echo echo "Available screens:" echo " Screen 1: Bitcoin Price and sats/currency." echo " Screen 2: Mempool information." echo " Screen 3: Current Bitcoin Block height." echo " Screen 4: Current Date and Time." echo echo "Please answer by typing yes or no then press the enter key." echo # a string to hold user screen choices userScreenChoices="" # Get user choice about screen 1 gettingUserChoice=true # Loop until user enters a valid choice while $gettingUserChoice do read -p "Would you like Bitcoin price and sats/currency to be shown as screen 1? " userAnswer # Convert to uppercase userAnswer=${userAnswer^^} # Check if entered a valid option if [ $userAnswer == "YES" ] then echo -e "\e[1;32m Adding screen 1. \e[0m" userScreenChoices="${userScreenChoices}Screen1," gettingUserChoice=false elif [ $userAnswer == "NO" ] then echo "Not Adding screen 1." gettingUserChoice=false else echo -e "\e[1;31m Your answer was not valid. \e[0m" fi done # Get user choice about screen 2 gettingUserChoice=true # Loop until user enters a valid choice while $gettingUserChoice do read -p "Would you like Mempool information to be shown as screen 2? " userAnswer # Convert to uppercase userAnswer=${userAnswer^^} # Check if entered a valid option if [ $userAnswer == "YES" ] then echo -e "\e[1;32m Adding screen 2. \e[0m" userScreenChoices="${userScreenChoices}Screen2," gettingUserChoice=false elif [ $userAnswer == "NO" ] then echo "Not Adding screen 2." gettingUserChoice=false else echo -e "\e[1;31m Your answer was not valid. \e[0m" fi done # Get user choice about screen 3 gettingUserChoice=true # Loop until user enters a valid choice while $gettingUserChoice do read -p "Would you like Current Bitcoin Block height to be shown as screen 3? " userAnswer # Convert to uppercase userAnswer=${userAnswer^^} # Check if entered a valid option if [ $userAnswer == "YES" ] then echo -e "\e[1;32m Adding screen 3. \e[0m" userScreenChoices="${userScreenChoices}Screen3," gettingUserChoice=false elif [ $userAnswer == "NO" ] then echo "Not Adding screen 3." gettingUserChoice=false else echo -e "\e[1;31m Your answer was not valid. \e[0m" fi done # Get user choice about screen 4 gettingUserChoice=true # Loop until user enters a valid choice while $gettingUserChoice do read -p "Would you like Current Date and Time to be shown as screen 4? " userAnswer # Convert to uppercase userAnswer=${userAnswer^^} # Check if entered a valid option if [ $userAnswer == "YES" ] then echo -e "\e[1;32m Adding screen 4. \e[0m" userScreenChoices="${userScreenChoices}Screen4" gettingUserChoice=false elif [ $userAnswer == "NO" ] then echo "Not Adding screen 4." gettingUserChoice=false else echo -e "\e[1;31m Your answer was not valid. \e[0m" fi done echo "User choices: ${userScreenChoices}" echo echo "==============================================================================================" echo " CURRENCY SELECTION" echo "==============================================================================================" # Get user currency gettingCurrency=true # Loop until user enters a valid currency while $gettingCurrency do echo read -p "Please Enter Currency Code e.g. USD for US Dollar: " newCurrency # Convert to uppercase newCurrency=${newCurrency^^} echo $newCurrency # Check if user entered a valid currency code validationResult=$(python3 ./CurrencyData.py ${newCurrency}) if [ "$validationResult" = "Valid" ]; then echo "Creating Umbrel ST7735 LCD Service." gettingCurrency=false # Get current working directory cwd=$(pwd) echo "==============================================================================================" echo " MEMPOOL.SPACE DATA RETRIEVAL" echo "==============================================================================================" # Get user mempool gettingMempool=true # Loop until user enters a valid mempool while $gettingMempool do echo "Do you wish to retrieve LCD data from your own Umbrel Mempool.space Api?" read -p "NOTE: Mempool.space must be installed and running via the Umbrel AppStore." useOwnMempool # Convert to uppercase useOwnMempool=${useOwnMempool^^} # Check if entered a valid option if [ $useOwnMempool == "YES" ] then echo -e "\e[1;32m LCD Screen data will be retrieve by your local Mempool.space Api. \e[0m" gettingMempool=false elif [ $useOwnMempool == "NO" ] then echo "LCD Screen data will be retrieve by the public Mempool.space Api." gettingMempool=false else echo -e "\e[1;31m Your answer was not valid. \e[0m" fi done # Create A Unit File sudo echo "[Unit] Description=Umbrel LCD Service After=multi-user.target [Service] Type=idle ExecStart=/usr/bin/python3 $cwd/UmbrelLCD.py $newCurrency $userScreenChoices $useOwnMempool [Install] WantedBy=multi-user.target" > /lib/systemd/system/UmbrelST7735LCD.service # The permission on the unit file needs to be set to 644 sudo chmod 644 /lib/systemd/system/UmbrelST7735LCD.service # Configure systemd sudo systemctl daemon-reload sudo systemctl enable UmbrelST7735LCD.service # Start the service sudo systemctl start UmbrelST7735LCD.service echo "Done Creating Umbrel ST7735 LCD Service." else #echo "Entered Currency code is not valid!!!" echo -e "\e[1;31m Entered Currency code is not valid!!! \e[0m" fi done
#!/bin/bash # RUNNING CASINO cd opt_u for dir in $(seq 1 1 6) ; do cd $dir runqmc -T 2h -p 128 --user.queue=medium cd .. done cd .. # cd opt_chi # for dir in $(seq 1 1 6) ; do # cd $dir # runqmc -T 2h -p 128 --user.queue=medium # cd .. # done # cd .. # cd opt_f # for dir in $(seq 0.5 0.5 3) ; do # cd $dir # runqmc -T 2h -p 128 --user.queue=medium # cd .. # done # cd ..
from urllib.parse import urlencode params = { 'name': 'chenzhiyuan', 'age': 24 } base_url = 'http://www.baidu.com?' url = base_url + urlencode(params) print(url)
def bubble_sort(arr): """Generate a code for bubble sort.""" n = len(arr) # Traverse through all array elements for i in range(n): # Last i elements are already in place for j in range(0, n-i-1): if arr[j] > arr[j+1] : arr[j], arr[j+1] = arr[j+1], arr[j] if __name__ == '__main__': bubble_sort(arr) print(arr)
<filename>src/facade/sdkFacade.ts import EvaluatorFacade, {TabContextFactory} from './evaluatorFacade'; import TrackerFacade from './trackerFacade'; import Context, {TokenScope} from '../context'; import UserFacade from './userFacade'; import Token from '../token'; import {formatCause} from '../error'; import {configurationSchema} from '../schema/sdkFacadeSchemas'; import Sdk from '../sdk'; import SessionFacade from './sessionFacade'; import {Logger} from '../logging'; import {SdkEventMap} from '../sdkEvents'; import {EventManager} from '../eventManager'; import CidAssigner from '../cid/index'; import {PartialTrackingEvent} from '../trackingEvents'; import {UrlSanitizer} from '../tab'; export type Configuration = { appId: string, tokenScope?: TokenScope, debug?: boolean, track?: boolean, token?: string | null, userId?: string, eventMetadata?: {[key: string]: string}, logger?: Logger, urlSanitizer?: UrlSanitizer, trackerEndpointUrl?: string, evaluationEndpointUrl?: string, bootstrapEndpointUrl?: string, }; function validateConfiguration(configuration: unknown): asserts configuration is Configuration { if (typeof configuration !== 'object' || configuration === null) { throw new Error('The configuration must be a key-value map.'); } try { configurationSchema.validate(configuration); } catch (violation) { throw new Error(`Invalid configuration: ${formatCause(violation)}`); } } export default class SdkFacade { private readonly sdk: Sdk; private trackerFacade?: TrackerFacade; private userFacade?: UserFacade; private sessionFacade?: SessionFacade; private evaluatorFacade?: EvaluatorFacade; private constructor(sdk: Sdk) { this.sdk = sdk; } public static init(configuration: Configuration): SdkFacade { validateConfiguration(configuration); const {track = true, userId, token, ...containerConfiguration} = configuration; if (userId !== undefined && token !== undefined) { throw new Error('Either the user ID or token can be specified, but not both.'); } const sdk = new SdkFacade( Sdk.init({ ...containerConfiguration, tokenScope: containerConfiguration.tokenScope ?? 'global', debug: containerConfiguration.debug ?? false, }), ); if (userId !== undefined) { sdk.identify(userId); } else if (token !== undefined) { if (token === null) { sdk.unsetToken(); } else { sdk.setToken(Token.parse(token)); } } if (track) { sdk.tracker.enable(); } return sdk; } public get context(): Context { return this.sdk.context; } public get cidAssigner(): CidAssigner { return this.sdk.cidAssigner; } public get tracker(): TrackerFacade { if (this.trackerFacade === undefined) { this.trackerFacade = new TrackerFacade(this.sdk.tracker); } return this.trackerFacade; } public get user(): UserFacade { if (this.userFacade === undefined) { this.userFacade = new UserFacade(this.context, this.sdk.tracker); } return this.userFacade; } public get session(): SessionFacade { if (this.sessionFacade === undefined) { this.sessionFacade = new SessionFacade(this.sdk.tracker); } return this.sessionFacade; } public get evaluator(): EvaluatorFacade { if (this.evaluatorFacade === undefined) { this.evaluatorFacade = new EvaluatorFacade( this.sdk.evaluator, new TabContextFactory(this.sdk.context.getTab()), ); } return this.evaluatorFacade; } public get eventManager(): EventManager<Record<string, object>, SdkEventMap> { const {eventManager} = this.sdk; return { addListener: eventManager.addListener.bind(eventManager), removeListener: eventManager.removeListener.bind(eventManager), dispatch: (eventName: string, event: object): void => { if (!/[a-z][a-z_]+\.[a-z][a-z_]+/i.test(eventName)) { throw new Error( 'The event name must be in the form of "namespaced.eventName", where ' + 'both the namespace and event name must start with a letter, followed by ' + 'any series of letters and underscores.', ); } eventManager.dispatch(eventName, event); }, }; } public identify(userId: string): void { this.setToken(Token.issue(this.sdk.appId, userId)); } public anonymize(): void { if (!this.context.isAnonymous()) { this.unsetToken(); } } public getToken(): Token|null { return this.context.getToken(); } public setToken(token: Token): void { const currentToken = this.getToken(); if (currentToken !== null && currentToken.toString() === token.toString()) { return; } const currentSubject = currentToken?.getSubject() ?? null; const subject = token.getSubject(); const logger = this.getLogger(); if (subject === currentSubject) { this.context.setToken(token); logger.debug('Token refreshed'); return; } if (currentSubject !== null) { this.trackInternalEvent({ type: 'userSignedOut', userId: currentSubject, }); logger.info('User signed out'); } this.context.setToken(token); if (subject !== null) { this.trackInternalEvent({ type: 'userSignedIn', userId: subject, }); logger.info(`User signed in as ${subject}`); } logger.debug('New token saved, '); } public unsetToken(): void { const token = this.getToken(); if (token === null) { return; } const logger = this.getLogger(); const subject = token.getSubject(); if (subject !== null) { this.trackInternalEvent({ type: 'userSignedOut', userId: subject, }); logger.info('User signed out'); } this.context.setToken(null); logger.debug('Token removed'); } private trackInternalEvent(event: PartialTrackingEvent): void { this.sdk.tracker.track(event).catch(() => { // suppress error as it is already logged by the tracker }); } public getLogger(...namespace: string[]): Logger { return this.sdk.getLogger(...namespace); } public getTabStorage(namespace: string, ...subnamespace: string[]): Storage { return this.sdk.getTabStorage(namespace, ...subnamespace); } public getBrowserStorage(namespace: string, ...subnamespace: string[]): Storage { return this.sdk.getBrowserStorage(namespace, ...subnamespace); } public close(): Promise<void> { return this.sdk.close(); } }
<reponame>zrwusa/expo-bunny<gh_stars>1-10 import React, {useEffect, useState} from 'react'; import {Animated, I18nManager, LayoutChangeEvent, StyleSheet, Text, TextInput, View} from 'react-native'; import {PanGestureHandler, PanGestureHandlerGestureEvent, State} from 'react-native-gesture-handler'; import {useBunnyKit} from '../../../src/hooks/bunny-kit'; const SMALL_SIZE = 24; const MEDIUM_SIZE = 34; const LARGE_SIZE = 44; const osRtl = I18nManager.isRTL; type Size = 'small' | 'medium' | 'large'; interface SliderProps { min: number, max: number, fromValueOnChange: (value: number) => void, toValueOnChange: (value: number) => void, step?: number, styleSize?: Size | number, fromKnobColor?: string, toKnobColor?: string, inRangeBarColor?: string, outOfRangeBarColor?: string, valueLabelsTextColor?: string, valueLabelsBackgroundColor?: string, rangeLabelsTextColor?: string, showRangeLabels?: boolean, showValueLabels?: boolean, initialFromValue?: number, initialToValue?: number, valueLabelsPosition?: 'up' | 'down', showBubbles?: boolean, showValueLabelsOnlyWhenDrag?: boolean, valueLabelsUnit?: string, fromValueOnIndicated?: (value: number) => void, toValueOnIndicated?: (value: number) => void, } export default (props: SliderProps) => { const {colors} = useBunnyKit(); const { min, max, fromValueOnChange, toValueOnChange, step = 1, styleSize = 'medium', fromKnobColor = colors.primary, toKnobColor = colors.primary, inRangeBarColor = colors.primary, outOfRangeBarColor = colors.divider, valueLabelsTextColor = colors.text2, valueLabelsBackgroundColor = '#3a4766', rangeLabelsTextColor = 'rgb(60,60,60)', showRangeLabels = true, showValueLabels = true, initialFromValue, initialToValue, valueLabelsPosition = 'down', showBubbles = false, showValueLabelsOnlyWhenDrag = false, valueLabelsUnit = '', fromValueOnIndicated, toValueOnIndicated, } = props; // settings const [wasInitialized, setWasInitialized] = useState(false); const [knobSize, setKnobSize] = useState(0); const [fontSize, setFontSize] = useState(15); const [stepInPixels, setStepInPixels] = useState(0); // rtl settings const [flexDirection, setFlexDirection] = useState<'row' | 'row-reverse' | 'column' | 'column-reverse' | undefined>('row'); const [svgOffset, setSvgOffset] = useState<object>({left: (knobSize - 40) / 2}); const [fromValueOffset, setFromValueOffset] = useState(0); const [toValueOffset, setToValueOffset] = useState(0); const [sliderWidth, setSliderWidth] = useState(0); const [fromElevation, setFromElevation] = useState(3); const [toElevation, setToElevation] = useState(3); // animation values const [translateXFromValue] = useState(new Animated.Value(0)); const [translateXtoValue] = useState(new Animated.Value(0)); const [fromValueScale] = useState(new Animated.Value(showValueLabelsOnlyWhenDrag ? 0.01 : 1)); const [toValueScale] = useState(new Animated.Value(showValueLabelsOnlyWhenDrag ? 0.01 : 1)); const [rightBarScaleX] = useState(new Animated.Value(0.01)); const [leftBarScaleX] = useState(new Animated.Value(0.01)); // refs const toValueTextRef = React.createRef<TextInput>(); const fromValueTextRef = React.createRef<TextInput>(); const opacity = React.useRef<Animated.Value>(new Animated.Value(0)).current; // initializing settings useEffect(() => { setFlexDirection(osRtl ? 'row-reverse' : 'row'); setSvgOffset(osRtl ? {right: (knobSize - 40) / 2} : {left: (knobSize - 40) / 2}); }, [knobSize]); useEffect(() => { if (wasInitialized) { const stepSize = setStepSize(max, min, step); fromValueTextRef.current?.setNativeProps({text: min.toString() + valueLabelsUnit}); toValueTextRef.current?.setNativeProps({text: max.toString() + valueLabelsUnit}); if (typeof initialFromValue === 'number' && initialFromValue >= min && initialFromValue <= max) { const offset = ((initialFromValue - min) / step) * stepSize - (knobSize / 2); setFromValueStatic(offset, knobSize, stepSize); setValueText(offset, true); } if (typeof initialToValue === 'number' && initialToValue >= min && initialToValue <= max && typeof initialFromValue === 'number' && initialToValue > initialFromValue) { const offset = ((initialToValue - min) / step) * stepSize - (knobSize / 2); setToValueStatic(offset, knobSize, stepSize); setValueText(offset, false); } Animated.timing(opacity, { toValue: 1, duration: 64, useNativeDriver: true }).start(); } }, [min, max, step, initialFromValue, initialToValue, wasInitialized]); const sizeMap: { [key in Size]: number } = { 'small': SMALL_SIZE, 'medium': MEDIUM_SIZE, 'large': LARGE_SIZE }; useEffect(() => { const size = typeof styleSize === 'number' ? styleSize : sizeMap[styleSize]; setKnobSize(size); translateXFromValue.setValue(-size / 4); }, [styleSize]); // initializing settings helpers const calculateFromValue = (newOffset: number, knobSize: number, stepInPixels: number) => { return Math.floor((newOffset + (knobSize / 2)) / stepInPixels) * stepInPixels - (knobSize / 2); }; const setFromValueStatic = (newOffset: number, knobSize: number, stepInPixels: number) => { newOffset = calculateFromValue(newOffset, knobSize, stepInPixels); setFromValue(newOffset); setFromValueOffset(newOffset); fromValueOnChange(Math.floor(((newOffset + (knobSize / 2)) * (max - min) / sliderWidth) / step) * step + min); }; const setFromValue = (newOffset: number) => { translateXFromValue.setValue(newOffset); leftBarScaleX.setValue((newOffset + (knobSize / 2)) / sliderWidth + 0.01); }; const calculateToValue = (newOffset: number, knobSize: number, stepInPixels: number) => { return Math.ceil((newOffset + (knobSize / 2)) / stepInPixels) * stepInPixels - (knobSize / 2); }; const setToValueStatic = (newOffset: number, knobSize: number, stepInPixels: number) => { newOffset = calculateToValue(newOffset, knobSize, stepInPixels); setToValue(newOffset); setToValueOffset(newOffset); toValueOnChange(Math.ceil(((newOffset + (knobSize / 2)) * (max - min) / sliderWidth) / step) * step + min); }; const setToValue = (newOffset: number) => { translateXtoValue.setValue(newOffset); rightBarScaleX.setValue(1.01 - ((newOffset + (knobSize / 2)) / sliderWidth)); }; const setStepSize = (max: number, min: number, step: number) => { const numberOfSteps = ((max - min) / step); const stepSize = sliderWidth / numberOfSteps; setStepInPixels(stepSize); return stepSize; }; const setValueText = (totalOffset: number, isFrom = true) => { if (isFrom && fromValueTextRef != null) { const numericValue: number = Math.floor(((totalOffset + (knobSize / 2)) * (max - min) / sliderWidth) / step) * step + min; fromValueOnIndicated?.(numericValue); fromValueTextRef.current?.setNativeProps({text: numericValue.toString() + valueLabelsUnit}); } else if (!isFrom && toValueTextRef != null) { const numericValue: number = Math.ceil(((totalOffset + (knobSize / 2)) * (max - min) / sliderWidth) / step) * step + min; toValueOnIndicated?.(numericValue); toValueTextRef.current?.setNativeProps({text: numericValue.toString() + valueLabelsUnit}); } }; // from value gesture events ------------------------------------------------------------------------ const onGestureEventFromValue = (event: PanGestureHandlerGestureEvent) => { let totalOffset = event.nativeEvent.translationX + fromValueOffset; if (totalOffset >= -knobSize / 2 && totalOffset < toValueOffset) { translateXFromValue.setValue(totalOffset); setValueText(totalOffset, true); leftBarScaleX.setValue((totalOffset + (knobSize / 2)) / sliderWidth + 0.01); } }; const onHandlerStateChangeFromValue = (event: PanGestureHandlerGestureEvent) => { if (event.nativeEvent.state === State.BEGAN) { if (showValueLabelsOnlyWhenDrag) scaleTo(fromValueScale, 1); setElevations(6, 5); } if (event.nativeEvent.state === State.END) { let newOffset = event.nativeEvent.translationX + fromValueOffset; newOffset = calculateFromValue(newOffset, knobSize, stepInPixels); if (newOffset < -knobSize / 2) { newOffset = -knobSize / 2; } else if (newOffset >= toValueOffset) { newOffset = toValueOffset - stepInPixels; } setFromValueStatic(newOffset, knobSize, stepInPixels); if (showValueLabelsOnlyWhenDrag) scaleTo(fromValueScale, 0.01); } }; // ------------------------------------------------------------------------------------------------ // to value gesture events ------------------------------------------------------------------------ const onGestureEventToValue = (event: PanGestureHandlerGestureEvent) => { const totalOffset = event.nativeEvent.translationX + toValueOffset; if (totalOffset <= sliderWidth - knobSize / 2 && totalOffset > fromValueOffset) { translateXtoValue.setValue(totalOffset); setValueText(totalOffset, false); rightBarScaleX.setValue(1.01 - ((totalOffset + (knobSize / 2)) / sliderWidth)); } }; const onHandlerStateChangeToValue = (event: PanGestureHandlerGestureEvent) => { if (event.nativeEvent.state === State.BEGAN) { if (showValueLabelsOnlyWhenDrag) scaleTo(toValueScale, 1); setElevations(5, 6); } if (event.nativeEvent.state === State.END) { let newOffset = event.nativeEvent.translationX + toValueOffset; newOffset = calculateToValue(newOffset, knobSize, stepInPixels); if (newOffset > sliderWidth - knobSize / 2) { newOffset = sliderWidth - knobSize / 2; } else if (newOffset <= fromValueOffset) { newOffset = fromValueOffset + stepInPixels; } setToValueOffset(newOffset); translateXtoValue.setValue(newOffset); rightBarScaleX.setValue(1.01 - ((newOffset + (knobSize / 2)) / sliderWidth)); if (showValueLabelsOnlyWhenDrag) scaleTo(toValueScale, 0.01); toValueOnChange(Math.ceil(((newOffset + (knobSize / 2)) * (max - min) / sliderWidth) / step) * step + min); } }; // ------------------------------------------------------------------------------------------------ // gesture events help functions ------------------------------------------------------------------ const scaleTo = (param: Animated.Value, toValue: number) => Animated.timing(param, { toValue, duration: 150, useNativeDriver: true } ).start(); const setElevations = (fromValue: number, toValue: number) => { setFromElevation(fromValue); setToElevation(toValue); }; // ------------------------------------------------------------------------------------------------ // setting bar width ------------------------------------------------------------------------------ const onLayout = (event: LayoutChangeEvent) => { if (!wasInitialized) { const {width} = event.nativeEvent.layout; setSliderWidth(width); translateXtoValue.setValue(width - knobSize / 2); setToValueOffset(width - knobSize / 2); setWasInitialized(true); } }; // ------------------------------------------------------------------------------------------------ const bubbleSizeMap: { [key in Size]: { width: number, height: number } } = { 'small': {width: 20, height: 28}, 'medium': {width: 40, height: 56}, 'large': {width: 50, height: 70}, }; // const bubbleSizeMap: { [key in Size]: { width: string, height: string } } = { // 'small': {width: `${100*20/40}%`, height: `${28*56/56}%`}, // 'medium': {width: `${100*40/40}%`, height: `${100*56/56}%`}, // 'large': {width: `${100*50/40}%`, height: `${100*70/56}%`}, // } const bubbleSize = typeof styleSize === 'number' ? {width: styleSize, height: styleSize} : bubbleSizeMap[styleSize]; const bubbleBottomValue = typeof styleSize === 'number' ? styleSize : bubbleSizeMap[styleSize].height; const bubbleBottom = valueLabelsPosition === 'up' ? 0 : -bubbleBottomValue; const renderValueLabels = () => { return (showValueLabels && <View style={{width: '100%', height: 1, flexDirection}}> <Animated.View style={{ position: 'absolute', bottom: 0, left: 0, transform: [{translateX: translateXFromValue}, {scale: fromValueScale}] }} > { showBubbles ? // <Svg {...bubbleSize} style={[svgOffset, {justifyContent: 'center', alignItems: 'center',position:'absolute',bottom:bubbleBottom}]}> // <Path // d="M20.368027196163986,55.24077513402203 C20.368027196163986,55.00364778429386 37.12897994729114,42.11537830086061 39.19501224411266,22.754628132990383 C41.26104454093417,3.393877965120147 24.647119286738516,0.571820003300814 20.368027196163986,0.7019902620266703 C16.088935105589453,0.8321519518460209 -0.40167016290734386,3.5393865664909434 0.7742997013327574,21.806127302984205 C1.950269565572857,40.07286803947746 20.368027196163986,55.4779024837502 20.368027196163986,55.24077513402203 z" // strokeWidth={1} // fill={valueLabelsBackgroundColor} // stroke={valueLabelsBackgroundColor} // /> // </Svg> <View style={[svgOffset, { ...bubbleSize, justifyContent: 'center', alignItems: 'center', position: 'absolute', bottom: bubbleBottom, backgroundColor: 'red' }]}/> : null } <TextInput editable={false} style={{ position: 'absolute', width: 50, textAlign: 'center', left: -50 / 4, color: valueLabelsTextColor, bottom: valueLabelsPosition === 'up' ? 18 : -18, }} ref={fromValueTextRef}/> </Animated.View> <Animated.View style={{ position: 'absolute', bottom: 0, left: 0, alignItems: 'center', transform: [{translateX: translateXtoValue}, {scale: toValueScale}] }} > { showBubbles ? // <Svg {...bubbleSize} style={[svgOffset, {justifyContent: 'center', alignItems: 'center',position:'absolute',bottom:bubbleBottom}]}> // <Path // d="M20.368027196163986,55.24077513402203 C20.368027196163986,55.00364778429386 37.12897994729114,42.11537830086061 39.19501224411266,22.754628132990383 C41.26104454093417,3.393877965120147 24.647119286738516,0.571820003300814 20.368027196163986,0.7019902620266703 C16.088935105589453,0.8321519518460209 -0.40167016290734386,3.5393865664909434 0.7742997013327574,21.806127302984205 C1.950269565572857,40.07286803947746 20.368027196163986,55.4779024837502 20.368027196163986,55.24077513402203 z" // strokeWidth={1} // fill={valueLabelsBackgroundColor} // stroke={valueLabelsBackgroundColor} // /> // </Svg> <View style={[svgOffset, { ...bubbleSize, justifyContent: 'center', alignItems: 'center', position: 'absolute', bottom: bubbleBottom, backgroundColor: 'red' }]}/> : null } <TextInput editable={false} style={{ position: 'absolute', width: 50, textAlign: 'center', left: -50 / 4, color: valueLabelsTextColor, bottom: valueLabelsPosition === 'up' ? 18 : -18, }} ref={toValueTextRef}/> </Animated.View> </View> ); }; const paddingSizeMap: { [key in Size]: number } = { 'small': 21, 'medium': 14, 'large': 7 }; const styles = getStyle(knobSize); return ( <Animated.View style={[styles.container, { opacity, padding: typeof styleSize === 'number' ? styleSize / 2 : paddingSizeMap[styleSize] }]}> { valueLabelsPosition === 'up' ? renderValueLabels() : null } <View style={{ width: '100%', height: knobSize, marginVertical: 4, position: 'relative', flexDirection, alignItems: 'center' }}> <View style={{ position: 'absolute', backgroundColor: inRangeBarColor, left: knobSize / 4, marginLeft: -knobSize / 4, right: knobSize / 4, height: knobSize / 3 }} onLayout={onLayout}/> <Animated.View style={{ position: 'absolute', left: knobSize / 4, marginLeft: -knobSize / 4, right: knobSize / 4, height: knobSize / 3, backgroundColor: outOfRangeBarColor, transform: [{translateX: sliderWidth / 2}, {scaleX: rightBarScaleX}, {translateX: -sliderWidth / 2}] }}/> <Animated.View style={{ position: 'absolute', left: -knobSize / 4, width: knobSize / 2, height: knobSize / 3, borderRadius: knobSize / 3, backgroundColor: outOfRangeBarColor }}/> <Animated.View style={{ width: sliderWidth, height: knobSize / 3, backgroundColor: outOfRangeBarColor, transform: [{translateX: -sliderWidth / 2}, {scaleX: leftBarScaleX}, {translateX: sliderWidth / 2}] }}/> <Animated.View style={{ position: 'absolute', left: sliderWidth - knobSize / 4, width: knobSize / 2, height: knobSize / 3, borderRadius: knobSize / 3, backgroundColor: outOfRangeBarColor }}/> <PanGestureHandler onGestureEvent={onGestureEventFromValue} onHandlerStateChange={onHandlerStateChangeFromValue}> {/*<Animated.View style={[styles.knob, {*/} {/* height: knobSize,*/} {/* width: knobSize,*/} {/* borderRadius: knobSize,*/} {/* backgroundColor: fromKnobColor,*/} {/* elevation: fromElevation,*/} {/* transform: [{translateX: translateXFromValue}]*/} {/*}]}/>*/} <Animated.View style={[styles.knob1, { backgroundColor: fromKnobColor, elevation: fromElevation, transform: [{translateX: translateXFromValue}] }]}> <Text style={styles.knobInnerDivider}>| | |</Text> </Animated.View> </PanGestureHandler> <PanGestureHandler onGestureEvent={onGestureEventToValue} onHandlerStateChange={onHandlerStateChangeToValue}> {/*<Animated.View style={[styles.knob, {*/} {/* height: knobSize,*/} {/* width: knobSize,*/} {/* borderRadius: knobSize,*/} {/* backgroundColor: toKnobColor,*/} {/* elevation: toElevation,*/} {/* transform: [{translateX: translateXtoValue}]*/} {/*}]}/>*/} <Animated.View style={[styles.knob1, { backgroundColor: toKnobColor, elevation: toElevation, transform: [{translateX: translateXtoValue}] }]}> <Text style={styles.knobInnerDivider}>| | |</Text> </Animated.View> </PanGestureHandler> </View> { valueLabelsPosition === 'down' ? renderValueLabels() : null } { showRangeLabels ? <View style={{width: '100%', flexDirection, justifyContent: 'space-between'}}> <Text style={{color: rangeLabelsTextColor, fontWeight: 'bold', fontSize}}>{min}</Text> <Text style={{color: rangeLabelsTextColor, fontWeight: 'bold', fontSize}}>{max}</Text> </View> : null } </Animated.View> ); } const getStyle = (knobSize: number) => { return StyleSheet.create({ container: { // height: 100, // width: '100%' }, knob: { position: 'absolute', elevation: 4 }, knob1: { height: knobSize, width: 2 * knobSize, left: -(0.5 * knobSize), borderRadius: 0.5 * knobSize, position: 'absolute', flexDirection: 'row', justifyContent: 'center', alignItems: 'center', elevation: 4 }, knobInnerDivider: { marginHorizontal: 3 * knobSize / 40, fontSize: 18 * knobSize / 40, lineHeight: 18 * knobSize / 40, color: 'white' } }); };
/* * Created Date: Sat, 28th Dec 2019, 17:57:15 pm * Author: <NAME> * Email: <EMAIL> * Copyright (c) 2019 The Distance */ import {NativeModules, Platform} from 'react-native'; import Environment from './Environment'; const iOSSecretsManager = NativeModules.iOSSecretsManager; const AndroidSecretsManager = NativeModules.AndroidSecretsManager; export default function fetchSecrets() { // return true; if (Platform.OS === 'ios') { try { const secrets = iOSSecretsManager.fetch(Environment); return secrets; } catch (error) { console.error(error); return null; } } else if (Platform.OS === 'android') { const secrets = AndroidSecretsManager.fetch(Environment); return secrets; } return null; }
echo ' Bringing Network Up and Running...' sudo docker-compose -f docker-compose-cli.yaml down sudo docker volume prune sudo docker network prune sudo docker-compose -f docker-compose-cli.yaml up -d sleep 20 echo 'Channel Creation Taking Place..' sudo docker exec -it cli peer channel create -o orderer.example.com:7050 /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -c mychannel -f ./channel-artifacts/channel.tx sudo docker exec -it cli peer channel join -b mychannel.block echo 'Exporting channel block to other Peer Containers..' sudo docker cp cli:/opt/gopath/src/github.com/hyperledger/fabric/peer/mychannel.block . sudo docker cp mychannel.block cli2:/opt/gopath/src/github.com/hyperledger/fabric/peer/mychannel.block sudo docker cp mychannel.block cli3:/opt/gopath/src/github.com/hyperledger/fabric/peer/mychannel.block rm mychannel.block echo 'Org2 Peer joining Channel..' sudo docker exec -it cli2 peer channel join -b mychannel.block echo 'Org3 Peer joining channel...' sudo docker exec -it cli3 peer channel join -b mychannel.block echo 'All Peers Joined mychannel..' echo 'creating channel12..' sudo docker exec -it cli peer channel create -o orderer.example.com:7050 /opt/gopath/src/github.com/hyperledger/fabric/peer/crypto/ordererOrganizations/example.com/orderers/orderer.example.com/msp/tlscacerts/tlsca.example.com-cert.pem -c channel12 -f ./channel-artifacts/channel12.tx sudo docker exec -it cli peer channel join -b channel12.block echo 'exporting channel12.block to org2 peer..' sudo docker cp cli:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel12.block . sudo docker cp channel12.block cli2:/opt/gopath/src/github.com/hyperledger/fabric/peer/channel12.block sudo docker exec -it cli2 peer channel join -b channel12.block rm channel12.block echo 'Peer2 joined channel12 successfully..' exit 1
#!/usr/bin/env bash CURRENT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )" HELPERS_DIR="$CURRENT_DIR/helpers" source "$HELPERS_DIR/plugin_functions.sh" source "$HELPERS_DIR/utility.sh" if [ "$1" == "--tmux-echo" ]; then # tmux-specific echo functions source "$HELPERS_DIR/tmux_echo_functions.sh" else # shell output functions source "$HELPERS_DIR/shell_echo_functions.sh" fi clone() { local plugin="$1" cd "$(tpm_path)" && GIT_TERMINAL_PROMPT=0 git clone --recursive "$plugin" >/dev/null 2>&1 } # tries cloning: # 1. plugin name directly - works if it's a valid git url # 2. expands the plugin name to point to a github repo and tries cloning again clone_plugin() { local plugin="$1" clone "$plugin" || clone "https://git::@github.com/$plugin" } # clone plugin and produce output install_plugin() { local plugin="$1" local plugin_name="$(plugin_name_helper "$plugin")" if plugin_already_installed "$plugin"; then echo_ok "Already installed \"$plugin_name\"" else echo_ok "Installing \"$plugin_name\"" clone_plugin "$plugin" && echo_ok " \"$plugin_name\" download success" || echo_err " \"$plugin_name\" download fail" fi } install_plugins() { local plugins="$(tpm_plugins_list_helper)" for plugin in $plugins; do install_plugin "$plugin" done } verify_tpm_path_permissions() { local path="$(tpm_path)" # check the write permission flag for all users to ensure # that we have proper access [ -w "$path" ] || echo_err "$path is not writable!" } main() { ensure_tpm_path_exists verify_tpm_path_permissions install_plugins exit_value_helper } main
#!/usr/bin/env bats # # secret-values.bats # # Test to see if we can get and set secret values on our test site # @test "set and retrieve secrets for t0" { # Set 'foo' to 'bar' terminus0 secrets set --site=$TERMINUS_SITE --env=dev foo bar # Fetch 'foo' back again run terminus0 secrets show --site=$TERMINUS_SITE --env=dev [[ "$output" == *"bar"* ]] # Set 'foo' to 'bar' terminus0 secrets set --site=$TERMINUS_SITE --env=dev foo baz # Fetch 'foo' back again run terminus0 secrets show --site=$TERMINUS_SITE --env=dev [[ "$output" == *"baz"* ]] }
<reponame>sptz45/coeus<gh_stars>0 /* - Coeus web framework ------------------------- * * Licensed under the Apache License, Version 2.0. * * Author: <NAME> */ package com.tzavellas.coeus.core import scala.collection.Map /** * Finds the {@code Handler} to handle a given request. */ trait RequestResolver { /** * Register the given {@code Hander} to handle requests for the specified * path and HTTP method. * * @param method the HTTP method of the request * @param path the path (requestUri) of the request * @param handler the {@code Handler} to register */ def register(method: Symbol, path: String, handler: Handler) /** * Finds the {@code Handler}s that can handle a request for the specified * path. * * @param path the path (requestUri) of the request * * @return a pair that contains the {@code HandlerMap} with the handlers for * the specified path and a map with any path variables. */ def resolve(path: String): (HandlerMap, Map[String, String]) }
import org.col.WsServerConfig; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import java.net.URI; @Path("/") @Produces(MediaType.TEXT_HTML) public class DocsResource { private final URI raml; private final String version; public DocsResource(WsServerConfig cfg) { this.raml = URI.create(cfg.raml); version = cfg.versionString(); } }
<filename>lib/vue/utils/settings.js<gh_stars>0 exports.pkg = [ "@ui5/webcomponents-react", "@ui5/webcomponents-fiori" ] exports.scripts = [ { name: "build:mta", value: "mbt build" } ]
numbers = [25, 12, 15, 32, 7] # initialize maximum number max = numbers[0] # loop through list for num in numbers: # compare each number to find the max if num > max: max = num # print maximum number print(max)
from django.forms import ModelForm from .models import Todo from django import forms from django.core.exceptions import NON_FIELD_ERRORS class AddTodoForm(ModelForm): class Meta: model = Todo fields = ['name'] labels = { 'name' : "Add Todo" } widgets = { 'name': forms.TextInput(attrs={'placeholder': "Add your Todo's here..."}), }
function validateTrainingData($postData) { $errors = []; // Validate 'tgl_plg_training' date format $tglPlgTraining = $postData['tgl_plg_training']; if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $tglPlgTraining)) { $errors[] = 'Invalid date format for tgl_plg_training'; } // Validate 'nominal_transport' and 'nominal_akomodasi' as numeric and non-negative $nominalTransport = $postData['nominal_transport']; $nominalAkomodasi = $postData['nominal_akomodasi']; if (!is_numeric($nominalTransport) || $nominalTransport < 0) { $errors[] = 'Nominal transport must be a non-negative number'; } if (!is_numeric($nominalAkomodasi) || $nominalAkomodasi < 0) { $errors[] = 'Nominal akomodasi must be a non-negative number'; } return empty($errors) ? ['valid' => true, 'errors' => []] : ['valid' => false, 'errors' => $errors]; } // Example usage: $postData = [ 'tgl_plg_training' => '2022-12-31', 'nominal_transport' => '150.50', 'nominal_akomodasi' => '200.00' ]; $result = validateTrainingData($postData); var_dump($result);
<filename>test/checker/test_base.py # coding=utf-8 import pytest from data_packer import checker from _common import verify class TestTypeChecker: def test_multi_type(self): ck = checker.TypeChecker((str, unicode)) verify(ck, '1')
#!/usr/bin/env python3 # encoding: utf-8 import os import yaml from typing import Dict, NoReturn def load_yaml(rel_filepath: str, msg: str = '') -> Dict: ''' Load YAML file. ''' if os.path.exists(rel_filepath): with open(rel_filepath, 'r', encoding='utf-8') as f: x = yaml.safe_load(f.read()) if msg != '': print(msg) return x else: raise Exception('cannot find this config.') def save_config(dicpath: str, config: Dict) -> NoReturn: if not os.path.exists(dicpath): os.makedirs(dicpath) with open(os.path.join(dicpath, 'config.yaml'), 'w', encoding='utf-8') as fw: yaml.dump(config, fw) print(f'save config to {dicpath}') def load_config(filename: str) -> Dict: if os.path.exists(filename): with open(filename, 'r', encoding='utf-8') as f: x = yaml.safe_load(f.read()) print(f'load config from {filename}') return x else: raise Exception('cannot find this config.')
require 'isomorfeus-preact' require 'isomorfeus/policy/config' require 'lucid_props' if RUBY_ENGINE == 'opal' Isomorfeus.zeitwerk.push_dir('isomorfeus_policy') require_tree 'isomorfeus_policy', autoload: true Isomorfeus.zeitwerk.push_dir('policies') else require 'isomorfeus_policy/lucid_policy/exception' require 'isomorfeus_policy/lucid_policy/helper' require 'isomorfeus_policy/lucid_policy/mixin' require 'isomorfeus_policy/lucid_policy/base' require 'isomorfeus_policy/lucid_authorization/mixin' require 'isomorfeus_policy/lucid_authorization/base' require 'isomorfeus_policy/anonymous' require 'iso_opal' Opal.append_path(__dir__.untaint) unless IsoOpal.paths_include?(__dir__.untaint) path = File.expand_path(File.join('app', 'policies')) Isomorfeus.zeitwerk.push_dir(path) if Dir.exist?(path) end
package it.madlabs.patternrec.web.rest.controllers.common; public class BadRequestException extends ApiException { public BadRequestException(String msg) { super(400, msg); } }
/* * This file is generated by jOOQ. */ package jooq.generated.entities.static_.tables.records; import java.sql.Time; import java.util.UUID; import javax.annotation.Generated; import jooq.generated.entities.static_.tables.ScheduleUpdate; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record4; import org.jooq.Row4; import org.jooq.impl.UpdatableRecordImpl; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.9.2" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class ScheduleUpdateRecord extends UpdatableRecordImpl<ScheduleUpdateRecord> implements Record4<UUID, UUID, Time, Time> { private static final long serialVersionUID = 250079931; /** * Setter for <code>public.schedule_update.id</code>. */ public ScheduleUpdateRecord setId(UUID value) { set(0, value); return this; } /** * Getter for <code>public.schedule_update.id</code>. */ public UUID getId() { return (UUID) get(0); } /** * Setter for <code>public.schedule_update.schedule</code>. */ public ScheduleUpdateRecord setSchedule(UUID value) { set(1, value); return this; } /** * Getter for <code>public.schedule_update.schedule</code>. */ public UUID getSchedule() { return (UUID) get(1); } /** * Setter for <code>public.schedule_update.actual_arrival</code>. */ public ScheduleUpdateRecord setActualArrival(Time value) { set(2, value); return this; } /** * Getter for <code>public.schedule_update.actual_arrival</code>. */ public Time getActualArrival() { return (Time) get(2); } /** * Setter for <code>public.schedule_update.actual_departure</code>. */ public ScheduleUpdateRecord setActualDeparture(Time value) { set(3, value); return this; } /** * Getter for <code>public.schedule_update.actual_departure</code>. */ public Time getActualDeparture() { return (Time) get(3); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<UUID> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record4 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row4<UUID, UUID, Time, Time> fieldsRow() { return (Row4) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row4<UUID, UUID, Time, Time> valuesRow() { return (Row4) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<UUID> field1() { return ScheduleUpdate.SCHEDULE_UPDATE.ID; } /** * {@inheritDoc} */ @Override public Field<UUID> field2() { return ScheduleUpdate.SCHEDULE_UPDATE.SCHEDULE; } /** * {@inheritDoc} */ @Override public Field<Time> field3() { return ScheduleUpdate.SCHEDULE_UPDATE.ACTUAL_ARRIVAL; } /** * {@inheritDoc} */ @Override public Field<Time> field4() { return ScheduleUpdate.SCHEDULE_UPDATE.ACTUAL_DEPARTURE; } /** * {@inheritDoc} */ @Override public UUID value1() { return getId(); } /** * {@inheritDoc} */ @Override public UUID value2() { return getSchedule(); } /** * {@inheritDoc} */ @Override public Time value3() { return getActualArrival(); } /** * {@inheritDoc} */ @Override public Time value4() { return getActualDeparture(); } /** * {@inheritDoc} */ @Override public ScheduleUpdateRecord value1(UUID value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public ScheduleUpdateRecord value2(UUID value) { setSchedule(value); return this; } /** * {@inheritDoc} */ @Override public ScheduleUpdateRecord value3(Time value) { setActualArrival(value); return this; } /** * {@inheritDoc} */ @Override public ScheduleUpdateRecord value4(Time value) { setActualDeparture(value); return this; } /** * {@inheritDoc} */ @Override public ScheduleUpdateRecord values(UUID value1, UUID value2, Time value3, Time value4) { value1(value1); value2(value2); value3(value3); value4(value4); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached ScheduleUpdateRecord */ public ScheduleUpdateRecord() { super(ScheduleUpdate.SCHEDULE_UPDATE); } /** * Create a detached, initialised ScheduleUpdateRecord */ public ScheduleUpdateRecord(UUID id, UUID schedule, Time actualArrival, Time actualDeparture) { super(ScheduleUpdate.SCHEDULE_UPDATE); set(0, id); set(1, schedule); set(2, actualArrival); set(3, actualDeparture); } }
package top.jasonkayzk.jutil; import org.junit.Test; import top.jasonkayzk.jutil.RandomUtils; /** * @author zk */ public class RandomUtilsTest { @Test public void testGetRandomInteger() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomInteger()); } } @Test public void testRandomIntegerByRange() { for (int i = 0; i < 100; ++i) { System.out.println(RandomUtils.getRandomInteger(0, 1000)); } } @Test public void testRandomIntegerByLength() { for (int i = 0; i < 10; ++i) { System.out.println(RandomUtils.getRandomInteger(i)); } } @Test public void testGetRandomString() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomString(i)); } } @Test public void testGetRandomText() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomText(32, 126, i)); } } @Test public void getRandomIntegerIgnoreRange() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomIntegerIgnoreRange(32, 126, new int[] {32, 100}, new int[] {102,126})); } } @Test public void getRandomStringWithoutSymbol() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomStringWithoutSymbol(i)); } } @Test public void getRandomTextIgnoreRange() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomTextIgnoreRange(32, 122, i, new int[] {32, 44})); } } @Test public void getRandomStringOnlyLetter() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomStringOnlyLetter(i)); } } @Test public void getRandomStringOnlyLowerCase() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomStringOnlyLowerCase(i)); } } @Test public void getRandomStringOnlyUpperCase() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomStringOnlyUpperCase(i)); } } @Test public void getRandomNumber() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomNumber(i)); } } @Test public void getRandomDouble() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomDouble()); } } @Test public void testGetRandomDouble() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomDouble(-5.0, 10.5)); } } @Test public void testGetRandomDouble1() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomDouble(-5.0, 10.5, 4)); } } @Test public void getRandomColor() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomColor(0.5)); } } @Test public void testGetRandomColor() { for (int i = 0; i < 10; i++) { System.out.println(RandomUtils.getRandomColor()); } } }
#!/bin/bash # Copyright # 2019 Johns Hopkins University (Author: Jesus Villalba) # Apache 2.0. # . ./cmd.sh . ./path.sh set -e stage=1 ngpu=4 config_file=default_config.sh resume=false interactive=false num_workers=8 lid_ipe=1 . parse_options.sh || exit 1; . $config_file . datapath.sh list_dir=data/train_lid_proc_audio_no_sil args="" if [ "$resume" == "true" ];then args="--resume" fi if [ "$interactive" == "true" ];then export cuda_cmd=run.pl fi lid_nnet_dir=exp/lid_nnets/lresnet34_lid_v1 # Network Training if [ $stage -le 1 ]; then train_exec=torch-train-resnet-xvec-from-wav.py mkdir -p $lid_nnet_dir/log $cuda_cmd \ --gpu $ngpu $lid_nnet_dir/log/train.log \ hyp_utils/conda_env.sh --conda-env $HYP_ENV --num-gpus $ngpu \ $train_exec --cfg conf/lresnet34_lid_v1.yaml \ --audio-path $list_dir/wav.scp \ --time-durs-file $list_dir/utt2dur \ --train-list $list_dir/lists_train_lid/train.scp \ --val-list $list_dir/lists_train_lid/val.scp \ --class-file $list_dir/lists_train_lid/class2int \ --iters-per-epoch $lid_ipe \ --num-workers $num_workers \ --num-gpus $ngpu \ --exp-path $lid_nnet_dir $args fi exit
//先定义一个主对象 var DropSelectMenu = { //存入顶部标题 top_titles : [], //存储下面的标题 bottom_titles : [], //记录顶上的索引 select_top : 0, //记录底部选中的记录,数组的底部个数 = 顶部数组的个数 select_bottom:[], //存储外部传过来的容器 menuContainer:null, //处理顶部标题的数据的函数 setTitleTop : function(titles){ this.top_titles = titles this.renderTopUI();//渲染 var self = this; $('#top_box li').click(function(){ if($(this).index() == 0){ self.selectReset() } //三角型的反转效果 if(self.select_top != 0 && self.select_top == $(this).index()&& $('.type_all').eq($(this).index()).css('display') != 'none'){ $('.type_all').eq($(this).index()).css('display','none') $("#top_box li img").eq($(this).index()).removeClass() return; } $("#top_box li img").removeClass() $("#top_box li img").eq($(this).index()).addClass('retate') $('.type_all').css('display','none') $('.type_all').eq($(this).index()).css('display','block') //记录顶部到底选择了哪一个 self.select_top = $(this).index() }) $('#top_box li').eq(0).click() //主动调用一次点击事件 }, renderTopUI:function(){ //制作点击头部标题 底下的容器 var top_box = '<ul id="top_box">'; var bot_html = '' $.each(this.top_titles, function(k,v) { top_box += '<li><span>'+v+'</span>&nbsp;<img src="img/sanjiao.png" style="width:10px;height:10px;"/></li>' bot_html += '<div class="type_all" style="widht:100%;overflow:hidden;"></div>' }); top_box += '</ul>' this.menuContainer.html(top_box+bot_html);//渲染顶部菜单 $("#top_box li img").eq(0).css('display','none') }, renderBottomUI:function(){ var self = this $.each(self.bottom_titles, function(k,v) { var html = '<div class="type_fen" id="type_bottom'+k+'" >'; var html_ = $('.type_all').eq(k) var reset = '<div class="type_res"><p class="select_reset" reset_index = '+k+'>恢复默认</p></div>' self.select_bottom = self.select_bottom.concat(v[0]) $.each(v, function(kk,vv) { html += '<span>'+vv.key+'</span>' }); html += '</div>' if(k == 0){ reset = '' } html_.html(html + reset) }); //页面记载完毕 $(function(){ var self = this $(".select_reset").click(function(){ var seletct_index = $(this).attr('reset_index') //alert($(this).attr('reset_index')) $($('.type_fen').eq(seletct_index).children('span')).css('color','#000') $($('.type_fen').eq(seletct_index).children('span').get(0)).css('color','red') DropSelectMenu.select_bottom[seletct_index] = DropSelectMenu.bottom_titles[seletct_index][0] //菜单还原 $("#top_box li span").eq(seletct_index).html(DropSelectMenu.top_titles[seletct_index]) $('.type_all').eq(seletct_index).css('display','none') }) }) }, //处理下面传过来的数据 setTitleBottom:function(titles,callback){ this.bottom_titles = titles; this.renderBottomUI();//渲染底下菜单 //console.log(self.select_bottom) this.selectReset()//调用重置函数 var that = this; $('.type_fen span').click(function(){ $("#top_box li img").removeClass() $('#type_bottom'+that.select_top+' span').css('color','#000') $('#type_bottom'+that.select_top+' span').eq($(this).index()).css('color','red') //将点击选中的记录到选中大数组里面去 var select_big = that.bottom_titles[that.select_top][$(this).index()] that.select_bottom[that.select_top] = select_big // 刚改顶部的标题 $("#top_box li span").eq(that.select_top).html(select_big.key) if(typeof callback === 'function'){//回调函数 callback(that.select_bottom) } $('.type_all').eq(that.select_top).css('display','none') }) }, selectReset:function(){//重置函数 var self = this; //点击当前项字体变红 $.each($(".type_fen"), function(k,v) { $($(this).children('span')).css('color','#000') $($(this).children('span').get(0)).css('color','red') }); //菜单内容还原 $.each(this.bottom_titles,function(k,v){ self.select_bottom[k] = v[0] }) //同上 $.each(this.top_titles,function(k,v){ $("#top_box li span").eq(k).html(v) }) } };
import java.io.*; public class Main { public static void main(String[] args) throws IOException { // using BufferedReader class to // read input BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); // array to store strings String lines[] = new String[5]; // take input and store it in array for (int i=0; i<5; i++) { lines[i] = br.readLine(); } // find line numbers of the word "Hello" for (int i=0; i<5; i++) { if (lines[i]. indexOf(“Hello”) >= 0) System.out.println("Line" + (i+1)); } } }
from opentrons import protocol_api import sys,json,timeit,time,math import importlib from queue import Queue sys.path.append("/var/lib/jupyter/notebooks") sys.path.append("/Users/chunxiao/Dropbox/python/aptitude_project/opentron") def _number_to_list(n,p): t=math.ceil(n/p) l=[] for i in range(t): if i ==t-1: l.append(n-p*(t-1)) else: l.append(p) return l class RobotClass: def __init__(self,simulate =True,**kwarg): self.status=RunLog() self.load_deck(simulate =simulate,**kwarg) def robot_initialize(self,simulate =False,**kwarg): """ connect, reset and home robot. create protocol variables to use. initialize is already built into load_deck(deck_plan). don't need to specifically use initialize. """ metadata = { 'protocolName': 'Saliva to DTT', } from opentrons import protocol_api import labwares.ams_labware as lw import sys # sys.path.append("/var/lib/jupyter/notebooks") # import labware_volume as lv # global protocol,lw self.lw=lw if simulate: import opentrons.simulate self.protocol = opentrons.simulate.get_protocol_api('2.1') time.sleep(3) else: import opentrons.execute # This returns the same kind of object - a ProtocolContext - that is passed into your protocol’s run function when you upload your protocol in the Opentrons App self.protocol = opentrons.execute.get_protocol_api('2.7') self.protocol.home() self.status.set_status("Robot status: Initialized") def assign_deck(self,tip_name = "opentrons_96_filtertiprack_200ul", tip_slots = ["7","8"],pip_name = "p300_multi",pip_location="left", trash_slots=[], src_name="None",src_slots = ["2"], dest_name = 'nest_96_wellplate_100ul_pcr_full_skirt', dest_slots =["3","4"],**kwarg): self.tip_name= tip_name self.tip_slots=tip_slots self.pip_name=pip_name self.pip_location=pip_location self.src_name=src_name self.src_slots=src_slots self.dest_name=dest_name self.dest_slots=dest_slots self.trash_slots=trash_slots if "temp_module_slot" in kwarg.keys(): self.temp_module_slot=kwarg["temp_module_slot"] self.tm_name=kwarg["tm_name"] def load_deck(self,**kwarg): """Single source, single destination""" self.robot_initialize(**kwarg) self.assign_deck(**kwarg) self.tips = [self.protocol.load_labware(self.tip_name, slot) for slot in self.tip_slots] if "tm" in kwarg.keys(): if len(kwarg["tm"])>1: self.tm_deck = self.protocol.load_module('temperature module', self.temp_module_slot[0]) self.tm_deck.start_set_temperature(10) try: self.tm_plate = self.tm_deck.load_labware(self.tm_name) except: if self.tm_name=="micronic_96_wellplate_1400ul" or self.tm_name=="None" or self.tm_name=="": self.tm_name = json.loads(self.lw.micronic_96_wellplate_1400ul) self.tm_plate = self.tm_deck.load_labware_from_definition(self.tm_name) try: self.src_plates = [self.protocol.load_labware(self.src_name,slot) for slot in self.src_slots] except: if self.src_name=="micronic_96_wellplate_1400ul" or self.src_name=="None" : self.src_name = json.loads(self.lw.micronic_96_wellplate_1400ul) self.src_plates = [self.protocol.load_labware_from_definition(self.src_name,slot) for slot in self.src_slots] self.src_tubes=[] for i in range(0,len(self.src_slots)): self.src_tubes += self.src_plates[i].rows()[0] self.dest_plates = [self.protocol.load_labware(self.dest_name, slot) for slot in self.dest_slots] self.dest_tubes=[] for i in range(0,len(self.dest_slots)): self.dest_tubes += self.dest_plates[i].rows()[0] multi_pipette = self.protocol.load_instrument(self.pip_name, self.pip_location, tip_racks=self.tips) self.multi_pipette=PipetteClass(multi_pipette,self.status) if len(self.trash_slots)>0: liquid_trash_rack=json.loads(self.lw.amsliquidtrash) self.trash = [self.protocol.load_labware_from_definition(liquid_trash_rack,slot) for slot in self.trash_slots] self.multi_pipette.pipette.trash_container=self.trash[0] class PipetteClass: def __init__(self,pipette,status): self.pipette=pipette self.status=status def _log_time(self,start_time,event = 'This step',print_log=1): stop = timeit.default_timer() run_time = stop - start_time unit = "sec" if run_time<60 else "min" run_time = run_time/60 if unit == "min" else run_time log ='{} takes {:.2} {}'.format(event,run_time,unit) self.status.set_status(log) # time.sleep(1) def set_p_param(self,**kwarg): self.p_param=kwarg def p_dispense(self,well,volume,disp=1,disp_bottom=3): """ Use pipette to perform multiple dispense volume: sample volume for each dispense disp: dispense times destination well by default is shift well by 1 row each time for disp times. """ def _next_well(w): """n_r_w: return the well in the next row. E.g. A1 well to B1 well n_c_w: return the well in the next column. E.g. A1 well to A2 well """ p=w.parent w_name = w._display_name.split(' ')[0] row = w_name[0] column = w_name[1:].strip() new_row = chr(ord(row) + 1) if ord(row)<ord("H") else chr(ord(row)) n_r_w= p[new_row+column] # new_column=str(int(column) + 1) if int(column)<12 else str(int(column)) n_c_w=p[row+new_column] return n_r_w , n_c_w for i in range(0,disp): # status="current dispensing well is {}".format(well) status = "Dispense {:.1f} uL to {}".format(volume,well) self.status.set_status(status) self.pipette.dispense(volume, well.bottom(disp_bottom)) well = _next_well(well)[1] def _change_tip(self,returnTip=0,get_time=1,**kwarg): st = timeit.default_timer() if returnTip: self.pipette.return_tip() st = timeit.default_timer() if get_time else st else: if self.pipette.trash_container.name=="ams_liquid_trash_tipbox": tr=self.pipette.trash_container.wells()[0] self.pipette.drop_tip(tr.bottom(40)) else: if self.pipette.name=="p20_multi_gen2": self.pipette.move_to(self.pipette.trash_container.rows()[0][0].bottom(60)) # Move pipette high to avoid touching anything self.pipette.drop_tip() self.pipette.move_to(self.pipette.trash_container.rows()[0][0].bottom(90)) # Move pipette high to avoid touching anything else: self.pipette.drop_tip() status=f"Tip dropped to {self.pipette.trash_container}" self.status.set_status(status) self._log_time(st,event = 'Drop tip') if get_time else 1 def _pickup_tip(self,tip_location=None,simulate=False,tip_presses=1,tip_press_increment=0.3,get_time=1,**kwarg): st = timeit.default_timer() if simulate: try: self.pipette.pick_up_tip(location=tip_location,presses=tip_presses, increment=tip_press_increment) self._log_time(st,event = f'Pick up tip from {tip_location}') if get_time else 1 except: pass else: if self.pipette.has_tip: pass else: self.pipette.pick_up_tip(location=tip_location,presses=tip_presses, increment=tip_press_increment) self._log_time(st,event = f'Pick up tip from {tip_location}') if get_time else 1 def p_transfer(self,s,d, b = 0,samp_vol= 50,air_vol = 0,mix=0, buffer_vol = 0,returnTip = False, chgTip=True,get_time = 1,disp=1,asp_bottom=2,disp_bottom=3,blowout = False,tip_presses = 1, tip_press_increment=0.3,reverse_vol=0,reverse_pip=0,simulate=False,asp_pausetime=0,disp_pausetime=0,**kwarg): """ s: source well d: destination well b: buffer well. dispense: how many times the same to be dispensed Transfer from source well: s to destination well""" #set up pipette parameter #pipette parameters asp_vol = (samp_vol*disp)*1.0 if reverse_pip: asp_vol+=reverse_vol total_vol = asp_vol+air_vol+buffer_vol self.asp_vol=total_vol start = timeit.default_timer() self._pickup_tip(simulate=simulate,**kwarg) st = timeit.default_timer() st = timeit.default_timer() if get_time else st if buffer_vol !=0: self.pipette.aspirate(buffer_vol, location = b.bottom(2)) self.pipette.air_gap(air_vol) total_vol +=air_vol self._log_time(st,event = 'Aspirate') if get_time else 1 st = timeit.default_timer() if get_time else 1 self.pipette.aspirate(asp_vol, s.bottom(asp_bottom)) time.sleep(asp_pausetime) status = "Aspirate {:.1f} uL from {}".format(asp_vol,s) self.status.set_status(status) self.pipette.air_gap(air_vol) self._log_time(st,event = 'Aspirate') if get_time else 1 st = timeit.default_timer() if get_time else 1 self.p_dispense(d,air_vol) if air_vol >0 else 1 self.p_dispense(d,samp_vol,disp=disp,disp_bottom=disp_bottom) time.sleep(disp_pausetime) # status = "Dispense {:.1f} uL to {}".format(samp_vol,d) # print (status) if blowout: self.pipette.blow_out() self._log_time(st,event = 'Dispense saliva') if get_time else 1 st = timeit.default_timer() if get_time else 1 if mix >0: if self.pipette.max_volume>100: self.pipette.flow_rate.dispense = 40 self.pipette.mix(mix,int(total_vol/2)) self.pipette.air_gap(air_vol) self._log_time(st,event = 'Mix saliva dtt') if get_time else 1 st = timeit.default_timer() if get_time else 1 stop = timeit.default_timer() if chgTip: self._change_tip(**kwarg) # if returnTip: # self.pipette.return_tip() # st = timeit.default_timer() if get_time else st # else: # # self.pipette.drop_tip(home_after=False,) # # self.pipette.home() # if self.pipette.trash_container.name=="ams_liquid_trash_tipbox": # tr=self.pipette.trash_container.wells()[0] # self.pipette.drop_tip(tr.bottom(45)) # else: # self.pipette.drop_tip() # status=f"Tip dropped to {self.pipette.trash_container}" # self.status.set_status(status) # self._log_time(st,event = 'Drop tip') if get_time else 1 # st = timeit.default_timer() if get_time else st def p_transfer_saliva(self,s,d, b = 0,samp_vol= 5,air_vol = 0,mix=0, buffer_vol = 0,returnTip = False, chgTip=True,get_time = 1,disp=1,asp_bottom=1,disp_bottom=0.5,blowout = False,tip_presses = 1, tip_press_increment=0.3,reverse_vol=0,reverse_pip=0,simulate=False,asp_pausetime=3,disp_pausetime=3,**kwarg): Debug_stepbystep=0 self._pickup_tip(simulate=simulate,**kwarg) st = timeit.default_timer() self.pipette.mix(2,samp_vol,s.bottom(asp_bottom)) self.pipette.aspirate(volume=samp_vol) status = "Aspirate {:.1f} uL from {}".format(samp_vol,s) self.status.set_status(status) time.sleep(asp_pausetime) if Debug_stepbystep: self.pipette.move_to(s.bottom(30)) val = input("Volumn match expectation?\n Press any keys to continue") self._log_time(st,event = 'Aspirate') st = timeit.default_timer() self.pipette.mix(1,10,d.bottom(disp_bottom)) self.pipette.dispense(volume=5) status = "Dispense {:.1f} uL to {}".format(samp_vol,d) self.status.set_status(status) time.sleep(disp_pausetime) if Debug_stepbystep: self.pipette.move_to(d.bottom(30)) val = input("Volumn match expectation?\n Press any keys to continue") self._log_time(st,event = 'Dispense') if chgTip: self._change_tip(**kwarg) class RunLog: def __init__(self): self.status="" self.statusQ=Queue() def set_status(self,s): self.status=s self.statusQ.put(s) print (s) class RunRobot(RobotClass): def __init__(self,**kwarg): self.robot=RobotClass(**kwarg) self.mp=self.robot.multi_pipette self.init_protocol(**kwarg) self.init_tm(**kwarg) self.statusQ=self.robot.status.statusQ def init_protocol(self,**kwarg): self.init_plate(**kwarg) self.init_well(**kwarg) self.init_pipette(**kwarg) def init_plate(self,src_plate=1,dest_plate=1,**kwarg): self.current_srcplate=src_plate-1 self.next_srcplate=self.current_srcplate+1 self.current_destplate=dest_plate-1 self.next_destplate=self.current_destplate+1 def init_well(self,start_tube=1,start_dest=1,**kwarg): start_tube=min(start_tube,12) start_dest=min(start_dest,12) self.current_srctube=start_tube-1 self.current_desttube=start_dest-1 def init_pipette(self,start_tip=1,**kwarg): start_tip=min(start_tip,12) self.mp.pipette.reset_tipracks() self.current_tip=start_tip-1 self.current_tip_rack=0 self.mp.pipette.starting_tip=self.robot.tips[self.current_tip_rack].rows()[0][start_tip-1] def init_tm(self,**kwarg): if "tm" in kwarg.keys(): if kwarg["tm"]=="src": self.robot.src_plates=[self.robot.tm_plate] elif kwarg["tm"]=="dest": self.robot.dest_plates=[self.robot.tm_plate] else: pass def set_temp(self,**kwarg): if "tm_temp" in kwarg.keys(): self.robot.tm_deck.set_temperature(int(kwarg["tm_temp"])) def deactivate_tm(self,**kwarg): self.robot.tm_deck.deactivate() def _set_transfer(self,**kwarg): self.sts=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube:self.current_srctube+1] self.dts=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube:self.current_desttube+1] def _update_aliquot(self,disp=1,**kwarg): self.next_srctube=self.current_srctube+1 self.next_desttube=self.current_desttube+disp def _set_replicate(self,replicates=1,**kwarg): self.sts=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube:self.current_srctube+1] self.dts=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube:self.current_desttube+replicates] def _update_replicate(self,replicates=1,**kwarg): self.next_srctube=self.current_srctube+1 self.next_desttube=self.current_desttube+replicates def _update_one(self,c,n): return n,n+1 def _update_tip(self): self.current_tip+=1 if self.current_tip>11: self.current_tip=0 self.current_tip_rack+=1 def _src_empty(self,trans_v,src_vol=150,**kwarg): pass # self.src_remaining_vol-=trans_v # print (f"{self.src_remaining_vol}ul remaining in {self.current_srctube}") # if self.src_remaining_vol>0: # return 0 # else: # return 1 def _aliquot(self,target_columns=1,**kwarg): disps=_number_to_list(target_columns,kwarg["disp"]) kwarg.update({"reverse_pip":1}) h=0 for disp in disps: h+=1 kwarg.pop("disp") kwarg.update({"chgTip":0}) kwarg.update({"disp":disp}) trans_v=(kwarg["disp"]*kwarg["samp_vol"])+(kwarg["reverse_pip"]*kwarg["reverse_vol"]) if self._src_empty(trans_v,**kwarg): self.current_srctube,self.next_srctube=self._update_one(self.current_srctube,self.next_srctube) self.src_remaining_vol=self.src_vol-trans_v self._set_transfer(disp=disp) for i, (s, d) in enumerate(zip(self.sts,self.dts)): if i==(len(self.dts)-1) and h==(len(disps)): kwarg.update({"chgTip":1}) self.mp.p_transfer(s,d,**kwarg) kwarg.update({"reverse_pip":0}) self._update_aliquot(disp=disp) self.current_desttube,self.next_desttube=self._update_one(self.current_desttube,self.next_desttube) def _aliquot_lamp_one_plate(self,**kwarg): self._aliquot(**kwarg) self.current_desttube=11 s=self.robot.src_plates[self.current_srcplate].rows()[0][11] d=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube] kwarg.update({"disp":1}) kwarg.update({"chgTip":1}) self.mp.p_transfer(s,d,**kwarg) def aliquot_dtt_p100(self,target_plates=1,**kwarg): self.src_vol=kwarg["src_vol"] self.src_remaining_vol=self.src_vol for p in range(0,target_plates): self._aliquot(**kwarg) self.current_destplate,self.next_destplate=self._update_one(self.current_destplate,self.next_destplate) self.current_desttube=kwarg["start_dest"]-1 def aliquot_lamp_p100(self,target_plates=1,**kwarg): self.src_vol=kwarg["src_vol"] self.src_remaining_vol=self.src_vol for p in range(0,target_plates): self._aliquot_lamp_one_plate(**kwarg) self.current_destplate,self.next_destplate=self._update_one(self.current_destplate,self.next_destplate) self.current_desttube=kwarg["start_dest"]-1 def sample_to_lamp(self,target_columns=1,rp4=0,**kwarg): target_columns=min(target_columns,11) for _ in range(0,target_columns): s=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube] d=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube] self.mp.p_transfer_saliva(s,d,**kwarg) if rp4: d=self.robot.dest_plates[self.current_destplate+1].rows()[0][self.current_desttube] self.mp.p_transfer_saliva(s,d,**kwarg) self.current_desttube+=1 self.current_srctube+=1 s=self.robot.src_plates[self.current_srcplate].rows()[0][11] d=self.robot.dest_plates[self.current_destplate].rows()[0][11] self.mp.p_transfer_saliva(s,d,**kwarg) if rp4: d=self.robot.dest_plates[self.current_destplate+1].rows()[0][11] self.mp.p_transfer_saliva(s,d,**kwarg) def _aliquot_p20_one_plate(self,target_columns=1,**kwarg): kwarg.update({"reverse_pip":1}) for i in range(0,target_columns): trans_v=(kwarg["disp"]*kwarg["samp_vol"])+(kwarg["reverse_pip"]*kwarg["reverse_vol"]) if self._src_empty(trans_v,**kwarg): self.current_srctube+=1 self.src_remaining_vol=self.src_vol-trans_v s=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube] d=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube] chgTip=1 if i==target_columns-1 else 0 kwarg.update({"chgTip":chgTip}) self.mp.p_transfer(s,d,**kwarg) kwarg.update({"reverse_pip":0}) self.current_desttube+=1 def _one_dtt_plate(self,target_columns=1,**kwarg): kwarg.update({"reverse_pip":1}) for i in range(0,target_columns): # trans_v=(kwarg["disp"]*kwarg["samp_vol"])+(kwarg["reverse_pip"]*kwarg["reverse_vol"]) # if self._src_empty(trans_v,**kwarg): # self.current_srctube+=1 # self.src_remaining_vol=self.src_vol-trans_v s=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube] d=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube] chgTip=0 kwarg.update({"chgTip":chgTip}) self.mp.p_transfer(s,d,**kwarg) kwarg.update({"reverse_pip":0}) self.current_desttube+=1 if target_columns==12: self.mp.pipette.drop_tip() else: s=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube] d=self.robot.dest_plates[self.current_destplate].rows()[0][11] chgTip=1 kwarg.update({"chgTip":chgTip}) self.mp.p_transfer(s,d,**kwarg) def aliquot_dtt_p20(self,target_plates=1,**kwarg): kwarg.update({"asp_pausetime":2}) kwarg.update({"disp_pausetime":2}) # self.src_vol=kwarg["src_vol"] # self.src_remaining_vol=self.src_vol for _ in range(0,target_plates): self._one_dtt_plate(**kwarg) self.current_destplate+=1 self.current_desttube=kwarg["start_dest"]-1 def _one_lamp_plate(self,well_list=[3,5],**kwarg): # self.src_vol=kwarg["src_vol"] # self.src_remaining_vol=self.src_vol self.current_srctube = well_list[0]-1 self.current_desttube=0 self._aliquot_p20_one_plate(**kwarg) # self.src_vol=kwarg["src_vol"] # self.src_remaining_vol=self.src_vol self.current_srctube = well_list[1]-1 self.current_desttube=11 kwarg["target_columns"]=1 self._aliquot_p20_one_plate(**kwarg) def aliquot_lamp_p20(self,n7_wells="3,5",rp4_wells="7,9",**kwarg): """It takes ource well position +1 string "n7, n7_nbc" as input All 4 source wells need to be on the same plate if rp4 position <1, then it will not aliquot rp4""" kwarg.update({"asp_pausetime":3}) kwarg.update({"disp_pausetime":3}) n7_l=[int(i) for i in n7_wells.split(",")] self._one_lamp_plate(n7_l,**kwarg) rp4_l=[int(i) for i in rp4_wells.split(",")] if rp4_l[0]>0: self.current_destplate+=1 self._one_lamp_plate(rp4_l,**kwarg) def _one_lamp_plate_noNBC(self,well_list=[3],target_columns=1,**kwarg): """This method add lamp mix to the target_columns. For the last control column, it will take tips from D to H, then dispense into A to E """ self.current_srctube = well_list[0]-1 s=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube] d=self.robot.dest_plates[self.current_destplate].rows()[0][11] t=self.robot.tips[self.current_tip_rack].rows()[3][self.current_tip] kwarg.update({"chgTip":1}) kwarg.update({"reverse_pip":1}) kwarg.update({"tip_location":t}) self.mp.p_transfer(s,d,**kwarg) self._update_tip() self.current_desttube=0 kwarg.update({"reverse_pip":1}) for i in range(0,target_columns): s=self.robot.src_plates[self.current_srcplate].rows()[0][self.current_srctube] d=self.robot.dest_plates[self.current_destplate].rows()[0][self.current_desttube] t=self.robot.tips[self.current_tip_rack].rows()[0][self.current_tip] kwarg.update({"tip_location":t}) chgTip=1 if i==target_columns-1 else 0 kwarg.update({"chgTip":chgTip}) self.mp.p_transfer(s,d,**kwarg) if chgTip: self._update_tip() kwarg.update({"reverse_pip":0}) self.current_desttube+=1 def _one_lamp_n7_rp4_p20_noNBC(self,n7_wells="3,5",rp4_wells="7,9",**kwarg): """Use 0,0 for RP4 wells if want to by pass RP4""" if not kwarg["simulate"]: kwarg.update({"asp_pausetime":3}) kwarg.update({"disp_pausetime":3}) n7_l=[int(i) for i in n7_wells.split(",")] self._one_lamp_plate_noNBC(n7_l,**kwarg) rp4_l=[int(i) for i in rp4_wells.split(",")] if rp4_l[0]>0: self.current_destplate+=1 self._one_lamp_plate_noNBC(rp4_l,**kwarg) def aliquot_lamp_p20_noNBC(self,target_plates=1,**kwarg): for _ in range(0,target_plates): self._one_lamp_n7_rp4_p20_noNBC(**kwarg) self.current_destplate+=1 self.current_desttube=kwarg["start_dest"]-1 # # # s="" # a=[int(i) for i in s.split(",")] # # r=RunRobot() # p=r.robot.multi_pipette.pipette # p # # trash.wells() # p.pick_up_tip() # drop_tip_location=p.trash_container.wells()[0].bottom(50) # p.move_to(drop_tip_location)
<gh_stars>10-100 // Copyright 2021 The Rode Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package v1alpha1_test import ( "flag" "log" "os" "testing" "github.com/brianvoe/gofakeit/v6" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/rode/rode/test/util" ) var ( fake = gofakeit.New(0) rode *util.RodeClientSet ) func TestMain(m *testing.M) { flag.Parse() if testing.Short() { log.Println("Skipping integration tests because the -short flag was passed") os.Exit(0) } var err error if rode, err = util.NewRodeClientSet(); err != nil { log.Fatal("Error creating Rode clients", err) } os.Exit(m.Run()) } func TestRode_v1alpha1(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "Rode v1alpha1 Suite") }
const languages = { 'C': 'Imperative', 'C++': 'Imperative', 'Java': 'Object-Oriented', 'Scala': 'Object-Oriented', 'Python': 'Object-Oriented', 'PHP': 'Object-Oriented', 'Go': 'Imperative/Functional', 'Ruby': 'Object-Oriented/Functional', ' JavaScript': 'Functional/Prototype-based', };
import { assert } from '@ember/debug'; import { assertPolymorphicType } from '@ember-data/store/-debug'; import type { StableRecordIdentifier } from '@ember-data/store/-private/ts-interfaces/identifier'; import type { ReplaceRelatedRecordOperation } from '../-operations'; import { isBelongsTo, isNew } from '../-utils'; import type { Graph } from '../index'; import { addToInverse, removeFromInverse } from './replace-related-records'; export default function replaceRelatedRecord(graph: Graph, op: ReplaceRelatedRecordOperation, isRemote = false) { const relationship = graph.get(op.record, op.field); assert( `You can only '${op.op}' on a belongsTo relationship. ${op.record.type}.${op.field} is a ${relationship.definition.kind}`, isBelongsTo(relationship) ); if (isRemote) { graph._addToTransaction(relationship); } const { definition, state } = relationship; const prop = isRemote ? 'remoteState' : 'localState'; const existingState: StableRecordIdentifier | null = relationship[prop]; /* case 1:1 ======== In a bi-directional graph with 1:1 edges, replacing a value results in up-to 4 discrete value transitions. If: A <-> B, C <-> D is the initial state, and: A <-> C, B, D is the final state then we would undergo the following 4 transitions. remove A from B add C to A remove C from D add A to C case 1:many =========== In a bi-directional graph with 1:Many edges, replacing a value results in up-to 3 discrete value transitions. If: A<->>B<<->D, C<<->D is the initial state (double arrows representing the many side) And: A<->>C<<->D, B<<->D is the final state Then we would undergo three transitions. remove A from B add C to A. add A to C case 1:? ======== In a uni-directional graph with 1:? edges (modeled in EmberData with `inverse:null`) with artificial (implicit) inverses, replacing a value results in up-to 3 discrete value transitions. This is because a 1:? relationship is effectively 1:many. If: A->B, C->B is the initial state And: A->C, C->B is the final state Then we would undergo three transitions. Remove A from B Add C to A Add A to C */ // nothing for us to do if (op.value === existingState) { // if we were empty before but now know we are empty this needs to be true state.hasReceivedData = true; // if this is a remote update we still sync if (isRemote) { const { localState } = relationship; // don't sync if localState is a new record and our canonicalState is null if ((localState && isNew(localState) && !existingState) || localState === existingState) { return; } relationship.localState = existingState; relationship.notifyBelongsToChange(); } return; } // remove this value from the inverse if required if (existingState) { removeFromInverse(graph, existingState, definition.inverseKey, op.record, isRemote); } // update value to the new value relationship[prop] = op.value; state.hasReceivedData = true; state.isEmpty = op.value === null; state.isStale = false; state.hasFailedLoadAttempt = false; if (op.value) { if (definition.type !== op.value.type) { assertPolymorphicType(relationship.identifier, definition, op.value, graph.store); graph.registerPolymorphicType(definition.type, op.value.type); } addToInverse(graph, op.value, definition.inverseKey, op.record, isRemote); } if (isRemote) { const { localState, remoteState } = relationship; if (localState && isNew(localState) && !remoteState) { return; } if (localState !== remoteState) { relationship.localState = remoteState; relationship.notifyBelongsToChange(); } } else { relationship.notifyBelongsToChange(); } }
/* * */ package net.community.chest.jfree.jfreechart.axis; import java.util.NoSuchElementException; import net.community.chest.dom.AbstractXmlValueStringInstantiator; import net.community.chest.lang.StringUtil; import org.jfree.chart.axis.AxisLocation; /** * <P>Copyright 2008 as per GPLv2</P> * * @author <NAME>. * @since Feb 5, 2009 3:51:21 PM */ public class AxisLocationValueStringInstantiator extends AbstractXmlValueStringInstantiator<AxisLocation> { public AxisLocationValueStringInstantiator () { super(AxisLocation.class); } /* * @see net.community.chest.convert.ValueStringInstantiator#convertInstance(java.lang.Object) */ @Override public String convertInstance (AxisLocation inst) throws Exception { if (null == inst) return null; final AxisLocationValue o=AxisLocationValue.fromLocation(inst); if (null == o) throw new NoSuchElementException("convertInstance(" + inst + ") unknown value"); return o.toString(); } /* * @see net.community.chest.convert.ValueStringInstantiator#newInstance(java.lang.String) */ @Override public AxisLocation newInstance (String v) throws Exception { final String s=StringUtil.getCleanStringValue(v); if ((null == s) || (s.length() <= 0)) return null; final AxisLocationValue o=AxisLocationValue.fromString(s); if (null == o) throw new NoSuchElementException("newInstance(" + s + ") unknown value"); return o.getLocation(); } public static final AxisLocationValueStringInstantiator DEFAULT=new AxisLocationValueStringInstantiator(); }
<reponame>Waltercito1/happy-camper-api class ItemsController < ApplicationController def index items = Item.all render json: items end def show item = Item.find(params[:id]) render json: item end def create item = Item.new(item_params) if item.save render json: item, status: :created, location: item else render json: item.errors, status: :unprocessable_entity end end def update item = Item.find(params[:id]) if item.update(item_params) render json: item else render json: item.errors, status: :unprocessable_entity end end def destroy item = Item.find(params[:id]) item.destroy end private def item_params params.require(:item).permit(:name, :description, :category_id) end end
package crash import ( "net/http" "os" "runtime/debug" "time" ) func RecoverLogger() func(next http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { defer func() { if r := recover(); r != nil { logPanicAsJSON(os.Stderr, r, time.Now(), debug.Stack()) http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError) } }() next.ServeHTTP(w, r) }) } }
<reponame>gastbob40/epimodo_bot import discord from src.utils.api_manager import APIManager from src.utils.embeds_manager import EmbedsManager from src.utils.permissions_manager import PermissionsManager from src.utils.log_manager import LogManager api_manager = APIManager() permissions_manager = PermissionsManager() async def report_message(client: discord.Client, reaction: discord.Reaction, user: discord.User): guild = reaction.message.guild state, results = permissions_manager.get_permissions(user, guild) if not state: return # Check lvl permissions if results == 0: return # Check role _, target_results = permissions_manager.get_permissions(reaction.message.author, guild) if target_results >= results: return await reaction.remove(user) reason = reaction.message.content api_manager.post_data('warns', target_id=reaction.message.author.id, author_id=user.id, server_id=guild.id, reason='Reported Message: ' + reason, ) await LogManager.complete_log(client, 'warns', user, guild, reason) try: await reaction.message.author.send( embed=EmbedsManager.sanction_embed('Reported Message', guild, reason) ) except Exception as e: print(e)
<filename>bind_rabbit_queue_exchange_command.go package messenger import "strings" type bindRabbitQueueExchangeCommand struct { channel Channel exchange Exchange queue Queue } func newBindRabbitQueueExchangeCommand(channel Channel, exchange Exchange, queue Queue) Command { return &bindRabbitQueueExchangeCommand{channel: channel, exchange: exchange, queue: queue} } func (c bindRabbitQueueExchangeCommand) Handle() error { if len(strings.TrimSpace(c.exchange.name)) <= 0 { // Binding on default exchange is not needed // and always done automatically return nil } return c.channel.BindQueueToExchange(c.exchange, c.queue) }
# Disable Flowcontrol setopt noflowcontrol stty -ixon # VIM always EDITOR=vim VISUAL=vim
<reponame>diegosiqueir4/wmss package de.wwu.wmss.junit; import static org.junit.Assert.assertEquals; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import org.junit.Test; import de.wwu.wmss.core.RequestParameter; import de.wwu.wmss.settings.Util; public class ExceptionsTest { private static String server = StartWMSS.server; private static int port = StartWMSS.port; private static String source = StartWMSS.source; public String getException(ArrayList<RequestParameter> parameters) { String result = ""; JSONObject jsonObject; String url = server+":"+port+"/wmss?"; for (int i = 0; i < parameters.size(); i++) { try { url = url + "&" + parameters.get(i).getRequest()+"="+ URLEncoder.encode(parameters.get(i).getValue(),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } catch (JSONException e) { e.printStackTrace(); } } System.out.println("\nRequest: " + url); try { jsonObject = Util.readJsonFromUrl(url); if(jsonObject !=null) { System.out.println("Code : "+jsonObject.get("code").toString()); System.out.println("Message: "+jsonObject.get("message").toString()); result = jsonObject.get("code").toString(); } } catch (JSONException | IOException e) { e.printStackTrace(); } return result; } @Test public void invalidDataSource() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", "invalid_data_source")); assertEquals("E0005", this.getException(parameters)); } @Test public void invalidRequestType() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "invalid_request_paramater")); assertEquals("E0002", this.getException(parameters)); } @Test public void invalidNoRequestType() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("solo", "true")); assertEquals("E0001", this.getException(parameters)); } @Test public void invalidScoreFormat() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "getScore")); parameters.add(new RequestParameter("identifier", "http://dbpedia.org/resource/Cello_Concerto_(Elgar)")); parameters.add(new RequestParameter("formatIdentifier", "invalid_score_format")); assertEquals("E0003", this.getException(parameters)); } @Test public void invalidTimeSignature() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("time", "invalid_time_signature")); assertEquals("E0004", this.getException(parameters)); } @Test public void invalidTimeSignature_PEA() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melody", "@x 8ABCDxDE")); assertEquals("E0004", this.getException(parameters)); } @Test public void invalidTimeSignature_PEA2() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melody", "@f/4 8ABCDxDE")); assertEquals("E0004", this.getException(parameters)); } @Test public void invalidMelodyEncoding() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melodyencoding", "invalid_melody_encoding")); assertEquals("E0006", this.getException(parameters)); } @Test public void invalidScoreIdentifier() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "GetScore")); parameters.add(new RequestParameter("source", source)); assertEquals("E0007", this.getException(parameters)); } @Test public void invalidTempoBPM() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("tempobeatsperminute", "invalid_bpm")); assertEquals("E0010", this.getException(parameters)); } @Test public void invalidTempoUnit() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("tempoBeatUnit", "invalid_tempo_unit")); assertEquals("E0011", this.getException(parameters)); } @Test public void invalidMelodyLength() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melody", "BA")); assertEquals("E0009", this.getException(parameters)); } @Test public void invalidMelodyNotes() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melody", "XPTO")); assertEquals("E0009", this.getException(parameters)); } @Test public void invalidDate() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("dateIssued", "invalid_date")); assertEquals("E0012", this.getException(parameters)); } @Test public void invalidKey() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("key", "invalid_key")); assertEquals("E0016", this.getException(parameters)); } @Test public void invalidKey_PEA() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melody", "$tF ,8AB'CDxDE")); assertEquals("E0016", this.getException(parameters)); } @Test public void invalidClef() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("clef", "X-9")); assertEquals("E0017", this.getException(parameters)); } @Test public void invalidClef_PEA() { ArrayList<RequestParameter> parameters = new ArrayList<RequestParameter>(); parameters.add(new RequestParameter("request", "ListScores")); parameters.add(new RequestParameter("source", source)); parameters.add(new RequestParameter("melody", "%wrong ,8AB'CDxD")); //assertEquals("E0017", this.getException(parameters)); } }
def knapsack(n, W, weights, values): # create a 2D array, dp[n+1][W+1], and fill with zeros dp = [[0 for x in range(W+1)] for x in range(n+1)]   #iterating over array rows for i in range(n+1): #iterating over array columns for w in range(W+1): if i==0 or w==0 : dp[i][w] = 0 elif weights[i-1] <= w: dp[i][w] = max(values[i-1] + dp[i-1][w-weights[i-1]], dp[i-1][w]) else: dp[i][w] = dp[i-1][w] return dp[n][W] # test print(knapsack(5, 8, [2, 3, 4, 5, 6], [2, 5, 6, 12, 9])) # Output: 20
package math; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.Arrays; import java.util.StringTokenizer; /** * * @author minchoba * 백준 1124번: 언더프라임 * * @see https://www.acmicpc.net/problem/1124/ * */ public class Boj1124 { private static final int INF = 100_001; public static void main(String[] args) throws Exception{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int A = Integer.parseInt(st.nextToken()); int B = Integer.parseInt(st.nextToken()); boolean[] prime = isPrime(); System.out.println(underPrime(A, B, prime)); // 결과 출력 } private static int underPrime(int from, int to, boolean[] primeList) { int res = 0; for(int i = from; i < to + 1; i++) { int idx = getPrimeListCounts(i, primeList); if(primeList[idx]) res++; // 약수의 개수를 소수로 갖는 수의 개수 (자신, 1 제외) } return res; } private static int getPrimeListCounts(int num, boolean[] arr) { int counts = 0, div = 2; while(num > 1) { if(num % div == 0) { counts++; num /= div; } else { while(true) { // 나눌 수가 소수가 될때까지 더함 div++; if(arr[div]) break; } } } return counts; } private static boolean[] isPrime() { boolean[] arr = new boolean[INF]; Arrays.fill(arr, true); arr[0] = arr[1] = false; for(int i = 2; i < INF; i++) { for(int j = i + i; j < INF; j += i) { if(!arr[j]) continue; arr[j] = false; } } return arr; } }
// health.rs use actix_web::{web, HttpResponse, Responder}; pub async fn get_health() -> impl Responder { HttpResponse::Ok().json("Service is healthy") } // users.rs use actix_web::{web, HttpResponse, Responder}; #[derive(Debug, serde::Serialize, serde::Deserialize)] struct User { id: u64, username: String, email: String, } pub fn init(cfg: &mut web::ServiceConfig) { cfg.service(web::resource("/users").route(web::post().to(register_user))); } async fn register_user(user: web::Json<User>) -> impl Responder { // Simulate user registration logic let registered_user = User { id: 1, username: user.username.clone(), email: user.email.clone(), }; HttpResponse::Created().json(registered_user) }
#!/usr/bin/env -S bash -euET -o pipefail -O inherit_errexit SCRIPT=$(readlink -f "$0") && cd $(dirname "$SCRIPT") # --- Script Init --- mkdir -p log rm -R -f log/* # --- Setup run dirs --- find output -type f -not -name '*summary-info*' -not -name '*.json' -exec rm -R -f {} + rm -R -f work/* mkdir work/kat/ rm -R -f /tmp/%FIFO_DIR%/ mkdir -p /tmp/%FIFO_DIR%/fifo/ mkfifo /tmp/%FIFO_DIR%/fifo/gul_P1 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P2 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P3 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P4 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P5 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P6 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P7 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P8 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P9 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P10 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P11 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P12 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P13 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P14 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P15 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P16 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P17 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P18 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P19 mkfifo /tmp/%FIFO_DIR%/fifo/gul_P20 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P1 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P1 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P2 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P2 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P3 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P3 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P4 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P4 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P5 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P5 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P6 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P6 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P7 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P7 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P8 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P8 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P9 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P9 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P10 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P10 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P11 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P11 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P12 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P12 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P13 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P13 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P14 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P14 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P15 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P15 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P16 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P16 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P17 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P17 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P18 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P18 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P19 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P19 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P20 mkfifo /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P20 # --- Do ground up loss computes --- summarycalctocsv < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P1 > work/kat/gul_S1_summarycalc_P1 & pid1=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P2 > work/kat/gul_S1_summarycalc_P2 & pid2=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P3 > work/kat/gul_S1_summarycalc_P3 & pid3=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P4 > work/kat/gul_S1_summarycalc_P4 & pid4=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P5 > work/kat/gul_S1_summarycalc_P5 & pid5=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P6 > work/kat/gul_S1_summarycalc_P6 & pid6=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P7 > work/kat/gul_S1_summarycalc_P7 & pid7=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P8 > work/kat/gul_S1_summarycalc_P8 & pid8=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P9 > work/kat/gul_S1_summarycalc_P9 & pid9=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P10 > work/kat/gul_S1_summarycalc_P10 & pid10=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P11 > work/kat/gul_S1_summarycalc_P11 & pid11=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P12 > work/kat/gul_S1_summarycalc_P12 & pid12=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P13 > work/kat/gul_S1_summarycalc_P13 & pid13=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P14 > work/kat/gul_S1_summarycalc_P14 & pid14=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P15 > work/kat/gul_S1_summarycalc_P15 & pid15=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P16 > work/kat/gul_S1_summarycalc_P16 & pid16=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P17 > work/kat/gul_S1_summarycalc_P17 & pid17=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P18 > work/kat/gul_S1_summarycalc_P18 & pid18=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P19 > work/kat/gul_S1_summarycalc_P19 & pid19=$! summarycalctocsv -s < /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P20 > work/kat/gul_S1_summarycalc_P20 & pid20=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P1 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P1 > /dev/null & pid21=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P2 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P2 > /dev/null & pid22=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P3 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P3 > /dev/null & pid23=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P4 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P4 > /dev/null & pid24=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P5 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P5 > /dev/null & pid25=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P6 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P6 > /dev/null & pid26=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P7 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P7 > /dev/null & pid27=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P8 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P8 > /dev/null & pid28=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P9 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P9 > /dev/null & pid29=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P10 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P10 > /dev/null & pid30=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P11 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P11 > /dev/null & pid31=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P12 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P12 > /dev/null & pid32=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P13 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P13 > /dev/null & pid33=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P14 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P14 > /dev/null & pid34=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P15 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P15 > /dev/null & pid35=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P16 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P16 > /dev/null & pid36=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P17 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P17 > /dev/null & pid37=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P18 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P18 > /dev/null & pid38=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P19 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P19 > /dev/null & pid39=$! tee < /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P20 /tmp/%FIFO_DIR%/fifo/gul_S1_summarycalc_P20 > /dev/null & pid40=$! summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P1 < /tmp/%FIFO_DIR%/fifo/gul_P1 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P2 < /tmp/%FIFO_DIR%/fifo/gul_P2 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P3 < /tmp/%FIFO_DIR%/fifo/gul_P3 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P4 < /tmp/%FIFO_DIR%/fifo/gul_P4 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P5 < /tmp/%FIFO_DIR%/fifo/gul_P5 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P6 < /tmp/%FIFO_DIR%/fifo/gul_P6 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P7 < /tmp/%FIFO_DIR%/fifo/gul_P7 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P8 < /tmp/%FIFO_DIR%/fifo/gul_P8 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P9 < /tmp/%FIFO_DIR%/fifo/gul_P9 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P10 < /tmp/%FIFO_DIR%/fifo/gul_P10 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P11 < /tmp/%FIFO_DIR%/fifo/gul_P11 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P12 < /tmp/%FIFO_DIR%/fifo/gul_P12 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P13 < /tmp/%FIFO_DIR%/fifo/gul_P13 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P14 < /tmp/%FIFO_DIR%/fifo/gul_P14 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P15 < /tmp/%FIFO_DIR%/fifo/gul_P15 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P16 < /tmp/%FIFO_DIR%/fifo/gul_P16 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P17 < /tmp/%FIFO_DIR%/fifo/gul_P17 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P18 < /tmp/%FIFO_DIR%/fifo/gul_P18 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P19 < /tmp/%FIFO_DIR%/fifo/gul_P19 & summarycalc -m -i -1 /tmp/%FIFO_DIR%/fifo/gul_S1_summary_P20 < /tmp/%FIFO_DIR%/fifo/gul_P20 & eve 1 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P1 & eve 2 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P2 & eve 3 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P3 & eve 4 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P4 & eve 5 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P5 & eve 6 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P6 & eve 7 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P7 & eve 8 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P8 & eve 9 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P9 & eve 10 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P10 & eve 11 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P11 & eve 12 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P12 & eve 13 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P13 & eve 14 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P14 & eve 15 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P15 & eve 16 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P16 & eve 17 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P17 & eve 18 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P18 & eve 19 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P19 & eve 20 20 | getmodel | gulcalc -S100 -L100 -r -a1 -i - > /tmp/%FIFO_DIR%/fifo/gul_P20 & wait $pid1 $pid2 $pid3 $pid4 $pid5 $pid6 $pid7 $pid8 $pid9 $pid10 $pid11 $pid12 $pid13 $pid14 $pid15 $pid16 $pid17 $pid18 $pid19 $pid20 $pid21 $pid22 $pid23 $pid24 $pid25 $pid26 $pid27 $pid28 $pid29 $pid30 $pid31 $pid32 $pid33 $pid34 $pid35 $pid36 $pid37 $pid38 $pid39 $pid40 # --- Do ground up loss kats --- kat work/kat/gul_S1_summarycalc_P1 work/kat/gul_S1_summarycalc_P2 work/kat/gul_S1_summarycalc_P3 work/kat/gul_S1_summarycalc_P4 work/kat/gul_S1_summarycalc_P5 work/kat/gul_S1_summarycalc_P6 work/kat/gul_S1_summarycalc_P7 work/kat/gul_S1_summarycalc_P8 work/kat/gul_S1_summarycalc_P9 work/kat/gul_S1_summarycalc_P10 work/kat/gul_S1_summarycalc_P11 work/kat/gul_S1_summarycalc_P12 work/kat/gul_S1_summarycalc_P13 work/kat/gul_S1_summarycalc_P14 work/kat/gul_S1_summarycalc_P15 work/kat/gul_S1_summarycalc_P16 work/kat/gul_S1_summarycalc_P17 work/kat/gul_S1_summarycalc_P18 work/kat/gul_S1_summarycalc_P19 work/kat/gul_S1_summarycalc_P20 > output/gul_S1_summarycalc.csv & kpid1=$! wait $kpid1 rm -R -f work/* rm -R -f /tmp/%FIFO_DIR%/
TERMUX_PKG_HOMEPAGE=http://joe-editor.sourceforge.net TERMUX_PKG_DESCRIPTION="Wordstar like text editor" TERMUX_PKG_LICENSE="GPL-2.0" TERMUX_PKG_DEPENDS="ncurses, libutil" TERMUX_PKG_CONFLICTS="jupp" TERMUX_PKG_VERSION=4.6 TERMUX_PKG_SHA256=495a0a61f26404070fe8a719d80406dc7f337623788e445b92a9f6de512ab9de TERMUX_PKG_SRCURL=https://sourceforge.net/projects/joe-editor/files/JOE%20sources/joe-${TERMUX_PKG_VERSION}/joe-${TERMUX_PKG_VERSION}.tar.gz TERMUX_PKG_EXTRA_CONFIGURE_ARGS="--disable-termcap"
package com.lightbend.hedgehog.testkit import hedgehog.core.{CoverPercentage, SuccessCount} import hedgehog.runner.Test import hedgehog.{Gen, Property} /** * These are values for binomial confidence intervals using a 99.99999% confidence level that were computed using this * <a href="https://statpages.info/confint.html">calculator</a>. */ trait Probabilities { val TestCount: SuccessCount = 10000 val OneToOne: CoverPercentage = 47.33 val OneToTwo: CoverPercentage = 30.85 val TwoToOne: CoverPercentage = 64.11 val OneToThree: CoverPercentage = 22.74 val ThreeToOne: CoverPercentage = 72.64 val TwoToThree: CoverPercentage = 37.41 val ThreeToTwo: CoverPercentage = 57.37 val TwentyFiveToOne: CoverPercentage = 2.91 // These are oddly specific but that is what the percentages are for Options. val TwoToOneHundredAndOne: CoverPercentage = 1.29 val OneHundredAndOneToTwo: CoverPercentage = 97.21 val OneToTenThousand: CoverPercentage = 99.80 val BirthdayDays: Short = 365 val BirthdayPeople: Short = 23 val BirthdayMatch: CoverPercentage = 47.38 val BirthdayNoMatch: CoverPercentage = 47.28 implicit class GeneratorProbabilityTests[A](tests: GeneratorTests[A]) { def addProbabilities(name: String => String, property: Property): GeneratorTests[A] = addProbabilitiesWithConfig(name, property, identity) def addProbabilitiesWithConfig( name: String => String, property: Property, configure: Test => Test ): GeneratorTests[A] = tests.addPropWithConfig(name, property, t => configure(t.withTests(TestCount))) def addGenProbabilities(name: String => String, property: Gen[A] => Property): GeneratorTests[A] = addGenProbabilitiesWithConfig(name, property, identity) def addGenProbabilitiesWithConfig( name: String => String, property: Gen[A] => Property, configure: Test => Test ): GeneratorTests[A] = tests.addGenPropWithConfig(name, property, t => configure(t.withTests(TestCount))) } }
#!/usr/bin/env bash PARALLELISM=10 curl --silent -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.8/install.sh | bash 2>&1 export NVM_DIR="/home/nvm/.nvm" source ${NVM_DIR}/nvm.sh read -r -d '' VERSIONS << EOM 9.4.0 9.3.0 9.2.1 9.1.0 9.0.0 8.9.4 8.8.1 8.7.0 8.6.0 8.5.0 8.4.0 8.3.0 8.2.1 8.1.4 8.0.0 6.12.3 6.11.5 6.10.3 6.9.5 6.8.1 6.7.0 6.6.0 6.5.0 6.4.0 6.3.1 6.2.2 6.1.0 6.0.0 EOM install_version() { local version=$1 # redirect stderr to /dev/null to not show progress bar nvm install ${version} 2> /dev/null } parallel=0 for version in ${VERSIONS}; do install_version ${version} & parallel=$(($parallel + 1)) if [ ${parallel} -eq ${PARALLELISM} ]; then wait parallel=0 fi done wait nvm cache clear nvm use 6 curl -L https://unpkg.com/@pnpm/self-installer | \ PNPM_VERSION=1.31.1 PNPM_DEST=/home/nvm/pnpm/lib/node_modules/pnpm PNPM_BIN_DEST=/usr/bin node
<reponame>JustinBreneman/Warframe_relics<gh_stars>0 class WarframeRelics::CLI def call puts "Welcome to the Warframe Relic scraping interface!" puts "Now retrieving Relic information" WarframeRelics::Relics.get_all_relics WarframeRelics::Relics.sort_relics input = " " until input == 'exit' puts " " puts "I can provide a list of relics: vaulted, available, or all." puts "I can also provide information on a specific relic." puts "Type exit at any time to leave." puts "What information would you like?" input = gets.chomp puts " " if input.downcase == 'vaulted' puts "---" WarframeRelics::Relics.vaulted.each {|relic| puts "#{relic.name}"} puts "---" elsif input.downcase == 'available' puts "---" WarframeRelics::Relics.un_vaulted.each {|relic| puts "#{relic.name}"} puts "---" elsif input.downcase == 'all' puts "---" puts "Vaulted:" puts " " WarframeRelics::Relics.vaulted.each {|relic| puts "#{relic.name}"} puts " " puts "Available:" puts " " WarframeRelics::Relics.un_vaulted.each {|relic| puts "#{relic.name}"} puts "---" elsif input.downcase == 'exit' puts "Goodbye." WarframeRelics::Relics.clear elsif WarframeRelics::Relics.get_drop_table(input) != nil puts "---" WarframeRelics::Relics.get_drop_table(input).each {|item| puts "#{item}"} puts "---" else puts " " puts "That is not a valid list or relic." puts "Please make a new selection" end end end end
import {createSelector, createStructuredSelector} from 'reselect'; import {Map} from 'immutable' export const routingSelector = createSelector((state) => state, (state = Map()) => { return state.get('routing', {}).locationBeforeTransitions || {}; }); export const routingStructuredSelector = createStructuredSelector({routing: routingSelector}); export const locationSelect = (state = Map()) => state.get('router').location || {} export const locationSelector = createStructuredSelector({location: locationSelect}) export default { routingSelector, routingStructuredSelector, };
<reponame>zarina494/fisrt_git_lesson list = [1,2,3,4] test_list = list1 test_list.reverse() print(list)
//##################################################################### // Copyright 2011. // This file is part of PhysBAM whose distribution is governed by the license contained in the accompanying file PHYSBAM_COPYRIGHT.txt. //##################################################################### #include <PhysBAM_Tools/Grids_Uniform/GRID.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_CELL.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_FACE.h> #include <PhysBAM_Tools/Grids_Uniform/UNIFORM_GRID_ITERATOR_NODE.h> #include <PhysBAM_Tools/Parallel_Computation/BOUNDARY_MPI.h> #include <PhysBAM_Tools/Parallel_Computation/MPI_UNIFORM_GRID.h> #include <PhysBAM_Tools/Vectors/VECTOR_3D.h> #include <PhysBAM_Dynamics/Incompressible_Flows/DIFFUSION.h> #define DEBUG 1 using namespace PhysBAM; template<class T_GRID,class T2> DIFFUSION_UNIFORM<T_GRID,T2>:: DIFFUSION_UNIFORM(T_MPI_GRID* mpi_grid_input) :diffuse_weights(false),diffuse_errors(false),mpi_grid(mpi_grid_input),num_diffusion_iterations(10),evenodd(0),evenodd_cell(0),max_value(0),min_value(0),hard_max(0),hard_min(-1) { for(int i=1;i<=TV::dimension;i++){solid_walls(i)(1)=true;solid_walls(i)(2)=true;} if(mpi_grid) mpi_grid->Initialize(solid_walls); for(int i=1;i<=TV::dimension;i++){mpi_boundary(i)(1)=!solid_walls(i)(1);mpi_boundary(i)(2)=!solid_walls(i)(2);} } template<class T_GRID,class T2> DIFFUSION_UNIFORM<T_GRID,T2>:: ~DIFFUSION_UNIFORM() { } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Cell_Diffusion_Value_Helper(FACE_ITERATOR& iterator,T_ARRAYS_T2& Z,ARRAY<bool,TV_INT>* inside) { if(inside && !((*inside)(iterator.First_Cell_Index()) && (*inside)(iterator.Second_Cell_Index()))) return; T2 Z_diff=(Z(iterator.First_Cell_Index())-Z(iterator.Second_Cell_Index()));Z_diff*=0.5; Z(iterator.Second_Cell_Index())+=Z_diff;Z(iterator.First_Cell_Index())-=Z_diff; } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Cell_Diffusion_Sum_Helper(FACE_ITERATOR& iterator,ARRAY<T,TV_INT>& sum_jc_cell,T_ARRAYS_T2& Z,ARRAY<bool,TV_INT>* inside) { if(inside && !((*inside)(iterator.First_Cell_Index()) && (*inside)(iterator.Second_Cell_Index()))) return; T wjc_diff=(sum_jc_cell(iterator.First_Cell_Index())-sum_jc_cell(iterator.Second_Cell_Index()))/(T)2.; T Z_diff=wjc_diff>0?wjc_diff/sum_jc_cell(iterator.First_Cell_Index()):wjc_diff/sum_jc_cell(iterator.Second_Cell_Index()); sum_jc_cell(iterator.Second_Cell_Index())+=wjc_diff;sum_jc_cell(iterator.First_Cell_Index())-=wjc_diff; T2 local_Z=wjc_diff>0?Z(iterator.First_Cell_Index()):Z(iterator.Second_Cell_Index()); Z(iterator.Second_Cell_Index())+=local_Z*(Z_diff);Z(iterator.First_Cell_Index())-=local_Z*(Z_diff); } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Cell_Diffusion_Error_Helper(FACE_ITERATOR& iterator,ARRAY<T,TV_INT>& error_cell,T_ARRAYS_T2& Z,ARRAY<bool,TV_INT>* inside) { if(inside && !((*inside)(iterator.First_Cell_Index()) && (*inside)(iterator.Second_Cell_Index()))) return; T wjc_diff=(error_cell(iterator.First_Cell_Index())-error_cell(iterator.Second_Cell_Index()))/(T)2.; if(hard_min>=0 && Z(iterator.Second_Cell_Index())-wjc_diff<hard_min) wjc_diff=Z(iterator.Second_Cell_Index())-hard_min; else if(hard_min>=0 && Z(iterator.First_Cell_Index())+wjc_diff<hard_min) wjc_diff=hard_min-Z(iterator.First_Cell_Index()); if(hard_max && Z(iterator.Second_Cell_Index())-wjc_diff>hard_max && Z(iterator.First_Cell_Index())+wjc_diff>hard_max){ if(Z(iterator.Second_Cell_Index())<hard_max || Z(iterator.First_Cell_Index())<hard_max){ if(Z(iterator.Second_Cell_Index())<hard_max) wjc_diff=Z(iterator.Second_Cell_Index())-hard_max; else if(Z(iterator.First_Cell_Index())<hard_max) wjc_diff=hard_max-Z(iterator.First_Cell_Index()); error_cell(iterator.Second_Cell_Index())+=wjc_diff;error_cell(iterator.First_Cell_Index())-=wjc_diff; Z(iterator.Second_Cell_Index())-=wjc_diff;Z(iterator.First_Cell_Index())+=wjc_diff; wjc_diff=(error_cell(iterator.First_Cell_Index())-error_cell(iterator.Second_Cell_Index()))/(T)2.;}} else if(hard_max && Z(iterator.Second_Cell_Index())-wjc_diff>hard_max) wjc_diff=Z(iterator.Second_Cell_Index())-hard_max; else if(hard_max && Z(iterator.First_Cell_Index())+wjc_diff>hard_max) wjc_diff=hard_max-Z(iterator.First_Cell_Index()); error_cell(iterator.Second_Cell_Index())+=wjc_diff;error_cell(iterator.First_Cell_Index())-=wjc_diff; Z(iterator.Second_Cell_Index())-=wjc_diff;Z(iterator.First_Cell_Index())+=wjc_diff; if(max_value){ if(Z(iterator.First_Cell_Index())>max_value) error_cell(iterator.First_Cell_Index())=max_value-Z(iterator.First_Cell_Index()); else if(Z(iterator.First_Cell_Index())<min_value) error_cell(iterator.First_Cell_Index())=min_value-Z(iterator.First_Cell_Index()); else error_cell(iterator.First_Cell_Index())=0; if(Z(iterator.Second_Cell_Index())>max_value) error_cell(iterator.Second_Cell_Index())=max_value-Z(iterator.Second_Cell_Index()); else if(Z(iterator.Second_Cell_Index())<min_value) error_cell(iterator.Second_Cell_Index())=min_value-Z(iterator.Second_Cell_Index()); else error_cell(iterator.Second_Cell_Index())=0;} } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Cell_Diffusion_Helper(FACE_ITERATOR& iterator,ARRAY<T,TV_INT>* sum_jc_cell,T_ARRAYS_T2& Z,ARRAY<bool,TV_INT>* inside) { if(!sum_jc_cell) Cell_Diffusion_Value_Helper(iterator,Z,inside); else if(diffuse_weights) Cell_Diffusion_Sum_Helper(iterator,*sum_jc_cell,Z,inside); else if(diffuse_errors) Cell_Diffusion_Error_Helper(iterator,*sum_jc_cell,Z,inside); else PHYSBAM_FATAL_ERROR(); } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Face_Diffusion_Sum_Helper(const GRID<TV>& grid,FACE_INDEX<TV::dimension>& first_face_index,FACE_INDEX<TV::dimension>& second_face_index,ARRAY<T,FACE_INDEX<TV::dimension> >& sum_jc,T_FACE_ARRAYS_SCALAR& Z,ARRAY<bool,FACE_INDEX<TV::dimension> >* inside) { if(inside && !((*inside)(first_face_index) && (*inside)(second_face_index))) return; if(sum_jc(first_face_index)==0 && sum_jc(second_face_index)==0) return; T wjc_diff=(sum_jc(first_face_index)-sum_jc(second_face_index))/(T)2.; T Z_diff=wjc_diff>0?wjc_diff/sum_jc(first_face_index):wjc_diff/sum_jc(second_face_index); sum_jc(second_face_index)+=wjc_diff;sum_jc(first_face_index)-=wjc_diff; T local_Z=wjc_diff>0?Z(first_face_index):Z(second_face_index); Z(second_face_index)+=local_Z*(Z_diff);Z(first_face_index)-=local_Z*(Z_diff); } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Face_Diffusion_Helper(FACE_ITERATOR& iterator,int axis,ARRAY<T,FACE_INDEX<TV::dimension> >* sum_jc,T_FACE_ARRAYS_SCALAR& Z,ARRAY<bool,FACE_INDEX<TV::dimension> >* inside) { assert(axis!=iterator.Axis()); FACE_INDEX<TV::dimension> first_face_index=FACE_INDEX<TV::dimension>(axis,iterator.First_Cell_Index()),second_face_index=FACE_INDEX<TV::dimension>(axis,iterator.Second_Cell_Index()); assert(diffuse_weights);Face_Diffusion_Sum_Helper(iterator.grid,first_face_index,second_face_index,*sum_jc,Z,inside); } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Face_Diffusion_Helper(CELL_ITERATOR& iterator,int axis,ARRAY<T,FACE_INDEX<TV::dimension> >* sum_jc,T_FACE_ARRAYS_SCALAR& Z,ARRAY<bool,FACE_INDEX<TV::dimension> >* inside) { FACE_INDEX<TV::dimension> first_face_index=FACE_INDEX<TV::dimension>(axis,iterator.First_Face_Index(axis)),second_face_index=FACE_INDEX<TV::dimension>(axis,iterator.Second_Face_Index(axis)); assert(diffuse_weights);Face_Diffusion_Sum_Helper(iterator.grid,first_face_index,second_face_index,*sum_jc,Z,inside); } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Cell_Diffusion(const T_GRID& grid,T_ARRAYS_T2& Z,T_BOUNDARY_T2& boundary,ARRAY<T,TV_INT>* sum_jc_cell,BOUNDARY_UNIFORM<T_GRID,T>* boundary_sum,ARRAY<bool,TV_INT>* inside) { T_ARRAYS_T2 Z_ghost_local(grid.Domain_Indices(1)); ARRAY<T,TV_INT>* sum_jc_cell_ghost=0;if(mpi_grid && sum_jc_cell) sum_jc_cell_ghost=new ARRAY<T,TV_INT>(grid.Domain_Indices(1)); for(int iter=1;iter<=num_diffusion_iterations;iter++){ for(int axis=1;axis<=TV::dimension;axis++){ if(evenodd_cell==0){ RANGE<TV_INT> domain=grid.Domain_Indices();domain.max_corner-=TV_INT::All_Ones_Vector();domain.min_corner+=TV_INT::All_Ones_Vector();domain.max_corner(axis)+=1; for(FACE_ITERATOR iterator(grid,domain,axis);iterator.Valid();iterator.Next()) Cell_Diffusion_Helper(iterator,sum_jc_cell,Z,inside);} else{ ARRAY<FACE_ITERATOR*> faces; RANGE<TV_INT> domain=grid.Domain_Indices();domain.max_corner-=TV_INT::All_Ones_Vector();domain.min_corner+=TV_INT::All_Ones_Vector();domain.max_corner(axis)+=1; for(FACE_ITERATOR iterator(grid,domain,axis);iterator.Valid();iterator.Next()) faces.Append(new FACE_ITERATOR(iterator)); for(int i=faces.m;i>=1;i--){FACE_ITERATOR& iterator=*faces(i);Cell_Diffusion_Helper(iterator,sum_jc_cell,Z,inside);} for(int i=faces.m;i>=1;i--) delete faces(i);} if(mpi_grid){ boundary.Fill_Ghost_Cells(grid,Z,Z_ghost_local,0,0,1); //Sync for mpi boundaries if(sum_jc_cell) boundary_sum->Fill_Ghost_Cells(grid,*sum_jc_cell,*sum_jc_cell_ghost,0,0,1); //Sync for mpi boundaries for(int side=1;side<=2;side++) if(mpi_boundary(axis)(side)){ if(evenodd_cell==0){ for(FACE_ITERATOR iterator(grid,0,GRID<TV>::BOUNDARY_REGION,2*(axis-1)+side);iterator.Valid();iterator.Next()) Cell_Diffusion_Helper(iterator,sum_jc_cell_ghost,Z_ghost_local,inside);} else{ ARRAY<FACE_ITERATOR*> faces; for(FACE_ITERATOR iterator(grid,0,GRID<TV>::BOUNDARY_REGION,2*(axis-1)+side);iterator.Valid();iterator.Next()) faces.Append(new FACE_ITERATOR(iterator)); for(int i=faces.m;i>=1;i--){FACE_ITERATOR& iterator=*faces(i);Cell_Diffusion_Helper(iterator,sum_jc_cell_ghost,Z_ghost_local,inside);} for(int i=faces.m;i>=1;i--) delete faces(i);}} for(CELL_ITERATOR iterator(grid);iterator.Valid();iterator.Next()) Z(iterator.Cell_Index())=Z_ghost_local(iterator.Cell_Index()); for(CELL_ITERATOR iterator(grid);iterator.Valid();iterator.Next()) (*sum_jc_cell)(iterator.Cell_Index())=(*sum_jc_cell_ghost)(iterator.Cell_Index());}} evenodd_cell++;evenodd_cell=evenodd_cell%2;} delete sum_jc_cell_ghost; } template<class T_GRID,class T2> void DIFFUSION_UNIFORM<T_GRID,T2>:: Face_Diffusion(const T_GRID& grid,ARRAY<T,FACE_INDEX<TV::dimension> >* sum_jc,T_FACE_ARRAYS_SCALAR& Z,T_BOUNDARY& boundary,BOUNDARY_UNIFORM<T_GRID,T>* boundary_sum,ARRAY<bool,FACE_INDEX<TV::dimension> >* inside) { T_FACE_ARRAYS_SCALAR Z_ghost_local(grid,1); ARRAY<T,FACE_INDEX<TV::dimension> >* sum_jc_ghost=0;if(sum_jc) sum_jc_ghost=new ARRAY<T,FACE_INDEX<TV::dimension> >(grid,1); for(int iter=1;iter<=num_diffusion_iterations;iter++){ for(int axis=1;axis<=TV::dimension;axis++){ if(evenodd==0){ for(int axis2=1;axis2<=TV::dimension;axis2++){if(axis==axis2) continue;//handled above RANGE<TV_INT> domain=grid.Domain_Indices(); domain.max_corner(axis)+=1;domain.min_corner(axis2)+=1; for(FACE_ITERATOR iterator(grid,domain,axis2);iterator.Valid();iterator.Next()) Face_Diffusion_Helper(iterator,axis,sum_jc,Z,inside);} RANGE<TV_INT> domain=grid.Domain_Indices(); if((mpi_grid && mpi_boundary(axis)(1))) domain.min_corner(axis)+=1; if((mpi_grid && mpi_boundary(axis)(2))) domain.max_corner(axis)-=1; for(CELL_ITERATOR iterator(grid,domain);iterator.Valid();iterator.Next()) Face_Diffusion_Helper(iterator,axis,sum_jc,Z,inside);} else{ ARRAY<FACE_ITERATOR*> faces;ARRAY<CELL_ITERATOR*> cells; for(int axis2=1;axis2<=TV::dimension;axis2++){if(axis==axis2) continue;//handled above RANGE<TV_INT> domain=grid.Domain_Indices(); domain.max_corner(axis)+=1;domain.min_corner(axis2)+=1; for(FACE_ITERATOR iterator(grid,domain,axis2);iterator.Valid();iterator.Next()) faces.Append(new FACE_ITERATOR(iterator));} RANGE<TV_INT> domain=grid.Domain_Indices(); if((mpi_grid && mpi_boundary(axis)(1))) domain.min_corner(axis)+=1; if((mpi_grid && mpi_boundary(axis)(2))) domain.max_corner(axis)-=1; for(CELL_ITERATOR iterator(grid,domain);iterator.Valid();iterator.Next()) cells.Append(new CELL_ITERATOR(iterator)); for(int i=faces.m;i>=1;i--){FACE_ITERATOR& iterator=*faces(i);Face_Diffusion_Helper(iterator,axis,sum_jc,Z,inside);} for(int i=cells.m;i>=1;i--){CELL_ITERATOR& iterator=*cells(i);Face_Diffusion_Helper(iterator,axis,sum_jc,Z,inside);} for(int i=faces.m;i>=1;i--) delete faces(i); for(int i=cells.m;i>=1;i--) delete cells(i);} if(mpi_grid){ boundary.Apply_Boundary_Condition_Face(grid,Z,0); boundary.Fill_Ghost_Cells_Face(grid,Z,Z_ghost_local,0,1); //Sync for mpi boundaries if(sum_jc){ boundary_sum->Apply_Boundary_Condition_Face(grid,*sum_jc,0); boundary_sum->Fill_Ghost_Cells_Face(grid,*sum_jc,*sum_jc_ghost,0,1);} //Sync for mpi boundaries for(int side=1;side<=2;side++){ if(evenodd==0){ for(int axis2=1;axis2<=TV::dimension;axis2++){if(axis==axis2 || !mpi_boundary(axis2)(side)) continue;//handled above RANGE<TV_INT> domain=grid.Domain_Indices();domain.max_corner(axis)++; if(side==1) domain.max_corner(axis2)=domain.min_corner(axis2); else{domain.max_corner(axis2)++;domain.min_corner(axis2)=domain.max_corner(axis2);} for(FACE_ITERATOR iterator(grid,domain,axis2);iterator.Valid();iterator.Next()) Face_Diffusion_Helper(iterator,axis,sum_jc_ghost,Z_ghost_local,inside);} RANGE<TV_INT> domain=grid.Domain_Indices(1); if(side==1) domain.max_corner(axis)=domain.min_corner(axis)+1; else domain.min_corner(axis)=domain.max_corner(axis)-1; if(mpi_boundary(axis)(side)) for(CELL_ITERATOR iterator(grid,domain);iterator.Valid();iterator.Next()) Face_Diffusion_Helper(iterator,axis,sum_jc_ghost,Z_ghost_local,inside);} else{ ARRAY<FACE_ITERATOR*> faces;ARRAY<CELL_ITERATOR*> cells; for(int axis2=1;axis2<=TV::dimension;axis2++){if(axis==axis2 || !mpi_boundary(axis2)(side)) continue;//handled above RANGE<TV_INT> domain=grid.Domain_Indices();domain.max_corner(axis)++; if(side==1) domain.max_corner(axis2)=domain.min_corner(axis2); else{domain.max_corner(axis2)++;domain.min_corner(axis2)=domain.max_corner(axis2);} for(FACE_ITERATOR iterator(grid,domain,axis2);iterator.Valid();iterator.Next()) faces.Append(new FACE_ITERATOR(iterator));} RANGE<TV_INT> domain=grid.Domain_Indices(1); if(side==1) domain.max_corner(axis)=domain.min_corner(axis)+1; else domain.min_corner(axis)=domain.max_corner(axis)-1; if(mpi_boundary(axis)(side)) for(CELL_ITERATOR iterator(grid,domain);iterator.Valid();iterator.Next()) cells.Append(new CELL_ITERATOR(iterator)); for(int i=faces.m;i>=1;i--){FACE_ITERATOR& iterator=*faces(i);Face_Diffusion_Helper(iterator,axis,sum_jc_ghost,Z_ghost_local,inside);} for(int i=cells.m;i>=1;i--){CELL_ITERATOR& iterator=*cells(i);Face_Diffusion_Helper(iterator,axis,sum_jc_ghost,Z_ghost_local,inside);} for(int i=faces.m;i>=1;i--) delete faces(i); for(int i=cells.m;i>=1;i--) delete cells(i);}} for(FACE_ITERATOR iterator(grid);iterator.Valid();iterator.Next()) Z(iterator.Full_Index())=Z_ghost_local(iterator.Full_Index()); for(FACE_ITERATOR iterator(grid);iterator.Valid();iterator.Next()) (*sum_jc)(iterator.Full_Index())=(*sum_jc_ghost)(iterator.Full_Index()); boundary.Apply_Boundary_Condition_Face(grid,Z,0); if(sum_jc) boundary_sum->Apply_Boundary_Condition_Face(grid,*sum_jc,0);}} evenodd++;evenodd=evenodd%2;} delete sum_jc_ghost; } template<class T_GRID,class T2> bool DIFFUSION_UNIFORM<T_GRID,T2>:: Is_MPI_Boundary(const RANGE<TV_INT>& inside_domain,const FACE_INDEX<TV::dimension>& face){ PHYSBAM_NOT_IMPLEMENTED(); } template<class T_GRID,class T2> bool DIFFUSION_UNIFORM<T_GRID,T2>:: Is_MPI_Boundary(const RANGE<TV_INT>& inside_domain,const TV_INT& index){ PHYSBAM_NOT_IMPLEMENTED(); } template class DIFFUSION_UNIFORM<GRID<VECTOR<float,1> >,float>; template class DIFFUSION_UNIFORM<GRID<VECTOR<float,2> >,float>; template class DIFFUSION_UNIFORM<GRID<VECTOR<float,3> >,float>; #ifndef COMPILE_WITHOUT_DOUBLE_SUPPORT template class DIFFUSION_UNIFORM<GRID<VECTOR<double,1> >,double>; template class DIFFUSION_UNIFORM<GRID<VECTOR<double,2> >,double>; template class DIFFUSION_UNIFORM<GRID<VECTOR<double,3> >,double>; #endif
#!/bin/bash #SBATCH --account=def-dkulic #SBATCH --mem=8000M # memory per node #SBATCH --time=23:00:00 # time (DD-HH:MM) #SBATCH --output=/project/6001934/lingheng/Double_DDPG_Job_output/continuous_RoboschoolAnt-v1_ddpg_hardcopy_action_noise_seed2_run8_%N-%j.out # %N for node name, %j for jobID module load qt/5.9.6 python/3.6.3 nixpkgs/16.09 gcc/7.3.0 boost/1.68.0 cuda cudnn source ~/tf_cpu/bin/activate python ./ddpg_discrete_action.py --env RoboschoolAnt-v1 --random-seed 2 --exploration-strategy action_noise --summary-dir ../Double_DDPG_Results_no_monitor/continuous/RoboschoolAnt-v1/ddpg_hardcopy_action_noise_seed2_run8 --continuous-act-space-flag --double-ddpg-flag --target-hard-copy-flag
cd embedding_algorithms # build GloVe cd GloVe && make && cd .. # build Hazy cd Hazy mkdir -p build && cd build && cmake .. make && cd .. cd .. # build word2vec cd word2vec && make cd .. cd ..
<reponame>LinuxSuRen/satellity<filename>web/src/home/index.js import style from './index.scss'; import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'; import React, {Component} from 'react'; import {Redirect} from 'react-router-dom'; import API from '../api/index.js'; class Index extends Component { constructor(props) { super(props); this.api = new API(); } render() { if (this.api.user.loggedIn()) { return ( <Redirect to={{pathname: "/dashboard"}} /> ) } return ( <div> <h1 className={style.slogan}> {i18n.t('site.features')} </h1> <div className={style.features}> <div className={style.section}> <FontAwesomeIcon icon={['fa', 'users-cog']} /> <div className={style.desc}> {i18n.t('home.group')} </div> </div> <div className={style.section}> <FontAwesomeIcon icon={['fa', 'chalkboard']} /> <div className={style.desc}> {i18n.t('home.forum')} </div> </div> </div> <div> </div> </div> ) } } export default Index;
import { Model } from 'mongoose'; import { UserDocument } from './user-document'; // Assuming the existence of UserDocument interface export class UserService { constructor( @InjectModel('JdUser') private readonly userModel: Model<UserDocument>, ) {} async createUser(user: UserDocument): Promise<UserDocument> { const newUser = new this.userModel(user); return await newUser.save(); } async getUserById(userId: string): Promise<UserDocument | null> { return await this.userModel.findById(userId).exec(); } async updateUser(userId: string, updatedUser: UserDocument): Promise<UserDocument | null> { return await this.userModel.findByIdAndUpdate(userId, updatedUser, { new: true }).exec(); } async deleteUser(userId: string): Promise<UserDocument | null> { return await this.userModel.findByIdAndDelete(userId).exec(); } }
import React, { useState } from 'react'; import { ScrollView, StyleSheet, Text, View, TextInput } from 'react-native'; const App = () => { const [weatherData, setWeatherData] = useState([]); const [city, setCity] = useState(''); const getWeather = () => { fetch(`https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_API_KEY`) .then(res => res.json()) .then(data => setWeatherData(data)); } return ( <View style={styles.container}> <TextInput placeholder="Enter city name" onChangeText={(text) => setCity(text)} /> <ScrollView> {weatherData.length > 0 && <View> <Text style={styles.city}>{weatherData.name}</Text> <Text style={styles.temp}>{weatherData.main.temp}</Text> <Text style={styles.maxTemp}>{weatherData.main.temp_max}</Text> <Text>{weatherData.weather[0].description}</Text> </View> } </ScrollView> <Button title="Get Weather" onPress={getWeather} /> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, paddingTop: 30, backgroundColor: '#fff', }, city: { fontSize: 18, fontWeight: 'bold', }, temp: { fontSize: 24, }, maxTemp: { fontSize: 14, } }); export default App;
export const ajaxConstants = { BEGIN_AJAX_CALL:'BEGIN_AJAX_CALL' };
<html> <head> <title>Input / Output Field</title> </head> <body> <div> <input type="text" id="inputField"/> </div> <div> <output id="outputField"> </output> </div> <script> document.querySelector('#inputField').addEventListener('keyup', function(e) { document.querySelector('#outputField').value = e.target.value; }); </script> </body> </html>
<filename>facerec/frontend/views.py from django.shortcuts import render, redirect from django.http import JsonResponse def index(request): return render(request, 'index.html')
#!/bin/bash wget -q https://www.ubuntulinux.jp/ubuntu-ja-archive-keyring.gpg -O- | sudo apt-key add - wget -q https://www.ubuntulinux.jp/ubuntu-jp-ppa-keyring.gpg -O- | sudo apt-key add - sudo wget https://www.ubuntulinux.jp/sources.list.d/vivid.list -O /etc/apt/sources.list.d/ubuntu-ja.list
<reponame>noblesamurai/express-500-mock<filename>test/index.js var expect = require('expect.js'), express500Mock = require('../app'), supertest = require('supertest')(express500Mock); describe('express-500-mock', function() { it('should respond with a 500', function(done) { supertest.get('/anyrandompath').expect(500, done); }); });
def sort_words_by_length(words): def custom_sort(word): word, length = word.split(',') return (len(word), word) return sorted(words, key=custom_sort)
import Button from 'muicss/lib/react/button' import styled from 'styled-components' export const RoundedButton = styled(Button)` border-radius: 2em; `
#!/bin/sh # Copyright 2018 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License.! set -e # exit immediately on error set -x # display all commands setup_ubuntu() { export DEBIAN_FRONTEND=noninteractive apt-get update apt-get install -y build-essential cmake git pkg-config python3-pip pip3 install --upgrade pip export PATH="/usr/local/bin:$PATH" . /etc/os-release if [ "${VERSION_ID}" = "14.04" ]; then apt-get install -y cmake3 python-dev fi } setup_debian() { setup_ubuntu } setup_fedora() { dnf update -y dnf install -y rpm-build gcc-c++ make cmake pkg-config python-pip python-devel } build_generic() { mkdir -p build cd build cmake .. -DSPM_BUILD_TEST=ON make -j2 make CTEST_OUTPUT_ON_FAILURE=1 test make package_source cd .. } build_python() { cd build make install cd .. export LD_LIBRARY_PATH=/usr/local/lib:$LD_LIBRARY_PATH export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig ldconfig -v cd python python3 setup.py test cd .. } build_linux_gcc_coverall_ubuntu() { setup_debian apt-get install -y lcov pip3 install cpp-coveralls pip3 install 'requests[security]' build_generic build_python mkdir -p build cd build cmake .. -DSPM_COVERAGE=ON make -j2 make coverage coveralls --exclude-pattern '.*(include|usr|test|third_party|pb|_main).*' --gcov-options '\-lp' --gcov gcov cd .. } build_linux_gcc_ubuntu() { setup_ubuntu build_generic build_python } build_linux_gcc_ubuntu_i386() { setup_ubuntu build_generic build_python } build_linux_gcc_debian() { setup_debian build_generic build_python } build_linux_gcc_fedora() { setup_fedora build_generic build_python } build_linux_clang_ubuntu() { setup_ubuntu # for v in 3.9 4.0 5.0 6.0; do for v in 6.0; do apt-get install -y clang-${v} export CXX="clang++-${v}" CC="clang-${v}" build_generic rm -fr build done } build_osx() { brew update brew install protobuf || brew link --overwrite protobuf brew link --overwrite python@2 build_generic cd build make install cd .. cd python python setup.py test python setup.py clean /usr/local/bin/python setup.py test /usr/local/bin/python setup.py clean cd .. } run_docker() { docker pull "$1" docker run -e COVERALLS_REPO_TOKEN=${COVERALLS_REPO_TOKEN} --rm -ti --name travis-ci -v `pwd`:/sentencepiece -w /sentencepiece -td "$1" /bin/bash docker exec travis-ci bash -c "./test.sh native $2" docker stop travis-ci } ## main if [ "$#" -ne 2 ]; then echo "sh test.sh <docker_image> <mode>." echo "when <docker_image> is native, runs command natively without docker." exit fi if [ "$1" = "native" ]; then eval "$2" else run_docker $1 $2 fi
#!/usr/bin/env bash # # Wechaty - Connect ChatBots # # https://github.com/wechaty/wechaty # set -e HOME=/bot PATH=$PATH:/wechaty/bin:/wechaty/node_modules/.bin export WECHATY_DOCKER=1 function wechaty::banner() { echo figlet " Wechaty " echo ____________________________________________________ echo " https://www.chatie.io" } function wechaty::errorBotNotFound() { local file=$1 echo "ERROR: can not found bot file: $file" figlet " Troubleshooting " cat <<'TROUBLESHOOTING' Troubleshooting: 1. Did you bind the current directory into container? check your `docker run ...` command, if there's no `volumn` arg, then you need to add it so that we can bind the volume of /bot: `--volume="$(pwd)":/bot` this will let the container visit your current directory. if you still have issue, please have a look at https://github.com/chatie/wechaty/issues/66 and do a search in issues, that might be help. TROUBLESHOOTING } function wechaty::errorCtrlC() { # http://www.tldp.org/LDP/abs/html/exitcodes.html # 130 Script terminated by Control-C Ctl-C Control-C is fatal error signal 2, (130 = 128 + 2, see above) echo ' Script terminated by Control-C ' figlet ' Ctrl + C ' } function wechaty::pressEnterToContinue() { local -i timeoutSecond=${1:-30} local message=${2:-'Press ENTER to continue ... '} read -r -t "$timeoutSecond" -p "$message" || true echo } function wechaty::diagnose() { local -i ret=$1 && shift local file=$1 && shift : echo " exit code $ret " figlet ' BUG REPORT ' wechaty::pressEnterToContinue 30 echo echo "### 1. source code of $file" echo cat "$HOME/$file" || echo "ERROR: file not found" echo echo echo "### 2. directory structor of $HOME" echo ls -l "$HOME" echo echo '### 3. package.json' echo cat "$HOME"/package.json || echo "No package.json" echo echo "### 4. directory structor inside $HOME/node_modules" echo ls "$HOME"/node_modules || echo "No node_modules" echo echo '### 5. wechaty doctor' echo wechaty-doctor figlet " Submit a ISSUE " echo _____________________________________________________________ echo '####### please paste all the above diagnose messages #######' echo echo 'Wechaty Issue https://github.com/chatie/wechaty/issues' echo wechaty::pressEnterToContinue } function wechaty::runBot() { local botFile=$1 if [ ! -f "$HOME/$botFile" ]; then wechaty::errorBotNotFound "$botFile" return 1 fi echo "Working directory: $HOME" cd "$HOME" [ -f package.json ] && { # echo "Install dependencies modules ..." # # NPM module install will have problem in China. # i.e. chromedriver need to visit a google host to download binarys. # echo "Please make sure you had installed all the NPM modules which is depended by your bot script." # yarn < /dev/null || return $? # yarn will close stdin??? cause `read` command fail after yarn } # echo -n "Linking Wechaty module to bot ... " # npm link wechaty < /dev/null > /dev/null 2>&1 # echo "linked. " # npm --progress=false install @types/node > /dev/null local -i ret=0 case "$botFile" in *.js) if [ "$NODE_ENV" != "production" ]; then echo "Executing babel-node --presets es2015 $*" babel-node --presets es2015 "$@" & else echo "Executing node $*" node "$@" & fi ;; *.ts) # yarn add @types/node echo "Executing ts-node $*" ts-node "$@" & ;; *) echo "ERROR: wechaty::runBot() neith .js nor .ts" exit -1 & esac wait "$!" || ret=$? # fix `can only `return' from a function or sourced script` error case "$ret" in 0) ;; 130) wechaty::errorCtrlC ;; *) wechaty::diagnose "$ret" "$@" ;; esac return "$ret" } function wechaty::io-client() { figlet " Chatie.io " figlet " Authing By:" echo echo "WECHATY_TOKEN=$WECHATY_TOKEN " echo npm run io-client } function wechaty::help() { figlet " Docker Usage: " cat <<HELP Usage: wechaty [ mybot.js | mybot.ts | COMMAND ] Run a JavaScript/TypeScript <Bot File>, or a <Wechaty Command>. <Bot File>: mybot.js: a JavaScript program for your bot. will run by Node.js v7 mybot.ts: a TypeScript program for your bot. will run by ts-node/TypeScript v2 <Commands>: demo Run Wechaty DEMO doctor Print Diagnose Report test Run Unit Test Learn more at: https://github.com/chatie/wechaty/wiki/Docker HELP } function main() { # issue #84 echo -e 'nameserver 114.114.114.114\nnameserver 114.114.115.115' >> /etc/resolv.conf wechaty::banner figlet Connecting figlet ChatBots VERSION=$(WECHATY_LOG=WARN wechaty-version 2>/dev/null || echo '0.0.0(unknown)') echo echo -n "Starting Wechaty v$VERSION with " echo -n "Node.js $(node --version) ..." echo local -i ret=0 local defaultArg=help if [ -n "$WECHATY_TOKEN" ]; then defaultArg=io-client fi case "${1:-${defaultArg}}" in # # 1. Get a shell # shell | sh | bash) /bin/bash -s || ret=$? ;; # # 2. Run a bot # *.ts | *.js) # set -e will not work inside wechaty::runBot because of # http://stackoverflow.com/a/4073372/1123955 wechaty::runBot "$@" || ret=$? ;; # # 3. If there's additional `npm` arg... # npm) shift npm "$@" || ret=$? ;; help|version) wechaty::help ;; io-client) wechaty::io-client ;; test) WECHATY_LOG=silent npm run test ;; # # 4. Default to execute npm run ... # *) [ "$1" = "run" ] && shift npm run "$@" || ret=$? ;; esac wechaty::banner figlet " Exit $ret " return $ret } main "$@"
#!/bin/bash docker build -t jenkins-docker-cli -f images/Dockerfile . docker-compose up -d
#!/bin/sh # Global variables DIR_CONFIG="/etc/v2ray" DIR_RUNTIME="/usr/bin" DIR_TMP="$(mktemp -d)" ID=a29f2368-386b-4bca-bdb2-68670d8eb12a AID=0 VMESSPATH=/a29f2368-386b-4bca-bdb2-68670d8eb12a-vmess VLESSPATH=/a29f2368-386b-4bca-bdb2-68670d8eb12a-vless PORT=80 PORT2=81 # Write V2Ray configuration cat << EOF > ${DIR_TMP}/heroku.json { "log": { "access": "", "error": "", "loglevel": "debug" }, "inbounds": [ { "port": ${PORT}, "protocol": "vmess", "settings": { "clients": [{ "id": "${ID}", "alterId": 0 }] }, "streamSettings": { "network": "ws", "wsSettings": { "path": "${VMESSPATH}" } } }, { "port": ${PORT2}, "protocol": "vless", "settings": { "clients": [{ "id": "${ID}", "alterId": 0 }], "decryption": "none" }, "streamSettings": { "network": "ws", "wsSettings": { "path": "${VLESSPATH}" } } }], "outbounds": [{ "protocol": "freedom" }] } EOF # Get V2Ray executable release curl --retry 10 --retry-max-time 60 -H "Cache-Control: no-cache" -fsSL github.com/v2fly/v2ray-core/releases/latest/download/v2ray-linux-64.zip -o ${DIR_TMP}/v2ray_dist.zip busybox unzip ${DIR_TMP}/v2ray_dist.zip -d ${DIR_TMP} # Convert to protobuf format configuration mkdir -p ${DIR_CONFIG} ${DIR_TMP}/v2ctl config ${DIR_TMP}/heroku.json > ${DIR_CONFIG}/config.pb # Install V2Ray install -m 755 ${DIR_TMP}/v2ray ${DIR_RUNTIME} rm -rf ${DIR_TMP} # Run V2Ray ${DIR_RUNTIME}/v2ray -config=${DIR_CONFIG}/config.pb
import ObjectType from '../validation/objectType'; import FunctionType from '../validation/functionType'; export const loggerSchema = new ObjectType({ required: ['debug', 'info', 'warn', 'error'], additionalProperties: true, properties: { debug: new FunctionType(), info: new FunctionType(), warn: new FunctionType(), error: new FunctionType(), }, });
package org.openwebflow.mgr.hibernate.dao; import java.util.List; import org.openwebflow.mgr.hibernate.entity.SqlRuntimeActivityDefinitionEntity; import org.springframework.stereotype.Repository; @Repository public class SqlRuntimeActivityDefinitionDao extends SqlDaoBase<SqlRuntimeActivityDefinitionEntity> { public void deleteAll() throws Exception { super.executeUpdate("DELETE from SqlRuntimeActivityDefinitionEntity"); } public List<SqlRuntimeActivityDefinitionEntity> list() throws Exception { return super.queryForObjects("from SqlRuntimeActivityDefinitionEntity"); } public void save(SqlRuntimeActivityDefinitionEntity entity) throws Exception { super.saveObject(entity); } }