repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Matthimatiker/risky
behaviour-detector/src/test/java/au/gov/amsa/geo/adhoc/PositionsInGbrMain.java
<reponame>Matthimatiker/risky package au.gov.amsa.geo.adhoc; import java.io.BufferedWriter; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Pattern; import com.github.davidmoten.rx.Schedulers; import au.gov.amsa.risky.format.BinaryFixes; import au.gov.amsa.risky.format.Fix; import au.gov.amsa.util.Files; import rx.Observable; public class PositionsInGbrMain { public static void main(String[] args) throws FileNotFoundException, IOException { long t = System.currentTimeMillis(); File out = new File("target/positions.txt"); out.delete(); try (BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(out)))) { Pattern pattern = Pattern.compile(".*\\.track"); List<File> list = new ArrayList<File>(); list.addAll(Files.find(new File("/media/an/binary-fixes-5-minute/2014"), pattern)); list.addAll(Files.find(new File("/media/an/binary-fixes-5-minute/2015"), pattern)); list.addAll(Files.find(new File("/media/an/binary-fixes-5-minute/2016"), pattern)); AtomicInteger count = new AtomicInteger(); int numFiles = list.size(); AtomicInteger fileNumber = new AtomicInteger(0); Observable.from(list) // .groupBy(f -> count.getAndIncrement() % Runtime.getRuntime().availableProcessors()) // .flatMap(files -> files // .doOnNext(file -> { int n = fileNumber.incrementAndGet(); if (n % 1000 == 0) System.out .println( "complete: " + new DecimalFormat("0.0").format( n / (double) numFiles * 100) + "%"); })// .concatMap(BinaryFixes::from) // .filter(x -> inGbr(x)) // .onBackpressureBuffer() // .subscribeOn(Schedulers.computation())) // .count() // .doOnNext(System.out::println) // .toBlocking() // .subscribe(); } System.out.println((System.currentTimeMillis() - t) + "ms"); } private static boolean inGbr(Fix fix) { return fix.lat() >= -27.8 && fix.lat() <= -8.4 && fix.lon() >= 142 && fix.lon() <= 162; } }
dragonli-outsource/zichanguanli
src/main/java/com/dt/core/cache/CacheableEntity.java
package com.dt.core.cache; /** * @author: jinjie * @date: 2018年4月3日 下午1:14:45 * @Description: TODO */ public class CacheableEntity { public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } private String value = ""; private String key = ""; private int expiredtime = -1; /** * @return the expiredtime */ public int getExpiredtime() { return expiredtime; } /** * @param expiredtime * the expiredtime to set */ public void setExpiredtime(int expiredtime) { this.expiredtime = expiredtime; } /** * @return the refreshtime */ public int getRefreshtime() { return refreshtime; } /** * @param refreshtime * the refreshtime to set */ public void setRefreshtime(int refreshtime) { this.refreshtime = refreshtime; } private int refreshtime = -1; public CacheableEntity(String value_in, String key_in) { value = value_in; key = key_in; } public String toString() { return "value:" + value + ",key:" + key + ",refreshtime:" + refreshtime + ",expiredtime:" + expiredtime; } }
4everalone/nano
sample/webservice/eBayDemoApp/src/com/ebay/trading/api/SetUserNotesRequestType.java
// Generated by xsd compiler for android/java // DO NOT CHANGE! package com.ebay.trading.api; import java.io.Serializable; import com.leansoft.nano.annotation.*; /** * * Enables users to add, replace, and delete My eBay notes for * items that are being tracked in the My eBay All Selling and * All Buying areas. * */ @RootElement(name = "SetUserNotesRequest", namespace = "urn:ebay:apis:eBLBaseComponents") public class SetUserNotesRequestType extends AbstractRequestType implements Serializable { private static final long serialVersionUID = -1L; @Element(name = "ItemID") @Order(value=0) public String itemID; @Element(name = "Action") @Order(value=1) public SetUserNotesActionCodeType action; @Element(name = "NoteText") @Order(value=2) public String noteText; @Element(name = "TransactionID") @Order(value=3) public String transactionID; @Element(name = "VariationSpecifics") @Order(value=4) public NameValueListArrayType variationSpecifics; @Element(name = "SKU") @Order(value=5) public String sku; @Element(name = "OrderLineItemID") @Order(value=6) public String orderLineItemID; }
MarcusTw/tp
src/test/java/atas/model/student/EmailTest.java
package atas.model.student; import static atas.testutil.Assert.assertThrows; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; public class EmailTest { public static final Email VALID_EMAIL = new Email("<EMAIL>"); public static final Email VALID_EMAIL_COPY = new Email(VALID_EMAIL.value); public static final Email DIFFERENT_VALID_EMAIL = new Email("<EMAIL>"); @Test public void constructor_null_throwsNullPointerException() { assertThrows(NullPointerException.class, () -> new Email(null)); } @Test public void constructor_invalidEmail_throwsIllegalArgumentException() { String invalidEmail = ""; assertThrows(IllegalArgumentException.class, () -> new Email(invalidEmail)); } @Test public void isValidEmail() { // null email assertThrows(NullPointerException.class, () -> Email.isValidEmail(null)); // blank email assertFalse(Email.isValidEmail("")); // empty string assertFalse(Email.isValidEmail(" ")); // spaces only // missing parts assertFalse(Email.isValidEmail("@u.nus.edu")); // missing local part assertFalse(Email.isValidEmail("peterjacku.nus.edu")); // missing '@' symbol assertFalse(Email.isValidEmail("peterjack@")); // missing domain name // invalid parts assertFalse(Email.isValidEmail("peterjack@-")); // invalid domain name assertFalse(Email.isValidEmail("<EMAIL>")); // underscore in domain name assertFalse(Email.isValidEmail("peter <EMAIL>")); // spaces in local part assertFalse(Email.isValidEmail("<EMAIL>")); // spaces in domain name assertFalse(Email.isValidEmail(" <EMAIL>")); // leading space assertFalse(Email.isValidEmail("<EMAIL> ")); // trailing space assertFalse(Email.isValidEmail("<EMAIL>")); // double '@' symbol assertFalse(Email.isValidEmail("<EMAIL>")); // '@' symbol in local part assertFalse(Email.isValidEmail("<EMAIL>")); // '@' symbol in domain name assertFalse(Email.isValidEmail("<EMAIL>")); // domain name starts with a period assertFalse(Email.isValidEmail("<EMAIL>.")); // domain name ends with a period assertFalse(Email.isValidEmail("<EMAIL>")); // domain name starts with a hyphen assertFalse(Email.isValidEmail("<EMAIL>-")); // domain name ends with a hyphen // valid email assertTrue(Email.isValidEmail("<EMAIL>")); assertTrue(Email.isValidEmail("<EMAIL>")); // minimal assertTrue(Email.isValidEmail("<EMAIL>")); // alphabets only assertTrue(Email.isValidEmail("!#$%&'*+/=?`{|}~^._-@<EMAIL>")); // special characters local part assertTrue(Email.isValidEmail("<EMAIL>")); // numeric local part and domain name assertTrue(Email.isValidEmail("a1+be!@<EMAIL>")); // mixture of alphanumeric and special characters assertTrue(Email.isValidEmail("if.you.dream.it_you.<EMAIL>")); // long local part assertTrue(Email.isValidEmail(VALID_EMAIL.value)); assertTrue(Email.isValidEmail(VALID_EMAIL_COPY.value)); assertTrue(Email.isValidEmail(DIFFERENT_VALID_EMAIL.value)); } @Test public void equals() { // this == other assertEquals(VALID_EMAIL, VALID_EMAIL); assertEquals(VALID_EMAIL_COPY, VALID_EMAIL_COPY); assertEquals(DIFFERENT_VALID_EMAIL, DIFFERENT_VALID_EMAIL); // same email value assertEquals(VALID_EMAIL_COPY, VALID_EMAIL); // different email value assertNotEquals(DIFFERENT_VALID_EMAIL, VALID_EMAIL); assertNotEquals(DIFFERENT_VALID_EMAIL, VALID_EMAIL_COPY); } }
illia-v/UAWebChallenge-IX
Semifinal/speech_order/our_pizzeria/tests/test_models.py
<reponame>illia-v/UAWebChallenge-IX<gh_stars>0 from datetime import datetime from django.test import TestCase from our_pizzeria.models import Order class PizzaOrderModelTestCase(TestCase): def setUp(self): self.order = Order.objects.create( slug='test', orderer_name='Karl', orderer_phone_number=123456789, orderer_address='the world', pizza='pepperoni', drink='water', method_of_payment='cash', date_of_delivery=datetime.now(), date_time_of_order=datetime.now(), status=0 ) def test_order_basic(self): """ Test base functionality of Order. """ self.assertEqual(self.order.orderer_name, 'Karl') self.assertEqual(self.order.orderer_phone_number, 123456789) self.assertEqual(self.order.orderer_address, 'the world') self.assertEqual(self.order.pizza, 'pepperoni') self.assertEqual(self.order.drink, 'water') self.assertEqual(self.order.method_of_payment, 'cash') self.assertEqual(self.order.status, 0) self.assertEqual(self.order.get_status_display(), 'Processing')
suomenriistakeskus/oma-riista-web
src/main/java/fi/riista/feature/permit/decision/derogation/PermitDecisionProtectedAreaTypeRepository.java
package fi.riista.feature.permit.decision.derogation; import fi.riista.feature.permit.decision.PermitDecision; import org.springframework.data.jpa.repository.JpaRepository; import java.util.List; public interface PermitDecisionProtectedAreaTypeRepository extends JpaRepository<PermitDecisionProtectedAreaType, Long> { public List<PermitDecisionProtectedAreaType> findByPermitDecision(PermitDecision decision); }
wjanczuk/grace-and-co
client/components/Cart.js
import React from 'react' import {connect} from 'react-redux' import { editQuantity, getOrder, removeItem, completeOrder, deleteCart } from '../store/order' import { editGuestQuantity, removeGuestItem, removeGuestCart, guestCheckout } from '../store/guestCart' import {Redirect} from 'react-router-dom' class Cart extends React.Component { constructor() { super() this.state = { cart: { items: [] }, displayCheckout: false, displayOrderSuccess: false, email: '' } this.handleClickMinus = this.handleClickMinus.bind(this) this.handleClickPlus = this.handleClickPlus.bind(this) this.handleRemove = this.handleRemove.bind(this) this.handleCheckout = this.handleCheckout.bind(this) this.startCheckout = this.startCheckout.bind(this) this.handleChange = this.handleChange.bind(this) } async componentDidMount() { if (this.props.user.id) { // if user exists, grab cart from store await this.props.getOrder(this.props.user.id) console.log('in componentDidMount') } else if (localStorage.getItem('cart')) { // if cart exists in localstorage grab cart and set to local state const localCart = JSON.parse(localStorage.getItem('cart')) this.setState({ cart: localCart }) } } handleClickPlus(id, quantity, orderId) { quantity++ const itemObj = {id, quantity, orderId} if (this.props.user.id) { this.props.editQuantity(itemObj) } else { const localCart = editGuestQuantity(id, quantity) this.setState({ cart: localCart }) } } handleClickMinus(id, quantity, orderId) { quantity-- const itemObj = {id, quantity, orderId} if (this.props.user.id) { this.props.editQuantity(itemObj) } else { const localCart = editGuestQuantity(id, quantity) this.setState({ cart: localCart }) } } async handleRemove(itemId, productId) { if (this.props.user.id) { await this.props.removeItem(itemId) } else { const localCart = removeGuestItem(productId) this.setState({ cart: localCart }) } } handleCheckout(evt) { evt.preventDefault() const orderObj = { products: this.state.cart.items, email: this.state.email, subtotal: this.state.cart.subtotal } guestCheckout(orderObj) this.setState({ cart: { items: [] }, email: '', displayOrderSuccess: true }) } handleChange(evt) { this.setState({ email: evt.target.value }) } startCheckout() { if (this.props.userId) { this.props.completeOrder(this.props.userId) this.setState({ displayOrderSuccess: true }) } this.setState({ displayCheckout: true }) } render() { const {displayOrderSuccess} = this.state const cart = this.props.user.id ? this.props.order : this.state.cart return displayOrderSuccess ? ( <Redirect to="/complete" /> ) : ( <div> {// (!this.props.userId && !this.state.cart.length) ? ( // cannot get this to work and also say cart is empty after loading ): // <h1>Cart Loading...</h1> // ) : ( Object.keys(cart).length && cart.items.map(item => ( <div key={item.id}> <img src={item.imageUrl} alt={item.name} style={{width: '150px'}} className="image left" /> <h4>{item.name}</h4> <p> <b>Price:</b> ${item.orderItem.price} | <b>Quantity:</b>{' '} {item.orderItem.quantity}{' '} <button onClick={() => this.handleClickPlus( item.orderItem.id, item.orderItem.quantity, item.orderItem.orderId ) } type="submit" className="button small" > + </button> <button onClick={() => this.handleClickMinus( item.orderItem.id, item.orderItem.quantity, item.orderItem.orderId ) } type="submit" className="button small" > - </button>{' '} | <b>Sub-Total:</b> ${item.orderItem.price * item.orderItem.quantity} </p> <button onClick={() => this.handleRemove(item.orderItem.id, item.id)} type="submit" className="button small" > Remove </button> <hr /> </div> ))} {/* {cart.items.length ? ( <div> Total: ${cart.subtotal} <button type="submit" onClick={() => this.startCheckout()}> Checkout </button> </div> ) : ( <h1>Your Cart Is Empty</h1> )} */} {cart.items.length ? ( <div> <p> <b>Cart Total:</b> ${cart.subtotal.toFixed(2)} </p> {/* ADDED DELETE CART BUTTON */} <button type="button" className="button small" onClick={() => { if (this.props.userId) this.props.deleteCart() else { removeGuestCart() this.setState({ cart: { items: [] } }) } }} > Clear Cart </button> <button type="submit" className="button small" onClick={() => this.startCheckout()} > Checkout </button> </div> ) : ( <h4>Your Cart Is Empty</h4> )} {this.state.displayCheckout && !this.props.user.id && ( <form onSubmit={this.handleCheckout}> <label htmlFor="email"> Please enter your email before continuing to checkout:{' '} </label> <input type="text" name="email" value={this.state.email} onChange={this.handleChange} /> <button type="submit">Continue</button> </form> )} </div> ) } } const mapState = state => { return { order: state.order, userId: state.user.id } } const mapDispatch = dispatch => ({ removeItem: itemId => dispatch(removeItem(itemId)), getOrder: userId => dispatch(getOrder(userId)), editQuantity: quantity => dispatch(editQuantity(quantity)), completeOrder: userId => dispatch(completeOrder(userId)), deleteCart: () => dispatch(deleteCart()) }) export default connect(mapState, mapDispatch)(Cart)
mjanes/client
app/src/main/java/org/projectbuendia/client/resolvables/Resolvable.java
<reponame>mjanes/client<gh_stars>10-100 // Copyright 2015 The Project Buendia 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 distrib- // uted 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 // specific language governing permissions and limitations under the License. package org.projectbuendia.client.resolvables; import android.content.res.Resources; /** A resource (e.g. String, Icon) that can be resolved using Android {@link Resources}. */ interface Resolvable<T> { T resolve(Resources resources); }
p12218319/Core
include/P12218319/core/Statistics.hpp
<reponame>p12218319/Core<filename>include/P12218319/core/Statistics.hpp /* Copyright 2016 <NAME> - P12218319 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. email : <EMAIL> */ #ifndef P12218319_CORE_STATISTICS_HPP #define P12218319_CORE_STATISTICS_HPP #include <map> #include <algorithm> #include "P12218319\core\Core.hpp" namespace P12218319 { template<class T, class ITERATOR> static T P12218319_CALL Mean(ITERATOR aBegin, const ITERATOR aEnd) throw() { T tmp = static_cast<T>(0); const uint32_t count = aEnd - aBegin; while(aBegin != aEnd) { tmp += *aBegin; ++aBegin; } return tmp / static_cast<T>(count); } template<class T, class ITERATOR> static T P12218319_CALL Mode(ITERATOR aBegin, const ITERATOR aEnd) throw() { std::map<T, uint32_t> frequency; typedef std::map<T, uint32_t>::iterator MapIterator; while(aBegin != aEnd) { MapIterator i = frequency.find(*aBegin); if(i == frequency.end()){ i = frequency.emplace(*aBegin, 0).first; } ++i->second; ++aBegin; } MapIterator mode = frequency.begin(); const MapIterator end = frequency.end(); MapIterator i = mode; ++i; for (i; i != end; ++i) { if(i->second > mode->second) mode = i; } return mode->first; } template<class T, class ITERATOR> static T P12218319_CALL Median(ITERATOR aBegin, const ITERATOR aEnd) throw() { const uint32_t count = aEnd - aBegin; T* ordered = new T[count]; for(uint32_t i = 0; i < count; ++i, ++aBegin) ordered[i] = *aBegin; std::sort(ordered, ordered + count, [](const T aLeft, const T aRight)->bool{return aLeft < aRight;}); const T tmp = count & 1 ? (ordered[count / 2] + ordered[(count / 2) + 1]) / static_cast<T>(2) : ordered[count / 2]; delete[] ordered; return tmp; } template<class T, class ITERATOR> static T P12218319_CALL Variance(ITERATOR aBegin, const ITERATOR aEnd) throw() { const T mean = Mean<T>(aBegin, aEnd); const uint32_t count = aEnd - aBegin; T* squares = new T[count]; for(uint32_t i = 0; i < count; ++i, ++aBegin) squares[i] = (*aBegin - mean) * (*aBegin - mean); const T tmp = Mean<T>(squares, squares + count); delete[] squares; return tmp; } template<class T, class ITERATOR> static T P12218319_CALL StandardDeviation(ITERATOR aBegin, const ITERATOR aEnd) throw() { return std::sqrt(Variance<T, ITERATOR >(aBegin, aEnd)); } } #endif
white-shark/leetcode-cpp
solution071.cpp
/** * Simplify Path * * cpselvis(<EMAIL>) * Nov 28th, 2016 */ #include<iostream> #include<stack> using namespace std; class Solution { public: string simplifyPath(string path) { stack<string> st; string ret = ""; for (int i = 0; i < path.size(); ) { // Jump when meet character / while (path[i] == '/' && i < path.size()) i ++; string s = ""; while (path[i] != '/' && i < path.size()) { s = s + path[i]; i ++; } if (s == ".." && !st.empty()) st.pop(); else if (s != "" && s != "." && s != "..") st.push(s); } if (st.empty()) ret = "/"; while (!st.empty()) { ret = "/" + st.top() + ret; st.pop(); } return ret; } }; int main(int argc, char **argv) { Solution s; cout << s.simplifyPath("/..") << endl; cout << s.simplifyPath("/home/") << endl; cout << s.simplifyPath("/a/./b/../../c/") << endl; }
CBIIT/cadsr-cdecurate
src/gov/nih/nci/cadsr/common/DbmsOutput.java
<gh_stars>1-10 package gov.nih.nci.cadsr.common; /** * Source: http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:45027262935845 */ import java.sql.*; import org.apache.log4j.Logger; public class DbmsOutput { private static final Logger logger = Logger.getLogger(DbmsOutput.class.getName()); /* * our instance variables. It is always best to use callable or prepared * statements and prepare (parse) them once per program execution, rather * then one per execution in the program. The cost of reparsing is very * high. Also -- make sure to use BIND VARIABLES! * * we use three statments in this class. One to enable dbms_output - * equivalent to SET SERVEROUTPUT on in SQL*PLUS. another to disable it -- * like SET SERVEROUTPUT OFF. the last is to "dump" or display the results * from dbms_output using system.out */ private CallableStatement enable_stmt; private CallableStatement disable_stmt; private CallableStatement show_stmt; private boolean enabled = false; /* * our constructor simply prepares the three statements we plan on * executing. * * the statement we prepare for SHOW is a block of code to return a String * of dbms_output output. Normally, you might bind to a PLSQL table type but * the jdbc drivers don't support PLSQL table types -- hence we get the * output and concatenate it into a string. We will retrieve at least one * line of output -- so we may exceed your MAXBYTES parameter below. If you * set MAXBYTES to 10 and the first line is 100 bytes long, you will get the * 100 bytes. MAXBYTES will stop us from getting yet another line but it * will not chunk up a line. */ public DbmsOutput(Connection conn) throws SQLException { enable_stmt = conn.prepareCall("begin dbms_output.enable(:1); end;"); // enable_stmt = conn.prepareCall("begin dbms_output.enable(:1);dbms_output.enable(NULL); end;"); //set it to unlimited c.f. http://stackoverflow.com/questions/16476568/how-to-increase-dbms-output-buffer disable_stmt = conn.prepareCall("begin dbms_output.disable; end;"); show_stmt = conn .prepareCall("declare " // + " l_line varchar2(255); " + " l_line varchar2(32000); " + " l_done number; " + " l_buffer long; " + "begin " + " loop " + " exit when length(l_buffer)+255 > :maxbytes OR l_done = 1; " + " dbms_output.get_line( l_line, l_done ); " + " l_buffer := l_buffer || l_line || chr(10); " + " end loop; " + " :done := l_done; " + " :buffer := l_buffer; " + "end;"); } /* * enable simply sets your size and executes the dbms_output.enable call */ public void enable(int size) throws SQLException { enable_stmt.setInt(1, size); enable_stmt.executeUpdate(); enabled = true; LogUtil.setLogger(logger); } //Caused: 14:47:02,418 ERROR [STDERR] java.sql.SQLException: Missing IN or OUT parameter at index:: 1 // public void enable() throws SQLException { // //NULL imply unlimited buffer (http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/d_output.htm) // // enable_stmt.executeUpdate(); // enabled = true; // LogUtil.setLogger(logger); // } /* * disable only has to execute the dbms_output.disable call */ public void disable() throws SQLException { disable_stmt.executeUpdate(); LogUtil.setLogger(null); } /* * show does most of the work. It loops over all of the dbms_output data, * fetching it in this case 32,000 bytes at a time (give or take 255 bytes). * It will print this output on stdout by default (just reset what * System.out is to change or redirect this output). */ public void show() throws SQLException { if(enabled) { int done = 0; show_stmt.registerOutParameter(2, java.sql.Types.INTEGER); show_stmt.registerOutParameter(3, java.sql.Types.VARCHAR); for (;;) { show_stmt.setInt(1, 1000000); show_stmt.executeUpdate(); LogUtil.log(show_stmt.getString(3)); if ((done = show_stmt.getInt(2)) == 1) break; } } else { logger.info("DBMS_OUTPUT disabled"); } } /* * close closes the callable statements associated with the DbmsOutput * class. Call this if you allocate a DbmsOutput statement on the stack and * it is going to go out of scope -- just as you would with any callable * statement, result set and so on. */ public void close() throws SQLException { enable_stmt.close(); disable_stmt.close(); show_stmt.close(); } }
hzx157/hex
xiushouguzhu_ios/xiushouguzhu_ios/Controllers/Server/RecommendTableViewController.h
// // RecommendTableViewController.h // xiushouguzhu_ios // // Created by Interest on 15/3/16. // Copyright (c) 2015年 Interest. All rights reserved. // #import <UIKit/UIKit.h> @interface RecommendTableViewController : UITableViewController @property (nonatomic,strong) void (^NurseIDBlock)(NSString *NurseID,NSString *nurseName); @property (nonatomic,strong) NSString *EnCrypId; @end
troth-llc/troth.mn
src/routes/user.js
<filename>src/routes/user.js const express = require("express"); const router = express.Router(); const user = require("../controllers/user"); const validate = require("../middleware/validator"); const token = require("../middleware/token"); /** * /api/user: * post: * description: * responses: * 200: */ router.get("/:username", validate.find, user.find); router.get("/follow/:id", token, validate.follow, user.follow); router.get("/unfollow/:id", token, validate.follow, user.unfollow); router.get("/followers/:id", validate.follow, user.followers); router.get("/following/:id", validate.follow, user.following); module.exports = router;
esell/ferret
pkg/runtime/collections/sort_test.go
package collections_test import ( "encoding/json" "github.com/MontFerret/ferret/pkg/runtime/collections" "github.com/MontFerret/ferret/pkg/runtime/core" "github.com/MontFerret/ferret/pkg/runtime/values" . "github.com/smartystreets/goconvey/convey" "testing" ) func TestSort(t *testing.T) { Convey("Should sort asc", t, func() { arr := []core.Value{ values.NewInt(5), values.NewInt(1), values.NewInt(3), values.NewInt(4), values.NewInt(2), } s, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { return first.Compare(second), nil }, collections.SortDirectionAsc, ) src, err := collections.NewSortIterator( collections.NewSliceIterator(arr), s, ) So(err, ShouldBeNil) res, err := collections.ToSlice(src) So(err, ShouldBeNil) numbers := []int{1, 2, 3, 4, 5} for idx, num := range numbers { So(res[idx].Unwrap(), ShouldEqual, num) } }) Convey("Should sort desc", t, func() { arr := []core.Value{ values.NewInt(5), values.NewInt(1), values.NewInt(3), values.NewInt(4), values.NewInt(2), } s, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { return first.Compare(second), nil }, collections.SortDirectionDesc, ) src, err := collections.NewSortIterator( collections.NewSliceIterator(arr), s, ) So(err, ShouldBeNil) res, err := collections.ToSlice(src) So(err, ShouldBeNil) numbers := []int{5, 4, 3, 2, 1} for idx, num := range numbers { So(res[idx].Unwrap(), ShouldEqual, num) } }) Convey("Should sort asc with multiple sorters", t, func() { makeObj := func(one, two int) *values.Object { obj := values.NewObject() obj.Set("one", values.NewInt(one)) obj.Set("two", values.NewInt(two)) return obj } arr := []core.Value{ makeObj(1, 2), makeObj(1, 1), makeObj(3, 1), makeObj(4, 2), makeObj(2, 1), makeObj(3, 2), makeObj(4, 1), makeObj(2, 2), } s1, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("one") o2, _ := second.(*values.Object).Get("one") return o1.Compare(o2), nil }, collections.SortDirectionAsc, ) s2, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("two") o2, _ := second.(*values.Object).Get("two") return o1.Compare(o2), nil }, collections.SortDirectionAsc, ) src, err := collections.NewSortIterator( collections.NewSliceIterator(arr), s1, s2, ) So(err, ShouldBeNil) res, err := collections.ToSlice(src) So(err, ShouldBeNil) j, _ := json.Marshal(res) So(string(j), ShouldEqual, `[{"one":1,"two":1},{"one":1,"two":2},{"one":2,"two":1},{"one":2,"two":2},{"one":3,"two":1},{"one":3,"two":2},{"one":4,"two":1},{"one":4,"two":2}]`) }) Convey("Should sort desc with multiple sorters", t, func() { makeObj := func(one, two int) *values.Object { obj := values.NewObject() obj.Set("one", values.NewInt(one)) obj.Set("two", values.NewInt(two)) return obj } arr := []core.Value{ makeObj(1, 2), makeObj(1, 1), makeObj(3, 1), makeObj(4, 2), makeObj(2, 1), makeObj(3, 2), makeObj(4, 1), makeObj(2, 2), } s1, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("one") o2, _ := second.(*values.Object).Get("one") return o1.Compare(o2), nil }, collections.SortDirectionDesc, ) s2, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("two") o2, _ := second.(*values.Object).Get("two") return o1.Compare(o2), nil }, collections.SortDirectionDesc, ) src, err := collections.NewSortIterator( collections.NewSliceIterator(arr), s1, s2, ) So(err, ShouldBeNil) res, err := collections.ToSlice(src) So(err, ShouldBeNil) j, _ := json.Marshal(res) So(string(j), ShouldEqual, `[{"one":4,"two":2},{"one":4,"two":1},{"one":3,"two":2},{"one":3,"two":1},{"one":2,"two":2},{"one":2,"two":1},{"one":1,"two":2},{"one":1,"two":1}]`) }) Convey("Should sort asc and desc with multiple sorters", t, func() { makeObj := func(one, two int) *values.Object { obj := values.NewObject() obj.Set("one", values.NewInt(one)) obj.Set("two", values.NewInt(two)) return obj } arr := []core.Value{ makeObj(1, 2), makeObj(1, 1), makeObj(3, 1), makeObj(4, 2), makeObj(2, 1), makeObj(3, 2), makeObj(4, 1), makeObj(2, 2), } s1, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("one") o2, _ := second.(*values.Object).Get("one") return o1.Compare(o2), nil }, collections.SortDirectionAsc, ) s2, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("two") o2, _ := second.(*values.Object).Get("two") return o1.Compare(o2), nil }, collections.SortDirectionDesc, ) src, err := collections.NewSortIterator( collections.NewSliceIterator(arr), s1, s2, ) So(err, ShouldBeNil) res, err := collections.ToSlice(src) So(err, ShouldBeNil) j, _ := json.Marshal(res) So(string(j), ShouldEqual, `[{"one":1,"two":2},{"one":1,"two":1},{"one":2,"two":2},{"one":2,"two":1},{"one":3,"two":2},{"one":3,"two":1},{"one":4,"two":2},{"one":4,"two":1}]`) }) Convey("Should sort desc and asc with multiple sorters", t, func() { makeObj := func(one, two int) *values.Object { obj := values.NewObject() obj.Set("one", values.NewInt(one)) obj.Set("two", values.NewInt(two)) return obj } arr := []core.Value{ makeObj(1, 2), makeObj(1, 1), makeObj(3, 1), makeObj(4, 2), makeObj(2, 1), makeObj(3, 2), makeObj(4, 1), makeObj(2, 2), } s1, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("one") o2, _ := second.(*values.Object).Get("one") return o1.Compare(o2), nil }, collections.SortDirectionDesc, ) s2, _ := collections.NewSorter( func(first core.Value, second core.Value) (int, error) { o1, _ := first.(*values.Object).Get("two") o2, _ := second.(*values.Object).Get("two") return o1.Compare(o2), nil }, collections.SortDirectionAsc, ) src, err := collections.NewSortIterator( collections.NewSliceIterator(arr), s1, s2, ) So(err, ShouldBeNil) res, err := collections.ToSlice(src) So(err, ShouldBeNil) j, _ := json.Marshal(res) So(string(j), ShouldEqual, `[{"one":4,"two":1},{"one":4,"two":2},{"one":3,"two":1},{"one":3,"two":2},{"one":2,"two":1},{"one":2,"two":2},{"one":1,"two":1},{"one":1,"two":2}]`) }) }
mcgaerty/icarus2-modeling-framework
icarus2-model-defaults/src/main/java/de/ims/icarus2/model/standard/members/structure/ImmutableStructureEditVerifier.java
/* * ICARUS2 Corpus Modeling Framework * Copyright (C) 2014-2022 <NAME> <<EMAIL>> * * 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 de.ims.icarus2.model.standard.members.structure; import static java.util.Objects.requireNonNull; import de.ims.icarus2.model.api.members.item.Edge; import de.ims.icarus2.model.api.members.item.Item; import de.ims.icarus2.model.api.members.structure.Structure; import de.ims.icarus2.model.api.members.structure.StructureEditVerifier; import de.ims.icarus2.model.standard.members.container.ImmutableContainerEditVerifier; import de.ims.icarus2.util.annotations.TestableImplementation; import de.ims.icarus2.util.collections.seq.DataSequence; /** * A simple {@link StructureEditVerifier} implementation that returns {@code false} * for all edit verification methods. * * @author <NAME> * */ @TestableImplementation(StructureEditVerifier.class) public class ImmutableStructureEditVerifier extends ImmutableContainerEditVerifier implements StructureEditVerifier { public ImmutableStructureEditVerifier(Structure source) { super(source); } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#getSource() */ @Override public Structure getSource() { return (Structure) super.getSource(); } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canAddEdge(de.ims.icarus2.model.api.members.item.Edge) */ @Override public boolean canAddEdge(Edge edge) { StructureEditVerifier.checkEdgeForAdd(getSource(), edge); return false; } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canAddEdges(de.ims.icarus2.util.collections.seq.DataSequence) */ @Override public boolean canAddEdges(DataSequence<? extends Edge> edges) { requireNonNull(edges); edges.forEach(this::canAddEdge); return false; } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canRemoveEdge(long) */ @Override public boolean canRemoveEdge(long index) { return false; } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canRemoveEdges(long, long) */ @Override public boolean canRemoveEdges(long index0, long index1) { return false; } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canSwapEdges(long, long) */ @Override public boolean canSwapEdges(long index0, long index1) { return false; } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canSetTerminal(de.ims.icarus2.model.api.members.item.Edge, de.ims.icarus2.model.api.members.item.Item, boolean) */ @Override public boolean canSetTerminal(Edge edge, Item terminal, boolean isSource) { StructureEditVerifier.checkEdgeForTerminalChange(getSource(), edge, terminal); return false; } /** * @see de.ims.icarus2.model.api.members.structure.StructureEditVerifier#canCreateEdge(de.ims.icarus2.model.api.members.item.Item, de.ims.icarus2.model.api.members.item.Item) */ @Override public boolean canCreateEdge(Item source, Item target) { StructureEditVerifier.checkNodesForEdgeCreation(getSource(), source, target); return false; } }
nickman/heliosutils
src/main/java/com/heliosapm/utils/counters/alarm/AlarmState.java
/** Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you 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 com.heliosapm.utils.counters.alarm; import java.util.Set; import com.heliosapm.utils.enums.BitMasked; import com.heliosapm.utils.enums.Rollup; import com.heliosapm.utils.enums.RollupType; /** * <p>Title: AlarmState</p> * <p>Description: Functional enumeration for alarm states</p> * <p>Company: Helios Development Group LLC</p> * @author Whitehead (nwhitehead AT heliosdev DOT org) * <p><code>com.heliosapm.utils.counters.alarm.AlarmState</code></p> */ @RollupType(Rollup.DOWN) public enum AlarmState implements BitMasked { /** The alarm has been disabled */ OFF(false, "Initial"), /** No data has been submitted to the alarm yet */ NODATA(false, "Initial"), /** State is stale as no data has been received */ STALE(false, "Major"), /** State is normal */ OK(true, "Normal"), /** State is iffy */ WARN(true, "Major"), /** State is critical */ CRITICAL(true, "Critical"); private AlarmState(final boolean evaluatable, final String snmpSeverity) { this.evaluatable = evaluatable; this.snmpSeverity = snmpSeverity; } private static final AlarmState[] EVAL = new AlarmState[]{OK, WARN, CRITICAL}; public final boolean evaluatable; public final String snmpSeverity; /** * Returns an array of the evaluatable alarm states * @return an array of the evaluatable alarm states */ public static AlarmState[] evaluatable() { return EVAL.clone(); } final int mask = StaticOps.ordinalBitMaskInt(this); public int getMask(){ return mask; } public boolean isEnabled(final int mask){ return StaticOps.isEnabled(this, mask); } public int enableFor(final int mask) { return StaticOps.enableFor(this, mask); } public int disableFor(final int mask) { return StaticOps.disableFor(this, mask); } public static int maskFor(final AlarmState... members) { return StaticOps.maskFor(members); } public static Set<AlarmState> membersFor(final int mask) { return StaticOps.membersFor(AlarmState.class, mask); }; }
wjtree/wechat-parent
wechat-sdk/src/main/java/com/app/wechat/request/WxCustomTypingRequest.java
<filename>wechat-sdk/src/main/java/com/app/wechat/request/WxCustomTypingRequest.java package com.app.wechat.request; import com.app.wechat.domain.WxCustomSendModel; import com.app.wechat.internal.code.HttpMethod; import com.app.wechat.internal.code.WxUrl; import com.app.wechat.response.WxCustomTypingResponse; /** * <p>功 能:客服输入状态API的请求信息</p> * <p>描 述:开发者可通过调用“客服输入状态”接口,返回客服当前输入状态给用户</p> * <p>版 权:Copyright (c) 2017</p> * <p>创建时间:2017年7月6日 下午6:53:48</p> * <br/> * <p>注 意:此接口需要客服消息接口权限</p> * <ol> * <li>如果不满足发送客服消息的触发条件,则无法下发输入状态</li> * <li>下发输入状态,需要客服之前30秒内跟用户有过消息交互</li> * <li>在输入状态中(持续15s),不可重复下发输入态</li> * <li>在输入状态中,如果向用户下发消息,会同时取消输入状态</li> * </ol> * * @author 王建 * @version 1.0 */ public class WxCustomTypingRequest extends AbstractWxRequest<WxCustomTypingResponse> { private static final long serialVersionUID = 1L; private WxCustomSendModel object; public WxCustomTypingRequest(WxCustomSendModel object) { this.object = object; } public WxCustomSendModel getObject() { return object; } public Class<WxCustomTypingResponse> getResponseClass() { return WxCustomTypingResponse.class; } public String getUrl(String accessToken) { return String.format(WxUrl.API_MESSAGE_CUSTOM_TYPING, accessToken); } public HttpMethod getMethod() { return HttpMethod.POST; } }
wizzifactory/wizzi
packages/wizzi-tools/dist/examples/typescript/index.js
<gh_stars>0 /* artifact generator: C:\My\wizzi\wizzi\node_modules\wizzi-js\lib\artifacts\js\module\gen\main.js primary source IttfDocument: C:\My\wizzi\wizzi\packages\wizzi-tools\.wizzi\ittf\examples\typescript\index.js.ittf */ 'use strict'; var util = require('util'); var path = require('path'); var file = require('wizzi-utils').file; var jswizzifier = require('../../lib/wizzifiers/jsparser/babel/wizzifier'); go('quick'); function go(name) { var src = path.join(__dirname, 'data', name + '.ts'); var out_babel = path.join(__dirname, 'data', name + '.babel.json'); var out_ittf = path.join(__dirname, 'data', name + '.js.ittf'); var out_ittf_js = path.join(__dirname, 'data', name + '.js.ittf.js'); jswizzifier.getWizziIttf(file.read(src), { kind: 'react', babel: { sourceType: 'module', ts_or_flow: 'typescript' }, syntaxOutFile: out_babel, verbose: false }, function(err, result) { if (err) { console.log('err', err); file.write(out_ittf, JSON.stringify(err, null, 4)); } else { var r1 = result.substring(0, 24); var r2 = result.substring(24); console.log('r1', r1); r1 = r1.replace('jsfile', 'react '); console.log('r1 after', r1); file.write(out_ittf, r1+r2); } }); }
Neradoc/circuitpython
tests/cpydiff/core_fstring_parser.py
""" categories: Core description: f-strings cannot support expressions that require parsing to resolve nested braces cause: MicroPython is optimised for code space. workaround: Only use simple expressions inside f-strings """ f'{"hello {} world"}' f"{repr({})}"
jeikabu/lumberyard
dev/Gems/EMotionFX/Code/EMotionFX/Pipeline/SceneAPIExt/Data/LodNodeSelectionList.h
#pragma once /* * All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or * its licensors. * * For complete copyright and license terms please see the LICENSE at the root of this * distribution (the "License"). All use of this software is governed by the License, * or, if provided, by the license below or the license accompanying this file. Do not * remove or modify any license notices. This file is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * */ #include <SceneAPI/SceneData/ManifestBase/SceneNodeSelectionList.h> #include <EMotionFX/Pipeline/AzSceneDef.h> namespace EMotionFX { namespace Pipeline { namespace Data { class LodNodeSelectionList; } typedef AZStd::fixed_vector<Data::LodNodeSelectionList, g_maxLods> LODNodeLists; namespace Data { /* * The main purpose to have a specific derived class of SceneNodeSelectionList is to have custom * override attribute for the UX need of LOD */ class LodNodeSelectionList : public SceneData::SceneNodeSelectionList { public: AZ_RTTI(LodNodeSelectionList, "{F19C7DD2-395C-4406-9CA9-DE572F5ADD5A}", SceneData::SceneNodeSelectionList); LodNodeSelectionList(); explicit LodNodeSelectionList(AZ::u32 lodLevel); virtual ~LodNodeSelectionList() override = default; AZStd::string GetNameLabelOverride() const; AZ::u32 GetLODLevel() const; bool ContainsNode(const AZStd::string& nodeName) const; AZStd::unique_ptr<SceneDataTypes::ISceneNodeSelectionList> Copy() const override; static void Reflect(AZ::ReflectContext* context); protected: AZ::u32 m_lodLevel; // Keep a reference to the owner to check the position of this list. }; } } }
ProgrammingLife2017/hygene
src/test/java/org/dnacronym/hygene/graph/SegmentAggregatorTest.java
package org.dnacronym.hygene.graph; import org.dnacronym.hygene.graph.edge.AggregateEdge; import org.dnacronym.hygene.graph.edge.Edge; import org.dnacronym.hygene.graph.edge.SimpleEdge; import org.dnacronym.hygene.graph.node.AggregateSegment; import org.dnacronym.hygene.graph.node.GfaNode; import org.dnacronym.hygene.graph.node.Node; import org.dnacronym.hygene.graph.node.Segment; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Unit tests for {@link SegmentAggregator}. */ class SegmentAggregatorTest { /** * Tests that aggregation fails if the node has no neighbours. */ @Test void testAggregateNoNeighbours() { assertThat(SegmentAggregator.aggregate(new Segment(14, 48, 51))).isEmpty(); } /** * Tests that aggregation fails if the node has only one neighbour. */ @Test void testAggregateOneNeighbour() { final GfaNode nodeA = new Segment(53, 81, 42); final GfaNode nodeB = new Segment(19, 4, 1); final GfaNode nodeC = new Segment(27, 3, 61); linkNodes(nodeA, nodeB); linkNodes(nodeB, nodeC); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that aggregation fails if the node has three neighbours. */ @Test void testAggregateThreeNeighbours() { final GfaNode nodeA = new Segment(1, 92, 10); final GfaNode nodeB = new Segment(21, 59, 1); final GfaNode nodeC = new Segment(27, 86, 1); final GfaNode nodeD = new Segment(35, 97, 1); final GfaNode nodeE = new Segment(42, 76, 21); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeA, nodeD); linkNodes(nodeB, nodeE); linkNodes(nodeC, nodeE); linkNodes(nodeD, nodeE); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that aggregation fails if one of the node's neighbours has a sequence length that is not 1. */ @Test void testAggregateNeighboursHaveInvalidSequenceLength() { final GfaNode nodeA = new Segment(75, 9, 93); final GfaNode nodeB = new Segment(98, 14, 1); final GfaNode nodeC = new Segment(93, 21, 50); final GfaNode nodeD = new Segment(45, 77, 85); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeB, nodeD); linkNodes(nodeC, nodeD); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that aggregation fails if one of the node's neighbours has no neighbours. */ @Test void testAggregateNeighbourHasNoNeighbours() { final GfaNode nodeA = new Segment(57, 37, 11); final GfaNode nodeB = new Segment(65, 85, 1); final GfaNode nodeC = new Segment(89, 5, 1); final GfaNode nodeD = new Segment(7, 100, 90); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeC, nodeD); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that aggregation fails if one of the node's neighbours has more than one neighbour. */ @Test void testAggregateNeighbourHasMultipleNeighbours() { final GfaNode nodeA = new Segment(91, 91, 68); final GfaNode nodeB = new Segment(100, 62, 1); final GfaNode nodeC = new Segment(85, 44, 1); final GfaNode nodeD = new Segment(24, 28, 81); final GfaNode nodeE = new Segment(64, 73, 35); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeB, nodeD); linkNodes(nodeC, nodeD); linkNodes(nodeC, nodeE); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that aggregation fails if the node's neighbours do not share their neighbour. */ @Test void testAggregateNeighboursHaveDifferentNeighbour() { final GfaNode nodeA = new Segment(13, 23, 20); final GfaNode nodeB = new Segment(75, 60, 1); final GfaNode nodeC = new Segment(54, 21, 1); final GfaNode nodeD = new Segment(24, 44, 48); final GfaNode nodeE = new Segment(66, 8, 100); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeB, nodeD); linkNodes(nodeC, nodeE); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that aggregation fails if the neighbour of the node's neighbours has a neighbour that is not one of the * original node's neighbours. * <p><pre> * . . . B . . . * . . / . \ . . * . A . D - E . * . . \ . / . . * . . . C . . . * </pre> */ @Test void testAggregateNeighbourNeighbourHasOtherIncomingNeighbour() { final GfaNode nodeA = new Segment(74, 55, 35); final GfaNode nodeB = new Segment(87, 53, 1); final GfaNode nodeC = new Segment(58, 55, 1); final GfaNode nodeD = new Segment(67, 42, 1); final GfaNode nodeE = new Segment(47, 90, 60); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeB, nodeE); linkNodes(nodeC, nodeE); linkNodes(nodeD, nodeE); assertThat(SegmentAggregator.aggregate(nodeA)).isEmpty(); } /** * Tests that an aggregated node contains the correct nodes. */ @Test void testAggregateSuccessContainment() { final GfaNode nodeA = new Segment(4, 13, 24); final GfaNode nodeB = new Segment(43, 97, 1); final GfaNode nodeC = new Segment(58, 44, 1); final GfaNode nodeD = new Segment(19, 57, 48); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeB, nodeD); linkNodes(nodeC, nodeD); final AggregateSegment aggregateSegment = SegmentAggregator.aggregate(nodeA) .orElseThrow(() -> new AssertionError("AggregateSegment is null.")); assertThat(aggregateSegment).isNotNull(); assertThat(aggregateSegment.getSegments()).containsExactly((Segment) nodeB, (Segment) nodeC); } /** * Tests that an aggregated node is correctly linked to the other nodes. */ @Test void testAggregateSuccessEdges() { final GfaNode nodeA = new Segment(93, 16, 46); final GfaNode nodeB = new Segment(47, 94, 1); final GfaNode nodeC = new Segment(60, 80, 1); final GfaNode nodeD = new Segment(63, 59, 64); linkNodes(nodeA, nodeB); linkNodes(nodeA, nodeC); linkNodes(nodeB, nodeD); linkNodes(nodeC, nodeD); final AggregateSegment aggregateSegment = SegmentAggregator.aggregate(nodeA) .orElseThrow(() -> new AssertionError("AggregateSegment is null.")); final AggregateEdge toAggregateSegment = (AggregateEdge) aggregateSegment.getIncomingEdges().iterator().next(); final AggregateEdge fromAggregateSegment = (AggregateEdge) aggregateSegment.getOutgoingEdges() .iterator().next(); assertThat(nodeA.getOutgoingEdges()).containsExactly(toAggregateSegment); assertThat(toAggregateSegment.getEdges()).containsExactly( nodeB.getIncomingEdges().iterator().next(), nodeC.getIncomingEdges().iterator().next() ); assertThat(fromAggregateSegment.getEdges()).containsExactly( nodeB.getOutgoingEdges().iterator().next(), nodeC.getOutgoingEdges().iterator().next() ); assertThat(nodeD.getIncomingEdges()).containsExactly(fromAggregateSegment); } /** * Tests that nothing happens if an empty collection is aggregated. */ @Test void testAggregateSubgraphEmpty() { final Subgraph subgraph = new Subgraph(); SegmentAggregator.aggregate(subgraph); assertThat(subgraph.getNodes()).isEmpty(); } /** * Tests that nothing happens if a collection with a single node is aggregated. */ @Test void testAggregateSubgraphSingleNode() { final Subgraph subgraph = new Subgraph(); final Node node = new Segment(90, 98, 55); subgraph.add(node); SegmentAggregator.aggregate(subgraph); assertThat(subgraph.getNodes()).containsExactly(node); } /** * Tests that a single aggregation takes place when the simplest aggregable collection of nodes is given. */ @Test void testAggregateSubgraphOneSuccess() { final Subgraph subgraph = new Subgraph(); final Segment segmentA = new Segment(4, 13, 24); final Segment segmentB = new Segment(43, 97, 1); final Segment segmentC = new Segment(58, 44, 1); final Segment segmentD = new Segment(19, 57, 48); linkNodes(segmentA, segmentB); linkNodes(segmentA, segmentC); linkNodes(segmentB, segmentD); linkNodes(segmentC, segmentD); subgraph.add(segmentA); subgraph.add(segmentB); subgraph.add(segmentC); subgraph.add(segmentD); SegmentAggregator.aggregate(subgraph); assertThat(segmentA.getOutgoingEdges()).hasSize(1); assertThat(segmentD.getIncomingEdges()).hasSize(1); final AggregateSegment aggregateSegment = (AggregateSegment) segmentA.getOutgoingEdges().iterator() .next().getTo(); assertThat(aggregateSegment.getSegments()).containsExactlyInAnyOrder(segmentB, segmentC); assertThat(subgraph.getNodes()).containsExactlyInAnyOrder(segmentA, aggregateSegment, segmentD); } @Test void testAggregateSubgraphTwoSuccesses() { final Subgraph subgraph = new Subgraph(); final Segment segmentA = new Segment(93, 36, 43); final Segment segmentB = new Segment(60, 28, 1); final Segment segmentC = new Segment(95, 85, 1); final Segment segmentD = new Segment(44, 69, 12); final Segment segmentE = new Segment(73, 46, 1); final Segment segmentF = new Segment(98, 73, 1); final Segment segmentG = new Segment(59, 20, 65); linkNodes(segmentA, segmentB); linkNodes(segmentA, segmentC); linkNodes(segmentB, segmentD); linkNodes(segmentC, segmentD); linkNodes(segmentD, segmentE); linkNodes(segmentD, segmentF); linkNodes(segmentE, segmentG); linkNodes(segmentF, segmentG); subgraph.add(segmentA); subgraph.add(segmentB); subgraph.add(segmentC); subgraph.add(segmentD); subgraph.add(segmentE); subgraph.add(segmentF); subgraph.add(segmentG); SegmentAggregator.aggregate(subgraph); assertThat(segmentA.getOutgoingEdges()).hasSize(1); assertThat(segmentD.getIncomingEdges()).hasSize(1); assertThat(segmentD.getOutgoingEdges()).hasSize(1); assertThat(segmentG.getIncomingEdges()).hasSize(1); final AggregateSegment aggregateSegment1 = (AggregateSegment) segmentA.getOutgoingEdges() .iterator().next().getTo(); assertThat(aggregateSegment1.getSegments()).containsExactlyInAnyOrder(segmentB, segmentC); final AggregateSegment aggregateSegment2 = (AggregateSegment) segmentD.getOutgoingEdges() .iterator().next().getTo(); assertThat(aggregateSegment2.getSegments()).containsExactlyInAnyOrder(segmentE, segmentF); assertThat(subgraph.getNodes()).containsExactlyInAnyOrder(segmentA, aggregateSegment1, segmentD, aggregateSegment2, segmentG); } /** * Tests that only a single aggregation takes place in a relatively complex graph. * <p><pre> * . . . . . . . . . . . . . . . * . . . . . C . . . G . . . . . * . . . . / . \ . / . \ . . . . * . A - B . . . E . . . I . . . * . . . . \ . / . \ . / . \ . . * . . . . . D . . . H . . . J . * . . . . . . \ . . . . . / . . * . . . . . . . F - - - - . . . * . . . . . . . . . . . . . . . * </pre> */ @Test void testAggregateSubgraphOneSuccessManyFailures() { final Subgraph subgraph = new Subgraph(); final Segment segmentA = new Segment(4, 76, 86); final Segment segmentB = new Segment(73, 12, 4); final Segment segmentC = new Segment(36, 49, 1); final Segment segmentD = new Segment(18, 64, 1); final Segment segmentE = new Segment(12, 88, 89); final Segment segmentF = new Segment(88, 100, 71); final Segment segmentG = new Segment(89, 87, 1); final Segment segmentH = new Segment(58, 61, 1); final Segment segmentI = new Segment(15, 34, 15); final Segment segmentJ = new Segment(51, 54, 71); final Segment segmentK = new Segment(8, 40, 99); linkNodes(segmentA, segmentB); linkNodes(segmentB, segmentC); linkNodes(segmentB, segmentD); linkNodes(segmentC, segmentE); linkNodes(segmentD, segmentE); linkNodes(segmentD, segmentF); linkNodes(segmentE, segmentG); linkNodes(segmentE, segmentH); linkNodes(segmentF, segmentJ); linkNodes(segmentG, segmentI); linkNodes(segmentH, segmentI); linkNodes(segmentI, segmentJ); subgraph.add(segmentA); subgraph.add(segmentB); subgraph.add(segmentC); subgraph.add(segmentD); subgraph.add(segmentE); subgraph.add(segmentF); subgraph.add(segmentG); subgraph.add(segmentH); subgraph.add(segmentI); subgraph.add(segmentJ); subgraph.add(segmentK); SegmentAggregator.aggregate(subgraph); assertThat(segmentB.getOutgoingEdges()).hasSize(2); assertThat(segmentE.getIncomingEdges()).hasSize(2); assertThat(segmentE.getOutgoingEdges()).hasSize(1); assertThat(segmentI.getIncomingEdges()).hasSize(1); final AggregateSegment aggregateSegment = (AggregateSegment) segmentE.getOutgoingEdges().iterator() .next().getTo(); assertThat(subgraph.getNodes()).containsExactlyInAnyOrder(segmentA, segmentB, segmentC, segmentD, segmentE, segmentF, aggregateSegment, segmentI, segmentJ, segmentK); assertThat(aggregateSegment.getSegments()).containsExactlyInAnyOrder(segmentG, segmentH); } /** * Connects two nodes with an edge. * * @param from the node from which the edge departs * @param to the node at which the edge arrives */ private void linkNodes(final GfaNode from, final GfaNode to) { final Edge edge = new SimpleEdge(from, to); from.getOutgoingEdges().add(edge); to.getIncomingEdges().add(edge); } }
dawood-dev/nyCapital
node_modules/swagger-client/lib/interfaces.js
<filename>node_modules/swagger-client/lib/interfaces.js<gh_stars>1-10 "use strict"; exports.__esModule = true; exports.makeExecute = makeExecute; exports.makeApisTagOperationsOperationExecute = makeApisTagOperationsOperationExecute; exports.makeApisTagOperation = makeApisTagOperation; exports.mapTagOperations = mapTagOperations; exports.self = void 0; var _pick = _interopRequireDefault(require("lodash/pick")); var _helpers = require("./helpers"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; } function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } const nullFn = () => null; const normalizeArray = arg => Array.isArray(arg) ? arg : [arg]; // To allow stubbing of functions const self = { mapTagOperations, makeExecute }; // Make an execute, bound to arguments defined in mapTagOperation's callback (cb) exports.self = self; function makeExecute(swaggerJs = {}) { return ({ pathName, method, operationId }) => (parameters, opts = {}) => swaggerJs.execute(_objectSpread(_objectSpread({ spec: swaggerJs.spec }, (0, _pick.default)(swaggerJs, 'requestInterceptor', 'responseInterceptor', 'userFetch')), {}, { pathName, method, parameters, operationId }, opts)); } // Creates an interface with tags+operations = execute // The shape // { apis: { [tag]: { operations: [operation]: { execute }}}} // NOTE: this is mostly for compatibility function makeApisTagOperationsOperationExecute(swaggerJs = {}) { // { apis: tag: operations: execute } const cb = self.makeExecute(swaggerJs); const tagOperations = self.mapTagOperations({ v2OperationIdCompatibilityMode: swaggerJs.v2OperationIdCompatibilityMode, spec: swaggerJs.spec, cb }); const apis = {}; // eslint-disable-next-line no-restricted-syntax, guard-for-in for (const tag in tagOperations) { apis[tag] = { operations: {} }; // eslint-disable-next-line no-restricted-syntax, guard-for-in for (const op in tagOperations[tag]) { apis[tag].operations[op] = { execute: tagOperations[tag][op] }; } } return { apis }; } // .apis[tag][operationId]:ExecuteFunction interface function makeApisTagOperation(swaggerJs = {}) { const cb = self.makeExecute(swaggerJs); return { apis: self.mapTagOperations({ v2OperationIdCompatibilityMode: swaggerJs.v2OperationIdCompatibilityMode, spec: swaggerJs.spec, cb }) }; } /** * Iterates over a spec, creating a hash of {[tag]: { [operationId], ... }, ...} * with the value of calling `cb`. * * `spec` is a OAI v2.0 compliant specification object * `cb` is called with ({ spec, operation, path, method }) * `defaultTag` will house all non-tagged operations * */ function mapTagOperations({ spec, cb = nullFn, defaultTag = 'default', v2OperationIdCompatibilityMode }) { const operationIdCounter = {}; const tagOperations = {}; // Will house all tags + operations (0, _helpers.eachOperation)(spec, ({ pathName, method, operation }) => { const tags = operation.tags ? normalizeArray(operation.tags) : [defaultTag]; tags.forEach(tag => { if (typeof tag !== 'string') { return; } tagOperations[tag] = tagOperations[tag] || {}; const tagObj = tagOperations[tag]; const id = (0, _helpers.opId)(operation, pathName, method, { v2OperationIdCompatibilityMode }); const cbResult = cb({ spec, pathName, method, operation, operationId: id }); if (operationIdCounter[id]) { operationIdCounter[id] += 1; tagObj[`${id}${operationIdCounter[id]}`] = cbResult; } else if (typeof tagObj[id] !== 'undefined') { // Bump counter ( for this operationId ) const originalCounterValue = operationIdCounter[id] || 1; operationIdCounter[id] = originalCounterValue + 1; // Append _x to the operationId tagObj[`${id}${operationIdCounter[id]}`] = cbResult; // Rename the first operationId const temp = tagObj[id]; delete tagObj[id]; tagObj[`${id}${originalCounterValue}`] = temp; } else { // Assign callback result ( usually a bound function ) tagObj[id] = cbResult; } }); }); return tagOperations; }
prathamesh-sonpatki/jruby
spec/regression/GH-814_defined_basicobject_spec.rb
if RUBY_VERSION >= "1.9" describe "defined?(::BasicObject)" do it "returns \"constant\"" do defined?(::BasicObject).should == "constant" end end end
slafon51/esup-publisher-webcomponents
@gip-recia/esup-publisher-webcomponents-utils/src/localization.js
<filename>@gip-recia/esup-publisher-webcomponents-utils/src/localization.js /** * Classe permettant de récupérer un label selon la langue définie. */ export class Localization { /** * Constructeur avec arguments. * * @param {Object} labels Labels * @param {String} lang Langue */ constructor(labels, lang) { this.labels = labels this.lang = lang } /** * Merge des labels dans ceux déjà définis. * * @param {Object} labels Labels à merger */ mergeLabels(labels) { Object.keys(labels).forEach(lang => { if (!Object.keys(this.labels).includes(lang)) { this.labels[lang] = labels[lang] } else { Object.keys(labels[lang]).forEach(key => { this.labels[lang][key] = labels[lang][key] }) } }) } /** * Retourne un label dans la langue définie. * * @param {String} key Clé du label * @param {Object} params Paramètres à insérer dans le label * @returns Label dans la langue définie */ getLabel(key, params) { var label if (this.labels[this.lang]) { label = this.labels[this.lang][key] || key } else { label = key } if (params) { label = label.replace(/{([^}]+)}/g, function (match, param) { return typeof params[param] != 'undefined' ? params[param] : match }) } return label } }
varadchoudhari/UA-Frontend
app/components/Common/maps-vector.js
<reponame>varadchoudhari/UA-Frontend // VectorMap // ----------------------------------- var seriesData = { 'CA': 11100, // Canada 'DE': 2510, // Germany 'FR': 3710, // France 'AU': 5710, // Australia 'GB': 8310, // Great Britain 'RU': 9310, // Russia 'BR': 6610, // Brazil 'IN': 7810, // India 'CN': 4310, // China 'US': 839, // USA 'SA': 410 // Saudi Arabia }; var markersData = [ { latLng:[41.90, 12.45], name:'Vatican City' }, { latLng:[43.73, 7.41], name:'Monaco' }, { latLng:[-0.52, 166.93], name:'Nauru' }, { latLng:[-8.51, 179.21], name:'Tuvalu' }, { latLng:[7.11,171.06], name:'Marshall Islands' }, { latLng:[17.3,-62.73], name:'Saint Kitts and Nevis' }, { latLng:[3.2,73.22], name:'Maldives' }, { latLng:[35.88,14.5], name:'Malta' }, { latLng:[41.0,-71.06], name:'New England' }, { latLng:[12.05,-61.75], name:'Grenada' }, { latLng:[13.16,-59.55], name:'Barbados' }, { latLng:[17.11,-61.85], name:'Antigua and Barbuda' }, { latLng:[-4.61,55.45], name:'Seychelles' }, { latLng:[7.35,134.46], name:'Palau' }, { latLng:[42.5,1.51], name:'Andorra' } ]; var defaultColors = { markerColor: '#23b7e5', // the marker points bgColor: 'transparent', // the background scaleColors: ['#878c9a'], // the color of the region in the serie regionFill: '#bbbec6' // the base region color }; // Class definition class VectorMap { constructor(element, seriesData, markersData) { if (!element || !element.length) return; var attrs = element.data(), mapHeight = attrs.height || '300', options = { markerColor: attrs.markerColor || defaultColors.markerColor, bgColor: attrs.bgColor || defaultColors.bgColor, scale: attrs.scale || 1, scaleColors: attrs.scaleColors || defaultColors.scaleColors, regionFill: attrs.regionFill || defaultColors.regionFill, mapName: attrs.mapName || 'world_mill_en' }; element.css('height', mapHeight); this.init(element, options, seriesData, markersData); } init($element, opts, series, markers) { $element.vectorMap({ map: opts.mapName, backgroundColor: opts.bgColor, zoomMin: 1, zoomMax: 8, zoomOnScroll: false, regionStyle: { initial: { 'fill': opts.regionFill, 'fill-opacity': 1, 'stroke': 'none', 'stroke-width': 1.5, 'stroke-opacity': 1 }, hover: { 'fill-opacity': 0.8 }, selected: { fill: 'blue' }, selectedHover: {} }, focusOn: { x: 0.4, y: 0.6, scale: opts.scale }, markerStyle: { initial: { fill: opts.markerColor, stroke: opts.markerColor } }, onRegionLabelShow: function(e, el, code) { if (series && series[code]) el.html(el.html() + ': ' + series[ code] + ' visitors'); }, markers: markers, series: { regions: [{ values: series, scale: opts.scaleColors, normalizeFunction: 'polynomial' }] }, }); } // end init }; export default function () { var element = $(this); // New vector map instance new VectorMap(element, seriesData, markersData); }
SUNWU07/arm-trusted-firmware
plat/st/common/stm32mp_fconf_io.c
<gh_stars>1-10 /* * Copyright (c) 2021, STMicroelectronics - All Rights Reserved * * SPDX-License-Identifier: BSD-3-Clause */ #include <assert.h> #include <common/debug.h> #include <common/fdt_wrappers.h> #include <drivers/io/io_storage.h> #include <drivers/mmc.h> #include <lib/fconf/fconf.h> #include <lib/object_pool.h> #include <libfdt.h> #include <tools_share/firmware_image_package.h> #include <platform_def.h> #include <stm32mp_efi.h> #include <stm32mp_fconf_getter.h> #include <stm32mp_io_storage.h> #if STM32MP_SDMMC || STM32MP_EMMC static io_block_spec_t gpt_block_spec = { .offset = 0U, .length = 34U * MMC_BLOCK_SIZE, /* Size of GPT table */ }; #endif #if (STM32MP_SDMMC || STM32MP_EMMC) && PSA_FWU_SUPPORT io_block_spec_t metadata_block_spec = { .offset = 0, /* To be filled at runtime */ .length = 0, /* To be filled at runtime */ }; #endif /* (STM32MP_SDMMC || STM32MP_EMMC) && PSA_FWU_SUPPORT */ /* By default, STM32 platforms load images from the FIP */ struct plat_io_policy policies[MAX_NUMBER_IDS] = { [FIP_IMAGE_ID] = { .dev_handle = &storage_dev_handle, .image_spec = (uintptr_t)&image_block_spec, .img_type_guid = STM32MP_FIP_GUID, .check = open_storage }, #if STM32MP_SDMMC || STM32MP_EMMC [GPT_IMAGE_ID] = { .dev_handle = &storage_dev_handle, .image_spec = (uintptr_t)&gpt_block_spec, .img_type_guid = NULL_GUID, .check = open_storage }, #endif #if (STM32MP_SDMMC || STM32MP_EMMC) && PSA_FWU_SUPPORT [FWU_METADATA_IMAGE_ID] = { .dev_handle = &storage_dev_handle, .image_spec = (uintptr_t)&metadata_block_spec, .img_type_guid = NULL_GUID, .check = open_storage }, [BKUP_FWU_METADATA_IMAGE_ID] = { .dev_handle = &storage_dev_handle, .image_spec = (uintptr_t)&metadata_block_spec, .img_type_guid = NULL_GUID, .check = open_storage }, #endif /* (STM32MP_SDMMC || STM32MP_EMMC) && PSA_FWU_SUPPORT */ }; #define FCONF_ST_IO_UUID_NUMBER U(8) static io_uuid_spec_t fconf_stm32mp_uuids[FCONF_ST_IO_UUID_NUMBER]; static OBJECT_POOL_ARRAY(fconf_stm32mp_uuids_pool, fconf_stm32mp_uuids); struct policies_load_info { unsigned int image_id; const char *name; }; /* image id to property name table */ static const struct policies_load_info load_info[FCONF_ST_IO_UUID_NUMBER] = { {FW_CONFIG_ID, "fw_cfg_uuid"}, {BL32_IMAGE_ID, "bl32_uuid"}, {BL32_EXTRA1_IMAGE_ID, "bl32_extra1_uuid"}, {BL32_EXTRA2_IMAGE_ID, "bl32_extra2_uuid"}, {BL33_IMAGE_ID, "bl33_uuid"}, {HW_CONFIG_ID, "hw_cfg_uuid"}, {TOS_FW_CONFIG_ID, "tos_fw_cfg_uuid"}, {NT_FW_CONFIG_ID, "nt_fw_cfg_uuid"}, }; int fconf_populate_stm32mp_io_policies(uintptr_t config) { int node; unsigned int i; /* As libfdt uses void *, we can't avoid this cast */ const void *dtb = (void *)config; /* Assert the node offset point to "st,io-fip-handle" compatible property */ const char *compatible_str = "st,io-fip-handle"; node = fdt_node_offset_by_compatible(dtb, -1, compatible_str); if (node < 0) { ERROR("FCONF: Can't find %s compatible in dtb\n", compatible_str); return node; } /* Locate the uuid cells and read the value for all the load info uuid */ for (i = 0U; i < FCONF_ST_IO_UUID_NUMBER; i++) { union uuid_helper_t uuid_helper; io_uuid_spec_t *uuid_ptr; int err; uuid_ptr = pool_alloc(&fconf_stm32mp_uuids_pool); err = fdtw_read_uuid(dtb, node, load_info[i].name, 16, (uint8_t *)&uuid_helper); if (err < 0) { WARN("FCONF: Read cell failed for %s\n", load_info[i].name); return err; } VERBOSE("FCONF: stm32mp-io_policies.%s cell found with value = " "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x\n", load_info[i].name, uuid_helper.uuid_struct.time_low[0], uuid_helper.uuid_struct.time_low[1], uuid_helper.uuid_struct.time_low[2], uuid_helper.uuid_struct.time_low[3], uuid_helper.uuid_struct.time_mid[0], uuid_helper.uuid_struct.time_mid[1], uuid_helper.uuid_struct.time_hi_and_version[0], uuid_helper.uuid_struct.time_hi_and_version[1], uuid_helper.uuid_struct.clock_seq_hi_and_reserved, uuid_helper.uuid_struct.clock_seq_low, uuid_helper.uuid_struct.node[0], uuid_helper.uuid_struct.node[1], uuid_helper.uuid_struct.node[2], uuid_helper.uuid_struct.node[3], uuid_helper.uuid_struct.node[4], uuid_helper.uuid_struct.node[5]); uuid_ptr->uuid = uuid_helper.uuid_struct; policies[load_info[i].image_id].image_spec = (uintptr_t)uuid_ptr; policies[load_info[i].image_id].dev_handle = &fip_dev_handle; policies[load_info[i].image_id].check = open_fip; } return 0; } FCONF_REGISTER_POPULATOR(TB_FW, stm32mp_io, fconf_populate_stm32mp_io_policies);
Valbod-I-am-a-Swiftie/jdi-light
jdi-light-angular-tests/src/test/java/io/github/epam/angular/tests/elements/common/BasicButtonTests.java
package io.github.epam.angular.tests.elements.common; import com.epam.jdi.light.common.ElementArea; import io.github.epam.TestsInit; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import static io.github.com.StaticSite.angularPage; import static io.github.com.pages.AngularPage.basicButtonsSection; import static io.github.com.pages.sections.BasicButtonsSection.*; import static io.github.epam.site.steps.States.shouldBeLoggedIn; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.is; public class BasicButtonTests extends TestsInit { private static final String BASIC_TEXT = "Basic"; private static final String PRIMARY_TEXT = "Primary"; private static final String ACCENT_TEXT = "Accent"; private static final String WARN_TEXT = "Warn"; private static final String DISABLED_TEXT = "Disabled"; private static final String LINK_TEXT = "Link"; private static final String FOCUSED_CLASS = "cdk-focused"; @BeforeTest public void before() { shouldBeLoggedIn(); angularPage.shouldBeOpened(); basicBasicButton.show(); } @Test public void basicTest() { basicBasicButton.is().displayed(); basicPrimaryButton.is().displayed(); basicAccentButton.is().displayed(); basicWarnButton.is().displayed(); basicDisabledButton.is().displayed(); basicLinkButton.is().displayed(); } @Test public void getTextTest() { basicBasicButton.is().text(BASIC_TEXT); basicPrimaryButton.is().text(PRIMARY_TEXT); basicAccentButton.is().text(ACCENT_TEXT); basicWarnButton.is().text(WARN_TEXT); basicDisabledButton.is().text(DISABLED_TEXT); basicLinkButton.is().text(LINK_TEXT); } @Test public void getValueTest() { basicBasicButton.is().value(BASIC_TEXT); basicPrimaryButton.is().value(PRIMARY_TEXT); basicAccentButton.is().value(ACCENT_TEXT); basicWarnButton.is().value(WARN_TEXT); basicDisabledButton.is().value(DISABLED_TEXT); basicLinkButton.is().value(LINK_TEXT); } @Test public void clickTest() { basicBasicButton.click(); basicBasicButton.has().cssClass(FOCUSED_CLASS); basicButtonsSection.basicButtonsLabel.is().has().text(containsString(BASIC_TEXT)); } @Test public void clickWithMoveTest() { basicWarnButton.click(ElementArea.TOP_LEFT); basicWarnButton.has().cssClass(FOCUSED_CLASS); basicButtonsSection.basicButtonsLabel.is().has().text(containsString(WARN_TEXT)); } @Test public void disableButtonTest() { basicDisabledButton.is().disabled(); } @Test public void assertValidationTest() { basicBasicButton.assertThat().text(is(BASIC_TEXT)); basicPrimaryButton.assertThat().text(is(PRIMARY_TEXT)); basicAccentButton.assertThat().text(is(ACCENT_TEXT)); basicWarnButton.assertThat().text(is(WARN_TEXT)); basicDisabledButton.assertThat().text(is(DISABLED_TEXT)); basicLinkButton.assertThat().text(is(LINK_TEXT)); } @Test public void isValidationTest() { basicWarnButton.is().displayed(); basicWarnButton.is().enabled(); basicWarnButton.is().text(is(WARN_TEXT)); basicWarnButton.is().text(containsString(WARN_TEXT)); assertThat(basicWarnButton.core().css("font-size"), is("14px")); basicWarnButton.assertThat().displayed() .and().text(is(WARN_TEXT)) .core() .css("font-size", is("14px")) .and() .cssClass("mat-button") .and() .attr("type") .tag(is("button")); basicDisabledButton.is().text(containsString(DISABLED_TEXT)); basicDisabledButton.is().disabled(); } }
mmarovich/UA-Frontend
app/containers/Dashboard/Roles/MilesZip/index.js
export { default } from './MilesZip';
lauracristinaes/aula-java
hibernate-release-5.3.7.Final/project/hibernate-core/src/test/java/org/hibernate/test/annotations/backquotes/Bug.java
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ //$Id$ package org.hibernate.test.annotations.backquotes; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import org.hibernate.annotations.Index; @Entity public class Bug { @Id @Column(name="`bug_id`") private int id; @Column(name="`title`") @Index(name="`titleindex`") private String title; @ManyToMany @JoinTable(name="`bug_category`") private List<Category> categories; public List<Category> getCategories() { return categories; } public void setCategories(List<Category> categories) { this.categories = categories; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
Maledictus/leechcraft
src/plugins/azoth/plugins/sarin/toxaccount.cpp
<filename>src/plugins/azoth/plugins/sarin/toxaccount.cpp /********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 <NAME> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "toxaccount.h" #include <QUuid> #include <QAction> #include <QDataStream> #include <QtDebug> #include <tox/tox.h> #include <util/xpc/util.h> #include <util/sll/slotclosure.h> #include <util/sll/functional.h> #include <util/threads/futures.h> #include <interfaces/core/ientitymanager.h> #include "toxprotocol.h" #include "toxthread.h" #include "showtoxiddialog.h" #include "toxcontact.h" #include "messagesmanager.h" #include "chatmessage.h" #include "accountconfigdialog.h" #include "util.h" #include "filetransfermanager.h" #ifdef ENABLE_MEDIACALLS #include "audiocall.h" #endif namespace LC::Azoth::Sarin { ToxAccount::ToxAccount (const QByteArray& uid, const QString& name, ToxProtocol *parent) : QObject { parent } , Proto_ { parent } , UID_ { uid } , Name_ { name } , ActionGetToxId_ { new QAction { tr ("Get Tox ID"), this } } , MsgsMgr_ { new MessagesManager { this } } , XferMgr_ { new FileTransferManager { this } } { connect (ActionGetToxId_, &QAction::triggered, this, &ToxAccount::HandleToxIdRequested); connect (MsgsMgr_, &MessagesManager::gotMessage, this, &ToxAccount::HandleInMessage); connect (this, &ToxAccount::threadChanged, XferMgr_, &FileTransferManager::HandleToxThreadChanged); } ToxAccount::ToxAccount (const QString& name, ToxProtocol *parent) : ToxAccount { QUuid::createUuid ().toByteArray (), name, parent } { } QByteArray ToxAccount::Serialize () { QByteArray ba; QDataStream str { &ba, QIODevice::WriteOnly }; str << static_cast<quint8> (2) << UID_ << Name_ << Nick_ << ToxState_ << ToxConfig_; return ba; } ToxAccount* ToxAccount::Deserialize (const QByteArray& data, ToxProtocol *proto) { QDataStream str { data }; quint8 version = 0; str >> version; if (version < 1 || version > 2) { qWarning () << Q_FUNC_INFO << "unknown version" << version; return nullptr; } QByteArray uid; QString name; str >> uid >> name; const auto acc = new ToxAccount { uid, name, proto }; str >> acc->Nick_ >> acc->ToxState_; if (version >= 2) str >> acc->ToxConfig_; return acc; } void ToxAccount::SetNickname (const QString& nickname) { if (nickname == Nick_) return; Nick_ = nickname; emit accountChanged (this); } ToxContact* ToxAccount::GetByAzothId (const QString& azothId) const { const auto& localId = azothId.section ('/', 1).toUtf8 (); if (!Contacts_.contains (localId)) qWarning () << Q_FUNC_INFO << "unable to find entry for Azoth ID" << azothId; return Contacts_.value (localId); } ToxContact* ToxAccount::GetByPubkey (const QByteArray& pubkey) const { return Contacts_.value (pubkey); } QObject* ToxAccount::GetQObject () { return this; } QObject* ToxAccount::GetParentProtocol () const { return Proto_; } IAccount::AccountFeatures ToxAccount::GetAccountFeatures () const { return FRenamable; } QList<QObject*> ToxAccount::GetCLEntries () { QList<QObject*> result; std::copy (Contacts_.begin (), Contacts_.end (), std::back_inserter (result)); return result; } QString ToxAccount::GetAccountName () const { return Name_; } QString ToxAccount::GetOurNick () const { return Nick_.isEmpty () ? Name_ : Nick_; } void ToxAccount::RenameAccount (const QString& name) { if (name == Name_) return; Name_ = name; emit accountRenamed (Name_); emit accountChanged (this); } QByteArray ToxAccount::GetAccountID () const { return UID_; } QList<QAction*> ToxAccount::GetActions () const { return { ActionGetToxId_ }; } void ToxAccount::OpenConfigurationDialog () { auto configDialog = new AccountConfigDialog; configDialog->setAttribute (Qt::WA_DeleteOnClose); configDialog->show (); configDialog->SetConfig (ToxConfig_); new Util::SlotClosure<Util::DeleteLaterPolicy> { [this, configDialog] { HandleConfigAccepted (configDialog); }, configDialog, SIGNAL (accepted ()), configDialog }; } EntryStatus ToxAccount::GetState () const { return Thread_ ? Thread_->GetStatus () : EntryStatus {}; } void ToxAccount::ChangeState (const EntryStatus& status) { if (status.State_ == SOffline) { if (Thread_ && Thread_->IsStoppable ()) { new Util::SlotClosure<Util::DeleteLaterPolicy> { [status, guard = Thread_, this] { emit statusChanged (status); }, Thread_.get (), SIGNAL (finished ()), Thread_.get () }; Thread_->Stop (); } Thread_.reset (); emit threadChanged (Thread_); return; } if (!Thread_) InitThread (status); else Thread_->SetStatus (status); } void ToxAccount::Authorize (QObject *entryObj) { if (!Thread_) return; const auto entry = qobject_cast<ToxContact*> (entryObj); Thread_->AddFriend (entry->GetPubKey ()); } void ToxAccount::DenyAuth (QObject*) { } void ToxAccount::RequestAuth (const QString& toxId, const QString& msg, const QString&, const QStringList&) { if (!Thread_) return; auto iem = Proto_->GetCoreProxy ()->GetEntityManager (); Util::Sequence (this, Thread_->AddFriend (toxId.toLatin1 (), msg)) >> [iem] (ToxThread::AddFriendResult result) { const auto notify = [iem] (Priority prio, const QString& text) { iem->HandleEntity (Util::MakeNotification ("<NAME>", text, prio)); }; switch (result) { case ToxThread::AddFriendResult::Added: return; case ToxThread::AddFriendResult::InvalidId: notify (Priority::Critical, tr ("Friend was not added: invalid Tox ID.")); return; case ToxThread::AddFriendResult::TooLong: notify (Priority::Critical, tr ("Friend was not added: too long greeting message.")); return; case ToxThread::AddFriendResult::NoMessage: notify (Priority::Critical, tr ("Friend was not added: no message.")); return; case ToxThread::AddFriendResult::OwnKey: notify (Priority::Critical, tr ("Why would you add yourself as friend?")); return; case ToxThread::AddFriendResult::AlreadySent: notify (Priority::Warning, tr ("Friend request has already been sent.")); return; case ToxThread::AddFriendResult::BadChecksum: notify (Priority::Critical, tr ("Friend was not added: bad Tox ID checksum.")); return; case ToxThread::AddFriendResult::NoSpam: notify (Priority::Critical, tr ("Friend was not added: nospam value has been changed. Get a freshier ID!")); return; case ToxThread::AddFriendResult::NoMem: notify (Priority::Critical, tr ("Friend was not added: no memory (but how do you see this in that case?).")); return; case ToxThread::AddFriendResult::Unknown: notify (Priority::Critical, tr ("Friend was not added because of some unknown error.")); return; } }; } void ToxAccount::RemoveEntry (QObject *entryObj) { if (!Thread_) return; const auto entry = qobject_cast<ToxContact*> (entryObj); if (!entry) { qWarning () << Q_FUNC_INFO << entryObj << "is not a ToxContact"; return; } Thread_->RemoveFriend (entry->GetHumanReadableID ().toUtf8 ()); } ISupportMediaCalls::MediaCallFeatures ToxAccount::GetMediaCallFeatures () const { #ifdef ENABLE_MEDIACALLS return MCFSupportsAudioCalls; #else return MCFNoFeatures; #endif } QObject* ToxAccount::Call (const QString& id, const QString&) { #ifdef ENABLE_MEDIACALLS if (!Thread_) { qWarning () << Q_FUNC_INFO << "thread is not running"; return nullptr; } const auto entry = GetByAzothId (id); if (!entry) { qWarning () << Q_FUNC_INFO << "unable to find contact by" << id; return nullptr; } const auto callMgr = Thread_->GetCallManager (); const auto call = new AudioCall { entry, callMgr, AudioCall::DOut }; emit called (call); Util::Sequence (entry, Thread_->ResolveFriendId (entry->GetPubKey ())) >> Util::BindMemFn (&AudioCall::SetCallIdx, call); return call; #else Q_UNUSED (id) return nullptr; #endif } QObject* ToxAccount::GetTransferManager () const { return XferMgr_; } void ToxAccount::SendMessage (const QByteArray& pkey, ChatMessage *message) { MsgsMgr_->SendMessage (pkey, message); } void ToxAccount::SetTypingState (const QByteArray& pkey, bool isTyping) { if (!Thread_) return; Thread_->ScheduleFunction ([pkey, isTyping] (Tox *tox) { const auto num = GetFriendId (tox, pkey); if (!num) { qWarning () << Q_FUNC_INFO << "unable to find user ID for" << pkey; return; } TOX_ERR_SET_TYPING error {}; if (!tox_self_set_typing (tox, *num, isTyping, &error)) qWarning () << Q_FUNC_INFO << "cannot set typing state to" << isTyping << "because of error" << error; }); } void ToxAccount::InitThread (const EntryStatus& status) { Thread_ = std::make_shared<ToxThread> (Nick_, ToxState_, ToxConfig_); Thread_->SetStatus (status); connect (Thread_.get (), &ToxThread::statusChanged, this, &ToxAccount::statusChanged); connect (Thread_.get (), &ToxThread::toxStateChanged, this, [this] (const QByteArray& toxState) { ToxState_ = toxState; emit accountChanged (this); }); connect (Thread_.get (), &ToxThread::gotFriendRequest, this, &ToxAccount::HandleGotFriendRequest); connect (Thread_.get (), &ToxThread::gotFriend, this, &ToxAccount::HandleGotFriend); connect (Thread_.get (), &ToxThread::friendNameChanged, this, &ToxAccount::HandleFriendNameChanged); connect (Thread_.get (), &ToxThread::friendStatusChanged, this, &ToxAccount::HandleFriendStatusChanged); connect (Thread_.get (), &ToxThread::friendTypingChanged, this, &ToxAccount::HandleFriendTypingChanged); connect (Thread_.get (), &ToxThread::removedFriend, this, &ToxAccount::HandleRemovedFriend); connect (Thread_.get (), &ToxThread::fatalException, this, &ToxAccount::HandleThreadFatalException); connect (Thread_.get (), &ToxThread::toxCreated, this, &ToxAccount::HandleThreadReady); emit threadChanged (Thread_); Thread_->start (QThread::IdlePriority); } void ToxAccount::InitEntry (const QByteArray& pkey) { const auto entry = new ToxContact { pkey, this }; Contacts_ [pkey] = entry; emit gotCLItems ({ entry }); } void ToxAccount::HandleConfigAccepted (AccountConfigDialog *dialog) { const auto& config = dialog->GetConfig (); if (config == ToxConfig_) return; ToxConfig_ = config; emit accountChanged (this); } void ToxAccount::HandleThreadReady () { if (!Thread_) return; #ifdef ENABLE_MEDIACALLS const auto callManager = Thread_->GetCallManager (); connect (callManager, &CallManager::gotIncomingCall, this, &ToxAccount::HandleIncomingCall); #endif } void ToxAccount::HandleIncomingCall (const QByteArray& pubkey, int32_t callIdx) { #ifdef ENABLE_MEDIACALLS qDebug () << Q_FUNC_INFO << pubkey << callIdx; const auto entry = Contacts_.value (pubkey); if (!entry) { qWarning () << Q_FUNC_INFO << "cannot find entry by pubkey" << pubkey; return; } const auto call = new AudioCall { entry, Thread_->GetCallManager (), AudioCall::DIn }; call->SetCallIdx (callIdx); emit called (call); #else Q_UNUSED (pubkey) Q_UNUSED (callIdx) #endif } void ToxAccount::HandleToxIdRequested () { if (!Thread_) return; auto dialog = new ShowToxIdDialog { tr ("Fetching self Tox ID...") }; dialog->show (); dialog->setAttribute (Qt::WA_DeleteOnClose); Util::Sequence (this, Thread_->GetToxId ()) >> [dialog] (const QByteArray& id) { dialog->setToxId (QString::fromLatin1 (id)); }; } void ToxAccount::HandleGotFriend (qint32 id) { Util::Sequence (this, Thread_->ResolveFriend (id)) >> [this] (const ToxThread::FriendInfo& info) { try { qDebug () << Q_FUNC_INFO << info.Pubkey_ << info.Name_; if (!Contacts_.contains (info.Pubkey_)) InitEntry (info.Pubkey_); const auto entry = Contacts_.value (info.Pubkey_); entry->SetEntryName (info.Name_); entry->SetStatus (info.Status_); } catch (const std::exception& e) { qWarning () << Q_FUNC_INFO << "cannot get friend info:" << e.what (); } }; } void ToxAccount::HandleGotFriendRequest (const QByteArray& pubkey, const QString& msg) { if (!Contacts_.contains (pubkey)) InitEntry (pubkey); emit authorizationRequested (Contacts_.value (pubkey), msg.trimmed ()); } void ToxAccount::HandleRemovedFriend (const QByteArray& pubkey) { if (!Contacts_.contains (pubkey)) return; const auto item = Contacts_.take (pubkey); emit removedCLItems ({ item }); item->deleteLater (); } void ToxAccount::HandleFriendNameChanged (const QByteArray& id, const QString& newName) { if (!Contacts_.contains (id)) { qWarning () << Q_FUNC_INFO << "unknown friend name change" << id << "; new name:" << newName; return; } Contacts_.value (id)->SetEntryName (newName); } void ToxAccount::HandleFriendStatusChanged (const QByteArray& pubkey, const EntryStatus& status) { if (!Contacts_.contains (pubkey)) { qWarning () << Q_FUNC_INFO << "unknown friend status" << pubkey; return; } Contacts_.value (pubkey)->SetStatus (status); } void ToxAccount::HandleFriendTypingChanged (const QByteArray& pubkey, bool isTyping) { if (!Contacts_.contains (pubkey)) { qWarning () << Q_FUNC_INFO << "unknown friend status" << pubkey; return; } Contacts_.value (pubkey)->SetTyping (isTyping); } void ToxAccount::HandleInMessage (const QByteArray& pubkey, const QString& body) { if (!Contacts_.contains (pubkey)) { qWarning () << Q_FUNC_INFO << "unknown pubkey for message" << body << pubkey; InitEntry (pubkey); } const auto contact = Contacts_.value (pubkey); const auto msg = new ChatMessage { body, IMessage::Direction::In, contact }; msg->Store (); } void ToxAccount::HandleThreadFatalException (const Util::QtException_ptr& e) { qWarning () << Q_FUNC_INFO << e->what (); emit statusChanged ({ SError, e->what () }); } }
maroozm/AliPhysics
PWGPP/EVCHAR/FlowVectorCorrections/QnCorrections/AliQnCorrectionsCutsSet.h
#ifndef ALIQNCORRECTIONS_CUTSSET_H #define ALIQNCORRECTIONS_CUTSSET_H /*************************************************************************** * Package: FlowVectorCorrections * * Authors: <NAME>, GSI, <EMAIL> * * <NAME>, GSI, <EMAIL> * * <NAME>, UCM, <EMAIL> * * Contributors are mentioned in the code where appropriate.* * Development: 2012-2016 * * See cxx source for GPL licence et. al. * ***************************************************************************/ #include "AliQnCorrectionsCutsBase.h" /// \file AliQnCorrectionsCutsSet.h /// \brief Set of cuts class support for the Q vector correction framework /// \class AliQnCorrectionsCutsSet /// \brief Set of cuts to assign to a detector /// /// Array of cuts that contains the whole set of cuts to assign to /// a concrete detector or detector configuration to filter the desired /// events (in the broad sense) it will have to handle. /// /// Inherits all the methods of TObjArray specially the /// subscript [] operator and Add method that allows /// the array to expand. /// /// Provides IsSelected that goes through the whole set of cuts /// to check whether the current variables values pass the them. /// /// The cuts objects are not own by the array so, /// they are not destroyed when the the set is destroyed. This allows /// to create several sets with the same cuts. /// Pay attention to this when you create your cuts, /// they should live at least the same time you expect the sets to /// live. /// /// \author <NAME> <<EMAIL>>, GSI /// \author <NAME> <<EMAIL>>, GSI /// \author <NAME> <<EMAIL>>, UCM /// \date Jan 4, 2016 class AliQnCorrectionsCutsSet : public TObjArray { public: /// Normal constructor /// \param n number of cuts in the set AliQnCorrectionsCutsSet(Int_t n = TCollection::kInitCapacity) : TObjArray(n) {} /// Copy constructor /// \param ccs the object instance to be copied AliQnCorrectionsCutsSet(const AliQnCorrectionsCutsSet &ccs) : TObjArray(ccs) {} /// Default destructor virtual ~AliQnCorrectionsCutsSet() {} /// Access the event class variable at the passed position /// \param i position in the array (starting at zero) /// \return the event class variable object a position i virtual AliQnCorrectionsCutsBase *At(Int_t i) const { return (AliQnCorrectionsCutsBase *) TObjArray::At(i); } Bool_t IsSelected(const Float_t *variableContainer); /// \cond CLASSIMP ClassDef(AliQnCorrectionsCutsSet, 1); /// \endcond }; /// Checks that the current content of the variableContainer passes /// the whole set of cuts by going through all the array components /// /// \param variableContainer the current variables content addressed by var Id /// \return kTRUE if the actual values pass the set of cuts else kFALSE inline Bool_t AliQnCorrectionsCutsSet::IsSelected(const Float_t *variableContainer) { for (Int_t icut = 0; icut < GetEntriesFast(); icut++) { if (!At(icut)->IsSelected(variableContainer)) { return kFALSE; } } return kTRUE; } #endif // ALIQNCORRECTIONS_CUTSSET_H
faddat/classic
crypto/mock/mock.go
package mock import ( "bytes" "fmt" "github.com/tendermint/classic/crypto" cmn "github.com/tendermint/classic/libs/common" amino "github.com/tendermint/go-amino-x" ) //------------------------------------- // These are fake crypto implementations, useful for testing. var _ crypto.PrivKey = PrivKeyMock{} // PrivKeyMock implements crypto.PrivKey. type PrivKeyMock []byte // Bytes marshals the privkey using amino encoding w/ type information. func (privKey PrivKeyMock) Bytes() []byte { return amino.MustMarshalAny(privKey) } // Make a fake signature. Its length is variable. func (privKey PrivKeyMock) Sign(msg []byte) ([]byte, error) { sigBytes := []byte(fmt.Sprintf("signature-for-%X-by-%X", msg, []byte(privKey))) return sigBytes, nil } func (privKey PrivKeyMock) PubKey() crypto.PubKey { return PubKeyMock(privKey) } func (privKey PrivKeyMock) Equals(other crypto.PrivKey) bool { if otherMock, ok := other.(PrivKeyMock); ok { return bytes.Equal(privKey, otherMock) } else { return false } } func GenPrivKey() PrivKeyMock { randstr := cmn.RandStr(12) return PrivKeyMock([]byte(randstr)) } //------------------------------------- var _ crypto.PubKey = PubKeyMock{} type PubKeyMock []byte // Returns address w/ pubkey as suffix (for debugging). func (pubKey PubKeyMock) Address() crypto.Address { if len(pubKey) > 20 { panic("PubKeyMock cannot have pubkey greater than 20 bytes") } addr := crypto.Address{} copy(addr[20-len(pubKey):], pubKey) return crypto.Address(addr) } // Bytes marshals the PubKey using amino encoding. func (pubKey PubKeyMock) Bytes() []byte { return amino.MustMarshalAny(pubKey) } func (pubKey PubKeyMock) VerifyBytes(msg []byte, sig []byte) bool { sigBytes := []byte(fmt.Sprintf("signature-for-%X-by-%X", msg, []byte(pubKey))) return bytes.Equal(sig, sigBytes) } func (pubKey PubKeyMock) String() string { return fmt.Sprintf("PubKeyMock{%X}", ([]byte(pubKey))[:]) } // nolint: golint func (pubKey PubKeyMock) Equals(other crypto.PubKey) bool { if otherMock, ok := other.(PubKeyMock); ok { return bytes.Equal(pubKey[:], otherMock[:]) } else { return false } }
rudylee/expo
ios/Pods/Headers/Public/ABI37_0_0ExpoKit/ABI37_0_0EXUpdates.h
<gh_stars>1-10 // Copyright 2016-present 650 Industries. All rights reserved. #import "ABI37_0_0EXResourceLoader.h" #import "ABI37_0_0EXScopedBridgeModule.h" #import "ABI37_0_0EXScopedModuleRegistry.h" NS_ASSUME_NONNULL_BEGIN FOUNDATION_EXPORT NSString * const ABI37_0_0EXUpdatesEventName; FOUNDATION_EXPORT NSString * const ABI37_0_0EXUpdatesErrorEventType; FOUNDATION_EXPORT NSString * const ABI37_0_0EXUpdatesNotAvailableEventType; FOUNDATION_EXPORT NSString * const ABI37_0_0EXUpdatesDownloadStartEventType; FOUNDATION_EXPORT NSString * const ABI37_0_0EXUpdatesDownloadProgressEventType; FOUNDATION_EXPORT NSString * const ABI37_0_0EXUpdatesDownloadFinishedEventType; @protocol ABI37_0_0EXUpdatesScopedModuleDelegate - (void)updatesModuleDidSelectReload:(id)scopedModule; - (void)updatesModuleDidSelectReloadFromCache:(id)scopedModule; - (void)updatesModule:(id)scopedModule didRequestManifestWithCacheBehavior:(ABI37_0_0EXManifestCacheBehavior)cacheBehavior success:(void (^)(NSDictionary * _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure; - (void)updatesModule:(id)scopedModule didRequestBundleWithManifest:(NSDictionary *)manifest progress:(void (^)(NSDictionary * _Nonnull))progress success:(void (^)(NSData * _Nonnull))success failure:(void (^)(NSError * _Nonnull))failure; @end @interface ABI37_0_0EXUpdates : ABI37_0_0EXScopedBridgeModule - (void)sendEventWithBody:(NSDictionary *)body; @end ABI37_0_0EX_DECLARE_SCOPED_MODULE_GETTER(ABI37_0_0EXUpdates, updates) NS_ASSUME_NONNULL_END
ifleeyo180/VspriteMoodleWebsite
htdocs/moodle/h5p/h5plib/v124/joubel/editor/scripts/h5peditor-file.js
/* global ns */ /** * Adds a file upload field to the form. * * @param {mixed} parent * @param {object} field * @param {mixed} params * @param {function} setValue * @returns {ns.File} */ ns.File = function (parent, field, params, setValue) { var self = this; // Initialize inheritance ns.FileUploader.call(self, field); this.parent = parent; this.field = field; this.params = params; this.setValue = setValue; this.library = parent.library + '/' + field.name; this.id = ns.getNextFieldId(field); if (params !== undefined) { this.copyright = params.copyright; } this.changes = []; this.passReadies = true; parent.ready(function () { self.passReadies = false; }); // Create remove file dialog this.confirmRemovalDialog = new H5P.ConfirmationDialog({ headerText: H5PEditor.t('core', 'removeFile'), dialogText: H5PEditor.t('core', 'confirmRemoval', {':type': 'file'}) }).appendTo(document.body); // Remove file on confirmation this.confirmRemovalDialog.on('confirmed', function () { delete self.params; self.setValue(self.field); self.addFile(); for (var i = 0; i < self.changes.length; i++) { self.changes[i](); } }); // When uploading starts self.on('upload', function () { // Insert throbber self.$file.html('<div class="h5peditor-uploading h5p-throbber">' + ns.t('core', 'uploading') + '</div>'); // Clear old error messages self.$errors.html(''); }); // Monitor upload progress self.on('uploadProgress', function (e) { self.$file.children().html(ns.t('core', 'uploading') + ' ' + Math.round(e.data * 100) + ' %'); }); // Handle upload complete self.on('uploadComplete', function (event) { var result = event.data; try { if (result.error) { throw result.error; } self.params = self.params || {}; self.params.path = result.data.path; self.params.mime = result.data.mime; self.params.copyright = self.copyright; // Make it possible for other widgets to process the result self.trigger('fileUploaded', result.data); self.setValue(self.field, self.params); for (var i = 0; i < self.changes.length; i++) { self.changes[i](self.params); } } catch (error) { self.$errors.append(ns.createError(error)); } self.addFile(); }); }; ns.File.prototype = Object.create(ns.FileUploader.prototype); ns.File.prototype.constructor = ns.File; /** * Append field to the given wrapper. * * @param {jQuery} $wrapper * @returns {undefined} */ ns.File.prototype.appendTo = function ($wrapper) { var self = this; var fileHtml = '<div class="file"></div>' + '<a class="h5p-copyright-button" href="#">' + ns.t('core', 'editCopyright') + '</a>' + '<div class="h5p-editor-dialog">' + '<a href="#" class="h5p-close" title="' + ns.t('core', 'close') + '"></a>' + '</div>'; var html = ns.createFieldMarkup(this.field, fileHtml, this.id); var $container = ns.$(html).appendTo($wrapper); this.$copyrightButton = $container.find('.h5p-copyright-button'); this.$file = $container.find('.file'); this.$errors = $container.find('.h5p-errors'); this.addFile(); var $dialog = $container.find('.h5p-editor-dialog'); $container.find('.h5p-copyright-button').add($dialog.find('.h5p-close')).click(function () { $dialog.toggleClass('h5p-open'); return false; }); ns.File.addCopyright(self, $dialog, function (field, value) { if (self.params !== undefined) { self.params.copyright = value; } self.copyright = value; }); }; /** * Help add copyright dialog to the given field * * @param {Object} field * @param {function} setCopyright */ ns.File.addCopyright = function (field, $dialog, setCopyright) { /** * Help find object in list with the given property value. * * @param {Object[]} list of objects to search through * @param {string} property to look for * @param {string} value to match property value against */ var find = function (list, property, value) { var properties = property.split('.'); for (var i = 0; i < list.length; i++) { var objProp = list[i]; for (var j = 0; j < properties.length; j++) { objProp = objProp[properties[j]]; } if (objProp === value) { return list[i]; } } }; // Re-map old licenses that have been moved if (field.copyright) { if (field.copyright.license === 'ODC PDDL') { field.copyright.license = 'PD'; field.copyright.version = 'CC0 1.0'; } else if (field.copyright.license === 'CC PDM') { field.copyright.license = 'PD'; field.copyright.version = 'CC PDM'; } } var group = new H5PEditor.widgets.group(field, H5PEditor.copyrightSemantics, field.copyright, setCopyright); // TODO: We'll have to do something here with metadataSemantics if we change the widgtets group.appendTo($dialog); group.expand(); group.$group.find('.title').remove(); field.children = [group]; // Locate license and version selectors var licenseField = find(group.children, 'field.name', 'license'); var versionField = find(group.children, 'field.name', 'version'); versionField.field.optional = true; // Avoid any error messages // Listen for changes to license licenseField.changes.push(function (value) { // Find versions for selected value var option = find(licenseField.field.options, 'value', value); var versions = option.versions; versionField.$select.prop('disabled', versions === undefined); if (versions === undefined) { // If no versions add default versions = [{ value: '-', label: '-' }]; } // Find default selected version var selected = (field.copyright.license === value && field.copyright.version ? field.copyright.version : versions[0].value); // Update versions selector versionField.$select.html(H5PEditor.Select.createOptionsHtml(versions, selected)).change(); }); // Trigger update straight away licenseField.changes[licenseField.changes.length - 1](field.copyright.license); }; /** * Creates thumbnail HTML and actions. * * @returns {Boolean} */ ns.File.prototype.addFile = function () { var that = this; if (this.params === undefined) { let html = '<a href="#" id="' + this.id + '" class="add"'; if (this.field.description !== undefined) { html += ' aria-describedby="' + ns.getDescriptionId(this.id) + '"'; } html += ' title="' + ns.t('core', 'addFile') + '">' + '<div class="h5peditor-field-file-upload-text">' + ns.t('core', 'add') + '</div>' + '</a>' this.$file.html(html).children('.add').click(function () { that.openFileSelector(); return false; }); this.$copyrightButton.addClass('hidden'); return; } var thumbnail; if (this.field.type === 'image') { thumbnail = {}; thumbnail.path = H5P.getPath(this.params.path, H5PEditor.contentId); thumbnail.height = 100; if (this.params.width !== undefined) { thumbnail.width = thumbnail.height * (this.params.width / this.params.height); } } else { thumbnail = ns.fileIcon; } var fileHtmlString = '<a href="#" id="' + this.id + '" title="' + ns.t('core', 'changeFile') + '" class="thumbnail"'; if (this.field.description !== undefined) { fileHtmlString += ' aria-describedby="' + ns.getDescriptionId(this.id) + '"'; } fileHtmlString += '><img ' + (thumbnail.width === undefined ? '' : ' width="' + thumbnail.width + '"') + 'height="' + thumbnail.height + '" '+ 'alt="' + (this.field.label === undefined ? '' : this.field.label) + '"/></a>' + '<a href="#" class="remove" title="' + ns.t('core', 'removeFile') + '"></a>'; this.$file.html(fileHtmlString).children(':eq(0)').click(function () { that.openFileSelector(); return false; }).children('img').attr('src', thumbnail.path).end().next().click(function () { that.confirmRemovalDialog.show(H5P.jQuery(this).offset().top); return false; }); that.$copyrightButton.removeClass('hidden'); }; /** * Validate this item */ ns.File.prototype.validate = function () { return true; }; /** * Remove this item. */ ns.File.prototype.remove = function () { // TODO: Check what happens when removed during upload. this.$file.parent().remove(); }; /** * Collect functions to execute once the tree is complete. * * @param {function} ready * @returns {undefined} */ ns.File.prototype.ready = function (ready) { if (this.passReadies) { this.parent.ready(ready); } else { ready(); } }; // Tell the editor what widget we are. ns.widgets.file = ns.File;
npocmaka/Windows-Server-2003
windows/advcore/duser/engine/rockall/library/sharelock.cpp
// Ruler // 1 2 3 4 5 6 7 8 //345678901234567890123456789012345678901234567890123456789012345678901234567890 /********************************************************************/ /* */ /* The standard layout. */ /* */ /* The standard layout for 'cpp' files in this code is as */ /* follows: */ /* */ /* 1. Include files. */ /* 2. Constants local to the class. */ /* 3. Data structures local to the class. */ /* 4. Data initializations. */ /* 5. Static functions. */ /* 6. Class functions. */ /* */ /* The constructor is typically the first function, class */ /* member functions appear in alphabetical order with the */ /* destructor appearing at the end of the file. Any section */ /* or function this is not required is simply omitted. */ /* */ /********************************************************************/ #include "LibraryPCH.hpp" #include "Sharelock.hpp" /********************************************************************/ /* */ /* Constants local to the class. */ /* */ /* The Windows NT kernel requires a maximum wakeup count when */ /* creating a semaphore. */ /* */ /********************************************************************/ CONST SBIT32 MaxShareLockUsers = 256; /********************************************************************/ /* */ /* Class constructor. */ /* */ /* Create a new lock and initialize it. This call is not */ /* thread safe and should only be made in a single thread */ /* environment. */ /* */ /********************************************************************/ SHARELOCK::SHARELOCK( SBIT32 NewMaxSpins, SBIT32 NewMaxUsers ) { // // Check the configurable values. // if ( NewMaxSpins > 0 ) { MaxSpins = NewMaxSpins; } else { Failure( "Maximum spins invalid in constructor for SHARELOCK" ); } if ( (NewMaxUsers > 0) && (NewMaxUsers <= MaxShareLockUsers) ) { MaxUsers = NewMaxUsers; } else { Failure( "Maximum share invalid in constructor for SHARELOCK" ); } // // Set the initial state. // Exclusive = 0; TotalUsers = 0; #ifdef ENABLE_RECURSIVE_LOCKS Owner = NULL; Recursive = 0; #endif Waiting = 0; // // Create a semaphore to sleep on when the spin count exceeds // its maximum. // if ( (Semaphore = CreateSemaphore( NULL,0,MaxShareLockUsers,NULL )) == NULL) { Failure( "Create semaphore in constructor for SHARELOCK" ); } #ifdef ENABLE_LOCK_STATISTICS // // Zero the statistics. // TotalExclusiveLocks = 0; TotalShareLocks = 0; TotalSleeps = 0; TotalSpins = 0; TotalTimeouts = 0; TotalWaits = 0; #endif } /********************************************************************/ /* */ /* Sleep waiting for the lock. */ /* */ /* We have decided it is time to sleep waiting for the lock */ /* to become free. */ /* */ /********************************************************************/ BOOLEAN SHARELOCK::SleepWaitingForLock( SBIT32 Sleep ) { // // We have been spinning waiting for the lock but it // has not become free. Hence, it is now time to // give up and sleep for a while. // (VOID) AtomicIncrement( & Waiting ); // // Just before we go to sleep we do one final check // to make sure that the lock is still busy and that // there is someone to wake us up when it becomes free. // if ( TotalUsers > 0 ) { #ifdef ENABLE_LOCK_STATISTICS // // Count the number of times we have slept on this lock. // (VOID) AtomicIncrement( & TotalSleeps ); #endif // // When we sleep we awoken when the lock becomes free // or when we timeout. If we timeout we simply exit // after decrementing various counters. // if ( WaitForSingleObject( Semaphore, Sleep ) != WAIT_OBJECT_0 ) { #ifdef ENABLE_LOCK_STATISTICS // // Count the number of times we have timed out // on this lock. // (VOID) AtomicIncrement( & TotalTimeouts ); #endif return False; } } else { // // Lucky - the lock was just freed so lets // decrement the sleep count and exit without // sleeping. // (VOID) AtomicDecrement( & Waiting ); } return True; } /********************************************************************/ /* */ /* Update the spin limit. */ /* */ /* Update the maximum number of spins while waiting for the lock. */ /* */ /********************************************************************/ BOOLEAN SHARELOCK::UpdateMaxSpins( SBIT32 NewMaxSpins ) { if ( NewMaxSpins > 0 ) { MaxSpins = NewMaxSpins; return True; } else { return False; } } /********************************************************************/ /* */ /* Update the sharing limit. */ /* */ /* Update the maximum number of users that can share the lock. */ /* */ /********************************************************************/ BOOLEAN SHARELOCK::UpdateMaxUsers( SBIT32 NewMaxUsers ) { // // We need to Verify the new value makes sense. // if ( (NewMaxUsers > 0) && (NewMaxUsers <= MaxShareLockUsers) ) { ClaimExclusiveLock(); // // Update the maximum number of users. // MaxUsers = NewMaxUsers; ReleaseExclusiveLock(); return True; } else { return False; } } /********************************************************************/ /* */ /* Wait for an exclusive lock. */ /* */ /* Wait for the spinlock to become free and then claim it. */ /* */ /********************************************************************/ BOOLEAN SHARELOCK::WaitForExclusiveLock( SBIT32 Sleep ) { REGISTER LONG Cpus = ((LONG) NumberOfCpus()); #ifdef ENABLE_LOCK_STATISTICS REGISTER SBIT32 Spins = 0; REGISTER SBIT32 Waits = 0; #endif // // We will loop round in this function until the // following condition becomes false. // while ( TotalUsers != 1 ) { // // The lock is busy so release it and spin waiting // for it to become free. // (VOID) AtomicDecrement( & TotalUsers ); // // We will only try spinning and sleeping if we // are permitted to do so by the parameters. // if ( Sleep != 0 ) { REGISTER SBIT32 Count; // // If there are already more threads waiting // than the number of CPUs then the odds of // getting the lock by spinning are slim, when // there is only one CPU the chance is zero, so // just bypass this step. // if ( (Cpus > 1) && (Cpus > Waiting) ) { // // Wait by spinning and repeatedly testing the // spinlock. We exit when the lock becomes free // or the spin limit is exceeded. // for ( Count = MaxSpins; (Count > 0) && (TotalUsers > 0); Count -- ); #ifdef ENABLE_LOCK_STATISTICS // // Update the statistics. // Spins += (MaxSpins - Count); Waits ++; #endif } else { Count = 0; } // // We have exhusted our spin count so it is time to // sleep waiting for the lock to clear. // if ( Count == 0 ) { // // We have decide that we need to sleep but are // still holding an exclusive lock so lets drop it // before sleeping. // (VOID) AtomicDecrement( & Exclusive ); // // We have decied that it is time to go to sleep // when we wake up the lock should be available // (or just aquired) unless we have timed out in // wich case we exit. // if ( ! SleepWaitingForLock( Sleep ) ) { return False; } // // We have woken up again so lets reclaim the // exclusive lock we had earlier. // (VOID) AtomicIncrement( & Exclusive ); } } else { // // We have decide that we need to exit but are still // holding an exclusive lock. so lets drop it and leave. // (VOID) AtomicDecrement( & Exclusive ); return False; } // // Lets test the lock again. // (VOID) AtomicIncrement( & TotalUsers ); } #ifdef ENABLE_LOCK_STATISTICS // // Update the statistics. // (VOID) AtomicAdd( & TotalSpins, Spins ); (VOID) AtomicAdd( & TotalWaits, Waits ); #endif return True; } /********************************************************************/ /* */ /* Wait for a shared lock. */ /* */ /* Wait for the lock to become free and then claim it. */ /* */ /********************************************************************/ BOOLEAN SHARELOCK::WaitForShareLock( SBIT32 Sleep ) { REGISTER LONG Cpus = ((LONG) NumberOfCpus()); #ifdef ENABLE_LOCK_STATISTICS REGISTER SBIT32 Spins = 0; REGISTER SBIT32 Waits = 0; #endif // // We will loop round in this function until the // following condition becomes false. // while ( (Exclusive > 0) || (TotalUsers > MaxUsers) ) { // // The lock is busy so release it and spin waiting // for it to become free. // (VOID) AtomicDecrement( & TotalUsers ); // // We will only try spinning and sleeping if we // are permitted to do so by the parameters. // if ( Sleep != 0 ) { REGISTER SBIT32 Count; // // If there are already more threads waiting // than the number of CPUs then the odds of // getting the lock by spinning are slim, when // there is only one CPU the chance is zero, so // just bypass this step. // if ( (Cpus > 1) && (Cpus > Waiting) ) { // // Wait by spinning and repeatedly testing the // spinlock. We exit when the lock becomes free // or the spin limit is exceeded. // for ( Count = MaxSpins; (Count > 0) && ((Exclusive > 0) || (TotalUsers >= MaxUsers)); Count -- ); #ifdef ENABLE_LOCK_STATISTICS // // Update the statistics. // Spins += (MaxSpins - Count); Waits ++; #endif } else { Count = 0; } // // We have exhusted our spin count so it is time to // sleep waiting for the lock to clear. // if ( Count == 0 ) { // // We have decied that it is time to go to sleep // when we wake up the lock should be available // (or just aquired) unless we have timed out in // wich case we exit. // if ( ! SleepWaitingForLock( Sleep ) ) { return False; } } } else { return False; } // // Lets test the lock again. // (VOID) AtomicIncrement( & TotalUsers ); } #ifdef ENABLE_LOCK_STATISTICS // // Update the statistics. // (VOID) AtomicAdd( & TotalSpins, Spins ); (VOID) AtomicAdd( & TotalWaits, Waits ); #endif return True; } /********************************************************************/ /* */ /* Wake all sleepers. */ /* */ /* Wake all the sleepers who are waiting for the spinlock. */ /* All sleepers are woken because this is much more efficent */ /* and it is known that the lock latency is short. */ /* */ /********************************************************************/ VOID SHARELOCK::WakeAllSleepers( VOID ) { REGISTER LONG Wakeup = AtomicExchange( & Waiting, 0 ); // // We make sure there is still someone to be woken // up if not we check that the count has not become // negative. // if ( Wakeup > 0 ) { REGISTER LONG Cpus = ((LONG) NumberOfCpus()); // // We will only wake enough threads to ensure that // there is one active thread per CPU. So if an // application has hundreds of threads we will try // prevent the system from becoming swampped. // if ( Wakeup > Cpus ) { (VOID) AtomicAdd( & Waiting,(Wakeup - Cpus) ); Wakeup = Cpus; } // // Wake up all sleepers as the lock has just been freed. // It is a straight race to decide who gets the lock next. // if ( ! ReleaseSemaphore( Semaphore, Wakeup, NULL ) ) { Failure( "Wakeup failed in ReleaseLock()" ); } } else { // // When multiple threads pass through the critical // section it is possible for the 'Waiting' count // to become negative. This should be very rare but // such a negative value needs to be preserved. // if ( Wakeup < 0 ) { (VOID) AtomicAdd( & Waiting, Wakeup ); } } } /********************************************************************/ /* */ /* Class destructor. */ /* */ /* Destory a lock. This call is not thread safe and should */ /* only be made in a single thread environment. */ /* */ /********************************************************************/ SHARELOCK::~SHARELOCK( VOID ) { #ifdef ENABLE_LOCK_STATISTICS // // Print the lock statistics. // DebugPrint ( "Sharelock: \t%8d exclusive, %8d shared, %8d timeouts, " "%8d locks per wait, %8d spins per wait, %8d waits per sleep.\n", TotalExclusiveLocks, TotalShareLocks, TotalTimeouts, ((TotalExclusiveLocks + TotalShareLocks) / ((TotalWaits <= 0) ? 1 : TotalWaits)), (TotalSpins / ((TotalWaits <= 0) ? 1 : TotalWaits)), (TotalWaits / ((TotalSleeps <= 0) ? 1 : TotalSleeps)) ); #endif // // Close the semaphore handle. // if ( ! CloseHandle( Semaphore ) ) { Failure( "Close semaphore in destructor for SHARELOCK" ); } }
FrankKwok/Oreo
com/android/keyguard/KeyguardClockAccessibilityDelegate.java
/* * Copyright (C) 2017 The Android Open Source Project * * 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 com.android.keyguard; import android.content.Context; import android.text.TextUtils; import android.view.View; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import android.widget.TextView; /** * Replaces fancy colons with regular colons. Only works on TextViews. */ class KeyguardClockAccessibilityDelegate extends View.AccessibilityDelegate { private final String mFancyColon; public KeyguardClockAccessibilityDelegate(Context context) { mFancyColon = context.getString(R.string.keyguard_fancy_colon); } @Override public void onInitializeAccessibilityEvent(View host, AccessibilityEvent event) { super.onInitializeAccessibilityEvent(host, event); CharSequence text = event.getContentDescription(); if (!TextUtils.isEmpty(text)) { event.setContentDescription(replaceFancyColon(text)); } } @Override public void onPopulateAccessibilityEvent(View host, AccessibilityEvent event) { CharSequence text = ((TextView) host).getText(); if (!TextUtils.isEmpty(text)) { event.getText().add(replaceFancyColon(text)); } } @Override public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfo info) { super.onInitializeAccessibilityNodeInfo(host, info); if (!TextUtils.isEmpty(info.getText())) { info.setText(replaceFancyColon(info.getText())); } if (!TextUtils.isEmpty(info.getContentDescription())) { info.setContentDescription(replaceFancyColon(info.getContentDescription())); } } private CharSequence replaceFancyColon(CharSequence text) { return text.toString().replace(mFancyColon, ":"); } }
DVSR1966/par4all
packages/PIPS/validation/C_syntax/ndecl08.c
<reponame>DVSR1966/par4all<filename>packages/PIPS/validation/C_syntax/ndecl08.c /* Purpose: what's wrong with struct? */ void ndecl08(char *dir) { /* Well, this is a struct called m */ struct m { int a; float b; }; }
JimCallahan/Pipeline
src/java/us/temerity/pipeline/OpNotifiable.java
package us.temerity.pipeline; import us.temerity.pipeline.message.NotifyRsp; import us.temerity.pipeline.math.ExtraMath; import java.io.*; import java.net.*; import java.util.Locale; /*------------------------------------------------------------------------------------------*/ /* O P N O T I F I A B L E */ /*------------------------------------------------------------------------------------------*/ /** * The interface of the network and direct helper classes used by server operations to * communicate the progress of a potentially long and expensive operation back to clients. */ public interface OpNotifiable { /*----------------------------------------------------------------------------------------*/ /* A C C E S S */ /*----------------------------------------------------------------------------------------*/ /** * Set the total number of steps required to complete the operation. */ public void setTotalSteps ( long total ); /*----------------------------------------------------------------------------------------*/ /* N O T I F I C A T I O N S */ /*----------------------------------------------------------------------------------------*/ /** * Notify the client of progress. * * @param timer * The current task timer. * * @param msg * The progress message. */ public void notify ( TaskTimer timer, String msg ); /** * Notify the client of progress. * * @param timer * The current task timer. * * @param msg * The progress message. * * @param percentage * An update of the estimated percentage complete or * <CODE>null</CODE> if no estimate is available. */ public void notify ( TaskTimer timer, String msg, Float percentage ); /** * Notify the client that a step has been completed. * * @param timer * The current task timer. */ public void step ( TaskTimer timer ); /** * Notify the client that a step has been completed. * * @param timer * The current task timer. * * @param msg * A message describing the step. */ public void step ( TaskTimer timer, String msg ); /** * Notify the client that a step has been completed. * * @param timer * The current task timer. * * @param msg * A message describing the step. * * @param completed * The number of steps completed. */ public void steps ( TaskTimer timer, String msg, long completed ); }
diogocs1/comps
web/addons/account/wizard/account_automatic_reconcile.py
<filename>web/addons/account/wizard/account_automatic_reconcile.py # -*- coding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>). # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Affero General Public License for more details. # # You should have received a copy of the GNU Affero General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. # ############################################################################## import time from openerp.osv import fields, osv from openerp.tools.translate import _ class account_automatic_reconcile(osv.osv_memory): _name = 'account.automatic.reconcile' _description = 'Automatic Reconcile' _columns = { 'account_ids': fields.many2many('account.account', 'reconcile_account_rel', 'reconcile_id', 'account_id', 'Accounts to Reconcile', domain = [('reconcile','=',1)],), 'writeoff_acc_id': fields.many2one('account.account', 'Account'), 'journal_id': fields.many2one('account.journal', 'Journal'), 'period_id': fields.many2one('account.period', 'Period'), 'max_amount': fields.float('Maximum write-off amount'), 'power': fields.selection([(p, str(p)) for p in range(2, 5)], 'Power', required=True, help='Number of partial amounts that can be combined to find a balance point can be chosen as the power of the automatic reconciliation'), 'reconciled': fields.integer('Reconciled transactions', readonly=True), 'unreconciled': fields.integer('Not reconciled transactions', readonly=True), 'allow_write_off': fields.boolean('Allow write off') } def _get_reconciled(self, cr, uid, context=None): if context is None: context = {} return context.get('reconciled', 0) def _get_unreconciled(self, cr, uid, context=None): if context is None: context = {} return context.get('unreconciled', 0) _defaults = { 'reconciled': _get_reconciled, 'unreconciled': _get_unreconciled, 'power': 2 } #TODO: cleanup and comment this code... For now, it is awfulllll # (way too complex, and really slow)... def do_reconcile(self, cr, uid, credits, debits, max_amount, power, writeoff_acc_id, period_id, journal_id, context=None): """ for one value of a credit, check all debits, and combination of them depending on the power. It starts with a power of one and goes up to the max power allowed. """ move_line_obj = self.pool.get('account.move.line') if context is None: context = {} def check2(value, move_list, power): def check(value, move_list, power): for i in range(len(move_list)): move = move_list[i] if power == 1: if abs(value - move[1]) <= max_amount + 0.00001: return [move[0]] else: del move_list[i] res = check(value - move[1], move_list, power-1) move_list[i:i] = [move] if res: res.append(move[0]) return res return False for p in range(1, power+1): res = check(value, move_list, p) if res: return res return False def check4(list1, list2, power): """ for a list of credit and debit and a given power, check if there are matching tuples of credit and debits, check all debits, and combination of them depending on the power. It starts with a power of one and goes up to the max power allowed. """ def check3(value, list1, list2, list1power, power): for i in range(len(list1)): move = list1[i] if list1power == 1: res = check2(value + move[1], list2, power - 1) if res: return ([move[0]], res) else: del list1[i] res = check3(value + move[1], list1, list2, list1power-1, power-1) list1[i:i] = [move] if res: x, y = res x.append(move[0]) return (x, y) return False for p in range(1, power): res = check3(0, list1, list2, p, power) if res: return res return False def check5(list1, list2, max_power): for p in range(2, max_power+1): res = check4(list1, list2, p) if res: return res return False ok = True reconciled = 0 while credits and debits and ok: res = check5(credits, debits, power) if res: move_line_obj.reconcile(cr, uid, res[0] + res[1], 'auto', writeoff_acc_id, period_id, journal_id, context) reconciled += len(res[0]) + len(res[1]) credits = [(id, credit) for (id, credit) in credits if id not in res[0]] debits = [(id, debit) for (id, debit) in debits if id not in res[1]] else: ok = False return (reconciled, len(credits)+len(debits)) def reconcile(self, cr, uid, ids, context=None): move_line_obj = self.pool.get('account.move.line') obj_model = self.pool.get('ir.model.data') if context is None: context = {} form = self.browse(cr, uid, ids, context=context)[0] max_amount = form.max_amount or 0.0 power = form.power allow_write_off = form.allow_write_off reconciled = unreconciled = 0 if not form.account_ids: raise osv.except_osv(_('User Error!'), _('You must select accounts to reconcile.')) for account_id in form.account_ids: params = (account_id.id,) if not allow_write_off: query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL AND state <> 'draft' GROUP BY partner_id HAVING ABS(SUM(debit-credit)) = 0.0 AND count(*)>0""" else: query = """SELECT partner_id FROM account_move_line WHERE account_id=%s AND reconcile_id IS NULL AND state <> 'draft' GROUP BY partner_id HAVING ABS(SUM(debit-credit)) < %s AND count(*)>0""" params += (max_amount,) # reconcile automatically all transactions from partners whose balance is 0 cr.execute(query, params) partner_ids = [id for (id,) in cr.fetchall()] for partner_id in partner_ids: cr.execute( "SELECT id " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND state <> 'draft' " \ "AND reconcile_id IS NULL", (account_id.id, partner_id)) line_ids = [id for (id,) in cr.fetchall()] if line_ids: reconciled += len(line_ids) if allow_write_off: move_line_obj.reconcile(cr, uid, line_ids, 'auto', form.writeoff_acc_id.id, form.period_id.id, form.journal_id.id, context) else: move_line_obj.reconcile_partial(cr, uid, line_ids, 'manual', context=context) # get the list of partners who have more than one unreconciled transaction cr.execute( "SELECT partner_id " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " \ "AND partner_id IS NOT NULL " \ "GROUP BY partner_id " \ "HAVING count(*)>1", (account_id.id,)) partner_ids = [id for (id,) in cr.fetchall()] #filter? for partner_id in partner_ids: # get the list of unreconciled 'debit transactions' for this partner cr.execute( "SELECT id, debit " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " \ "AND debit > 0 " \ "ORDER BY date_maturity", (account_id.id, partner_id)) debits = cr.fetchall() # get the list of unreconciled 'credit transactions' for this partner cr.execute( "SELECT id, credit " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND partner_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " \ "AND credit > 0 " \ "ORDER BY date_maturity", (account_id.id, partner_id)) credits = cr.fetchall() (rec, unrec) = self.do_reconcile(cr, uid, credits, debits, max_amount, power, form.writeoff_acc_id.id, form.period_id.id, form.journal_id.id, context) reconciled += rec unreconciled += unrec # add the number of transactions for partners who have only one # unreconciled transactions to the unreconciled count partner_filter = partner_ids and 'AND partner_id not in (%s)' % ','.join(map(str, filter(None, partner_ids))) or '' cr.execute( "SELECT count(*) " \ "FROM account_move_line " \ "WHERE account_id=%s " \ "AND reconcile_id IS NULL " \ "AND state <> 'draft' " + partner_filter, (account_id.id,)) additional_unrec = cr.fetchone()[0] unreconciled = unreconciled + additional_unrec context = dict(context, reconciled=reconciled, unreconciled=unreconciled) model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','account_automatic_reconcile_view1')]) resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])[0]['res_id'] return { 'view_type': 'form', 'view_mode': 'form', 'res_model': 'account.automatic.reconcile', 'views': [(resource_id,'form')], 'type': 'ir.actions.act_window', 'target': 'new', 'context': context, } # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
TheUntraceable/SentinelJS
Bot Files/commands/Fun/meme.js
<filename>Bot Files/commands/Fun/meme.js const axios = require("axios"); const { MessageEmbed } = require("discord.js"); const { SlashCommandBuilder } = require("@discordjs/builders") const randomInt = (min, max) => { return Math.floor(Math.random() * (max - min)) + min; } function getRandomPost(posts) { const randomIndex = randomInt(0, posts.length); return posts[randomIndex].data; } module.exports = { data: new SlashCommandBuilder() .setName("meme") .setDescription("Get a random meme."), // I was about to let users choose what subreddits they wanted to get memes from, but I decided to just get a random one because I can't be asked to check if it's dangerous. Maybe Soon? cooldown: 5, async execute(interaction) { const subReddits = [ "r/programmerreactions", "r/memes", "r/meme", "r/dankmemes", "r/ProgrammerHumor", "r/programme_irl", "r/badUIbattles" ]; const randomIndex = randomInt(0, subReddits.length); axios.get(`https://reddit.com/${subReddits[randomIndex]}/.json`).then(async resp => { const { title, url, subreddit_name_prefixed: subreddit } = getRandomPost(resp.data.data.children); await interaction.reply({embeds : [new MessageEmbed().setTitle(title).setURL(url).setImage(url).setFooter(`from ${subreddit}`)]}) }) } }
hoolatech/datarouter-1
datarouter-storage/src/main/java/io/datarouter/storage/file/Pathbean.java
/* * Copyright © 2009 HotPads (<EMAIL>) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.datarouter.storage.file; import java.util.List; import java.util.function.Supplier; import io.datarouter.model.databean.BaseDatabean; import io.datarouter.model.field.Field; import io.datarouter.model.field.imp.comparable.LongField; import io.datarouter.model.field.imp.comparable.LongFieldKey; import io.datarouter.model.serialize.fielder.BaseDatabeanFielder; public class Pathbean extends BaseDatabean<PathbeanKey,Pathbean>{ private Long size; public static class FieldKeys{ public static final LongFieldKey size = new LongFieldKey("size"); } public static class PathbeanFielder extends BaseDatabeanFielder<PathbeanKey,Pathbean>{ public PathbeanFielder(){ super(PathbeanKey::new); } @Override public List<Field<?>> getNonKeyFields(Pathbean databean){ return List.of( new LongField(FieldKeys.size, databean.size)); } } @Override public Supplier<PathbeanKey> getKeySupplier(){ return PathbeanKey::new; } public Pathbean(){ super(new PathbeanKey(null, null)); } public Pathbean(PathbeanKey key){ super(key); } public Pathbean(PathbeanKey key, Long size){ super(key); this.size = size; } public Long getSize(){ return size; } }
VictorBG/Raco
app/src/main/java/com/victorbg/racofib/data/repository/base/Repository.java
<filename>app/src/main/java/com/victorbg/racofib/data/repository/base/Repository.java package com.victorbg.racofib.data.repository.base; public abstract class Repository { public abstract void clean(); }
eFaps/eFaps-Kernel
src/main/java/org/efaps/db/databases/information/ForeignKeyInformation.java
/* * Copyright 2003 - 2017 The eFaps Team * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.efaps.db.databases.information; import java.io.Serializable; import org.apache.commons.lang3.builder.ToStringBuilder; /** * The class is used to store information about foreign keys within SQL tables. * * @author The eFaps Team * */ public class ForeignKeyInformation implements Serializable { /** * Needed for serialization. */ private static final long serialVersionUID = 1L; /** * Name of the foreign key. */ private final String fkName; /** * Column name which references the foreign key. */ private final String colName; /** * Name of the referenced SQL table. */ private final String refTableName; /** * Name of column in the referenced SQL table. */ private final String refColName; /** * Is the foreign key a cascade delete, means that if the foreign row is * deleted, this row referencing the foreign row must also be deleted? */ private final boolean cascadeDelete; /** * Constructor to initialize all instance variables. * * @param _foreignKeyName name of foreign key * @param _columnName name of column name * @param _referencedTableName name of referenced SQL table * @param _referencedColumnName name of column within referenced SQL table * @param _cascadeDelete delete cascade activated */ protected ForeignKeyInformation(final String _foreignKeyName, final String _columnName, final String _referencedTableName, final String _referencedColumnName, final boolean _cascadeDelete) { this.fkName = _foreignKeyName.toUpperCase(); this.colName = _columnName.toUpperCase(); this.refTableName = _referencedTableName.toUpperCase(); this.refColName = _referencedColumnName.toUpperCase(); this.cascadeDelete = _cascadeDelete; } /** * Returns string representation of this class instance. The information * includes {@link #fkName}, {@link #colName}, {@link #refTableName}, * {@link #refColName} and {@link #cascadeDelete}. * * @return string representation for the foreign key information */ @Override public String toString() { return ToStringBuilder.reflectionToString(this); } /** * Getter method for the instance variable {@link #fkName}. * * @return value of instance variable {@link #fkName} */ public String getFkName() { return this.fkName; } /** * Getter method for the instance variable {@link #colName}. * * @return value of instance variable {@link #colName} */ public String getColName() { return this.colName; } /** * Getter method for the instance variable {@link #refTableName}. * * @return value of instance variable {@link #refTableName} */ public String getRefTableName() { return this.refTableName; } /** * Getter method for the instance variable {@link #refColName}. * * @return value of instance variable {@link #refColName} */ public String getRefColName() { return this.refColName; } /** * Getter method for the instance variable {@link #cascadeDelete}. * * @return value of instance variable {@link #cascadeDelete} */ public boolean isCascadeDelete() { return this.cascadeDelete; } }
MannPE/KawAnime
src/main/externals/kitsu.io/auth/retrieveToken.js
import setup from './setup' import { getCreds } from '../../vault' const properties = [ 'expiresAt', 'accessToken', 'tokenType', 'refreshToken', 'userId' ] export default async function () { let { expiresAt, accessToken, tokenType, refreshToken, userId } = await getCreds('kitsu', properties) const now = (new Date()).getTime() // We refresh the token only when the expire date is // less than a day away. if (expiresAt - now < 24 * 60 * 60 * 1000) { const newData = await setup.getAccessToken({ token: refreshToken }, true) accessToken = newData.accessToken tokenType = newData.tokenType } return { accessToken, tokenType, userId } }
DavideAG/polycube
src/services/pcn-packetcapture/src/serializer/GlobalheaderJsonObject.h
<reponame>DavideAG/polycube /** * packetcapture API generated from packetcapture.yang * * NOTE: This file is auto generated by polycube-codegen * https://github.com/polycube-network/polycube-codegen */ /* Do not edit this file manually */ /* * GlobalheaderJsonObject.h * * */ #pragma once #include "JsonObjectBase.h" namespace polycube { namespace service { namespace model { /// <summary> /// /// </summary> class GlobalheaderJsonObject : public JsonObjectBase { public: GlobalheaderJsonObject(); GlobalheaderJsonObject(const nlohmann::json &json); ~GlobalheaderJsonObject() final = default; nlohmann::json toJson() const final; /// <summary> /// magic number /// </summary> uint32_t getMagic() const; void setMagic(uint32_t value); bool magicIsSet() const; void unsetMagic(); /// <summary> /// major version number /// </summary> uint16_t getVersionMajor() const; void setVersionMajor(uint16_t value); bool versionMajorIsSet() const; void unsetVersionMajor(); /// <summary> /// minor version number /// </summary> uint16_t getVersionMinor() const; void setVersionMinor(uint16_t value); bool versionMinorIsSet() const; void unsetVersionMinor(); /// <summary> /// GMT to local correction /// </summary> int32_t getThiszone() const; void setThiszone(int32_t value); bool thiszoneIsSet() const; void unsetThiszone(); /// <summary> /// accuracy of timestamps /// </summary> uint32_t getSigfigs() const; void setSigfigs(uint32_t value); bool sigfigsIsSet() const; void unsetSigfigs(); /// <summary> /// max length of captured packets, in octets /// </summary> uint32_t getSnaplen() const; void setSnaplen(uint32_t value); bool snaplenIsSet() const; void unsetSnaplen(); /// <summary> /// Capture linktype (eg. ethernet, wifi..) /// </summary> uint32_t getLinktype() const; void setLinktype(uint32_t value); bool linktypeIsSet() const; void unsetLinktype(); private: uint32_t m_magic; bool m_magicIsSet; uint16_t m_versionMajor; bool m_versionMajorIsSet; uint16_t m_versionMinor; bool m_versionMinorIsSet; int32_t m_thiszone; bool m_thiszoneIsSet; uint32_t m_sigfigs; bool m_sigfigsIsSet; uint32_t m_snaplen; bool m_snaplenIsSet; uint32_t m_linktype; bool m_linktypeIsSet; }; } } }
ScalablyTyped/SlinkyTyped
o/office-ui-fabric-react/src/main/scala/typingsSlinky/officeUiFabricReact/panelStylesMod.scala
package typingsSlinky.officeUiFabricReact import typingsSlinky.officeUiFabricReact.panelTypesMod.IPanelStyleProps import typingsSlinky.officeUiFabricReact.panelTypesMod.IPanelStyles import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object panelStylesMod { @JSImport("office-ui-fabric-react/lib/components/Panel/Panel.styles", "getStyles") @js.native def getStyles(props: IPanelStyleProps): IPanelStyles = js.native }
akai10tsuki/mkvbatchmultiplex
MKVBatchMultiplex/delegates/delegates.py
""" deleage classes """ # pylint: disable=unused-argument from PySide2.QtWidgets import ( QStyledItemDelegate, QStyleOptionButton, QApplication, QStyle, QComboBox, ) from PySide2.QtCore import Qt, QRect, QPoint, QEvent, Slot from ..jobs import JobStatus class StatusComboBoxDelegate(QStyledItemDelegate): """ StatusComboBoxDelegate - activate a ComboBox in a Status cell of a JobsTableViewWidget in order to edit the cell Args: model (TableDataModel): model used in a table model/view class """ comboItems = ["Wait", "Wait..", "Wait..."] def __init__(self, model): super(StatusComboBoxDelegate, self).__init__() self.model = model def createEditor(self, parent, option, index): """ createEditor edit item at index Args: parent (QWidget): editor parent object option (QStyleOptionViewItem): item options index (QModelIndex): index of item in table Returns: QComboBox: editor is a ComboBox. Defaults to None if no list of items can be made. """ sourceIndex = self.model.mapToSource(index) row = sourceIndex.row() column = sourceIndex.column() status = self.model.sourceModel().dataset[row, column] self.comboItems = _comboBoxItems(status) if self.comboItems: editor = QComboBox(parent) editor.addItems(self.comboItems) editor.currentIndexChanged.connect(self.currentIndexChanged) editor.setEditable(True) editor.lineEdit().setReadOnly(True) editor.lineEdit().setAlignment(Qt.AlignCenter) return editor return None def editorEvent(self, event, model, option, index): """ editorEvent proccess events received by editor Args: **event** (QEvent): event received **model** (TableDataModel): model/view used **option** (QStyleOptionViewItem): item options **index** (QModelIndex): index of item in table Returns: bool: True if event attended. False otherwise. """ sourceIndex = model.mapToSource(index) column = sourceIndex.column() if column and event.type() == QEvent.MouseButtonRelease: self.setModelData(None, model.sourceModel(), sourceIndex) # return False # if column and (event.type() == QEvent.KeyPress): # if event.key() in [Qt.Key_Enter, Qt.Key_Return]: # self.setModelData(None, model.sourceModel(), sourceIndex) # return True return False def setModelData(self, editor, model, index): """ setModelData setup model data if editor for editor to use Args: **editor** (QWidget): current editor widget **model** (TableDataModel): model in use for model/view **index** (QModelIndex): index of item in table """ if editor: comboIndex = editor.currentIndex() text = self.comboItems[comboIndex] model.setData(index, text) @Slot() def currentIndexChanged(self): """ currentIndexChanged emit commitData Signal when index is changed """ self.commitData.emit(self.sender()) def _comboBoxItems(status): """ _comboBoxItems helper function to StatusComboBoxDelegate that construct the list used in the ComboBox editor Args: status (string): current status in cell Returns: list: list with comboBox items. None depending of current status. """ if status in [JobStatus.AbortJobError, JobStatus.Error]: return None if status in [ JobStatus.Skip, JobStatus.Skipped, JobStatus.Aborted, JobStatus.Done, JobStatus.Removed, ]: comboItems = [status, JobStatus.Waiting] elif status in [JobStatus.Queue, JobStatus.Waiting]: comboItems = [status, JobStatus.Skip] elif status == JobStatus.Running: comboItems = [status, JobStatus.Abort] elif status == JobStatus.Abort: return None else: return None return comboItems class FillColorDelegate(QStyledItemDelegate): """FillColorDelegate""" def __init__(self, model, color): """ This delegate replaces a cell's display with a solid fill color surrounded by a thin white border :param model: underlying ProxyModel object :param color: QColor object """ super().__init__() self.color = color self.model = model def createEditor(self, parent, option, index): return None def paint(self, painter, option, index): source_index = self.model.mapToSource(index) row = source_index.row() column = source_index.column() value = self.model.sourceModel().dataset[row][column] rect = QRect( option.rect.x() + 1, option.rect.y() + 1, option.rect.width() - 2, option.rect.height() - 2, ) if value: painter.save() painter.setBrush(self.color) painter.fillRect(rect, painter.brush()) class CheckBoxDelegate(QStyledItemDelegate): """ CheckBoxDelegate """ def __init__(self, proxy_model): """ This delegate replaces a cell's display with a check box. Underlying data are updated when the box is checked or unchecked. Persistant editor needs to be set on the table's cells in order to update the box. :param model: underlying ProxyModel object """ self.proxy_model = proxy_model super().__init__() def createEditor(self, parent, option, index): return None def paint(self, painter, option, index): # Check data source_index = self.proxy_model.mapToSource(index) row = source_index.row() column = source_index.column() checked = self.proxy_model.sourceModel().dataset[row][column] # Build rect to draw style_option = QStyleOptionButton() check_box_rect = QApplication.style().subElementRect( QStyle.SE_CheckBoxIndicator, style_option, None ) check_box_pos = QPoint( option.rect.x() + option.rect.width() / 2 - check_box_rect.width() / 2, option.rect.y() + option.rect.height() / 2 - check_box_rect.height() / 2, ) rect_to_draw = QRect(check_box_pos, check_box_rect.size()) # Build check box opts = QStyleOptionButton() opts.state |= QStyle.State_Active | QStyle.State_Enabled opts.state |= QStyle.State_On if checked else QStyle.State_Off opts.rect = rect_to_draw QApplication.style().drawControl(QStyle.CE_CheckBox, opts, painter) def editorEvent(self, event, model, option, index): source_index = model.mapToSource(index) column = source_index.column() if column and event.type() == QEvent.MouseButtonRelease: self.setModelData(None, model.sourceModel(), source_index) return True return False def setModelData(self, editor, model, index): row = index.row() column = index.column() model.dataset[row][column] = not model.dataset[row][column] class ComboBoxDelegateNew(QStyledItemDelegate): """ ComboBoxDelegate [summary] Args: QStyledItemDelegate ([type]): [description] Returns: [type]: [description] """ comboItems = ["Wait", "Wait..", "Wait..."] def __init__(self, proxyModel): self.proxyModel = proxyModel super().__init__() def createEditor(self, parent, option, proxyModelIndex): editor = QComboBox(self) editor.addItems(self.comboItems) editor.currentIndexChanged.connect(self.currentIndexChanged) return editor def editorEvent(self, event, model, option, index): source_index = model.mapToSource(index) column = source_index.column() if column and event.type() == QEvent.MouseButtonRelease: self.setModelData(None, model.sourceModel(), source_index) return True return False def setModelData(self, editor, model, index): row = index.row() column = index.column() model.dataset[row][column] = not model.dataset[row][column] @Slot() def currentIndexChanged(self): self.commitData.emit(self.sender())
Revan1985/SoACode-Public
SoA/GameplayRenderer.h
<reponame>Revan1985/SoACode-Public /// /// GameplayRenderer.h /// Seed of Andromeda /// /// Created by <NAME> on 1 Nov 2014 /// Copyright 2014 Regrowth Studios /// MIT License /// /// This file implements the render pipeline for the /// GamePlayScreen. /// #pragma once #ifndef GamePlayRenderer_h__ #define GamePlayRenderer_h__ #include <Vorb/graphics/FullQuadVBO.h> #include <Vorb/graphics/GBuffer.h> #include <Vorb/graphics/RTSwapChain.hpp> #include <Vorb/vorb_rpc.h> #include "Camera.h" #include "ChunkGridRenderStage.h" #include "ChunkRenderer.h" #include "ColoredFullQuadRenderer.h" #include "CutoutVoxelRenderStage.h" #include "DevHudRenderStage.h" #include "GameRenderParams.h" #include "HdrRenderStage.h" #include "LiquidVoxelRenderStage.h" #include "NightVisionRenderStage.h" #include "OpaqueVoxelRenderStage.h" #include "PauseMenuRenderStage.h" #include "PdaRenderStage.h" #include "PhysicsBlockRenderStage.h" #include "SkyboxRenderStage.h" #include "SpaceSystemRenderStage.h" #include "SsaoRenderStage.h" #include "TransparentVoxelRenderStage.h" #include "BloomRenderStage.h" #include "ExposureCalcRenderStage.h" /// Forward declarations class App; class ChunkGridRenderStage; class ChunkMeshManager; class ChunkSlot; class CutoutVoxelRenderStage; class DevHudRenderStage; class GameSystem; class GameplayScreen; class HdrRenderStage; class LiquidVoxelRenderStage; class MeshManager; class NightVisionRenderStage; class OpaqueVoxelRenderStage; class PDA; class PauseMenu; class PauseMenuRenderStage; class PdaRenderStage; class PhysicsBlockRenderStage; class Player; class SkyboxRenderStage; class SpaceSystem; class SpaceSystemRenderStage; class TransparentVoxelRenderStage; class DebugRenderer; struct MTRenderState; struct CommonState; struct SoaState; class GameplayRenderer { public: /// Initializes the pipeline and passes dependencies void init(vui::GameWindow* window, StaticLoadContext& context, GameplayScreen* gameplayScreen, CommonState* commonState); /// Call this every frame before render void setRenderState(const MTRenderState* renderState); void hook(); void load(StaticLoadContext& context); void dispose(StaticLoadContext& context); void reloadShaders(); void updateGL(); /// Renders the pipeline. /// Make sure to call setRenderState first. virtual void render(); /// Cycles the dev hud /// @param offset: How much to offset the current mode void cycleDevHud(int offset = 1); /// Toggle the visibility of night vision void toggleNightVision(); /// Load night vision data void loadNightVision(); /// Toggle the visibility of chunkGrid void toggleChunkGrid(); void toggleWireframe() { m_wireframe = !m_wireframe; } void takeScreenshot() { m_shouldScreenshot = true; } volatile const bool& isLoaded() const { return m_isLoaded; } struct { OpaqueVoxelRenderStage opaqueVoxel; ///< Renders opaque voxels CutoutVoxelRenderStage cutoutVoxel; ///< Renders cutout voxels ChunkGridRenderStage chunkGrid; TransparentVoxelRenderStage transparentVoxel; ///< Renders transparent voxels LiquidVoxelRenderStage liquidVoxel; ///< Renders liquid voxels DevHudRenderStage devHud; ///< Renders the dev/debug HUD PdaRenderStage pda; ///< Renders the PDA PauseMenuRenderStage pauseMenu; ///< Renders the pause menu NightVisionRenderStage nightVision; ///< Renders night vision SSAORenderStage ssao; ///< Renders SSAO BloomRenderStage bloom; ///< Renders Bloom effect ExposureCalcRenderStage exposureCalc; ///< Calculate exposure } stages; DebugRenderer* debugRenderer = nullptr; private: void updateCameras(); void dumpScreenshot(); Camera m_voxelCamera; ChunkRenderer m_chunkRenderer; ColoredFullQuadRenderer m_coloredQuadRenderer; ///< For rendering full screen colored quads vg::GBuffer m_hdrTarget; ///< Framebuffer needed for the HDR rendering vg::RTSwapChain<2> m_swapChain; ///< Swap chain of framebuffers used for post-processing GameRenderParams m_gameRenderParams; ///< Shared rendering parameters for voxels GameplayScreen* m_gameplayScreen = nullptr; vui::GameWindow* m_window; CommonState* m_commonState = nullptr; SoaState* m_state = nullptr; ///< Game State vcore::RPCManager m_glrpc; std::thread* m_loadThread = nullptr; volatile bool m_isLoaded = false; // TODO: This is only for visualization purposes, must remove std::vector<NightVisionRenderParams> m_nvParams; ///< Different night vision styles ui32 m_nvIndex = 0; ui32v4 m_viewport; ///< Viewport to draw to ChunkMeshManager* m_meshManager; ///< Handle to the meshes const MTRenderState* m_renderState = nullptr; ///< The current MT render state float m_coloredQuadAlpha = 0.0f; bool m_increaseQuadAlpha = false; bool m_wireframe = false; bool m_shouldScreenshot = false; }; #endif // GamePlayRenderer_h__
diegopacheco/scala-playground
scala-playground/src/com/github/diegopacheco/sandbox/scripts/scala/basic/oo/SealedCaseClassFun.scala
package com.github.diegopacheco.sandbox.scripts.scala.basic.oo object SealedCaseClassFun extends App { sealed case class BadGuy sealed case class TheJoker(name:String,enemy:String) extends BadGuy{ override def toString():String = name + " :-> " + enemy } val coringa = new TheJoker("Curinga","Batima") println( coringa ) }
gracielundell/scienceBlog
tmp/babel-output_path-xb4GCqUW.tmp/modules/lodash/internal/assignWith.js
<reponame>gracielundell/scienceBlog<gh_stars>0 import keys from '../object/keys'; /** * A specialized version of `_.assign` for customizing assigned values without * support for argument juggling, multiple sources, and `this` binding `customizer` * functions. * * @private * @param {Object} object The destination object. * @param {Object} source The source object. * @param {Function} customizer The function to customize assigned values. * @returns {Object} Returns `object`. */ function assignWith(object, source, customizer) { var index = -1, props = keys(source), length = props.length; while (++index < length) { var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source); if ((result === result ? result !== value : value === value) || value === undefined && !(key in object)) { object[key] = result; } } return object; } export default assignWith;
DesZou/Eros
test/20171017/source/std/slope.cpp
#include <cstdio> #include <iostream> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> #include <queue> using namespace std; typedef double db; const int N=500010; struct P{ int x,y; bool operator<(const P& a)const{ return x<a.x; } }a[N]; int main(){ #ifndef ONLINE_JUDGE freopen("slope.in","r",stdin); freopen("slope.out","w",stdout); #endif int i,n; db ans=-(int)2e9; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d %d",&a[i].x,&a[i].y); sort(a+1,a+n+1); for(i=2;i<=n;i++) ans=max(ans,1.0*(a[i].y-a[i-1].y)/(a[i].x-a[i-1].x)); printf("%.3lf\n",ans); return 0; }
yashbhutwala/blackduck-docker-inspector
src/test/java/com/synopsys/integration/blackduck/dockerinspector/httpclient/IiClientContainersStartedAsNeededTest.java
<gh_stars>10-100 package com.synopsys.integration.blackduck.dockerinspector.httpclient; import static org.junit.Assert.assertEquals; import com.synopsys.integration.blackduck.dockerinspector.programversion.ProgramVersion; import com.synopsys.integration.rest.client.IntHttpClient; import java.io.IOException; import java.net.URI; import java.net.URL; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.springframework.test.context.junit4.SpringRunner; import com.github.dockerjava.api.model.Container; import com.synopsys.integration.blackduck.dockerinspector.config.Config; import com.synopsys.integration.blackduck.dockerinspector.dockerclient.DockerClientManager; import com.synopsys.integration.blackduck.dockerinspector.httpclient.response.SimpleResponse; import com.synopsys.integration.blackduck.imageinspector.api.ImageInspectorOsEnum; import com.synopsys.integration.exception.IntegrationException; import com.synopsys.integration.rest.RestConstants; @RunWith(SpringRunner.class) public class IiClientContainersStartedAsNeededTest { @InjectMocks private ImageInspectorClientStartServices imageInspectorClientContainersStartedAsNeeded; @Mock private Config config; @Mock private ImageInspectorServices imageInspectorServices; @Mock private HttpConnectionCreator httpConnectionCreator; @Mock private HttpRequestor httpRequestor; @Mock private InspectorImages inspectorImages; @Mock private DockerClientManager dockerClientManager; @Mock private ProgramVersion programVersion; @Mock private ContainerName containerName; @Test public void test() throws IntegrationException, IOException, InterruptedException { Mockito.when(config.isImageInspectorServiceStart()).thenReturn(true); Mockito.when(imageInspectorServices.getDefaultImageInspectorHostPortBasedOnDistro()).thenReturn(8080); Mockito.when(config.getCommandTimeout()).thenReturn(5000L); Mockito.when(config.getImageInspectorDefaultDistro()).thenReturn("ubuntu"); Mockito.when(containerName.deriveContainerNameFromImageInspectorRepo(Mockito.anyString())).thenReturn("testContainerName"); Mockito.when(imageInspectorServices.getServiceVersion(Mockito.any(IntHttpClient.class), Mockito.any(URI.class))).thenReturn("2.2.2"); Mockito.when(programVersion.getInspectorImageVersion()).thenReturn("2.2.2"); Mockito.when(imageInspectorServices.startService(Mockito.any(IntHttpClient.class), Mockito.any( URI.class), Mockito.anyString(), Mockito.anyString())).thenReturn(true); final Container targetContainer = Mockito.mock(Container.class); Mockito.when(targetContainer.getImage()).thenReturn("target"); Mockito.when(dockerClientManager.getRunningContainerByAppName(Mockito.anyString(), Mockito.any(ImageInspectorOsEnum.class))).thenReturn(targetContainer); final IntHttpClient restConnection = Mockito.mock(IntHttpClient.class); Mockito.when( httpConnectionCreator.createNonRedirectingConnection(Mockito.any(URI.class), Mockito.anyInt())).thenReturn(restConnection); Mockito.when(httpRequestor.executeSimpleGetRequest(Mockito.any(IntHttpClient.class), Mockito.any(URI.class), Mockito.anyString())).thenReturn("{\"status\":\"UP\"}"); final SimpleResponse response = new SimpleResponse(RestConstants.OK_200, null, "testResult"); Mockito.when(httpRequestor .executeGetBdioRequest(Mockito.any(IntHttpClient.class), Mockito.any(URI.class), Mockito.anyString(), Mockito.isNull(), Mockito.isNull(), Mockito.isNull(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.anyBoolean(), Mockito.isNull(), Mockito.isNull())).thenReturn(response); Mockito.when(inspectorImages.getInspectorImageName(Mockito.any(ImageInspectorOsEnum.class))).thenReturn("blackduck/blackduck-imageinspector"); Mockito.when(inspectorImages.getInspectorImageTag(Mockito.any(ImageInspectorOsEnum.class))).thenReturn("1.1.1"); assertEquals(true, imageInspectorClientContainersStartedAsNeeded.isApplicable()); assertEquals("testResult", imageInspectorClientContainersStartedAsNeeded.getBdio("/tmp/t.tar", "/tmp/t.tar", null, null, null, "containerFileSystemFilename", false, true, false, null, null)); } }
robdobsn/RdWebServer
src/RdWebDataFrame.h
///////////////////////////////////////////////////////////////////////////////////////////////////////////////// // // RdWebServer // // <NAME> 2020 // ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// #pragma once #include <string.h> #include <stdint.h> #include <vector> // Buffer for tx queue class RdWebDataFrame { public: RdWebDataFrame() { } RdWebDataFrame(const uint8_t* pBuf, uint32_t bufLen) { frame.resize(bufLen); memcpy(frame.data(), pBuf, frame.size()); } const uint8_t* getData() { return frame.data(); } uint32_t getLen() { return frame.size(); } private: std::vector<uint8_t> frame; };
mobilise-xyz/mobilise-frontend
src/components/forms/RepeatingShiftForm/index.js
<filename>src/components/forms/RepeatingShiftForm/index.js<gh_stars>0 import RepeatingShiftForm from './RepeatingShiftForm'; export default RepeatingShiftForm;
AlexGilleran/IceSoap2
IceSoapTest/src/test/java/com/alexgilleran/icesoap/xpath/test/XPathRepositoryTest.java
package com.alexgilleran.icesoap.xpath.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import com.alexgilleran.icesoap.exception.XPathParsingException; import com.alexgilleran.icesoap.xpath.XPathFactory; import com.alexgilleran.icesoap.xpath.XPathRepository; import com.alexgilleran.icesoap.xpath.elements.XPathElement; public class XPathRepositoryTest extends XPathTest { private XPathRepository<String> repo; @Before public void setUp() { repo = new XPathRepository<String>(); } @Test public void testBasic() throws XPathParsingException { for (String xpathElement : getTestXPaths()) { testPut(xpathElement, xpathElement); } } @Test public void testSingleSlashes() throws XPathParsingException { testPut("/xpath", "/xpath"); testPut("/xpath", "/xpath[@predicate=\"predicate\"]"); } @Test public void testDoubleSlashes() throws XPathParsingException { testPut("//xpath", "/herp/xpath"); testPut("//xpath", "/herp/xpath[@predicate=\"predicate\"]"); } @Test public void testPredicateSelection() throws XPathParsingException { final String xpathNoPred = "/xpath1/xpath2"; final String xpathWrongValuePred = "/xpath1/xpath2[@predicate=\"wrongvalue\"]"; final String xpathRightValuePred = "/xpath1/xpath2[@predicate=\"rightvalue\"]"; repo.put(XPathFactory.getInstance().compile(xpathNoPred).keySet().iterator().next(), xpathNoPred); repo.put(XPathFactory.getInstance().compile(xpathWrongValuePred).keySet().iterator().next(), xpathWrongValuePred); repo.put(XPathFactory.getInstance().compile(xpathRightValuePred).keySet().iterator().next(), xpathRightValuePred); assertEquals(xpathNoPred, repo.get(XPathFactory.getInstance().compile(xpathNoPred).keySet().iterator().next())); assertEquals(xpathWrongValuePred, repo.get(XPathFactory.getInstance().compile(xpathWrongValuePred).keySet().iterator().next())); assertEquals(xpathRightValuePred, repo.get(XPathFactory.getInstance().compile(xpathRightValuePred).keySet().iterator().next())); } @Test public void testAttributeSelection() throws XPathParsingException { final String nodeXPath = "/xpath1/xpath"; final String attributeXPath = "/xpath1/@xpath"; repo.put(XPathFactory.getInstance().compile(nodeXPath).keySet().iterator().next(), nodeXPath); repo.put(XPathFactory.getInstance().compile(attributeXPath).keySet().iterator().next(), attributeXPath); assertEquals(repo.get(XPathFactory.getInstance().compile(nodeXPath).keySet().iterator().next()), nodeXPath); assertEquals(repo.get(XPathFactory.getInstance().compile(attributeXPath).keySet().iterator().next()), attributeXPath); } @Test public void testRemove() throws XPathParsingException { XPathElement xpath1 = XPathFactory.getInstance().compile("//this/is/a/test").keySet().iterator().next(); XPathElement xpath2 = XPathFactory.getInstance().compile("/blah/herp").keySet().iterator().next(); XPathElement xpath3 = XPathFactory.getInstance().compile("//test").keySet().iterator().next(); repo.put(xpath1, xpath1.toString()); repo.put(xpath2, xpath2.toString()); repo.put(xpath3, xpath3.toString()); assertEquals(3, repo.size()); repo.remove(xpath2); assertEquals(2, repo.size()); assertEquals(xpath1.toString(), repo.get(xpath1)); assertNull(repo.get(xpath2)); assertEquals(xpath3.toString(), repo.get(xpath3)); } @Test public void testRemoveEnsureExactMatch() throws XPathParsingException { XPathElement xpath1 = XPathFactory.getInstance().compile("//test/is/a/this").keySet().iterator().next(); XPathElement xpath2 = XPathFactory.getInstance().compile("/a/this").keySet().iterator().next(); XPathElement xpath3 = XPathFactory.getInstance().compile("//this").keySet().iterator().next(); repo.put(xpath1, xpath1.toString()); repo.put(xpath2, xpath2.toString()); repo.put(xpath3, xpath3.toString()); repo.remove(xpath1); assertEquals(xpath2.toString(), repo.get(xpath2)); assertEquals(xpath3.toString(), repo.get(xpath3)); } private void testPut(String xpathToGet, String xpathToPut) throws XPathParsingException { repo = new XPathRepository<String>(); XPathElement xpathElementToPut = XPathFactory.getInstance().compile(xpathToPut).keySet().iterator().next(); XPathElement xpathElementToGet = XPathFactory.getInstance().compile(xpathToGet).keySet().iterator().next(); assertNull(repo.get(xpathElementToGet)); repo.put(xpathElementToPut, xpathToGet); assertEquals(xpathToGet, repo.get(xpathElementToPut)); } }
YukiMuraRindon/JavaTest
elms/src/elms/service/cgthservice.java
<filename>elms/src/elms/service/cgthservice.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package elms.service; import java.util.Date; /** * * @author YukiMuraRindon */ public interface cgthservice { public boolean purchasereturn(String purid, int proid, int returnnum, Date returntime, String returnreason); }
barbashovtd/kvant
backend/core/migrations/0006_auto_20210902_1529.py
# Generated by Django 3.2.4 on 2021-09-02 15:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0005_auto_20210902_0057'), ] operations = [ migrations.AlterField( model_name='student', name='qr', field=models.ImageField(blank=True, null=True, upload_to='qr', verbose_name='QR'), ), migrations.AlterField( model_name='teacher', name='qr', field=models.ImageField(blank=True, null=True, upload_to='qr', verbose_name='QR'), ), ]
Lzw2016/clever-canal
clever-canal-dbsync/src/main/java/org/clever/canal/parse/dbsync/binlog/event/ExecuteLoadLogEvent.java
<filename>clever-canal-dbsync/src/main/java/org/clever/canal/parse/dbsync/binlog/event/ExecuteLoadLogEvent.java package org.clever.canal.parse.dbsync.binlog.event; import org.clever.canal.parse.dbsync.binlog.LogBuffer; import org.clever.canal.parse.dbsync.binlog.LogEvent; /** * Execute_load_log_event. */ @SuppressWarnings({"WeakerAccess", "unused"}) public final class ExecuteLoadLogEvent extends LogEvent { private final long fileId; /* EL = "Execute Load" */ public static final int EL_FILE_ID_OFFSET = 0; public ExecuteLoadLogEvent(LogHeader header, LogBuffer buffer, FormatDescriptionLogEvent descriptionEvent) { super(header); final int commonHeaderLen = descriptionEvent.commonHeaderLen; buffer.position(commonHeaderLen + EL_FILE_ID_OFFSET); fileId = buffer.getUint32(); // EL_FILE_ID_OFFSET } public final long getFileId() { return fileId; } }
neroroxxx/BMC
src/BMC.timedEvents.cpp
/* See https://www.RoxXxtar.com/bmc for more details Copyright (c) 2020 RoxXxtar.com Licensed under the MIT license. See LICENSE file in the project root for full license information. */ #include <BMC.h> #if BMC_MAX_TIMED_EVENTS > 0 void BMC::readTimedEvent(){ if(timedEvents.available()==0){ return; } for(uint8_t index = 0, n=timedEvents.available(); index < n; index++){ if(timedEvents.isReady(index)){ processTimedEvent(index); } } } void BMC::processTimedEvent(uint8_t n){ // ready to trigger if(n>=BMC_MAX_TIMED_EVENTS){ return; } uint32_t event = store.global.timedEvents[n].event; switch(BMC_GET_BYTE(0, event)){ case BMC_NONE: return; case BMC_TIMED_EVENT_TYPE_LIBRARY: #if BMC_MAX_LIBRARY>0 // byteA = index of the library item library.send(BMC_EVENT_TO_LIBRARY_NUM(event>>8)); #endif break; case BMC_TIMED_EVENT_TYPE_LIBRARY2: #if BMC_MAX_LIBRARY>1 // byteA = index of the 1st library item to send // byteB = index of the 2nd library item to send library.send(BMC_EVENT_TO_LIBRARY_NUM(event>>8), BMC_EVENT_TO_LIBRARY_NUM(event>>18)); #endif break; case BMC_TIMED_EVENT_TYPE_RELAY_NL_CONTROL: #if BMC_MAX_NL_RELAYS>0 if(BMC_GET_BYTE(1, event) < BMC_MAX_NL_RELAYS){ relaysNL[BMC_GET_BYTE(1, event)].command(BMC_GET_BYTE(2, event)); } #endif break; case BMC_TIMED_EVENT_TYPE_RELAY_L_CONTROL: #if BMC_MAX_L_RELAYS>0 if(BMC_GET_BYTE(1, event) < BMC_MAX_L_RELAYS){ relaysL[BMC_GET_BYTE(1, event)].command(BMC_GET_BYTE(2, event)); } #endif break; case BMC_TIMED_EVENT_TYPE_BUTTON_EVENT: #if BMC_MAX_BUTTONS > 0 { uint8_t btnN = BMC_GET_BYTE(1, event); uint8_t btnEventN = BMC_GET_BYTE(2, event); bmcStoreButtonEvent &data = store.pages[page].buttons[btnN].events[btnEventN]; uint8_t type = BMC_GET_BYTE(0,data.event); if(type!=BMC_NONE){ handleButtonEvent(type, data); } } #endif break; case BMC_TIMED_EVENT_TYPE_GLOBAL_BUTTON_EVENT: #if BMC_MAX_GLOBAL_BUTTONS > 0 { uint8_t btnN = BMC_GET_BYTE(1, event); uint8_t btnEventN = BMC_GET_BYTE(2, event); bmcStoreButtonEvent &data = globalData.buttons[btnN].events[btnEventN]; uint8_t type = BMC_GET_BYTE(0,data.event); if(type!=BMC_NONE){ handleButtonEvent(type, data); } } #endif break; case BMC_TIMED_EVENT_TYPE_ENCODER: #if BMC_MAX_ENCODERS > 0 { uint8_t enc = BMC_GET_BYTE(1, event); uint8_t inc = BMC_GET_BYTE(2, event); uint8_t type = BMC_GET_BYTE(0, store.pages[page].encoders[enc].event); if(type!=BMC_NONE){ handleEncoder(store.pages[page].encoders[enc], inc); } } #endif break; case BMC_TIMED_EVENT_TYPE_GLOBAL_ENCODER: #if BMC_MAX_GLOBAL_ENCODERS > 0 { uint8_t enc = BMC_GET_BYTE(1, event); uint8_t inc = BMC_GET_BYTE(2, event); uint8_t type = BMC_GET_BYTE(0, globalData.encoders[enc].event); if(type!=BMC_NONE){ handleEncoder(globalData.encoders[enc], inc); } } #endif break; case BMC_TIMED_EVENT_TYPE_PAGE: #if BMC_MAX_GLOBAL_ENCODERS > 1 setPage(BMC_GET_BYTE(1, event)); #endif break; case BMC_TIMED_EVENT_TYPE_MASTER_CLOCK: midiClock.setBpm((event >> 8) & 0x1FF); break; case BMC_TIMED_EVENT_TYPE_CUSTOM: callback.timedEventCustom(n, BMC_GET_BYTE(1,event), BMC_GET_BYTE(2,event), BMC_GET_BYTE(3,event)); break; } } #endif
recursion/newsy-react-client
app/components/StoriesList/index.js
export { default } from './StoriesList';
itandrik/Hedbanz
app/src/main/java/com/transcendensoft/hedbanz/presentation/rooms/list/RoomItemContract.java
package com.transcendensoft.hedbanz.presentation.rooms.list; /** * Copyright 2017. <NAME> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.support.annotation.DrawableRes; import android.view.ViewGroup; /** * View and Presenter interfaces contract for room item presentation * * @author <NAME>. E-mail: <EMAIL> * Developed by <u>Transcendensoft</u> */ public interface RoomItemContract { interface View { void setIcon(@DrawableRes int icon, @DrawableRes int stickerBg); void setName(String name); void setCurAndMaxPlayers(int currentPlayers, int maxPlayers); void setIsProtected(boolean isProtected); void setIsActive(boolean isActive); void showLoadingItem(); void showCard(); void showErrorServer(); void showErrorNetwork(); ViewGroup getItemView(); Context provideContext(); void showLoadingDialog(); void hideLoadingDialog(); } interface Presenter { void onClickRoom(); } }
AnnMarieW/dash-app-gallery
pages/stopwatch.py
import dash from utils.code_and_show import example_app dash.register_page( __name__, description="Stopwatch timer application with 1 button and an input field.", layout_type="general", components_type=["leddisplay", "input", "interval", "powerbutton"], graph_type="none", callback_type="general", ) filename = __name__.split("pages.")[1] # make a mini layout with the links to the docs that would go under each app # all_links: {"input": "https://dash.plotly.com/dash-core-components/input", # "interval": "https://dash.plotly.com/dash-core-components/interval", # "dash-daq": "https://dash.plotly.com/dash-daq"} # links = html.Div([all_links]) layout = example_app(filename)
AndriiMysko/travis-api
spec/lib/services/find_log_spec.rb
describe Travis::Services::FindLog do let(:params) { {} } let(:service) { described_class.new(double('user'), params) } let(:job) { FactoryBot.create(:job) } describe 'run' do it 'finds the log with the given id' do params[:id] = 1 found_by_id = double('found-by-id', job_id: job.id) remote = double('remote') expect(remote).to receive(:find_by_id).with(1).and_return(found_by_id) expect(Travis::RemoteLog::Remote).to receive(:new).and_return(remote) expect(service.run).to eq(found_by_id) end it 'finds the log with the given job_id' do params[:job_id] = job.id found_by_job_id = double('found-by-job-id', job_id: job.id) remote = double('remote') expect(remote).to receive(:find_by_job_id).with(job.id).and_return(found_by_job_id) expect(Travis::RemoteLog::Remote).to receive(:new).and_return(remote) expect(service.run).to eq(found_by_job_id) end it 'does not raise if the log could not be found' do params[:id] = 17 remote = double('remote') expect(remote).to receive(:find_by_id).with(17).and_return(nil) expect(Travis::RemoteLog::Remote).to receive(:new).and_return(remote) expect { service.run }.not_to raise_error end end end
taeb3/anchor
app/shared/components/Welcome/Breadcrumb.js
// @flow import React, { Component } from 'react'; import { Icon, Step } from 'semantic-ui-react'; import { withTranslation } from 'react-i18next'; class WelcomeBreadcrumb extends Component<Props> { render() { const { onStageSelect, stage, t, walletMode } = this.props; return false return ( <Step.Group attached="bottom" fluid size="small" vertical> {(walletMode !== 'cold') ? ( <Step active={(stage === 0)} completed={(stage > 0)} description="test" icon="wifi" key="connection_stage" onClick={(stage > 0) ? () => onStageSelect(0) : null} title={t('welcome_stage_connection')} /> ) : ( <Step description="test" icon="snowflake" key="connection_stage_cold" title={t('welcome_stage_coldwallet')} /> ) } <Step active={(stage === 2)} completed={(stage > 2)} disabled={(stage < 2)} description="test" icon="id badge" onClick={(stage > 2) ? () => onStageSelect(2) : null} title={t('welcome_stage_account')} /> {(walletMode !== 'watch') ? ( <React.Fragment> <Step active={(stage === 3)} completed={(stage > 3)} description="test" disabled={(stage < 3)} icon="key" onClick={(stage > 3) ? () => onStageSelect(3) : null} title={t('welcome_stage_authorize')} /> <Step active={(stage === 4)} description="test" disabled={(stage < 4)} icon="lock" title={t('welcome_stage_wallet')} /> </React.Fragment> ) : ( <Step active={(stage === 3)} disabled={(stage < 3)} icon="info" title={t('welcome_stage_watchwallet')} /> ) } </Step.Group> ); } } export default withTranslation('welcome')(WelcomeBreadcrumb);
Playermet/gbmath
forward_decl.h
<reponame>Playermet/gbmath<filename>forward_decl.h /** \file \brief forward-declaration */ #pragma once #ifndef __GBMATH_H__ #error DO NOT INCLUDE THIS FILE. USE: #include <gbmath/_gbmath.h> #endif namespace gbmath { class aabb; struct color4_32; class point2; class point3; class normal2; class normal3; class Circle; class Rect; struct plane_s; class euler_angles; class Quaternion; struct axies_angle; struct vec2; struct vec3; struct vec4; struct mat22; struct mat33; struct mat44; struct TransformData; }
ccrowley96/shareit.space
client/src/hooks/provideTheme.js
<filename>client/src/hooks/provideTheme.js import React, { useContext, useEffect, useState } from 'react'; import { themes } from '../constants/constants'; const Theme = React.createContext(); export const useTheme = () => useContext(Theme); export const ProvideTheme = ({ children }) => { const theme = useProvideTheme(); return <Theme.Provider value={theme}>{children}</Theme.Provider>; }; const useProvideTheme = () => { const initialTheme = localStorage.getItem('theme') ? localStorage.getItem('theme') : themes.dark; useEffect(() => { document.documentElement.setAttribute('data-theme', initialTheme); }, [initialTheme]); const [theme, setTheme] = useState(initialTheme); const toggleTheme = () => { if (theme === themes.dark) { document.documentElement.setAttribute('data-theme', 'light'); localStorage.setItem('theme', themes.light); setTheme(themes.light); } else { document.documentElement.setAttribute('data-theme', 'dark'); localStorage.setItem('theme', themes.dark); setTheme(themes.dark); } }; return { theme, toggleTheme }; };
lozanasc/restoms
src/components/layouts/Customer/CustomerLayout.js
<reponame>lozanasc/restoms import React from 'react'; import MainCustomer from '../../views/Customer/CustomerView'; import { CustomerProvider } from '../../contexts/CustomerContext'; import './style/CustomerLayout.scss'; export const CustomerOrder = () => { window.addEventListener('beforeunload', function (e) { // Cancel the event e.preventDefault(); // If you prevent default behavior in Mozilla Firefox prompt will always be shown // Chrome requires returnValue to be set e.returnValue = ''; }); return ( <CustomerProvider> <div className="CustomerLayoutContainer"> <MainCustomer/> </div> </CustomerProvider> ) } export const CustomerCheckout = () => { return ( <div className="CustomerLayoutContainer"> <h1> This is the Checkout component </h1> </div> ) }
helloingob/Steamgifter
Steamgifter-GUI/src/main/java/com/helloingob/gifter/IndexController.java
<reponame>helloingob/Steamgifter<filename>Steamgifter-GUI/src/main/java/com/helloingob/gifter/IndexController.java package com.helloingob.gifter; import java.text.SimpleDateFormat; import java.util.Optional; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Executions; import org.zkoss.zk.ui.event.Event; import org.zkoss.zk.ui.event.EventListener; import org.zkoss.zk.ui.event.Events; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zul.Box; import org.zkoss.zul.Hlayout; import org.zkoss.zul.Image; import org.zkoss.zul.Label; import org.zkoss.zul.Menuitem; import org.zkoss.zul.Menupopup; import org.zkoss.zul.Tab; import org.zkoss.zul.Vlayout; import org.zkoss.zul.Window; import com.helloingob.gifter.dao.UserDAO; import com.helloingob.gifter.dao.WonGiveawayDAO; import com.helloingob.gifter.to.UserTO; import com.helloingob.gifter.to.WonGiveawayTO; import com.helloingob.gifter.utilities.GUIHelper; import com.helloingob.gifter.utilities.GUISettings; import com.helloingob.gifter.utilities.MenuCreator; import com.helloingob.gifter.utilities.TimeHelper; import com.helloingob.gifter.utilities.manager.NotificationManager; import com.helloingob.gifter.utilities.manager.SessionManager; public class IndexController extends GenericForwardComposer<Component> { private static final long serialVersionUID = 1L; private Hlayout hlLastGiveaway; private Label lblLastWonGame; private Box boxUserImage; private Menupopup mnpMenu; private Tab tabDashboard; private Tab tabUserPanel; private Tab tabAdminPanel; private Tab tabWonGiveaways; private Vlayout vlDashBaordContent; @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); init(); } private void init() { initLastWonGame(); vlDashBaordContent.appendChild(new DashboardContent().getTable()); vlDashBaordContent.appendChild(new DashboardContent().getWidgets()); updateUserSpecificComponents(); showUserEditNotification(); refreshLastLogin(); } private void initLastWonGame() { Optional<WonGiveawayTO> optWonGiveaway = new WonGiveawayDAO().getLastWonGiveaway(); if (optWonGiveaway.isPresent()) { WonGiveawayTO wonGiveaway = optWonGiveaway.get(); String formattedDate = new SimpleDateFormat("dd.MM.yy").format(wonGiveaway.getEndDate()); lblLastWonGame.setValue("Last won giveaway: " + wonGiveaway.getTitle() + " (" + formattedDate + ", " + GUIHelper.convertDateDifferenceToString(TimeHelper.getCurrentTimestamp().getTime(), wonGiveaway.getEndDate().getTime()) + ")"); Menupopup menu = MenuCreator.createMenupopup(wonGiveaway.getSteamLink(), wonGiveaway.getGiveawayLink(), wonGiveaway.getTitle(), wonGiveaway.getPk()); menu.setPage(getPage()); hlLastGiveaway.addEventListener(Events.ON_RIGHT_CLICK, new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { menu.open(hlLastGiveaway); } }); Image userImage = GUIHelper.createImage(wonGiveaway.getUser().getImageLink(), wonGiveaway.getUserName()); userImage.setWidth("25px"); userImage.setHeight("25px"); userImage.setTooltiptext(wonGiveaway.getUserName()); boxUserImage.appendChild(userImage); } else { hlLastGiveaway.setVisible(false); } } private void updateUserSpecificComponents() { updateMenu(); toggleTabVisibility(); } private void updateMenu() { mnpMenu.getChildren().clear(); if (SessionManager.getUser().isPresent()) { Menuitem mniLogout = MenuCreator.createLogoutMenuitem(); mniLogout.addEventListener(Events.ON_CLICK, createLogoutMenuListener()); mnpMenu.appendChild(mniLogout); } else { Menuitem mniLogin = MenuCreator.createLoginMenuitem(); mniLogin.addEventListener(Events.ON_CLICK, createLoginMenuListener()); mnpMenu.appendChild(mniLogin); } } private EventListener<Event> createLoginMenuListener() { return new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { Window win = new Window(); win = (Window) Executions.createComponents("login.zul", null, null); win.setPosition("center"); win.setClosable(true); win.setBorder("normal"); win.setMaximizable(false); win.setSizable(false); win.doModal(); win.addEventListener(GUISettings.LOGIN_EVENT, new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { UserTO user = SessionManager.getUser().get(); NotificationManager.showInfo("Welcome, " + user.getLoginName(), tabUserPanel, NotificationManager.BEFORE_CENTER); Events.postEvent(GUISettings.SHOW_USERPANEL_EVENT, tabUserPanel.getLinkedPanel().getFirstChild().getFirstChild(), null); if (user.getIsAdmin()) { Events.postEvent(GUISettings.SHOW_ADMINPANEL_EVENT, tabAdminPanel.getLinkedPanel().getFirstChild().getFirstChild(), null); } updateUserSpecificComponents(); } }); } }; } private void toggleTabVisibility() { if (SessionManager.getUser().isPresent()) { tabUserPanel.setVisible(true); if (SessionManager.getUser().get().getIsAdmin()) { tabAdminPanel.setVisible(true); } else { tabAdminPanel.setVisible(false); } } else { if (tabUserPanel.isSelected() || tabAdminPanel.isSelected()) { tabDashboard.setSelected(true); } tabUserPanel.setVisible(false); tabAdminPanel.setVisible(false); } } private EventListener<Event> createLogoutMenuListener() { return new EventListener<Event>() { @Override public void onEvent(Event event) throws Exception { SessionManager.setUser(null); updateUserSpecificComponents(); } }; } private void refreshLastLogin() { if (SessionManager.getUser().isPresent()) { UserTO user = SessionManager.getUser().get(); user.setLastLogin(TimeHelper.getCurrentTimestamp()); new UserDAO().updateLastLogin(user); } } private void showUserEditNotification() { if (SessionManager.getUserEditNotification().isPresent()) { NotificationManager.showInfo(SessionManager.getUserEditNotification().get(), tabUserPanel, NotificationManager.BEFORE_CENTER); tabUserPanel.setSelected(true); SessionManager.setNotification(null); } } public void onClick$tabWonGiveaways() { Events.postEvent(GUISettings.SHOW_WON_GIVEAWAYS_EVENT, tabWonGiveaways.getLinkedPanel().getFirstChild().getFirstChild(), null); } }
tehcoderer/GamestonkTerminal
tests/openbb_terminal/economy/test_econ_data_helper.py
<reponame>tehcoderer/GamestonkTerminal # IMPORTATION STANDARD # IMPORTATION THIRDPARTY import pandas as pd import pytest # IMPORTATION INTERNAL from openbb_terminal.economy import econ_data_helper STOCK_DF = pd.DataFrame( data={ "Open": { pd.Timestamp("2022-01-20 00:00:00"): 101.05999755859375, pd.Timestamp("2022-01-21 00:00:00"): 102.63999938964844, }, "High": { pd.Timestamp("2022-01-20 00:00:00"): 102.77999877929688, pd.Timestamp("2022-01-21 00:00:00"): 103.75, }, "Low": { pd.Timestamp("2022-01-20 00:00:00"): 100.68000030517578, pd.Timestamp("2022-01-21 00:00:00"): 102.33000183105469, }, "Close": { pd.Timestamp("2022-01-20 00:00:00"): 102.0199966430664, pd.Timestamp("2022-01-21 00:00:00"): 102.91999816894531, }, "Adj Close": { pd.Timestamp("2022-01-20 00:00:00"): 102.0199966430664, pd.Timestamp("2022-01-21 00:00:00"): 102.91999816894531, }, "Volume": { pd.Timestamp("2022-01-20 00:00:00"): 5589700, pd.Timestamp("2022-01-21 00:00:00"): 5423100, }, "date_id": { pd.Timestamp("2022-01-20 00:00:00"): 1, pd.Timestamp("2022-01-21 00:00:00"): 2, }, "OC_High": { pd.Timestamp("2022-01-20 00:00:00"): 102.0199966430664, pd.Timestamp("2022-01-21 00:00:00"): 102.91999816894531, }, "OC_Low": { pd.Timestamp("2022-01-20 00:00:00"): 101.05999755859375, pd.Timestamp("2022-01-21 00:00:00"): 102.63999938964844, }, "OC_High_trend": { pd.Timestamp("2022-01-20 00:00:00"): 102.0199966430664, pd.Timestamp("2022-01-21 00:00:00"): 102.91999816894531, }, "OC_Low_trend": { pd.Timestamp("2022-01-20 00:00:00"): 101.05999755859375, pd.Timestamp("2022-01-21 00:00:00"): 102.63999938964844, }, } ) @pytest.fixture(scope="module") def vcr_config(): return { "filter_headers": [("User-Agent", None)], "filter_query_parameters": [ ("period1", "MOCK_PERIOD_1"), ("period2", "MOCK_PERIOD_2"), ("date", "MOCK_DATE"), ], } @pytest.mark.vcr def test_draw_graph(mocker): # MOCK PLOT mock_plot = mocker.Mock() mocker.patch( target="openbb_terminal.economy.econ_data_helper.mpf.plot", new=mock_plot, ) econ_data_helper.draw_graph( ticker="PM", report_cache_dir=None, time_delta=3, line_type="candle", draw_mas=(20, 50), draw_volume=True, high_trend=True, low_trend=True, ) mock_plot.assert_called_once() @pytest.mark.vcr(record_mode="none") def test_draw_graph_cache_with_file(mocker): # MOCK IS_FILE mocker.patch( target="openbb_terminal.economy.econ_data_helper.os.path.isfile", return_value=True, ) # MOCK READ_PICKLE mocker.patch( target="openbb_terminal.economy.econ_data_helper.pd.read_pickle", return_value=STOCK_DF, ) # MOCK PLOT mock_plot = mocker.Mock() mocker.patch( target="openbb_terminal.economy.econ_data_helper.mpf.plot", new=mock_plot, ) # MOCK CACHE_DIR mock_cache_dir = "MOCK_CACHE_DIR" econ_data_helper.draw_graph( ticker="PM", report_cache_dir=mock_cache_dir, time_delta=3, line_type="candle", draw_mas=(20, 50), draw_volume=True, high_trend=True, low_trend=True, ) mock_plot.assert_called_once() @pytest.mark.vcr(record_mode="none") def test_draw_graph_cache_without_file(mocker): # MOCK IS_FILE mocker.patch( target="openbb_terminal.economy.econ_data_helper.os.path.isfile", return_value=False, ) # MOCK LOAD_TICKER mocker.patch( target="openbb_terminal.economy.econ_data_helper.stocks_helper.load_ticker", return_value=STOCK_DF, ) # MOCK FIND_TRENDLINE mocker.patch( target="openbb_terminal.economy.econ_data_helper.stocks_helper.find_trendline", return_value=STOCK_DF, ) # MOCK TO_PICKLE mocker.patch( target="openbb_terminal.economy.econ_data_helper.pd.DataFrame.to_pickle", return_value=STOCK_DF, ) # MOCK PLOT mock_plot = mocker.Mock() mocker.patch( target="openbb_terminal.economy.econ_data_helper.mpf.plot", new=mock_plot, ) # MOCK CACHE_DIR mock_cache_dir = "MOCK_CACHE_DIR" econ_data_helper.draw_graph( ticker="PM", report_cache_dir=mock_cache_dir, time_delta=3, line_type="candle", draw_mas=(20, 50), draw_volume=True, high_trend=True, low_trend=True, ) mock_plot.assert_called_once()
liyong299/normal
java/src/main/java/com/ly/java/observer/ConcreteObserverA.java
<reponame>liyong299/normal package com.ly.java.observer; public class ConcreteObserverA implements AbstractObserver { @Override public void update(Object obj, Subject subject) { System.out.println("观察者A收到消息:" + obj); } }
webeyemob/WeSdkiOSPub
WeSdk/1.3.5/WeMobSdk.framework/Headers/WeMobILineItem.h
<gh_stars>0 // // WeMobILinItem.h // Created by Matthew on 2019/6/24. // #import <Foundation/Foundation.h> #import "WeMobBannerAdSize.h" #import "WeMobNetwork.h" @interface WeMobILineItem : NSObject -(NSString *)getName; -(WeMobNetwork *)getNetwork; -(int)getPriority; -(float)getEcpm; -(WeMobBannerAdSize)getBannerAdSize; -(int)getBannerRefreshInterval; -(int)getRequestTimeOut; -(NSDictionary *)getServerExtras; @end
vlumi/photo-diary
react-app/src/components/Gallery/Link.js
import React from "react"; import PropTypes from "prop-types"; import { Link as ReactLink } from "react-router-dom"; const Link = ({ children, className, gallery, year, month, photo, day, context, }) => { if (gallery && context === "stats") { return ( <ReactLink className={className} to={gallery.statsPath()}> {children} </ReactLink> ); } if (photo) { return ( <ReactLink className={className} to={photo.path(gallery)}> {children} </ReactLink> ); } if (!gallery) { return ( <ReactLink className={className} to="/g"> {children} </ReactLink> ); } const path = gallery.path(year, month, day); return ( <ReactLink className={className} to={path}> {children} </ReactLink> ); }; Link.propTypes = { children: PropTypes.any.isRequired, className: PropTypes.string, gallery: PropTypes.object, year: PropTypes.number, month: PropTypes.number, day: PropTypes.number, photo: PropTypes.object, context: PropTypes.string, }; export default Link;
hakmesyo/OpenJazariLibrary
src/test/TestHSV.java
<reponame>hakmesyo/OpenJazariLibrary /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package test; import jazari.matrix.CMatrix; import javax.swing.GrayFilter; /** * * @author BAP1 */ public class TestHSV { public static void main(String[] args) { CMatrix cm = CMatrix.getInstance() .imread("images/pullar.png") .imshow(); CMatrix cm2=cm.rgb2hsv().imshow().rgb2gray().imshow(); CMatrix cm3=cm.toGrayLevel().imshow(); CMatrix cm4 = cm2.multiplyElement(cm3).imshow(); } }
JavaScriptTesting/LJS
WebKit/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h
<filename>WebKit/Source/WebKit2/UIProcess/API/gtk/tests/WebViewTest.h<gh_stars>1-10 /* * Copyright (C) 2011 <NAME>. * Portions Copyright (c) 2011 Motorola Mobility, Inc. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #ifndef WebViewTest_h #define WebViewTest_h #include "TestMain.h" #include <webkit2/webkit2.h> #include <wtf/text/CString.h> class WebViewTest: public Test { public: MAKE_GLIB_TEST_FIXTURE(WebViewTest); WebViewTest(); virtual ~WebViewTest(); void loadURI(const char* uri); void loadHtml(const char* html, const char* baseURI); void loadPlainText(const char* plainText); void loadAlternateHTML(const char* html, const char* baseURI, const char* unreachableURI); void loadRequest(WebKitURIRequest*); void goBack(); void goForward(); void goToBackForwardListItem(WebKitBackForwardListItem*); void wait(double seconds); WebKitWebView* m_webView; GMainLoop* m_mainLoop; CString m_activeURI; }; #endif // WebViewTest_h
ssjlee93/infosys-kaggle-exercise
node/node_modules/npm/lib/ll.js
<filename>node/node_modules/npm/lib/ll.js const LS = require('./ls.js') class LL extends LS { /* istanbul ignore next - see test/lib/load-all-commands.js */ static get name () { return 'll' } /* istanbul ignore next - see test/lib/load-all-commands.js */ static get usage () { return ['[[<@scope>/]<pkg> ...]'] } exec (args, cb) { this.npm.config.set('long', true) super.exec(args, cb) } } module.exports = LL
NeuroRoboticTech/AnimatLabPublicSource
Libraries/AnimatCarlSimCUDA/CsSpikingCurrentSynapse.cpp
<reponame>NeuroRoboticTech/AnimatLabPublicSource<gh_stars>1-10 /** \file CsSpikingCurrentSynapse.cpp \brief Implements the synapse class. **/ #include "StdAfx.h" #include "CsNeuronGroup.h" #include "CsNeuralModule.h" #include "CsSpikingCurrentSynapse.h" namespace AnimatCarlSim { /** \brief Default constructor. \author dcofer \date 3/29/2011 **/ CsSpikingCurrentSynapse::CsSpikingCurrentSynapse() { m_lpFromNeuron = NULL; m_lpToNeuron = NULL; m_fltPulseDecay = 0; m_fltPulseMagnitude = 0; m_fltPulseSign = 1; m_bWholePopulation = true; m_fltPulseTC = 0; m_fltCurrentMagnitude = 0; m_fltAppliedCurrent = 0; m_fltDecrementCurrent = 0; m_ulSpikeTestTime = 0; m_iStepsPerTest = 0; m_iStepsPerTestCount = -1; m_lTotalSpikesAdded = 0; } /** \brief Destructor. \author dcofer \date 3/29/2011 **/ CsSpikingCurrentSynapse::~CsSpikingCurrentSynapse() { try { m_arySpikeTimes.RemoveAll(); } catch(...) {Std_TraceMsg(0, "Caught Error in desctructor of CsSpikingCurrentSynapse\r\n", "", -1, false, true);} } void CsSpikingCurrentSynapse::PulseDecay(float fltVal) { Std_IsAboveMin((float) 0, fltVal, true, "PulseDecay"); m_fltPulseDecay = fltVal; if(m_lpModule && m_lpModule->TimeStep() > 0) { float fltTm = m_lpModule->TimeStep() / (1 - exp(-m_lpModule->TimeStep() / m_fltPulseDecay)); m_fltPulseTC = m_lpModule->TimeStep() / fltTm; } } float CsSpikingCurrentSynapse::PulseDecay() {return m_fltPulseDecay;} void CsSpikingCurrentSynapse::PulseCurrent(float fltVal) { Std_IsAboveMin((float) 0, fltVal, true, "PulseCurrent"); m_fltPulseMagnitude = fabs(fltVal); m_fltPulseSign = Std_Sign(fltVal); } float CsSpikingCurrentSynapse::PulseCurrent() {return (m_fltPulseMagnitude*m_fltPulseSign);} void CsSpikingCurrentSynapse::Coverage(std::string strType) { std::string strVal = Std_CheckString(strType); if(strVal == "INDIVIDUALS") WholePopulation(false); else if(strVal == "WHOLEPOPULATION") WholePopulation(true); else THROW_PARAM_ERROR(Cs_Err_lInvalidFiringRateCoverage, Cs_Err_strInvalidFiringRateCoverage, "Coverage", strType); } bool CsSpikingCurrentSynapse::WholePopulation() {return m_bWholePopulation;} void CsSpikingCurrentSynapse::WholePopulation(bool bVal) { m_bWholePopulation = bVal; if(m_lpFromNeuron) m_lpFromNeuron->CollectFromWholePopulation(bVal); } void CsSpikingCurrentSynapse::Cells(std::string strXml) { CStdXml oXml; oXml.Deserialize(strXml); oXml.FindElement("Root"); oXml.FindChildElement("Cells"); LoadCells(oXml); } void CsSpikingCurrentSynapse::CalculateStepsPerTest() { m_ulSpikeTestTime = 0; m_iStepsPerTestCount = -1; m_ulSpikeTestTime = 0; if(m_lpModule && m_lpModule->TimeStep() > 0) { m_iStepsPerTest = (int) ((CARLSIM_STEP_INCREMENT/m_lpModule->TimeStep())+0.5); if(m_iStepsPerTest>0) m_iStepsPerTest--; } else m_iStepsPerTest = 0; } void CsSpikingCurrentSynapse::TimeStepModified() { Link::TimeStepModified(); //Reset the exponential pulse decay constant PulseDecay(m_fltPulseDecay); CalculateStepsPerTest(); } void CsSpikingCurrentSynapse::MonitorSpikeEventFired(int iGroupID, int iNeuronID, long lTimeIdx) { if(m_lpFromNeuron && m_lpFromNeuron->GroupID() == iGroupID && (m_bWholePopulation || (!m_bWholePopulation && m_aryCells.count(iNeuronID))) ) { m_AccessSpikes.lock(); m_arySpikeTimes.Add(lTimeIdx); m_AccessSpikes.unlock(); //std::string strMsg = "Received Spike Group: " + STR(iGroupID) + ", Neuron: " + STR(iNeuronID) + ", Time: " + STR(lTimeIdx) + "\r\n"; //OutputDebugString(strMsg.c_str()); } } void CsSpikingCurrentSynapse::Initialize() { Link::Initialize(); m_lpFromNeuron = dynamic_cast<CsNeuronGroup *>(m_lpSim->FindByID(m_strFromID)); if(!m_lpFromNeuron) THROW_PARAM_ERROR(Al_Err_lNodeNotFound, Al_Err_strNodeNotFound, "ID: ", m_strFromID); m_lpToNeuron = dynamic_cast<AnimatSim::Node *>(m_lpSim->FindByID(m_strToID)); if(!m_lpToNeuron) THROW_PARAM_ERROR(Al_Err_lNodeNotFound, Al_Err_strNodeNotFound, "ID: ", m_strToID); CalculateStepsPerTest(); if(m_lpFromNeuron) { m_lpFromNeuron->CollectFromWholePopulation(m_bWholePopulation); if(m_MonitoredSpikeEvent.connected()) m_MonitoredSpikeEvent.disconnect(); m_MonitoredSpikeEvent = m_lpFromNeuron->MonitoredSpikeEvent.connect(boost::bind(&CsSpikingCurrentSynapse::MonitorSpikeEventFired, this, _1, _2, _3)); } } #pragma region DataAccesMethods float *CsSpikingCurrentSynapse::GetDataPointer(const std::string &strDataType) { std::string strType = Std_CheckString(strDataType); float *lpData = NULL; if(strType == "APPLIEDCURRENT") return &m_fltAppliedCurrent; else if(strType == "DECREMENTCURRENT") return &m_fltDecrementCurrent; return Link::GetDataPointer(strDataType); } void CsSpikingCurrentSynapse::VerifySystemPointers() { AnimatBase::VerifySystemPointers(); if(!m_lpStructure) THROW_PARAM_ERROR(Al_Err_lStructureNotDefined, Al_Err_strStructureNotDefined, "Link: ", m_strID); if(!m_lpOrganism) THROW_PARAM_ERROR(Al_Err_lConvertingClassToType, Al_Err_strConvertingClassToType, "Link: ", m_strID); if(!m_lpModule) THROW_PARAM_ERROR(Al_Err_lNeuralModuleNotDefined, Al_Err_strNeuralModuleNotDefined, "Link: ", m_strID); } bool CsSpikingCurrentSynapse::SetData(const std::string &strDataType, const std::string &strValue, bool bThrowError) { std::string strType = Std_CheckString(strDataType); if(Link::SetData(strDataType, strValue, false)) return true; if(strType == "PULSEDECAY") { PulseDecay(atof(strValue.c_str())); return true; } else if(strType == "PULSECURRENT") { PulseCurrent(atof(strValue.c_str())); return true; } else if(strType == "COVERAGE") { Coverage(strValue); return true; } else if(strType == "CELLS") { Cells(strValue); return true; } //If it was not one of those above then we have a problem. if(bThrowError) THROW_PARAM_ERROR(Al_Err_lInvalidDataType, Al_Err_strInvalidDataType, "Data Type", strDataType); return false; } void CsSpikingCurrentSynapse::QueryProperties(CStdPtrArray<TypeProperty> &aryProperties) { Link::QueryProperties(aryProperties); aryProperties.Add(new TypeProperty("AppliedCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get)); aryProperties.Add(new TypeProperty("DecrementCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Get)); aryProperties.Add(new TypeProperty("PulseDecay", AnimatPropertyType::Float, AnimatPropertyDirection::Set)); aryProperties.Add(new TypeProperty("PulseCurrent", AnimatPropertyType::Float, AnimatPropertyDirection::Set)); aryProperties.Add(new TypeProperty("Coverage", AnimatPropertyType::String, AnimatPropertyDirection::Set)); aryProperties.Add(new TypeProperty("Cells", AnimatPropertyType::Xml, AnimatPropertyDirection::Set)); } #pragma endregion void CsSpikingCurrentSynapse::ResetSimulation() { Link::ResetSimulation(); m_fltCurrentMagnitude = 0; m_fltAppliedCurrent = 0; m_fltDecrementCurrent = 0; m_iStepsPerTestCount = -1; m_ulSpikeTestTime = 0; m_lTotalSpikesAdded = 0; } void CsSpikingCurrentSynapse::ProcessSpikes() { //If the steps per count is < 0 it is the first time so run it then, then count normally. if(m_iStepsPerTestCount < 0 || m_iStepsPerTestCount == m_iStepsPerTest) { //std::string strMsg = "ProcessSpike Compare: Time: " + STR(m_lpSim->Time()) + ", ITime: " + STR(m_ulSpikeTestTime) + "\r\n"; //OutputDebugString(strMsg.c_str()); if(m_arySpikeTimes.GetSize() > 0) { int iIdx=0; long lNextTime = m_arySpikeTimes[iIdx]; bool bDone = false; while(lNextTime <= m_ulSpikeTestTime && !bDone) { m_fltCurrentMagnitude+=m_fltPulseMagnitude; m_lTotalSpikesAdded++; //std::string strMsg = "Added Spike Time: " + STR(m_lpSim->Time()) + "]\r\n"; //OutputDebugString(strMsg.c_str()); iIdx++; if(iIdx >= m_arySpikeTimes.GetSize()) bDone = true; else lNextTime = m_arySpikeTimes[iIdx]; } if(iIdx > 0) { m_AccessSpikes.lock(); for(int iIdx2=0; iIdx2<iIdx; iIdx2++) m_arySpikeTimes.RemoveAt(0); m_AccessSpikes.unlock(); } } m_ulSpikeTestTime++; m_iStepsPerTestCount = 0; } else m_iStepsPerTestCount++; } void CsSpikingCurrentSynapse::StepSimulation() { if(m_bEnabled && m_lpFromNeuron) { m_fltDecrementCurrent = (m_fltCurrentMagnitude*m_fltPulseTC); m_fltCurrentMagnitude -= m_fltDecrementCurrent; if(m_fltCurrentMagnitude <= 0) m_fltCurrentMagnitude = 0; ProcessSpikes(); m_fltAppliedCurrent = m_fltCurrentMagnitude * m_fltPulseSign; m_lpToNeuron->AddExternalNodeInput(0, m_fltAppliedCurrent); } } void CsSpikingCurrentSynapse::LoadCells(CStdXml &oXml) { oXml.IntoElem(); m_aryCells.RemoveAll(); int iCount = oXml.NumberOfChildren(); for(int iIdx=0; iIdx<iCount; iIdx++) { oXml.FindChildByIndex(iIdx); int iNeuronIdx = oXml.GetChildInt(); if(iNeuronIdx < 0) THROW_PARAM_ERROR(Cs_Err_lInvalidNeuralIndex, Cs_Err_strInvalidNeuralIndex, "Neuron Index", iNeuronIdx); if(!m_aryCells.count(iNeuronIdx)) m_aryCells.Add(iNeuronIdx, 1); } oXml.OutOfElem(); } void CsSpikingCurrentSynapse::Load(CStdXml &oXml) { Link::Load(oXml); oXml.IntoElem(); //Into Synapse Element m_strFromID = oXml.GetChildString("FromID"); if(Std_IsBlank(m_strFromID)) THROW_TEXT_ERROR(Std_Err_lBlankAttrib, Std_Err_strBlankAttrib, "Attribute: FromID"); m_strToID = oXml.GetChildString("ToID"); if(Std_IsBlank(m_strToID)) THROW_TEXT_ERROR(Std_Err_lBlankAttrib, Std_Err_strBlankAttrib, "Attribute: ToID"); PulseDecay(oXml.GetChildFloat("PulseDecay", m_fltPulseDecay)); PulseCurrent(oXml.GetChildFloat("PulseCurrent", m_fltPulseMagnitude)); Coverage(oXml.GetChildString("Coverage", "WholePopulation")); if(oXml.FindChildElement("Cells", false)) LoadCells(oXml); oXml.OutOfElem(); //OutOf Synapse Element } } //AnimatCarlSim
miathedev/BoostForArduino
src/boost_numeric_odeint_stepper_symplectic_euler.hpp
<filename>src/boost_numeric_odeint_stepper_symplectic_euler.hpp<gh_stars>1-10 #include <boost/numeric/odeint/stepper/symplectic_euler.hpp>
voltek62/h2o-3
h2o-core/src/main/java/water/api/Route.java
package water.api; import com.google.code.regexp.Pattern; import java.lang.reflect.Method; import java.util.Arrays; import water.H2O; import water.Iced; import water.util.MarkdownBuilder; /** * Routing of an http request to a handler method, with path parameter parsing. */ final class Route extends Iced { static final int MIN_VERSION = 1; // TODO: handlers are now stateless, so create a single instance and stash it here // TODO: all fields should be final! // TODO: remove no-args ctor, since it is not used public String _http_method; public String _url_pattern_raw; public Pattern _url_pattern; public String _summary; public Class<? extends Handler> _handler_class; public Method _handler_method; public Method _doc_method; // NOTE: Java 7 captures and lets you look up subpatterns by name but won't give you the list of names, so we need this redundant list: public String[] _path_params; // list of params we capture from the url pattern, e.g. for /17/MyComplexObj/(.*)/(.*) public Handler _handler; /** Handler factory configures a way how handler is instantiated. * * PLEASE: do not remove it even H2O is not using it. It is used by Sparkling Water, since * it needs to pass a Spark context to a new handler */ final HandlerFactory _handler_factory; public Route() { _handler_factory = null; } public Route(String http_method, String url_pattern_raw, Pattern url_pattern, String summary, Class<? extends Handler> handler_class, Method handler_method, Method doc_method, String[] path_params, HandlerFactory handler_factory) { assert http_method != null && url_pattern != null && handler_class != null && handler_method != null && path_params != null; assert handler_factory != null : "handler_factory should be not null, caller has to pass it!"; _http_method = http_method; _url_pattern_raw = url_pattern_raw; _url_pattern = url_pattern; _summary = summary; _handler_class = handler_class; _handler_method = handler_method; _doc_method = doc_method; _path_params = path_params; _handler_factory = handler_factory; try { _handler = _handler_factory.create(_handler_class); } catch (Exception ie) { H2O.fail("failed to register handler " + handler_class.getSimpleName() + "." + handler_method .getName(), ie); } } /** * Generate Markdown documentation for this Route. */ public StringBuffer markdown(Schema sinput, Schema soutput) { MarkdownBuilder builder = new MarkdownBuilder(); builder.comment("Preview with http://jbt.github.io/markdown-editor"); builder.heading1(_http_method, _url_pattern_raw.replace("(?<", "{").replace(">.*)", "}")); builder.hline(); builder.paragraph(_summary); // parameters and output tables builder.heading1("Input schema: "); builder.append(sinput .markdown(true ,false)); builder.heading1("Output schema: "); builder.append(soutput.markdown(false, true)); return builder.stringBuffer(); } @Override public boolean equals(Object o) { if( this == o ) return true; if( !(o instanceof Route) ) return false; Route route = (Route) o; if( !_handler_class .equals(route._handler_class )) return false; if( !_handler_method.equals(route._handler_method)) return false; if( !_doc_method.equals(route._doc_method)) return false; if( !_http_method.equals(route._http_method)) return false; if( !_url_pattern_raw.equals(route._url_pattern_raw)) return false; if( !Arrays.equals(_path_params, route._path_params)) return false; return true; } @Override public int hashCode() { long result = _http_method.hashCode(); result = 31 * result + _url_pattern_raw.hashCode(); result = 31 * result + _handler_class.hashCode(); result = 31 * result + _handler_method.hashCode(); result = 31 * result + _doc_method.hashCode(); result = 31 * result + Arrays.hashCode(_path_params); return (int)result; } @Override public String toString() { return "Route{" + "_http_method='" + _http_method + '\'' + ", _url_pattern=" + _url_pattern_raw + ", _summary='" + _summary + '\'' + ", _handler_class=" + _handler_class + ", _handler_method=" + _handler_method + ", _input_schema=" + Handler.getHandlerMethodInputSchema(_handler_method) + ", _output_schema=" + Handler.getHandlerMethodOutputSchema(_handler_method) + ", _doc_method=" + _doc_method + ", _path_params=" + Arrays.toString(_path_params) + '}'; } } // Route
fuldaros/paperplane_kernel_wileyfox-spark
sources/drivers/misc/mediatek/accelerometer/lsm6ds3/lsm6ds3.h
<reponame>fuldaros/paperplane_kernel_wileyfox-spark<filename>sources/drivers/misc/mediatek/accelerometer/lsm6ds3/lsm6ds3.h<gh_stars>1-10 /* lsm6ds3.h * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef L3M6DS3_H #define L3M6DS3_H #include <linux/ioctl.h> #define LSM6DS3_I2C_SLAVE_ADDR 0xD0 #define LSM6DS3_FIXED_DEVID 0x69 /* LSM6DS3 Register Map (Please refer to LSM6DS3 Specifications) */ #define LSM6DS3_FUNC_CFG_ACCESS 0x00 #define LSM6DS3_RAM_ACCESS 0X01 #define LSM6DS3_SENSOR_SYNC_TIME_FRAME 0X04 /*FIFO control register*/ #define LSM6DS3_FIFO_CTRL1 0x06 #define LSM6DS3_FIFO_CTRL2 0x07 #define LSM6DS3_FIFO_CTRL3 0x08 #define LSM6DS3_FIFO_CTRL4 0x09 #define LSM6DS3_FIFO_CTRL5 0x0a /*Orientation configuration*/ #define LSM6DS3_ORIENT_CFG_G 0x0B /*Interrupt control*/ #define LSM6DS3_INT1_CTRL 0x0D #define LSM6DS3_INT2_CTRL 0x0E #define LSM6DS3_WHO_AM_I 0x0F /*Acc and Gyro control registers*/ #define LSM6DS3_CTRL1_XL 0x10 #define LSM6DS3_CTRL2_G 0x11 #define LSM6DS3_CTRL3_C 0x12 #define LSM6DS3_CTRL4_C 0x13 #define LSM6DS3_CTRL5_C 0x14 #define LSM6DS3_CTRL6_C 0x15 #define LSM6DS3_CTRL7_G 0x16 #define LSM6DS3_CTRL8_XL 0x17 #define LSM6DS3_CTRL9_XL 0x18 #define LSM6DS3_CTRL10_C 0x19 #define LSM6DS3_MASTER_CONFIG 0x1A #define LSM6DS3_WAKE_UP_SRC 0x1B #define LSM6DS3_TAP_SRC 0x1C #define LSM6DS3_D6D_SRC 0x1D #define LSM6DS3_STATUS_REG 0x1E /*Output register*/ #define LSM6DS3_OUT_TEMP_L 0x20 #define LSM6DS3_OUT_TEMP_H 0x21 #define LSM6DS3_OUTX_L_G 0x22 #define LSM6DS3_OUTX_H_G 0x23 #define LSM6DS3_OUTY_L_G 0x24 #define LSM6DS3_OUTY_H_G 0x25 #define LSM6DS3_OUTZ_L_G 0x26 #define LSM6DS3_OUTZ_H_G 0x27 #define LSM6DS3_OUTX_L_XL 0x28 #define LSM6DS3_OUTX_H_XL 0x29 #define LSM6DS3_OUTY_L_XL 0x2A #define LSM6DS3_OUTY_H_XL 0x2B #define LSM6DS3_OUTZ_L_XL 0x2C #define LSM6DS3_OUTZ_H_XL 0x2D /*Sensor Hub registers*/ #define LSM6DS3_SENSORHUB1_REG 0x2E #define LSM6DS3_SENSORHUB2_REG 0x2F #define LSM6DS3_SENSORHUB3_REG 0x30 #define LSM6DS3_SENSORHUB4_REG 0x31 #define LSM6DS3_SENSORHUB5_REG 0x32 #define LSM6DS3_SENSORHUB6_REG 0x33 #define LSM6DS3_SENSORHUB7_REG 0x34 #define LSM6DS3_SENSORHUB8_REG 0x35 #define LSM6DS3_SENSORHUB9_REG 0x36 #define LSM6DS3_SENSORHUB10_REG 0x37 #define LSM6DS3_SENSORHUB11_REG 0x38 #define LSM6DS3_SENSORHUB12_REG 0x39 #define LSM6DS3_SENSORHUB13_REG 0x4D #define LSM6DS3_SENSORHUB14_REG 0x4E #define LSM6DS3_SENSORHUB15_REG 0x4F #define LSM6DS3_SENSORHUB16_REG 0x50 #define LSM6DS3_SENSORHUB17_REG 0x51 #define LSM6DS3_SENSORHUB18_REG 0x52 /*FIFO status registers*/ #define LSM6DS3_FIFO_STATUS1 0x3A #define LSM6DS3_FIFO_STATUS2 0x3B #define LSM6DS3_FIFO_STATUS3 0x3C #define LSM6DS3_FIFO_STATUS4 0x3D #define LSM6DS3_FIFO_DATA_OUT_L 0x3E #define LSM6DS3_FIFO_DATA_OUT_H 0x3F #define LSM6DS3_TIMESTAMP0_REG 0x40 #define LSM6DS3_TIMESTAMP1_REG 0x41 #define LSM6DS3_TIMESTAMP2_REG 0x42 #define LSM6DS3_STEP_TIMESTAMP_L 0x49 #define LSM6DS3_STEP_TIMESTAMP_H 0x4A #define LSM6DS3_STEP_COUNTER_L 0x4B #define LSM6DS3_STEP_COUNTER_H 0x4C #define LSM6DS3_FUNC_SRC 0x53 #define LSM6DS3_TAP_CFG 0x58 #define LSM6DS3_TAP_THS_6D 0x59 #define LSM6DS3_INT_DUR2 0x5A #define LSM6DS3_WAKE_UP_THS 0x5B #define LSM6DS3_WAKE_UP_DUR 0x5C #define LSM6DS3_FREE_FALL 0x5D #define LSM6DS3_MD1_CFG 0x5E #define LSM6DS3_MD2_CFG 0x5F /*Output Raw data*/ #define LSM6DS3_OUT_MAG_RAW_X_L 0x66 #define LSM6DS3_OUT_MAG_RAW_X_H 0x67 #define LSM6DS3_OUT_MAG_RAW_Y_L 0x68 #define LSM6DS3_OUT_MAG_RAW_Y_H 0x69 #define LSM6DS3_OUT_MAG_RAW_Z_L 0x6A #define LSM6DS3_OUT_MAG_RAW_Z_H 0x6B /*Embedded function register*/ #define LSM6DS3_SLV0_ADD 0x02 #define LSM6DS3_SLV0_SUBADD 0x03 #define LSM6DS3_SLAVE0_CONFIG 0x04 #define LSM6DS3_SLV1_ADD 0x05 #define LSM6DS3_SLV1_SUBADD 0x06 #define LSM6DS3_SLAVE1_CONFIG 0x07 #define LSM6DS3_SLV2_ADD 0x08 #define LSM6DS3_SLV2_SUBADD 0x09 #define LSM6DS3_SLAVE2_CONFIG 0x0a #define LSM6DS3_SLV3_ADD 0x0b #define LSM6DS3_SLV3_SUBADD 0x0c #define LSM6DS3_SLAVE3_CONFIG 0x0d #define LSM6DS3_DATAWRITE_SRC_MODE_SUB_SLV0 0x0e #define LSM6DS3_SM_THS 0x13 #define LSM6DS3_STEP_COUNT_DELTA 0x15 #define LSM6DS3_MAG_SI_XX 0x24 #define LSM6DS3_MAG_SI_XY 0x25 #define LSM6DS3_MAG_SI_XZ 0x26 #define LSM6DS3_MAG_SI_YX 0x27 #define LSM6DS3_MAG_SI_YY 0x28 #define LSM6DS3_MAG_SI_YZ 0x29 #define LSM6DS3_MAG_SI_ZX 0x2a #define LSM6DS3_MAG_SI_ZY 0x2b #define LSM6DS3_MAG_SI_ZZ 0x2c #define LSM6DS3_MAG_OFFX_L 0x2D #define LSM6DS3_MAG_OFFX_H 0x2E #define LSM6DS3_MAG_OFFY_L 0x2F #define LSM6DS3_MAG_OFFY_H 0x30 #define LSM6DS3_MAG_OFFZ_L 0x31 #define LSM6DS3_MAG_OFFZ_H 0x32 /*LSM6DS3 Register Bit definitions*/ #define LSM6DS3_ACC_RANGE_MASK 0x0C #define LSM6DS3_ACC_RANGE_2g 0x00 #define LSM6DS3_ACC_RANGE_4g 0x08 #define LSM6DS3_ACC_RANGE_8g 0x0C #define LSM6DS3_ACC_RANGE_16g 0x04 #define LSM6DS3_ACC_ODR_MASK 0xF0 #define LSM6DS3_ACC_ODR_POWER_DOWN 0x00 #define LSM6DS3_ACC_ODR_13HZ 0x10 #define LSM6DS3_ACC_ODR_26HZ 0x20 #define LSM6DS3_ACC_ODR_52HZ 0x30 #define LSM6DS3_ACC_ODR_104HZ 0x40 #define LSM6DS3_ACC_ODR_208HZ 0x50 #define LSM6DS3_ACC_ODR_416HZ 0x60 #define LSM6DS3_ACC_ODR_833HZ 0x70 #define LSM6DS3_ACC_ODR_1660HZ 0x80 #define LSM6DS3_ACC_ODR_3330HZ 0x90 #define LSM6DS3_ACC_ODR_6660HZ 0xA0 #define LSM6DS3_GYRO_RANGE_MASK 0x0E #define LSM6DS3_GYRO_RANGE_125DPS 0x02 #define LSM6DS3_GYRO_RANGE_245DPS 0x00 #define LSM6DS3_GYRO_RANGE_500DPS 0x04 #define LSM6DS3_GYRO_RANGE_1000DPS 0x08 #define LSM6DS3_GYRO_RANGE_2000DPS 0x0c #define LSM6DS3_GYRO_ODR_MASK 0xf0 #define LSM6DS3_GYRO_ODR_POWER_DOWN 0x00 #define LSM6DS3_GYRO_ODR_13HZ 0x10 #define LSM6DS3_GYRO_ODR_26HZ 0x20 #define LSM6DS3_GYRO_ODR_52HZ 0x30 #define LSM6DS3_GYRO_ODR_104HZ 0x40 #define LSM6DS3_GYRO_ODR_208HZ 0x50 #define LSM6DS3_GYRO_ODR_416HZ 0x60 #define LSM6DS3_GYRO_ODR_833HZ 0x70 #define LSM6DS3_GYRO_ODR_1660HZ 0x80 #define AUTO_INCREMENT 0x80 #define LSM6DS3_CTRL3_C_IFINC 0x04 #define LSM6DS3_ACC_SENSITIVITY_2G 61 /*ug/LSB*/ #define LSM6DS3_ACC_SENSITIVITY_4G 122 /*ug/LSB*/ #define LSM6DS3_ACC_SENSITIVITY_8G 244 /*ug/LSB*/ #define LSM6DS3_ACC_SENSITIVITY_16G 488 /*ug/LSB*/ #define LSM6DS3_ACC_ENABLE_AXIS_MASK 0X38 #define LSM6DS3_ACC_ENABLE_AXIS_X 0x08 #define LSM6DS3_ACC_ENABLE_AXIS_Y 0x10 #define LSM6DS3_ACC_ENABLE_AXIS_Z 0x20 #define LSM6DS3_GYRO_SENSITIVITY_125DPS 4375 /*udps/LSB*/ #define LSM6DS3_GYRO_SENSITIVITY_245DPS 8750 /*udps/LSB*/ #define LSM6DS3_GYRO_SENSITIVITY_500DPS 17500 /*udps/LSB*/ #define LSM6DS3_GYRO_SENSITIVITY_1000DPS 35000 /*udps/LSB*/ #define LSM6DS3_GYRO_SENSITIVITY_2000DPS 70000 /*udps/LSB*/ #define LSM6DS3_GYRO_ENABLE_AXIS_MASK 0x38 #define LSM6DS3_GYRO_ENABLE_AXIS_X 0x08 #define LSM6DS3_GYRO_ENABLE_AXIS_Y 0x10 #define LSM6DS3_GYRO_ENABLE_AXIS_Z 0x20 #define LSM6DS3_ACC_GYRO_FUNC_EN_MASK 0x04 #define LSM6DS3_PEDO_EN_MASK 0x40 typedef enum { LSM6DS3_ACC_GYRO_PEDO_EN_DISABLED = 0x00, LSM6DS3_ACC_GYRO_PEDO_EN_ENABLED = 0x40, } LSM6DS3_ACC_GYRO_PEDO_EN_t; #define LSM6DS3_TILT_EN_MASK 0x20 typedef enum { LSM6DS3_ACC_GYRO_TILT_EN_DISABLED = 0x00, LSM6DS3_ACC_GYRO_TILT_EN_ENABLED = 0x20, } LSM6DS3_ACC_GYRO_TILT_EN_t; typedef enum { LSM6DS3_ACC_GYRO_INT1 = 0, LSM6DS3_ACC_GYRO_INT2 = 1, } LSM6DS3_ACC_GYRO_ROUNT_INT_t; typedef enum { LSM6DS3_ACC_GYRO_FUNC_EN_DISABLED = 0x00, LSM6DS3_ACC_GYRO_FUNC_EN_ENABLED = 0x04, } LSM6DS3_ACC_GYRO_FUNC_EN_t; typedef enum { LSM6DS3_ACC_GYRO_INT_TILT_DISABLED = 0x00, LSM6DS3_ACC_GYRO_INT_TILT_ENABLED = 0x02, } LSM6DS3_ACC_GYRO_INT2_TILT_t; #define LSM6DS3_ACC_GYRO_INT_TILT_MASK 0x02 typedef enum { LSM6DS3_ACC_GYRO_TILT_DISABLED = 0x00, LSM6DS3_ACC_GYRO_TILT_ENABLED = 0x02, } LSM6DS3_ACC_GYRO_TILT_t; #define LSM6DS3_ACC_GYRO_TILT_MASK 0x02 typedef enum { LSM6DS3_ACC_GYRO_INT_SIGN_MOT_DISABLED = 0x00, LSM6DS3_ACC_GYRO_INT_SIGN_MOT_ENABLED = 0x40, } LSM6DS3_ACC_GYRO_INT_SIGN_MOT_t; #define LSM6DS3_ACC_GYRO_INT_SIGN_MOT_MASK 0x40 typedef enum { LSM6DS3_ACC_GYRO_SIGN_MOT_DISABLED = 0x00, LSM6DS3_ACC_GYRO_SIGN_MOT_ENABLED = 0x01, } LSM6DS3_ACC_GYRO_SIGN_MOT_t; #define LSM6DS3_ACC_GYRO_SIGN_MOT_MASK 0x01 typedef enum { LSM6DS3_ACC_GYRO_RAM_PAGE_DISABLED = 0x00, LSM6DS3_ACC_GYRO_RAM_PAGE_ENABLED = 0x80, } LSM6DS3_ACC_GYRO_RAM_PAGE_t; #define LSM6DS3_RAM_PAGE_MASK 0x80 #define LSM6DS3_CONFIG_PEDO_THS_MIN 0x0F typedef enum { LSM6DS3_ACC_GYRO_PEDO_RST_STEP_DISABLED = 0x00, LSM6DS3_ACC_GYRO_PEDO_RST_STEP_ENABLED = 0x02, } LSM6DS3_ACC_GYRO_PEDO_RST_STEP_t; #define LSM6DS3_PEDO_RST_STEP_MASK 0x02 typedef enum { LSM6DS3_ACC_GYRO_INT_ACTIVE_HIGH = 0x00, LSM6DS3_ACC_GYRO_INT_ACTIVE_LOW = 0x20, } LSM6DS3_ACC_GYRO_INT_ACTIVE_t; #define LSM6DS3_ACC_GYRO_INT_ACTIVE_MASK 0x20 typedef enum { LSM6DS3_ACC_GYRO_INT_LATCH = 0x01, LSM6DS3_ACC_GYRO_INT_NO_LATCH = 0x00, } LSM6DS3_ACC_GYRO_INT_LATCH_CTL_t; #define LSM6DS3_ACC_GYRO_INT_LATCH_CTL_MASK 0x01 #define LSM6DS3_SIGNICANT_MOTION_INT_STATUS 0x40 #define LSM6DS3_TILT_INT_STATUS 0x20 #define LSM6DS3_STEP_DETECT_INT_STATUS 0x10 #define LSM6DS3_SUCCESS 0 #define LSM6DS3_ERR_I2C -1 #define LSM6DS3_ERR_STATUS -3 #define LSM6DS3_ERR_SETUP_FAILURE -4 #define LSM6DS3_ERR_GETGSENSORDATA -5 #define LSM6DS3_ERR_IDENTIFICATION -6 #define LSM6DS3_BUFSIZE 60 /*------------------------------------------------------------------*/ /* 1 rad = 180/PI degree, L3G4200D_OUT_MAGNIFY = 131,*/ /* 180*131/PI = 7506*/ #define DEGREE_TO_RAD 180*1000000/PI/*7506 // fenggy mask*/ #endif /*L3M6DS3_H*/
kuanfan99/zeva
frontend/src/app/components/Modal.js
import React from 'react'; import PropTypes from 'prop-types'; const Modal = (props) => { const { cancelLabel, children, confirmClass, confirmLabel, handleCancel, handleSubmit, modalClass, showModal, title, icon, } = props; return ([ <div className={`modal ${showModal ? 'd-block' : 'd-none'}`} key="modal-window" role="dialog" tabIndex="-1"> <div className={`modal-dialog ${modalClass}`} role="document"> <div className="modal-content"> <div className="modal-header"> <h3 className="modal-title">{title}</h3> <button aria-label="Close" className="close" data-dismiss="modal" onClick={handleCancel} type="button" > <span aria-hidden="true">&times;</span> </button> </div> <div className="modal-body"> {children} </div> <div className="modal-footer"> <button className="btn btn-outline-secondary" data-dismiss="modal" id="cancel" onClick={handleCancel} type="button" >{cancelLabel} </button> <button className={`btn ${confirmClass}`} id="confirm" type="button" onClick={handleSubmit} >{icon}{confirmLabel} </button> </div> </div> </div> </div>, <div className={`modal-backdrop ${showModal ? 'd-block' : 'd-none'}`} key="modal-backdrop" />, ]); }; Modal.defaultProps = { children: undefined, icon: '', cancelLabel: 'Cancel', confirmClass: 'btn-outline-primary', confirmLabel: 'Confirm', modalClass: '', title: 'Confirm', }; Modal.propTypes = { cancelLabel: PropTypes.string, children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]), confirmClass: PropTypes.string, confirmLabel: PropTypes.string, handleCancel: PropTypes.func.isRequired, handleSubmit: PropTypes.func.isRequired, modalClass: PropTypes.string, showModal: PropTypes.bool.isRequired, title: PropTypes.string, icon: PropTypes.node, }; export default Modal;
Keneral/ae1
jetty/src/java/org/eclipse/jetty/http/HttpBuffers.java
// // ======================================================================== // Copyright (c) 1995-2014 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // All rights reserved. This program and the accompanying materials // are made available under the terms of the Eclipse Public License v1.0 // and Apache License v2.0 which accompanies this distribution. // // The Eclipse Public License is available at // http://www.eclipse.org/legal/epl-v10.html // // The Apache License v2.0 is available at // http://www.opensource.org/licenses/apache2.0.php // // You may elect to redistribute this code under either of these licenses. // ======================================================================== // package org.eclipse.jetty.http; import org.eclipse.jetty.io.Buffers; import org.eclipse.jetty.io.BuffersFactory; import org.eclipse.jetty.util.component.AbstractLifeCycle; /* ------------------------------------------------------------ */ /** Abstract Buffer pool. */ public interface HttpBuffers { /** * @return the requestBufferSize */ public int getRequestBufferSize(); /** * @param requestBufferSize the requestBufferSize to set */ public void setRequestBufferSize(int requestBufferSize); /** * @return the requestHeaderSize */ public int getRequestHeaderSize(); /** * @param requestHeaderSize the requestHeaderSize to set */ public void setRequestHeaderSize(int requestHeaderSize); /** * @return the responseBufferSize */ public int getResponseBufferSize(); /** * @param responseBufferSize the responseBufferSize to set */ public void setResponseBufferSize(int responseBufferSize); /** * @return the responseHeaderSize */ public int getResponseHeaderSize(); /** * @param responseHeaderSize the responseHeaderSize to set */ public void setResponseHeaderSize(int responseHeaderSize); /** * @return the requestBufferType */ public Buffers.Type getRequestBufferType(); /** * @return the requestHeaderType */ public Buffers.Type getRequestHeaderType(); /** * @return the responseBufferType */ public Buffers.Type getResponseBufferType(); /** * @return the responseHeaderType */ public Buffers.Type getResponseHeaderType(); /** * @param requestBuffers the requestBuffers to set */ public void setRequestBuffers(Buffers requestBuffers); /** * @param responseBuffers the responseBuffers to set */ public void setResponseBuffers(Buffers responseBuffers); public Buffers getRequestBuffers(); public Buffers getResponseBuffers(); public void setMaxBuffers(int maxBuffers); public int getMaxBuffers(); }
jeveleth/api
test/app/api/v1/domain/profile_test.js
const chai = require('chai') const sinon = require('sinon') const { ProfileDomain } = require('../../../../../app/api/v1/domain') const models = require('../../../../../app/models') const assert = chai.assert describe('Domain Profile', () => { let activityFindStub let notificationFindStub let sandbox beforeEach(() => { sandbox = sinon.createSandbox() }) afterEach(() => { sandbox.restore() }) it('should be defined', () => { assert.isDefined(ProfileDomain) }) it('getActivity should be defined', () => { assert.isDefined(ProfileDomain.getActivity) }) it('getNotifications should be defined', () => { assert.isDefined(ProfileDomain.getNotifications) }) describe('getActivity', () => { beforeEach(() => { activityFindStub = sandbox.stub(models.user_activity, 'findAll') }) it('should return activity', (done) => { const fakeUserID = 123 const fakeActivity = { set: sinon.stub(), save: sinon.stub(), activity: [ { id: 1, user_id: 123, follow_user_id: 12, type: 'followed_user' }, { id: 1, user_id: 123, follow_user_id: null, type: 'login' } ] } activityFindStub.returns(Promise.resolve(fakeActivity)) ProfileDomain.getActivity(fakeUserID).then((foundUser) => { assert.isDefined(foundUser) done() }) }) it('should fail with no userID', (done) => { const fakeUserID = 123 activityFindStub.returns(Promise.reject('No activity found for user ' + fakeUserID)) ProfileDomain.getActivity(fakeUserID).catch((error) => { assert.isDefined(error) done() }) }) it('should not return activity', (done) => { const fakeUserID = 123 activityFindStub.returns(Promise.resolve(null)) ProfileDomain.getActivity(fakeUserID).catch((error) => { assert.isDefined(error) done() }) }) }) describe('getNotifications', () => { beforeEach(() => { notificationFindStub = sandbox.stub(models.user_activity, 'findAll') }) it('should return notifications', (done) => { const fakeUserID = 123 notificationFindStub.returns(Promise.resolve(fakeUserID)) ProfileDomain.getNotifications(fakeUserID).then((response) => { assert.isDefined(response) assert.isTrue(response === fakeUserID) done() }) }) }) })
zarelaky/fuchsia
src/media/audio/audio_core/utils_unittest.cc
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/media/audio/audio_core/utils.h" #include <fuchsia/scheduler/cpp/fidl.h> #include <lib/fidl/cpp/binding_set.h> #include <lib/gtest/test_loop_fixture.h> #include <lib/sys/cpp/testing/component_context_provider.h> #include <cstdint> #include <unordered_map> namespace media::audio { namespace { class FakeProfileProvider : public fuchsia::scheduler::ProfileProvider { public: fidl::InterfaceRequestHandler<fuchsia::scheduler::ProfileProvider> GetHandler() { return bindings_.GetHandler(this); } // |GetProfile| will return ZX_ERR_NOT_FOUND/ZX_HANDLE_INVALID for any priority that has not // previously been marked as valid with a call to |SetProfile|. // // Note that currently the only works for a single |GetProfile| call since we don't duplicate // a new handle before sending it back to the client. bool SetProfile(uint32_t priority) { // Since there's no easy way to create a profile handle in a test context, we'll just use an // event handle. This will be sufficient to allow the handle to be sent over the channel back // to the caller, but it will obviously not work of the caller is doing anything that requires // a zx::profile. This limitation is sufficient for the purposes of our tests. zx::event e; zx::event::create(0, &e); return profiles_by_priority_.insert({priority, zx::profile(e.release())}).second; } private: // |fuchsia::scheduler::ProfileProvider| void GetProfile(uint32_t priority, std::string name, GetProfileCallback callback) override { auto it = profiles_by_priority_.find(priority); if (it == profiles_by_priority_.end()) { callback(ZX_ERR_NOT_FOUND, zx::profile()); } else { callback(ZX_OK, std::move(it->second)); } } // |fuchsia::scheduler::ProfileProvider| // TODO(eieio): Temporary until the deadline scheduler fully lands in tree. void GetDeadlineProfile(uint64_t capacity, uint64_t deadline, uint64_t period, std::string name, GetProfileCallback callback) override {} // |fuchsia::scheduler::ProfileProvider| void GetCpuAffinityProfile(fuchsia::scheduler::CpuSet cpu_mask, GetProfileCallback callback) override {} std::unordered_map<uint32_t, zx::profile> profiles_by_priority_; fidl::BindingSet<fuchsia::scheduler::ProfileProvider> bindings_; }; class UtilsTest : public gtest::TestLoopFixture { protected: void SetUp() override { TestLoopFixture::SetUp(); auto svc = context_provider_.service_directory_provider(); ASSERT_EQ(ZX_OK, svc->AddService(profile_provider_.GetHandler())); } FakeProfileProvider* profile_provider() { return &profile_provider_; } sys::ComponentContext* context() { return context_provider_.context(); } private: FakeProfileProvider profile_provider_; sys::testing::ComponentContextProvider context_provider_; }; TEST_F(UtilsTest, AcquireAudioCoreImplProfile) { ASSERT_TRUE(profile_provider()->SetProfile(24)); zx::profile profile; ASSERT_FALSE(profile); AcquireAudioCoreImplProfile(context(), [&profile](zx::profile p) { profile = std::move(p); }); RunLoopUntilIdle(); ASSERT_TRUE(profile); } TEST_F(UtilsTest, AcquireAudioCoreImplProfile_ProfileUnavailable) { zx::profile profile; bool callback_invoked = false; AcquireAudioCoreImplProfile(context(), [&](zx::profile p) { profile = std::move(p); callback_invoked = true; }); RunLoopUntilIdle(); ASSERT_FALSE(profile); ASSERT_TRUE(callback_invoked); } } // namespace } // namespace media::audio
kjthegod/chromium
remoting/webapp/browser_test/unauthenticated_browser_test.js
<reponame>kjthegod/chromium // Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * @fileoverview * @suppress {checkTypes} * * Browser test to verify that an unauthenticated state is handled correctly * in the following situations: * 1. When launching the app. * 2. When refreshing the host-list. * * TODO(jamiewalch): Add a test case for connecting to a host. */ 'use strict'; /** @constructor */ browserTest.Unauthenticated = function() { }; browserTest.Unauthenticated.prototype.run = function(data) { remoting.MockIdentity.setActive(true); remoting.MockHostListApi.setActive(true); remoting.MockOAuth2Api.setActive(true); remoting.mockIdentity.setAccessToken( remoting.MockIdentity.AccessToken.NONE); remoting.startDesktopRemoting(); browserTest.waitFor( browserTest.isVisible('auth-button') ).then( this.restoreSignedInState.bind(this) ).then( function() { console.log('waiting for enabled'); return browserTest.waitFor(browserTest.isEnabled('get-started-me2me')); } ).then( // Show the Me2Me UI, invalidate the access token again, and refresh the // host-list to verify that the user is prompted to sign in again. function() { console.log('clicking get-started-me2me'); browserTest.clickOnControl('get-started-me2me'); remoting.mockIdentity.setAccessToken( remoting.MockIdentity.AccessToken.INVALID); browserTest.clickOnControl('host-list-reload'); return browserTest.waitFor( browserTest.isVisible('host-list-refresh-failed-button')); } ).then( this.restoreSignedInState.bind(this) // TODO(jamiewalch): The sign-in button of the host-list doesn't work // for apps v2, because it assumes the v1 sign-in flow. Fix this and // extend this test to handle an authentication failure at this point. ).then(browserTest.pass, browserTest.fail); }; // Set a valid access token, then re-authenticate. Note that we're not // trying to test the sign-in flow here (that's tested elsewhere), we're // just getting the app back into a signed-in state so that we can continue // to test its behaviour if the token becomes invalid at various stages. browserTest.Unauthenticated.prototype.restoreSignedInState = function() { remoting.mockIdentity.setAccessToken( remoting.MockIdentity.AccessToken.VALID); browserTest.clickOnControl('auth-button'); return Promise.resolve(); };
factset/enterprise-sdk
code/java/VirtualPortfolioAPIforDigitalPortals/v1/src/main/java/com/factset/sdk/VirtualPortfolioAPIforDigitalPortals/models/InlineResponse2008Data.java
<filename>code/java/VirtualPortfolioAPIforDigitalPortals/v1/src/main/java/com/factset/sdk/VirtualPortfolioAPIforDigitalPortals/models/InlineResponse2008Data.java /* * Prime Developer Trial * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) * * The version of the OpenAPI document: v1 * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ package com.factset.sdk.VirtualPortfolioAPIforDigitalPortals.models; import java.util.Objects; import java.util.Arrays; import java.util.Map; import java.util.HashMap; import com.factset.sdk.VirtualPortfolioAPIforDigitalPortals.models.InlineResponse2008Notation; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.io.Serializable; import com.fasterxml.jackson.annotation.JsonPropertyOrder; import com.factset.sdk.VirtualPortfolioAPIforDigitalPortals.JSON; /** * InlineResponse2008Data */ @JsonPropertyOrder({ InlineResponse2008Data.JSON_PROPERTY_ID, InlineResponse2008Data.JSON_PROPERTY_NOTATION, InlineResponse2008Data.JSON_PROPERTY_TYPE, InlineResponse2008Data.JSON_PROPERTY_TIME, InlineResponse2008Data.JSON_PROPERTY_NUMBER_SHARES, InlineResponse2008Data.JSON_PROPERTY_PRICE, InlineResponse2008Data.JSON_PROPERTY_CHARGES, InlineResponse2008Data.JSON_PROPERTY_EXCHANGE_RATE }) @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class InlineResponse2008Data implements Serializable { private static final long serialVersionUID = 1L; public static final String JSON_PROPERTY_ID = "id"; private String id; public static final String JSON_PROPERTY_NOTATION = "notation"; private InlineResponse2008Notation notation; /** * Type of transaction */ public enum TypeEnum { BUY("buy"), SELL("sell"), CASH("cash"), PAYOUT("payout"), SHORT("short"), COVER("cover"); private String value; TypeEnum(String value) { this.value = value; } @JsonValue public String getValue() { return value; } @Override public String toString() { return String.valueOf(value); } @JsonCreator public static TypeEnum fromValue(String value) { for (TypeEnum b : TypeEnum.values()) { if (b.value.equals(value)) { return b; } } throw new IllegalArgumentException("Unexpected value '" + value + "'"); } } public static final String JSON_PROPERTY_TYPE = "type"; private TypeEnum type; public static final String JSON_PROPERTY_TIME = "time"; private String time; public static final String JSON_PROPERTY_NUMBER_SHARES = "numberShares"; private BigDecimal numberShares; public static final String JSON_PROPERTY_PRICE = "price"; private BigDecimal price; public static final String JSON_PROPERTY_CHARGES = "charges"; private BigDecimal charges; public static final String JSON_PROPERTY_EXCHANGE_RATE = "exchangeRate"; private BigDecimal exchangeRate; public InlineResponse2008Data() { } public InlineResponse2008Data id(String id) { this.id = id; return this; } /** * Identifier of transaction. * @return id **/ @javax.annotation.Nullable @ApiModelProperty(value = "Identifier of transaction.") @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getId() { return id; } @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setId(String id) { this.id = id; } public InlineResponse2008Data notation(InlineResponse2008Notation notation) { this.notation = notation; return this; } /** * Get notation * @return notation **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NOTATION) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public InlineResponse2008Notation getNotation() { return notation; } @JsonProperty(JSON_PROPERTY_NOTATION) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setNotation(InlineResponse2008Notation notation) { this.notation = notation; } public InlineResponse2008Data type(TypeEnum type) { this.type = type; return this; } /** * Type of transaction * @return type **/ @javax.annotation.Nullable @ApiModelProperty(value = "Type of transaction") @JsonProperty(JSON_PROPERTY_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public TypeEnum getType() { return type; } @JsonProperty(JSON_PROPERTY_TYPE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setType(TypeEnum type) { this.type = type; } public InlineResponse2008Data time(String time) { this.time = time; return this; } /** * Date and time of the trade. * @return time **/ @javax.annotation.Nullable @ApiModelProperty(value = "Date and time of the trade.") @JsonProperty(JSON_PROPERTY_TIME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getTime() { return time; } @JsonProperty(JSON_PROPERTY_TIME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setTime(String time) { this.time = time; } public InlineResponse2008Data numberShares(BigDecimal numberShares) { this.numberShares = numberShares; return this; } /** * Number of shares bought or sold. * @return numberShares **/ @javax.annotation.Nullable @ApiModelProperty(value = "Number of shares bought or sold.") @JsonProperty(JSON_PROPERTY_NUMBER_SHARES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getNumberShares() { return numberShares; } @JsonProperty(JSON_PROPERTY_NUMBER_SHARES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setNumberShares(BigDecimal numberShares) { this.numberShares = numberShares; } public InlineResponse2008Data price(BigDecimal price) { this.price = price; return this; } /** * Price the securities were purchased / sold for. * @return price **/ @javax.annotation.Nullable @ApiModelProperty(value = "Price the securities were purchased / sold for.") @JsonProperty(JSON_PROPERTY_PRICE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getPrice() { return price; } @JsonProperty(JSON_PROPERTY_PRICE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setPrice(BigDecimal price) { this.price = price; } public InlineResponse2008Data charges(BigDecimal charges) { this.charges = charges; return this; } /** * Charges accrued in portfolio&#39;s base currency. * @return charges **/ @javax.annotation.Nullable @ApiModelProperty(value = "Charges accrued in portfolio's base currency.") @JsonProperty(JSON_PROPERTY_CHARGES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getCharges() { return charges; } @JsonProperty(JSON_PROPERTY_CHARGES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setCharges(BigDecimal charges) { this.charges = charges; } public InlineResponse2008Data exchangeRate(BigDecimal exchangeRate) { this.exchangeRate = exchangeRate; return this; } /** * The exchange rate between the notation&#39;s currency and the portfolio currency. * @return exchangeRate **/ @javax.annotation.Nullable @ApiModelProperty(value = "The exchange rate between the notation's currency and the portfolio currency.") @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public BigDecimal getExchangeRate() { return exchangeRate; } @JsonProperty(JSON_PROPERTY_EXCHANGE_RATE) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setExchangeRate(BigDecimal exchangeRate) { this.exchangeRate = exchangeRate; } /** * Return true if this inline_response_200_8_data object is equal to o. */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InlineResponse2008Data inlineResponse2008Data = (InlineResponse2008Data) o; return Objects.equals(this.id, inlineResponse2008Data.id) && Objects.equals(this.notation, inlineResponse2008Data.notation) && Objects.equals(this.type, inlineResponse2008Data.type) && Objects.equals(this.time, inlineResponse2008Data.time) && Objects.equals(this.numberShares, inlineResponse2008Data.numberShares) && Objects.equals(this.price, inlineResponse2008Data.price) && Objects.equals(this.charges, inlineResponse2008Data.charges) && Objects.equals(this.exchangeRate, inlineResponse2008Data.exchangeRate); } @Override public int hashCode() { return Objects.hash(id, notation, type, time, numberShares, price, charges, exchangeRate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InlineResponse2008Data {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" notation: ").append(toIndentedString(notation)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" time: ").append(toIndentedString(time)).append("\n"); sb.append(" numberShares: ").append(toIndentedString(numberShares)).append("\n"); sb.append(" price: ").append(toIndentedString(price)).append("\n"); sb.append(" charges: ").append(toIndentedString(charges)).append("\n"); sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
djvanhelmond/AdventofCode2017
Day 02: Corruption Checksum/Day 2: Corruption Checksum.py
<gh_stars>0 #!/usr/local/bin/python3 with open("./input.txt") as f: INPUT = f.readlines() star1_checksum = 0 star2_checksum = 0 for row in INPUT: star1_checksum += max(map(int, row.split('\t'))) - min(map(int, row.split('\t'))) for row in INPUT: all = sorted(list(map(int, row.split('\t')))) edFound = False while not edFound: for j in all[::-1]: for i in all: if (j != i) and (j % i == 0): edFound = True star2_checksum += (j / i) print star1_checksum print star2_checksum
UniversalMinecraftAPI/UniversialMinecraftAPI
common/src/test/java/com/koenv/universalminecraftapi/parser/ExpressionParserTest.java
<reponame>UniversalMinecraftAPI/UniversialMinecraftAPI package com.koenv.universalminecraftapi.parser; import com.koenv.universalminecraftapi.parser.expressions.*; import org.junit.Test; import java.util.*; import static org.hamcrest.CoreMatchers.instanceOf; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertThat; public class ExpressionParserTest { @Test public void oneMethod() throws Exception { new ExpressionParser().parse("getIt()"); } @Test public void chainedMethods() throws Exception { new ExpressionParser().parse("getIt().getIt()"); } @Test public void integerAsParameter() throws Exception { new ExpressionParser().parse("getIt(12)"); } @Test public void negativeIntegerAsParameter() throws Exception { new ExpressionParser().parse("getIt(-12)"); } @Test public void stringAsParameter() throws Exception { new ExpressionParser().parse("getIt(\"test\")"); } @Test public void doubleAsParameter() throws Exception { new ExpressionParser().parse("getIt(12.67)"); } @Test public void negativeDoubleAsParameter() throws Exception { new ExpressionParser().parse("getIt(-12.67)"); } @Test public void booleanAsParameter() throws Exception { new ExpressionParser().parse("getIt(true)"); } @Test public void stringWithEscapes() throws Exception { new ExpressionParser().parse("'\\b\\t\\n\\r\\f\\''"); } @Test public void stringWithUnicodeEscape() throws Exception { assertEquals(new StringExpression("15\u00f8C"), new ExpressionParser().parse("'15\\u00f8C'")); } @Test public void mapAsParameter() throws Exception { Expression expression = new ExpressionParser().parse("getIt({\"key\" = \"value\"})"); assertThat(expression, instanceOf(ChainedMethodCallExpression.class)); List<Expression> expressions = ((ChainedMethodCallExpression) expression).getExpressions(); assertEquals(1, expressions.size()); assertThat(expressions.get(0), instanceOf(MethodCallExpression.class)); MethodCallExpression methodCall = (MethodCallExpression) expressions.get(0); assertEquals("getIt", methodCall.getMethodName()); assertEquals(1, methodCall.getParameters().size()); assertThat(methodCall.getParameters().get(0), instanceOf(MapExpression.class)); MapExpression parameter = (MapExpression) methodCall.getParameters().get(0); Map<Expression, Expression> expectedMap = new HashMap<>(); expectedMap.put(new StringExpression("key"), new StringExpression("value")); assertEquals(expectedMap, parameter.getValue()); } @Test public void nestedMap() throws Exception { Expression expression = new ExpressionParser().parse("getIt({\"key\" = {\"key\" = getIt()}, \"key2\"=\"value\"})"); assertThat(expression, instanceOf(ChainedMethodCallExpression.class)); List<Expression> expressions = ((ChainedMethodCallExpression) expression).getExpressions(); assertEquals(1, expressions.size()); assertThat(expressions.get(0), instanceOf(MethodCallExpression.class)); MethodCallExpression methodCall = (MethodCallExpression) expressions.get(0); assertEquals("getIt", methodCall.getMethodName()); assertEquals(1, methodCall.getParameters().size()); assertThat(methodCall.getParameters().get(0), instanceOf(MapExpression.class)); MapExpression parameter = (MapExpression) methodCall.getParameters().get(0); Map<Expression, Expression> expectedNestedMap = new HashMap<>(); expectedNestedMap.put(new StringExpression("key"), new ChainedMethodCallExpression(Collections.singletonList(new MethodCallExpression("getIt", new ArrayList<>())))); Map<Expression, Expression> expectedMap = new HashMap<>(); expectedMap.put(new StringExpression("key"), new MapExpression(expectedNestedMap)); expectedMap.put(new StringExpression("key2"), new StringExpression("value")); assertEquals(expectedMap, parameter.getValue()); } @Test public void mapWithAlternateStringAndAlternateStringParameter() throws Exception { new ExpressionParser().parse("it.get('test', {'key'='value'})"); } @Test public void mapWithStringAndStringParameter() throws Exception { new ExpressionParser().parse("it.get(\"test\", {\"key\"=\"value\"})"); } @Test public void mapWithAlternateStringAndStringAndDoubleParameter() throws Exception { new ExpressionParser().parse("it.get({'key'='value', 'key2'='value2'}, 'test', 12)"); } @Test public void alternateStringAndMap() throws Exception { new ExpressionParser().parse("streams.subscribe('console', {'nostrip'='true'})"); } @Test public void mapWithTrailingComma() throws Exception { new ExpressionParser().parse("it.get({'key'='value',})"); } @Test public void simpleStringList() throws Exception { List<Expression> items = Arrays.asList(new StringExpression("test"), new StringExpression("test")); ListExpression parameter = new ListExpression(items); NamespaceExpression namespaceExpression = new NamespaceExpression("test"); MethodCallExpression methodCallExpression = new MethodCallExpression("getIt", Collections.singletonList(parameter)); ChainedMethodCallExpression root = new ChainedMethodCallExpression(Arrays.asList(namespaceExpression, methodCallExpression)); assertEquals(root, new ExpressionParser().parse("test.getIt(['test', 'test'])")); } @Test public void listWithMixedItems() throws Exception { new ExpressionParser().parse("test.getIt([\"test\", {'key'='value', 'test'=['test']}, method.getMethod(), 12])"); } @Test public void listWithTrailingComma() throws Exception { new ExpressionParser().parse("test.getIt(['test',])"); } @Test public void methodAsParameter() throws Exception { new ExpressionParser().parse("getIt(getIt())"); } @Test public void methodWithParametersAsParameter() throws Exception { new ExpressionParser().parse("getIt(getThat(12, \"test\"))"); } @Test public void simpleNamespace() throws Exception { new ExpressionParser().parse("test.getThat()"); } @Test public void multipleNamespaces() throws Exception { new ExpressionParser().parse("test.getThat(test.getThat())"); } @Test public void methodWithManyDifferentParameters() throws Exception { new ExpressionParser().parse("test.getThat(test.getThat(12, \"get\"), 67.23)"); } @Test public void methodWithParametersAsParameterAndIntegerAsParameter() throws Exception { Expression expression = new ExpressionParser().parse("it.getIt(getThat(12, \"test\"), 12)"); assertThat(expression, instanceOf(ChainedMethodCallExpression.class)); List<Expression> expressions = ((ChainedMethodCallExpression) expression).getExpressions(); assertEquals(2, expressions.size()); assertThat(expressions.get(0), instanceOf(NamespaceExpression.class)); assertThat(expressions.get(1), instanceOf(MethodCallExpression.class)); NamespaceExpression firstNamespace = (NamespaceExpression) expressions.get(0); assertEquals("it", firstNamespace.getName()); MethodCallExpression firstMethodCall = (MethodCallExpression) expressions.get(1); assertEquals("getIt", firstMethodCall.getMethodName()); assertEquals(2, firstMethodCall.getParameters().size()); assertThat(firstMethodCall.getParameters().get(0), instanceOf(ChainedMethodCallExpression.class)); assertThat(firstMethodCall.getParameters().get(1), instanceOf(IntegerExpression.class)); ChainedMethodCallExpression secondChainedMethodCall = (ChainedMethodCallExpression) firstMethodCall.getParameters().get(0); assertThat(secondChainedMethodCall.getExpressions().get(0), instanceOf(MethodCallExpression.class)); MethodCallExpression secondMethodCall = (MethodCallExpression) secondChainedMethodCall.getExpressions().get(0); assertEquals("getThat", secondMethodCall.getMethodName()); assertEquals(2, secondMethodCall.getParameters().size()); assertThat(secondMethodCall.getParameters().get(0), instanceOf(IntegerExpression.class)); assertThat(secondMethodCall.getParameters().get(1), instanceOf(StringExpression.class)); IntegerExpression secondMethodCallParameter1 = (IntegerExpression) secondMethodCall.getParameters().get(0); assertEquals(12, (int) secondMethodCallParameter1.getValue()); StringExpression secondMethodCallParameter2 = (StringExpression) secondMethodCall.getParameters().get(1); assertEquals("test", secondMethodCallParameter2.getValue()); IntegerExpression firstMethodCallParameter2 = (IntegerExpression) firstMethodCall.getParameters().get(1); assertEquals(12, (int) firstMethodCallParameter2.getValue()); } @Test(expected = ParseException.class) public void constantAsParameterThrowsParseException() throws Exception { new ExpressionParser().parse("getIt(name)"); } @Test(expected = ParseException.class) public void invalidMethodThrowsParseException() throws Exception { new ExpressionParser().parse("namespace.getIt(name)as"); } @Test(expected = ParseException.class) public void invalidNumberExpressionThrowsParseException() throws Exception { new ExpressionParser().parse("getIt().12.67"); } @Test(expected = ParseException.class) public void invalidNumberOfParenthesesThrowsParseException() throws Exception { new ExpressionParser().parse("getIt(getIt()"); } @Test(expected = ParseException.class) public void invalidNumberOfBracesOnItsOwnThrowsParseException() throws Exception { new ExpressionParser().parse("{'key'='value'"); } @Test(expected = ParseException.class) public void invalidNumberOfBracesExceptionThrowsParseException() throws Exception { new ExpressionParser().parse("getIt({'key'='value')"); } @Test(expected = ParseException.class) public void invalidNumberOfParenthesesAndBracesThrowsParseException() throws Exception { new ExpressionParser().parse("getIt(}"); } @Test(expected = ParseException.class) public void invalidNamespacesThrowsParseException() throws Exception { new ExpressionParser().parse("test.getThat().test.getThat()"); } @Test(expected = ParseException.class) public void invalidMapThrowsParseException() throws Exception { new ExpressionParser().parse("{'key'}"); } @Test(expected = ParseException.class) public void invalidEscapeThrowsParseException() throws Exception { new ExpressionParser().parse("'my\\ name'"); } @Test(expected = ParseException.class) public void invalidUnicodeEscapeThrowsParseException() throws Exception { new ExpressionParser().parse("'\\u23'"); } @Test(expected = ParseException.class) public void unterminatedString() throws Exception { new ExpressionParser().parse("'\n'"); } }
paullewallencom/web-978-1-7858-8457-3
_/Chapter 3/app/store/Item.js
Ext.define('TodoApp.store.Item', { extend: 'Ext.data.Store', config: { model: 'TodoApp.model.Item', autoLoad: true } });
bedirhanbuyukoz/JavaBootCamp
9day/HRMS/src/main/java/bedirhan/hrms/entities/concretes/JobPosition.java
<filename>9day/HRMS/src/main/java/bedirhan/hrms/entities/concretes/JobPosition.java package burakimdat.hrms.entities.concretes; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @Table(name = "job_positions") @AllArgsConstructor @NoArgsConstructor @JsonIgnoreProperties({ "hibernateLazyInitializer", "handler", "jobAds" }) public class JobPosition { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "job_pos_id") private int id; @Column(name = "name", nullable = false) private String jobPositionName; @OneToMany(mappedBy = "jobPosition") @JsonIgnore private List<JobAd> jobAds; @OneToMany(mappedBy = "jobPosition") @JsonIgnore private List<Experience> experiences; }
chyroc/pylark
pylark/api_service_application_message_trend.py
# Code generated by lark_sdk_gen. DO NOT EDIT. from pylark.lark_request import RawRequestReq, _new_method_option from pylark import lark_type, lark_type_sheet, lark_type_approval import attr import typing import io @attr.s class GetApplicationMessageTrendReq(object): app_id: str = attr.ib( default="", metadata={"req_type": "json", "key": "app_id"} ) # 目标应用的 ID time_start: int = attr.ib( default=0, metadata={"req_type": "json", "key": "time_start"} ) # 起始时间戳(秒),时间跨度最长支持180天 time_end: int = attr.ib( default=0, metadata={"req_type": "json", "key": "time_end"} ) # 截止时间戳(秒),时间跨度最长支持180天 time_interval: int = attr.ib( default=0, metadata={"req_type": "json", "key": "time_interval"} ) # 步长(秒),最小步长为60秒,需满足(${time_end} - ${time_start}) / ${time_interval} <= 2*24*60 chat_type: lark_type.ChatType = attr.ib( default=None, metadata={"req_type": "json", "key": "chat_type"} ) # 聊天类型,大小写不敏感,p2p:私聊;group:群聊 message_type: lark_type.MsgType = attr.ib( default=None, metadata={"req_type": "json", "key": "message_type"} ) # 消息类型,大小写不敏感,text:文本消息;image:图片消息;card:卡片消息;post:富文本消息;share_chat:群名片 @attr.s class GetApplicationMessageTrendRespGroupReadTimestamp(object): pv: int = attr.ib(default=0, metadata={"req_type": "json", "key": "pv"}) # 消息已读用户数量 uv: int = attr.ib( default=0, metadata={"req_type": "json", "key": "uv"} ) # 去重的消息已读用户数量 @attr.s class GetApplicationMessageTrendRespGroupRead(object): timestamp: GetApplicationMessageTrendRespGroupReadTimestamp = attr.ib( default=None, metadata={"req_type": "json", "key": "timestamp"} ) # 时间戳(秒) @attr.s class GetApplicationMessageTrendRespGroupReceivedTimestamp(object): pv: int = attr.ib(default=0, metadata={"req_type": "json", "key": "pv"}) # 消息接收群聊数量 uv: int = attr.ib( default=0, metadata={"req_type": "json", "key": "uv"} ) # 去重的消息接收群聊数量 @attr.s class GetApplicationMessageTrendRespGroupReceived(object): timestamp: GetApplicationMessageTrendRespGroupReceivedTimestamp = attr.ib( default=None, metadata={"req_type": "json", "key": "timestamp"} ) # 时间戳(秒) @attr.s class GetApplicationMessageTrendRespGroupSentTimestamp(object): pv: int = attr.ib(default=0, metadata={"req_type": "json", "key": "pv"}) # 消息接收群聊数量 uv: int = attr.ib( default=0, metadata={"req_type": "json", "key": "uv"} ) # 去重的消息接收群聊数量 @attr.s class GetApplicationMessageTrendRespGroupSent(object): timestamp: GetApplicationMessageTrendRespGroupSentTimestamp = attr.ib( default=None, metadata={"req_type": "json", "key": "timestamp"} ) # 时间戳(秒) @attr.s class GetApplicationMessageTrendRespP2pReadTimestamp(object): pv: int = attr.ib(default=0, metadata={"req_type": "json", "key": "pv"}) # 消息已读用户数量 uv: int = attr.ib( default=0, metadata={"req_type": "json", "key": "uv"} ) # 去重的消息已读用户数量 @attr.s class GetApplicationMessageTrendRespP2pRead(object): timestamp: GetApplicationMessageTrendRespP2pReadTimestamp = attr.ib( default=None, metadata={"req_type": "json", "key": "timestamp"} ) # 时间戳(秒) @attr.s class GetApplicationMessageTrendRespP2pReceivedTimestamp(object): pv: int = attr.ib(default=0, metadata={"req_type": "json", "key": "pv"}) # 消息接收用户数量 uv: int = attr.ib( default=0, metadata={"req_type": "json", "key": "uv"} ) # 去重的消息接收用户数量 @attr.s class GetApplicationMessageTrendRespP2pReceived(object): timestamp: GetApplicationMessageTrendRespP2pReceivedTimestamp = attr.ib( default=None, metadata={"req_type": "json", "key": "timestamp"} ) # 时间戳(秒) @attr.s class GetApplicationMessageTrendRespP2pSentTimestamp(object): pv: int = attr.ib(default=0, metadata={"req_type": "json", "key": "pv"}) # 消息接收用户数量 uv: int = attr.ib( default=0, metadata={"req_type": "json", "key": "uv"} ) # 去重的消息接收用户数量 @attr.s class GetApplicationMessageTrendRespP2pSent(object): timestamp: GetApplicationMessageTrendRespP2pSentTimestamp = attr.ib( default=None, metadata={"req_type": "json", "key": "timestamp"} ) # 时间戳(秒) @attr.s class GetApplicationMessageTrendResp(object): p2p_sent: GetApplicationMessageTrendRespP2pSent = attr.ib( default=None, metadata={"req_type": "json", "key": "p2p_sent"} ) # 单聊发送 p2p_received: GetApplicationMessageTrendRespP2pReceived = attr.ib( default=None, metadata={"req_type": "json", "key": "p2p_received"} ) # 单聊接收 p2p_read: GetApplicationMessageTrendRespP2pRead = attr.ib( default=None, metadata={"req_type": "json", "key": "p2p_read"} ) # 单聊已读 group_sent: GetApplicationMessageTrendRespGroupSent = attr.ib( default=None, metadata={"req_type": "json", "key": "group_sent"} ) # 群聊发送 group_received: GetApplicationMessageTrendRespGroupReceived = attr.ib( default=None, metadata={"req_type": "json", "key": "group_received"} ) # 群聊接收 group_read: GetApplicationMessageTrendRespGroupRead = attr.ib( default=None, metadata={"req_type": "json", "key": "group_read"} ) # 群聊已读 def _gen_get_application_message_trend_req(request, options) -> RawRequestReq: return RawRequestReq( dataclass=GetApplicationMessageTrendResp, scope="Application", api="GetApplicationMessageTrend", method="POST", url="https://open.feishu.cn/open-apis/application/v1/app_message_trend", body=request, method_option=_new_method_option(options), need_tenant_access_token=True, )
kifferltd/open-mika
tool/visualtest/java/com/acunia/wonka/test/awt/Choice/ChoiceTest.java
<filename>tool/visualtest/java/com/acunia/wonka/test/awt/Choice/ChoiceTest.java /************************************************************************** * Copyright (c) 2001 by Acunia N.V. All rights reserved. * * * * This software is copyrighted by and is the sole property of Acunia N.V. * * and its licensors, if any. All rights, title, ownership, or other * * interests in the software remain the property of Acunia N.V. and its * * licensors, if any. * * * * This software may only be used in accordance with the corresponding * * license agreement. Any unauthorized use, duplication, transmission, * * distribution or disclosure of this software is expressly forbidden. * * * * This Copyright notice may not be removed or modified without prior * * written consent of Acunia N.V. * * * * Acunia N.V. reserves the right to modify this software without notice. * * * * Acunia N.V. * * <NAME> 35 <EMAIL> * * 3000 Leuven http://www.acunia.com * * Belgium - EUROPE * **************************************************************************/ package com.acunia.wonka.test.awt.Choice; import java.awt.BorderLayout; import java.awt.Button; import java.awt.Choice; import java.awt.GridLayout; import java.awt.Label; import java.awt.Panel; import java.awt.TextField; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; import com.acunia.wonka.test.awt.VisualTestImpl; public class ChoiceTest extends VisualTestImpl implements ActionListener, ItemListener { private TextField newItem; private Button addButton; private Choice items; private Label selection; private Button removeButton; private int selectedIndex; private final static int ITEMCOUNT=10; private final static String ITEMNAME="item"; public ChoiceTest() { this(ITEMCOUNT,ITEMNAME); } public ChoiceTest(int itemcount, String itemname) { super(); //layout setLayout(new BorderLayout()); Panel top = new Panel(new GridLayout(2,1)); newItem = new TextField(); top.add(newItem); addButton = new Button("add this"); addButton.addActionListener(this); top.add(addButton); add(top, BorderLayout.NORTH); items = new Choice(); items.addItemListener(this); add(items, BorderLayout.CENTER); Panel bottom = new Panel(new GridLayout(2,1)); selection= new Label("No selection made yet"); selectedIndex = -1; bottom.add(selection); removeButton = new Button("remove this"); removeButton.addActionListener(this); bottom.add(removeButton); add(bottom, BorderLayout.SOUTH); // fill box for(int i=0; i<itemcount; i++) { items.add(itemname+"_"+i); } } public String getHelpText() { return "A test for class 'Choice'. The central part of the panel shows a Choice that can be expanded by pressing its right " + "button. At the top of the panel, a textfield allows you to enter the label of a new element for the choice. The " + "new element can be added by pressing the button labeled 'add this', below the textfield." + "At the bottom of the panel another button labeled 'remove this' allows to remove the selected element from the " + "choice. The selected element is indicated in the central part of the panel, above the 'remove' button."; } /** Our Action listener: * when 'add' pressed, add contents of textframe * when delete pressed, deete current selection */ public void actionPerformed(ActionEvent evt) { if(evt.getSource()==addButton && newItem.getText()!="") { items.add(newItem.getText()); } else if(evt.getSource()==removeButton && selectedIndex>=0) { items.remove(selectedIndex); selectedIndex = -1; items.select(-1); } } /** Our item listener: * when choosen an item from the Choice, dispay it */ public void itemStateChanged(ItemEvent evt) { // we don't need the event data here, we can just as well get everything from the Choice selectedIndex=items.getSelectedIndex(); selection.setText( ((evt.getStateChange()==ItemEvent.SELECTED)?"selected :":"deselected :")+evt.getItem()); } }
yuichigoto/ccg2lambda
scripts/visualization_latex.py
#!/usr/bin/python3 # -*- coding: utf-8 -*- import cgi import re from ccg2lambda_tools import build_ccg_tree from lxml import etree from semantic_index import find_node_by_id kUpwardsTree = True kDisplaySemantics = True kDisplayFeatures = True def get_fraction_latex(numerator, denominator, rule = '', upwards = kUpwardsTree): if upwards: numerator, denominator = denominator, numerator latex_str = "\infer{" + numerator + "}" \ + "{" + denominator + "}" if rule: numerator, denominator = denominator, numerator label = cgi.escape(rule) normalized = label.replace('&lt;B1','\\FC') \ .replace('&gt;B1','\\BC') \ .replace('&lt;','\\FA') \ .replace('&gt;','\\BA') \ .replace('fa','\\FA') \ .replace('ba','\\BA') \ .replace('ba','\\BA') \ .replace('&','') latex_str = "\n\infer[" + normalized + "]{" + numerator + "}" \ + "{" + denominator + "}" return latex_str def get_lex_latex(numerator, denominator, rule = '', upwards = kUpwardsTree): if upwards: numerator, denominator = denominator, numerator latex_str = "\infer{" + numerator + "}" \ + "{" + denominator + "}" if rule: numerator, denominator = denominator, numerator latex_str = "\n\infer{" + numerator + "}" \ + "{" + denominator + "}" return latex_str def get_sem_latex(numerator, denominator, rule = '', upwards = kUpwardsTree): if upwards: numerator, denominator = denominator, numerator latex_str = "\deduce{" + numerator + "}" \ + "{" + denominator + "}" if rule: numerator, denominator = denominator, numerator latex_str = "\deduce{" + numerator + "}{" + denominator + "}" latex_str = "\n\deduce{\\SR{" + numerator + "}}{" + denominator + "}" # latex_str = "\deduce{\\begin{tabular}{c}$" + numerator + "$\\end{tabular}}" \ # + "{" + denominator + "}" return latex_str def get_category_latex(category): cats_feats = re.findall(r'([\w\\/()]+)(\[.+?\])*', category) latex_str = '' for cat, feat in cats_feats: cat_latex = cat.replace('\\','\\backslash ') if feat != '' and kDisplayFeatures: normalized = feat.replace('=true','') \ .replace('mod=','') \ .replace('case=','') \ .replace('fin=','') \ .replace('form=','') latex_str += cat_latex + normalized else: latex_str += cat_latex return latex_str def get_surface_latex(surface): return "\mbox{" + surface + "}" def get_pos_latex(pos): return "\mathrm{" + pos + "}" def get_semantics_latex(semantics): normalized = semantics.replace('\\','\\lambda ') \ .replace('&','$\\\\$\\,\\wedge\\,') \ .replace('|','\\vee') \ .replace('->','\\to') \ .replace('all ','\\forall ') \ .replace('exists ','\\exists ') \ .replace(' TrueP','\\top') \ .replace(' True','\\top') \ .replace('-','\\neg ') \ .replace('_','') return normalized def convert_node_to_latex(ccg_node, sem_tree, tokens): latex_str = '' category = ccg_node.get('category').strip() category_latex = get_category_latex(category) if len(ccg_node) == 0: token_id = ccg_node.get('terminal') token = find_node_by_id(token_id, tokens) surf = token.get('surf') surf_latex = get_surface_latex(surf) if surf == '.': latex_str = '.' else: latex_str = get_lex_latex(surf_latex, category_latex) elif len(ccg_node) == 1: latex_str_child = convert_node_to_latex(ccg_node[0], sem_tree, tokens) rule = ccg_node.get('rule') latex_str = get_fraction_latex(category_latex, latex_str_child, rule) elif len(ccg_node) > 0: latex_str_children = '' for child in ccg_node: latex_str_child = convert_node_to_latex(child, sem_tree, tokens) if latex_str_children == '': latex_str_children = latex_str_child else: latex_str_children = latex_str_children + " & " + latex_str_child # latex_str_children += latex_str_child rule = ccg_node.get('rule') latex_str = get_fraction_latex(category_latex, latex_str_children, rule) if sem_tree is not None and kDisplaySemantics: span_id = ccg_node.get('id') sem_node = find_node_by_id(span_id, sem_tree) semantics = sem_node.get('sem') semantics_latex = get_semantics_latex(semantics) latex_str = get_sem_latex(latex_str, semantics_latex) return latex_str def get_sentence_surface_from_tokens(ccg_tokens, attribute = 'surf'): return ' '.join([token.get(attribute) for token in ccg_tokens]) def convert_doc_to_latex(doc, verbatim_strings = [], use_gold_trees=False): """ This function expects a list of ccg_trees, and a list of tokens (as produced by transccg). Then, it converts each pair (ccg_tree, ccg_tokens) into a presentation MathML string, and wraps them with HTML code. verbatim_strings contains a list of strings that should be printed verbatim at the end of the HTML document, for debugging. """ ccg_trees = [] if use_gold_trees: for sentence in doc.xpath('//sentence'): gold_tree_index = int(sentence.get('gold_tree', '0')) ccg_trees.append(sentence.xpath('./ccg')[gold_tree_index]) ccg_trees = [build_ccg_tree(c) for c in ccg_trees] else: ccg_trees = [build_ccg_tree(c) for c in doc.xpath('//sentence/ccg[1]')] sem_trees = [build_ccg_tree(c) for c in doc.xpath('//semantics')] if not sem_trees: sem_trees = [None] * len(ccg_trees) tokens = doc.xpath('//tokens') assert len(ccg_trees) == len(tokens) num_hypotheses = len(ccg_trees) - 1 sentence_ids = ["Premise {0}: ".format(i + 1) for i in range(num_hypotheses)] sentence_ids.append("Conclusion: ") latex_str = "" for i in range(len(ccg_trees)): sentence_surface = ' '.join(tokens[i].xpath('token/@surf')) latex_str += "\n\n\\vspace{2em}\n\n\\noindent\n" + sentence_ids[i] + sentence_surface + "\n\n\medskip\n\n" \ + convert_node_to_latex(ccg_trees[i], sem_trees[i], tokens[i]) verbatim_text = "" if verbatim_strings: verbatim_text = "<p>Script piped to coq</p>" for vb_str in verbatim_strings: verbatim_text += "<pre>\n" + vb_str + "\n</pre>\n" html_str = "\documentclass{article}\n" \ + "\\usepackage{proof,lscape}\n" \ + "\\pagestyle{empty}\n" \ + "\\newcommand{\\rulelabelsize}{\\scriptsize}\n" \ + "\\newcommand{\\FA}{\\mbox{\\rulelabelsize $<$}}\n" \ + "\\newcommand{\\BA}{\\mbox{\\rulelabelsize $>$}}\n" \ + "\\newcommand{\\FC}{\\mbox{\\rulelabelsize $>\\!\\mathbf{B}$}}\n" \ + "\\newcommand{\\BC}{\\mbox{\\rulelabelsize $>\\!\\mathbf{B}$}}\n" \ + "\\newcommand{\\SR}[1]{\\begin{tabular}{c}$#1$\\end{tabular}}\n" \ + "\\begin{document}\n" \ + "\\small\n" \ html_str += "%\\begin{landscape}" html_str += latex_str html_str += verbatim_text html_str += "\n%\\end{landscape}" html_str += "\n\\end{document}" return html_str
wuchunfu/crawlab-core
i18n/service.go
package i18n import "github.com/crawlab-team/crawlab-core/interfaces" var translations []interfaces.Translation var _svc interfaces.I18nService type Service struct { } func (svc *Service) AddTranslations(t []interfaces.Translation) { translations = append(translations, t...) } func (svc *Service) GetTranslations() (t []interfaces.Translation) { return translations } func GetI18nService(cfgPath string) (svc2 interfaces.I18nService, err error) { if _svc != nil { return _svc, nil } _svc, err = NewI18nService() if err != nil { return nil, err } return _svc, nil } func ProvideGetI18nService(cfgPath string) func() (svc interfaces.I18nService, err error) { return func() (svc interfaces.I18nService, err error) { return GetI18nService(cfgPath) } } func NewI18nService() (svc2 interfaces.I18nService, err error) { svc := &Service{} return svc, nil }
flystack/misty
lib/misty/http/method_builder.rb
module Misty module HTTP module MethodBuilder def method_missing(method_name, *args) if method = get_method(method_name) method_call(method, *args) else raise NoMethodError, "#{self.class}: #{method_name}" end end private def process_data(header, args) if args.size == 1 && Misty::Helper.json_encode?(args[0]) header.add('Content-Type' => 'application/json') return Misty::Helper.to_json(args[0]) elsif args.size == 1 return args[0] end end def method_call(method, *args) base, path = prefixed_path(method[:path]) size_path_parameters = count_path_params(path) path_params = args[0, size_path_parameters] args_left = args - path_params path = inject_elements(path, path_params) final_path = base_filter(base, path) case method[:request] when :COPY http_copy(final_path, @request_headers.get) when :DELETE http_delete(final_path, @request_headers.get) when :GET final_path << query_param(args_left.shift) if args_left && args_left.size == 1 http_get(final_path, @request_headers.get) when :HEAD http_head(final_path, @request_headers.get) when :POST final_path << query_param(args_left.shift) if args_left && args_left.size == 2 data = process_data(@request_headers, args_left) http_post(final_path, @request_headers.get, data) when :PUT final_path << query_param(args_left.shift) if args_left && args_left.size == 2 data = process_data(@request_headers, args_left) http_put(final_path, @request_headers.get, data) when :PATCH final_path << query_param(args_left.shift) if args_left && args_left.size == 2 data = process_data(@request_headers, args_left) http_patch(final_path, @request_headers.get, data) else raise SyntaxError, "Invalid HTTP request: #{method[:request]}" end end def base_filter(base, path) return (@base_path + path) if base return path end def count_path_params(str) subpath = /(.*)(\{.*\})(.*)/.match(str) return 0 unless subpath return count_path_params(subpath[1]) + 1 end def get_method(name) api.each do |path, verbs_list| verbs_list.each do |verb, methods| if methods.include?(name) return {:path => path, :request => verb, :name => name} end end end nil end def inject_elements(str, args) subpath = /(.*)(\{.*\})(.*)/.match(str) return str unless subpath arg = args.pop raise ArgumentError, 'Not enough arguments' unless arg return inject_elements(subpath[1], args) + arg + subpath[3] end def prefixed_path(path) unless prefix_path_to_ignore.empty? if path =~ %r{#{prefix_path_to_ignore}} return true, path.gsub(prefix_path_to_ignore, '') else return false, path end end return true, path end def query_param(data) result = nil if data.is_a? String result = '' if data != '' result = '?' result.force_encoding('ASCII-8BIT') result << data end elsif data.is_a? Hash result = data.empty? ? '' : '?' + URI.encode_www_form(data) end return result end end end end
GinRex/phaser-blockly
dist-modules/client/actions/home.js
import axios from 'axios'; export const selectFile = selectedFile => ({ type: 'SELECT_FILE', selectedFile }); export const buildGame = gameObjects => ({ type: 'BUILD_GAME', gameObjects }); export const addObject = gameObject => ({ type: 'ADD_OBJECT', gameObject }); export const addScene = scene => dispatch => axios.post('http://localhost:8080/api/createScene', scene, {}).then(res => { dispatch({ type: 'ADD_SCENE', scene }); }); export const setSlectedGameobjectIndex = index => ({ type: 'SET_INDEX', index }); export const setSlectedSceneIndex = index => dispatch => axios.post('http://localhost:8080/api/selectScene', { index }, {}).then(res => { dispatch({ type: 'SET_SCENE_INDEX', index }); }); export const updateWorkspace = gameObjects => ({ type: 'UPDATE_WORKSPACE', gameObjects }); export const updateSceneWorkspace = scenes => ({ type: 'UPDATE_SCENE_WORKSPACE', scenes }); export const uploadImage = file => dispatch => { console.log(file.file); const data = new FormData(); data.append('file', file.file); return axios.post('http://localhost:8080/api/uploadImage', data, {}).then(res => { dispatch(addObject({ name: res.data.name, filename: res.data.filename, workspace: ['', '', ''], jsCode: ['', '', ''], key: res.data.name, animations: [], variables: [], instances: [] })); }); }; export const uploadImageForTile = file => dispatch => { console.log(file.file); const data = new FormData(); data.append('file', file.file); return axios.post('http://localhost:8080/api/uploadImageForTile', data, {}).then(res => { dispatch({ type: 'ADD_IMAGE', image: { name: res.data.name, filename: res.data.filename } }); }); }; export const uploadJson = (file, name) => dispatch => { console.log(file); const data = new FormData(); data.append('file', file); data.append('className', name); console.log(data); return axios.post('http://localhost:8080/api/uploadJson', data, {}).then(res => { dispatch({ type: 'UPDATE_JSON_SPRITE', data: res.data }); }); }; export const restartGame = () => ({ type: 'RESTART_GAME' }); export const updateGame = gameObjects => dispatch => { const data = gameObjects; return axios.post('http://localhost:8080/api/updateCode', data, {}).then(res => { const frame = document.getElementById('sandboxed'); frame.contentWindow.postMessage('reload', '*'); }); }; export const updateScene = scenes => dispatch => { const data = scenes; return axios.post('http://localhost:8080/api/updateSceneCode', data, {}).then(res => { console.log('xxx'); // const frame = document.getElementById('sandboxed'); // frame.contentWindow.postMessage('reload', '*'); }); }; export const createNewGame = game => dispatch => { localStorage.removeItem('persist:root'); const data = game; return axios.post('http://localhost:8080/api/createGame', data, {}).then(res => { window.location.reload(); }); }; export const setGame = game => ({ type: 'SET_GAME', game }); export const updateToolbox = category => ({ type: 'UPDATE_TOOL_BOX', category }); export const setSpriteEditorState = open => ({ type: 'SET_SPRITE_EDIT_STATE', open }); export const setVariableDialogState = open => ({ type: 'SET_VARIABLE_DIALOG_STATE', open }); export const setObjectMenuState = open => ({ type: 'SET_OBJECT_MENU_STATE', open }); export const updateAnimations = animations => ({ type: 'UPDATE_ANIMATIONS', animations }); // export const addAnimations = className => ({ // type: 'ADD_ANIMATION', // className, // }); export const addAnimations = (className, animation) => dispatch => axios.post('http://localhost:8080/api/createAnimation', { className, animation }, {}).then(res => { dispatch({ type: 'ADD_ANIMATION', className }); }); export const updateSpriteInfo = info => ({ type: 'UPDATE_SPRITE_INFO', info }); export const addJsonSprite = gameObjects => ({ type: 'UPDATE_SPRITE_INFO', gameObjects }); export const addVariable = (name, variable) => ({ type: 'ADD_VARIABLE', data: { name, variable } }); export const addClassVariable = (name, variable) => ({ type: 'ADD_CLASS_VARIABLE', data: { name, variable } }); export const addInstance = (instance, name) => ({ type: 'ADD_INSTANCE', data: { name, instance } }); // delete this export const addInstancesToScene = scene => dispatch => { const data = scene; return axios.post('http://localhost:8080/api/initObject', data, {}).then(res => { console.log('aaa'); }); }; export const saveGame = gameName => dispatch => { const data = localStorage.getItem('persist:root'); return axios.post('http://localhost:8080/api/saveGame', { gameName, data }, {}).then(res => { console.log('aaa'); }); }; export const loadGame = gameName => dispatch => axios.post('http://localhost:8080/api/loadGame', { gameName }, {}).then(res => { localStorage.setItem('persist:root', JSON.stringify(res.data)); window.location.reload(); }); export const loadListGame = () => dispatch => axios.post('http://localhost:8080/api/loadListGame', {}, {}).then(res => { dispatch({ type: 'SET_LIST_GAMES', listGames: res.data }); });
TheRakeshPurohit/CodingSpectator
plug-ins/helios/org.eclipse.jdt.core/compiler/org/eclipse/jdt/internal/compiler/lookup/BaseTypeBinding.java
/******************************************************************************* * Copyright (c) 2000, 2009 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.compiler.lookup; public final class BaseTypeBinding extends TypeBinding { public static final int[] CONVERSIONS; public static final int IDENTITY= 1; public static final int WIDENING= 2; public static final int NARROWING= 4; public static final int MAX_CONVERSIONS= 16 * 16; // well-known x well-known static { CONVERSIONS= initializeConversions(); } public static final int[] initializeConversions() { // fromType destType --> conversion // 0000 0000 0000 int[] table= new int[MAX_CONVERSIONS]; table[TypeIds.Boolean2Boolean]= IDENTITY; table[TypeIds.Byte2Byte]= IDENTITY; table[TypeIds.Byte2Short]= WIDENING; table[TypeIds.Byte2Char]= NARROWING; table[TypeIds.Byte2Int]= WIDENING; table[TypeIds.Byte2Long]= WIDENING; table[TypeIds.Byte2Float]= WIDENING; table[TypeIds.Byte2Double]= WIDENING; table[TypeIds.Short2Byte]= NARROWING; table[TypeIds.Short2Short]= IDENTITY; table[TypeIds.Short2Char]= NARROWING; table[TypeIds.Short2Int]= WIDENING; table[TypeIds.Short2Long]= WIDENING; table[TypeIds.Short2Float]= WIDENING; table[TypeIds.Short2Double]= WIDENING; table[TypeIds.Char2Byte]= NARROWING; table[TypeIds.Char2Short]= NARROWING; table[TypeIds.Char2Char]= IDENTITY; table[TypeIds.Char2Int]= WIDENING; table[TypeIds.Char2Long]= WIDENING; table[TypeIds.Char2Float]= WIDENING; table[TypeIds.Char2Double]= WIDENING; table[TypeIds.Int2Byte]= NARROWING; table[TypeIds.Int2Short]= NARROWING; table[TypeIds.Int2Char]= NARROWING; table[TypeIds.Int2Int]= IDENTITY; table[TypeIds.Int2Long]= WIDENING; table[TypeIds.Int2Float]= WIDENING; table[TypeIds.Int2Double]= WIDENING; table[TypeIds.Long2Byte]= NARROWING; table[TypeIds.Long2Short]= NARROWING; table[TypeIds.Long2Char]= NARROWING; table[TypeIds.Long2Int]= NARROWING; table[TypeIds.Long2Long]= IDENTITY; table[TypeIds.Long2Float]= WIDENING; table[TypeIds.Long2Double]= WIDENING; table[TypeIds.Float2Byte]= NARROWING; table[TypeIds.Float2Short]= NARROWING; table[TypeIds.Float2Char]= NARROWING; table[TypeIds.Float2Int]= NARROWING; table[TypeIds.Float2Long]= NARROWING; table[TypeIds.Float2Float]= IDENTITY; table[TypeIds.Float2Double]= WIDENING; table[TypeIds.Double2Byte]= NARROWING; table[TypeIds.Double2Short]= NARROWING; table[TypeIds.Double2Char]= NARROWING; table[TypeIds.Double2Int]= NARROWING; table[TypeIds.Double2Long]= NARROWING; table[TypeIds.Double2Float]= NARROWING; table[TypeIds.Double2Double]= IDENTITY; return table; } /** * Predicate telling whether "left" can store a "right" using some narrowing conversion (is left * smaller than right) * * @param left - the target type to convert to * @param right - the actual type * @return true if legal narrowing conversion */ public static final boolean isNarrowing(int left, int right) { int right2left= right + (left << 4); return right2left >= 0 && right2left < MAX_CONVERSIONS && (CONVERSIONS[right2left] & (IDENTITY | NARROWING)) != 0; } /** * Predicate telling whether "left" can store a "right" using some widening conversion (is left * bigger than right) * * @param left - the target type to convert to * @param right - the actual type * @return true if legal widening conversion */ public static final boolean isWidening(int left, int right) { int right2left= right + (left << 4); return right2left >= 0 && right2left < MAX_CONVERSIONS && (CONVERSIONS[right2left] & (IDENTITY | WIDENING)) != 0; } public char[] simpleName; private char[] constantPoolName; BaseTypeBinding(int id, char[] name, char[] constantPoolName) { this.tagBits|= TagBits.IsBaseType; this.id= id; this.simpleName= name; this.constantPoolName= constantPoolName; } /** * int -> I */ public char[] computeUniqueKey(boolean isLeaf) { return constantPoolName(); } /* Answer the receiver's constant pool name. */ public char[] constantPoolName() { return this.constantPoolName; } public PackageBinding getPackage() { return null; } /* Answer true if the receiver type can be assigned to the argument type (right) */ public final boolean isCompatibleWith(TypeBinding left) { if (this == left) return true; int right2left= this.id + (left.id << 4); if (right2left >= 0 && right2left < MAX_CONVERSIONS && (CONVERSIONS[right2left] & (IDENTITY | WIDENING)) != 0) return true; return this == TypeBinding.NULL && !left.isBaseType(); } /** * T_null is acting as an unchecked exception * * @see org.eclipse.jdt.internal.compiler.lookup.TypeBinding#isUncheckedException(boolean) */ public boolean isUncheckedException(boolean includeSupertype) { return this == TypeBinding.NULL; } /** * @see org.eclipse.jdt.internal.compiler.lookup.Binding#kind() */ public int kind() { return Binding.BASE_TYPE; } public char[] qualifiedSourceName() { return this.simpleName; } public char[] readableName() { return this.simpleName; } public char[] shortReadableName() { return this.simpleName; } public char[] sourceName() { return this.simpleName; } public String toString() { return new String(this.constantPoolName) + " (id=" + this.id + ")"; //$NON-NLS-1$ //$NON-NLS-2$ } }
thlaegler/openbanking
openbanking-api-soap-transform/src/main/gen/com/laegler/openbanking/soap/service/POSTCreateDomesticStandingOrders500.java
<reponame>thlaegler/openbanking package com.laegler.openbanking.soap.service; import javax.xml.ws.WebFault; /** * Internal Server Error * * This class was generated by Apache CXF 3.3.3 * 2019-10-21T07:01:26.786+13:00 * Generated source version: 3.3.3 */ @WebFault(name = "POST_CreateDomesticStandingOrders_500", targetNamespace = "http://laegler.com/openbanking/soap/model") public class POSTCreateDomesticStandingOrders500 extends Exception { private com.laegler.openbanking.soap.model.OBErrorResponse1 postCreateDomesticStandingOrders500; public POSTCreateDomesticStandingOrders500() { super(); } public POSTCreateDomesticStandingOrders500(String message) { super(message); } public POSTCreateDomesticStandingOrders500(String message, java.lang.Throwable cause) { super(message, cause); } public POSTCreateDomesticStandingOrders500(String message, com.laegler.openbanking.soap.model.OBErrorResponse1 postCreateDomesticStandingOrders500) { super(message); this.postCreateDomesticStandingOrders500 = postCreateDomesticStandingOrders500; } public POSTCreateDomesticStandingOrders500(String message, com.laegler.openbanking.soap.model.OBErrorResponse1 postCreateDomesticStandingOrders500, java.lang.Throwable cause) { super(message, cause); this.postCreateDomesticStandingOrders500 = postCreateDomesticStandingOrders500; } public com.laegler.openbanking.soap.model.OBErrorResponse1 getFaultInfo() { return this.postCreateDomesticStandingOrders500; } }
hjholtz/PyExt
src/objects/PyLongObject.cpp
<reponame>hjholtz/PyExt #include "PyLongObject.h" #include "../ExtHelpers.h" #include <engextcpp.hpp> #include <string> #include <stdexcept> #include <vector> #include <algorithm> using namespace std; namespace PyExt::Remote { PyLongObject::PyLongObject(Offset objectAddress) : PyVarObject(objectAddress, "PyLongObject") { } auto PyLongObject::isNegative() const -> bool { return size() < 0; } auto PyLongObject::repr(bool /*pretty*/) const -> string { auto digits = remoteType().Field("ob_digit"); const auto bytesPerDigit = digits.ArrayElement(0).GetTypeSize(); // Set up our constants based on how CPython was compiled. // See: https://github.com/python/cpython/blob/master/Include/longintrepr.h int64_t SHIFT = 0, DECIMAL_BASE = 0, DECIMAL_SHIFT = 0; if (bytesPerDigit == 4) { SHIFT = 30; DECIMAL_SHIFT = 9; DECIMAL_BASE = 1000000000; } else if (bytesPerDigit == 2) { SHIFT = 15; DECIMAL_SHIFT = 4; DECIMAL_BASE = 10000; } else { throw runtime_error("Unexpected PyLong bytes per digit of " + to_string(bytesPerDigit)); } const auto BASE = static_cast<int64_t>(1) << SHIFT; const auto MASK = BASE - 1; // Convert from BASE to DECIMAL_BASE and store the result in `buff`. vector<uint64_t> buff; const auto numDigits = abs(size()); for (int64_t i = numDigits - 1; i >= 0; --i) { auto hiElement = digits.ArrayElement(i); auto hi = utils::readIntegral<uint64_t>(hiElement); for (auto& buffDigit : buff) { uint64_t z = buffDigit << SHIFT | hi; hi = z / DECIMAL_BASE; buffDigit = z - hi * DECIMAL_BASE; } while (hi) { buff.push_back(hi % DECIMAL_BASE); hi /= DECIMAL_BASE; } } // If the buffer is empty, use 0. if (buff.empty()) buff.push_back(0); // Convert `buff` from DECIMAL_BASE to base 10 and store the characters in `out`. string out; for (size_t i = 0; i < buff.size() - 1; i++) { auto rem = buff[i]; for (int64_t j = 0; j < DECIMAL_SHIFT; ++j) { out.push_back('0' + rem % 10); rem /= 10; } } // Consume the last digit. auto rem = buff.back(); do { out.push_back('0' + rem % 10); rem /= 10; } while (rem != 0); // Append a negative sign if needed. if (isNegative()) out.push_back('-'); reverse(out.begin(), out.end()); return out; } }
piotrjaniszewski1/Tourie-backend
services/google_maps.js
/* eslint-disable no-await-in-loop */ const googleMaps = require('@google/maps'); const debug = require('debug')('services:googleMaps'); const mSleep = require('../helpers/mSleep'); const GOOGLE_API_SLEEP_TIMEOUT = 600; const GOOGLE_DETAILS_FIELDS = ['price_level', 'rating', 'formatted_phone_number', 'review', 'website']; class GoogleMaps { constructor() { this.client = googleMaps.createClient({ key: process.env.GOOGLE_MAPS_API_KEY, Promise, }); } findPlaces(location, radius) { debug('location, radius: ', location, radius); return new Promise(async (resolve, reject) => { let pageNum = 0; const places = []; let nextPageToken = null; do { const query = nextPageToken ? { pagetoken: nextPageToken } : { location, radius }; try { const res = await this.client.placesNearby(query).asPromise(); nextPageToken = res.json.next_page_token; const newPlaces = res.json.results; for (let i = 0; i < newPlaces.length; i++) { const detailsQuery = { placeid: newPlaces[i].place_id, fields: GOOGLE_DETAILS_FIELDS }; const placeDetails = await this.client.place(detailsQuery, (err) => { debug(err); }).asPromise(); places.push({ ...newPlaces[i], ...placeDetails.json.result }); } } catch (err) { reject(err); } // Wait for Google to create the next places array. await mSleep(GOOGLE_API_SLEEP_TIMEOUT); pageNum++; } while (pageNum < 2 && nextPageToken); debug('Finished building up the places[60] array.'); resolve(places); }); } } module.exports = GoogleMaps;
bleack114/notify.moe
patches/delete-private-data/delete-private-data.go
<reponame>bleack114/notify.moe package main import ( "github.com/animenotifier/arn" "github.com/fatih/color" ) func main() { color.Yellow("Deleting private user data") defer arn.Node.Close() emailToUser := arn.DB.Collection("EmailToUser") testRecord, _ := emailToUser.Get("<EMAIL>") emailToUser.Clear() emailToUser.Set("<EMAIL>", testRecord) // Iterate over the stream count := 0 for user := range arn.StreamUsers() { count++ println(count, user.Nick) // Delete private data user.Email = "" user.Gender = "" user.FirstName = "" user.LastName = "" user.IP = "" user.Accounts.Facebook.ID = "" user.Accounts.Google.ID = "" user.AgeRange = arn.UserAgeRange{} user.Location = arn.Location{} user.PushSubscriptions().Items = []*arn.PushSubscription{} user.PushSubscriptions().Save() // Save in DB user.Save() } color.Green("Finished.") }