text
stringlengths
1
1.05M
<gh_stars>1-10 package org.o7planning.springmvconlinestore.dao; import java.util.List; import java.util.Map; import org.o7planning.springmvconlinestore.entity.Order; import org.o7planning.springmvconlinestore.entity.Product; import org.o7planning.springmvconlinestore.model.CartInfo; import org.o7planning.springmvconlinestore.model.OrderDetailInfo; import org.o7planning.springmvconlinestore.model.OrderInfo; import org.o7planning.springmvconlinestore.model.PaginationResult; public interface OrderDAO { public void saveOrder(CartInfo cartInfo); public PaginationResult<OrderInfo> listOrderInfo(int page, int maxResult, int maxNavigationPage); public Order findSingleOrder(int orderId); public Order findOrderForCustomer(int orderId, int customerId); public List<Order> listAllOrderItemsForSingleOrder(int orderId); public List<Product> listAllOrderItemsForAllOrders(); }
def manipulateString(string): # convert the string to upper case output = string.upper() # reverse the string output = output[::-1] return output print(manipulateString("Hello World")) # prints "DLRO WOLLEH"
package org.javastack.mapexpression.example; import java.util.HashMap; import org.javastack.mapexpression.MapExpression; import org.javastack.mapexpression.mapper.MapMapper; public class Example3 { public static void main(final String[] args) throws Throwable { final HashMap<String, String> map = new HashMap<String, String>(); map.put("user", "john"); final MapExpression m = new MapExpression(); // m.setExpression("Hi ###user###") // .setDelimiters("###", "###") // .setPostMapper(new MapMapper(map)); System.out.println(m.parse().eval().get()); // m.setExpression("{{user}}? {{user}}?") // .setDelimiters("{{", "}}") // .setPostMapper(new MapMapper(map)); System.out.println(m.parse().eval().get()); // m.setExpression("Hi |user|, how are you?") // .setDelimiters("|", "|") // .setPostMapper(new MapMapper(map)); System.out.println(m.parse().eval().get()); } }
package sort; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.PriorityQueue; import java.util.StringTokenizer; /** * * @author exponential-e * 백준 20124번: 모르고리즘 회장님 추천 받습니다 * * @see https://www.acmicpc.net/problem/20124 * */ public class Boj20124 { private static class Candidate implements Comparable<Candidate>{ String name; int count; public Candidate(String name, int count) { this.name = name; this.count = count; } @Override public int compareTo(Candidate c) { return c.count != this.count ? c.count - this.count : this.name.compareTo(c.name); } } public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); PriorityQueue<Candidate> candidates = new PriorityQueue<>(); int N = Integer.parseInt(br.readLine()); while(N-- > 0) { StringTokenizer st = new StringTokenizer(br.readLine()); candidates.offer(new Candidate(st.nextToken(), Integer.parseInt(st.nextToken()))); } System.out.println(candidates.poll().name); } }
<reponame>mason-fish/brim<gh_stars>0 import {createZealotMock, zng} from "zealot" import {fetchNextPage} from "./fetchNextPage" import Workspaces from "../state/Workspaces" import Current from "../state/Current" import Search from "../state/Search" import Spaces from "../state/Spaces" import Tab from "../state/Tab" import Tabs from "../state/Tabs" import Viewer from "../state/Viewer" import fixtures from "../test/fixtures" import initTestStore from "../test/initTestStore" const records = zng.createRecords([ { id: 1, schema: { type: "record", of: [ {name: "td", type: "string"}, {name: "ts", type: "time"} ] }, values: ["1", "100"] }, { id: 1, values: ["1", "200"] }, { id: 1, values: ["1", "300"] } ]) let store, zealot, tabId beforeEach(() => { zealot = createZealotMock() zealot.stubStream("search", []) store = initTestStore(zealot.zealot) tabId = Tabs.getActive(store.getState()) const ws = fixtures("workspace1") const space = fixtures("space1") store.dispatchAll([ Workspaces.add(ws), Spaces.setDetail(ws.id, space), Current.setWorkspaceId(ws.id), Current.setSpaceId(space.id), Search.setSpanArgsFromDates([new Date(0), new Date(10 * 1000)]), Tab.computeSpan(), Viewer.appendRecords(tabId, records) ]) store.clearActions() }) test("#fetchNextPage dispatches splice", () => { store.dispatch(fetchNextPage()) expect(store.getActions()).toEqual( expect.arrayContaining([{tabId, type: "VIEWER_SPLICE", index: 2}]) ) }) test("#fetchNextPage adds 1ms to ts of last change", () => { const search = jest.spyOn(zealot.zealot, "search") store.dispatch(fetchNextPage()) const data = records[1].at(1) // This should be fixed so that all data have a value field or getValue method if (!("value" in data)) throw new Error("boom") const lastChangeTs = data.value expect(search).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ from: new Date(0), to: new Date(+lastChangeTs * 1000 + 1) }) ) }) test("#fetchNextPage when there is only 1 event", () => { const search = jest.spyOn(zealot.zealot, "search") store.dispatch(Viewer.splice(tabId, 1)) store.dispatch(fetchNextPage()) expect(search).toHaveBeenCalledWith( expect.any(String), expect.objectContaining({ from: new Date(0), to: new Date(10 * 1000) }) ) }) test("#fetchNextPage does not mutate the exisiting span", () => { const before = [...Tab.getSpanAsDates(store.getState())] store.dispatch(fetchNextPage()) const after = [...Tab.getSpanAsDates(store.getState())] expect(before).toEqual(after) })
#!/bin/bash # Source utils.sh, which is 2 directories above auditd_utils.sh script_dir="$( dirname "${BASH_SOURCE[0]}" )" . $script_dir/../../utils.sh function prepare_auditd_test_enviroment { get_packages audit audispd-plugins }
require 'spec_helper' require 'yt/models/comment_thread' describe Yt::CommentThread do subject(:comment_thread) { Yt::CommentThread.new attrs } describe '#snippet' do context 'given fetching a comment thread returns a snippet' do let(:attrs) { {snippet: {"videoId" => "12345"}} } it { expect(comment_thread.snippet).to be_a Yt::Snippet } end end describe '#video_id' do context 'given a snippet with a video id' do let(:attrs) { {snippet: {"videoId"=>"12345"}} } it { expect(comment_thread.video_id).to eq '12345' } end context 'given a snippet without a video id' do let(:attrs) { {snippet: {}} } it { expect(comment_thread.video_id).to be_nil } end end describe '#top_level_comment' do context 'given a snippet with a top level comment' do let(:attrs) { {snippet: {"topLevelComment"=> {}}} } it { expect(comment_thread.top_level_comment).to be_a Yt::Comment } end end describe 'attributes from #top_level_comment delegations' do context 'with values' do let(:attrs) { {snippet: {"topLevelComment"=> {"id" => "xyz123", "snippet" => { "textDisplay" => "funny video!", "authorDisplayName" => "fullscreen", "likeCount" => 99, "updatedAt" => "2016-03-22T12:56:56.3Z"}}}} } it { expect(comment_thread.top_level_comment.id).to eq 'xyz123' } it { expect(comment_thread.text_display).to eq 'funny video!' } it { expect(comment_thread.author_display_name).to eq 'fullscreen' } it { expect(comment_thread.like_count).to eq 99 } it { expect(comment_thread.updated_at).to eq Time.parse('2016-03-22T12:56:56.3Z') } end context 'without values' do let(:attrs) { {snippet: {"topLevelComment"=> {"snippet" => {}}}} } it { expect(comment_thread.text_display).to be_nil } it { expect(comment_thread.author_display_name).to be_nil } it { expect(comment_thread.like_count).to be_nil } it { expect(comment_thread.updated_at).to be_nil } end end describe '#total_reply_count' do context 'given a snippet with a total reply count' do let(:attrs) { {snippet: {"totalReplyCount"=>1}} } it { expect(comment_thread.total_reply_count).to eq 1 } end context 'given a snippet without a total reply count' do let(:attrs) { {snippet: {}} } it { expect(comment_thread.total_reply_count).to be_nil } end end describe '#can_reply?' do context 'given a snippet with canReply set' do let(:attrs) { {snippet: {"canReply"=>true}} } it { expect(comment_thread.can_reply?).to be true } end context 'given a snippet without canReply set' do let(:attrs) { {snippet: {}} } it { expect(comment_thread.can_reply?).to be false } end end describe '#is_public?' do context 'given a snippet with isPublic set' do let(:attrs) { {snippet: {"isPublic"=>true}} } it { expect(comment_thread).to be_public } end context 'given a snippet without isPublic set' do let(:attrs) { {snippet: {}} } it { expect(comment_thread).to_not be_public } end end end
/* TITLE Class name-age pairs Chapter9Exercise3.cpp Bjarne Stroustrup "Programming: Principles and Practice Using C++" COMMENT Objective: Implement a class Name_pairs: Data members: Member functions: Overloaded operator: string name, double age; read_names(); operator<< vector<string> name; read_ages(); operator== vector<double> age; sort(); operator!= size(); Input: Prompts user to type name-age pairs. Output: Prints all the above / sorted. Author: <NAME> Date: 14.03.2015 */ #include <iostream> #include <string> #include <vector> #include <algorithm> #include "Chapter9Exercise3.h" NamePairs::Name_pairs np; void input_loop(); //========================================================================================= int main() { try { std::cout <<"\t\tWelcome to this simple name-age pair sorting algorithm.\n"; input_loop(); } catch(std::exception& e) { std::cerr << e.what() << std::endl; } } //========================================================================================= void input_loop() { std::cout <<"How many pairs do you want to enter:\n>>"; int number_of_names; std::cin >> number_of_names; // read pairs np.read_names(number_of_names); getchar(); np.read_ages(); // input confirmation std::cout << "You have typed the following pairs: \n"; std::cout << np; // sort and print np.sort(); std::cout << "The ordered pairs are:\n"; std::cout << np; if (np == np) { std::cout <<"Objects are identical.\n"; } if (np != np) { std::cout <<"Objects are different.\n"; } }
<reponame>LuChangliCN/medas-iot package com.foxconn.iot.core.service.impl; import java.util.ArrayList; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageImpl; import org.springframework.data.domain.Pageable; import org.springframework.stereotype.Service; import com.alibaba.druid.util.StringUtils; import com.foxconn.iot.core.dto.ClientDto; import com.foxconn.iot.core.entity.Client; import com.foxconn.iot.core.exception.BizException; import com.foxconn.iot.core.exception.ErrorCode; import com.foxconn.iot.core.repository.ClientRepository; import com.foxconn.iot.core.service.ClientService; @Service public class ClientServiceImpl implements ClientService { @Autowired private ClientRepository clientRepository; @Override public ClientDto create(ClientDto client) { Client entity = new Client(); BeanUtils.copyProperties(client, entity); clientRepository.save(entity); client.setId(entity.getId()); return client; } @Override public ClientDto save(ClientDto client) { Client entity = clientRepository.findByAppId(client.getAppId()); if (entity == null) { throw new BizException(ErrorCode.ENTITY_NOT_FOUND); } if (!StringUtils.isEmpty(client.getSecret())) { entity.setSecret(client.getSecret()); } if (!StringUtils.isEmpty(client.getName())) { entity.setName(client.getName()); } entity.setStatus(client.getStatus()); clientRepository.save(entity); BeanUtils.copyProperties(entity, client); return client; } @Override public ClientDto findById(long id) { Client client = clientRepository.findById(id); ClientDto dto = new ClientDto(); BeanUtils.copyProperties(client, dto); return dto; } @Override @Transactional public void updateStatusById(int status, long id) { clientRepository.updateStatusById(status, id); } @Override @Transactional public void deleteById(long id) { clientRepository.deleteById(id); } @Override public Page<ClientDto> findAll(Pageable pageable) { Page<Client> clients = clientRepository.findAll(pageable); List<ClientDto> dtos = new ArrayList<>(); for (Client client : clients.getContent()) { ClientDto dto = new ClientDto(); BeanUtils.copyProperties(client, dto); dtos.add(dto); } return new PageImpl<>(dtos, pageable, clients.getTotalElements()); } }
import React, { Component } from 'react'; import {NavLink} from 'react-router-dom'; import { connect } from 'react-redux'; import { logout } from '../Redux/actions/auth' import './navbar.css'; class Navbar extends Component { logoutHandler = () => { this.props.logout(); } render() { return ( <header className="navbar-container"> <div className="navbar-logo"> <h1>Grocery Getter</h1> </div> <div className="navbar-items"> <ul> <li><NavLink to="/menu">Menu</NavLink></li> <li><NavLink to="/grocery">Grocery Items</NavLink></li> <li><NavLink to="/recipe">Recipes</NavLink></li> <li><NavLink to="/auth" onClick={this.logoutHandler}>Logout</NavLink></li> </ul> </div> </header> ); } } const mapDispatchToProps = { logout } export default connect(null, mapDispatchToProps)(Navbar);
package textgen; import java.util.AbstractList; /** * A class that implements a doubly linked list * * @author UC San Diego Intermediate Programming MOOC team * @param <E> The type of the elements stored in the list */ public class MyLinkedList<E> extends AbstractList<E> { LLNode<E> head; LLNode<E> tail; int size; /** Create a new empty LinkedList */ public MyLinkedList() { head = null; tail = null; size = 0; } /** * Appends an element to the end of the list * * @param element The element to add */ public boolean add(E element) { add(size, element); return true; } /** * Get the element at position index * * @throws IndexOutOfBoundsException if the index is out of bounds. */ public E get(int index) { if (size <= index || index < 0) { throw new IndexOutOfBoundsException( String.format("Index must be between 0 and %s but is %s", size - 1, index)); } LLNode node = head; for (int i = 0; i < index; i++) { node = node.next; } return (E) node.data; } /** * Add an element to the list at the specified index * * @param The index where the element should be added * @param element The element to add */ public void add(int index, E element) { if (size < index || index < 0) { throw new IndexOutOfBoundsException( String.format("Index must be between 0 and %s but is %s", size, index)); } if (element == null) { throw new NullPointerException(String.format("The element is null")); } LLNode new_node = new LLNode(element); if (head == null) { head = tail = new_node; } else if (index == 0) { new_node.next = head; head.prev = new_node; head = new_node; } else if (index == size) { new_node.prev = tail; tail.next = new_node; tail = new_node; } else { LLNode node = head; for (int i = 0; i < index - 1; i++) { node = node.next; } LLNode next_node = node.next; node.next = new_node; new_node.prev = node; next_node.prev = new_node; new_node.next = next_node; } size++; } /** Return the size of the list */ public int size() { return size; } /** * Remove a node at the specified index and return its data element. * * @param index The index of the element to remove * @return The data element removed * @throws IndexOutOfBoundsException If index is outside the bounds of the list */ public E remove(int index) { if (size <= index || index < 0) { throw new IndexOutOfBoundsException( String.format("Index must be between 0 and %s but is %s", size - 1, index)); } LLNode node_to_remove = head; if (size == 1) { head = tail = null; } else if (index == 0) { head = node_to_remove.next; head.prev = null; } else if (index == size - 1) { node_to_remove = tail; tail = node_to_remove.prev; tail.next = null; } else { for (int i = 0; i < index; i++) { node_to_remove = node_to_remove.next; } LLNode next_node = node_to_remove.next; LLNode prev_node = node_to_remove.prev; next_node.prev = prev_node; prev_node.next = next_node; } size--; return (E) node_to_remove.data; } /** * Set an index position in the list to a new element * * @param index The index of the element to change * @param element The new element * @return The element that was replaced * @throws IndexOutOfBoundsException if the index is out of bounds. */ public E set(int index, E element) { if (size <= index || index < 0) { throw new IndexOutOfBoundsException( String.format("Index must be between 0 and %s but is %s", size - 1, index)); } if (element == null) { throw new NullPointerException(String.format("The element cannot be null")); } LLNode node = head; for (int i = 0; i < index; i++) { node = node.next; } E original_element = (E) node.data; node.data = element; return original_element; } } class LLNode<E> { LLNode<E> prev; LLNode<E> next; E data; // TODO: Add any other methods you think are useful here // E.g. you might want to add another constructor public LLNode(E e) { this.data = e; this.prev = null; this.next = null; } }
<reponame>zzlc/WebRTC<filename>modules/audio_device/linux/audio_device_alsa_linux.cc /* * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #include <assert.h> #include "modules/audio_device/audio_device_config.h" #include "modules/audio_device/linux/audio_device_alsa_linux.h" #include "rtc_base/logging.h" #include "system_wrappers/include/event_wrapper.h" #include "system_wrappers/include/sleep.h" webrtc::adm_linux_alsa::AlsaSymbolTable AlsaSymbolTable; // Accesses ALSA functions through our late-binding symbol table instead of // directly. This way we don't have to link to libasound, which means our binary // will work on systems that don't have it. #define LATE(sym) \ LATESYM_GET(webrtc::adm_linux_alsa::AlsaSymbolTable, &AlsaSymbolTable, sym) // Redefine these here to be able to do late-binding #undef snd_ctl_card_info_alloca #define snd_ctl_card_info_alloca(ptr) \ do { \ *ptr = (snd_ctl_card_info_t*)__builtin_alloca( \ LATE(snd_ctl_card_info_sizeof)()); \ memset(*ptr, 0, LATE(snd_ctl_card_info_sizeof)()); \ } while (0) #undef snd_pcm_info_alloca #define snd_pcm_info_alloca(pInfo) \ do { \ *pInfo = (snd_pcm_info_t*)__builtin_alloca(LATE(snd_pcm_info_sizeof)()); \ memset(*pInfo, 0, LATE(snd_pcm_info_sizeof)()); \ } while (0) // snd_lib_error_handler_t void WebrtcAlsaErrorHandler(const char* file, int line, const char* function, int err, const char* fmt, ...){}; namespace webrtc { static const unsigned int ALSA_PLAYOUT_FREQ = 48000; static const unsigned int ALSA_PLAYOUT_CH = 2; static const unsigned int ALSA_PLAYOUT_LATENCY = 40 * 1000; // in us static const unsigned int ALSA_CAPTURE_FREQ = 48000; static const unsigned int ALSA_CAPTURE_CH = 2; static const unsigned int ALSA_CAPTURE_LATENCY = 40 * 1000; // in us static const unsigned int ALSA_CAPTURE_WAIT_TIMEOUT = 5; // in ms #define FUNC_GET_NUM_OF_DEVICE 0 #define FUNC_GET_DEVICE_NAME 1 #define FUNC_GET_DEVICE_NAME_FOR_AN_ENUM 2 AudioDeviceLinuxALSA::AudioDeviceLinuxALSA() : _ptrAudioBuffer(NULL), _inputDeviceIndex(0), _outputDeviceIndex(0), _inputDeviceIsSpecified(false), _outputDeviceIsSpecified(false), _handleRecord(NULL), _handlePlayout(NULL), _recordingBuffersizeInFrame(0), _recordingPeriodSizeInFrame(0), _playoutBufferSizeInFrame(0), _playoutPeriodSizeInFrame(0), _recordingBufferSizeIn10MS(0), _playoutBufferSizeIn10MS(0), _recordingFramesIn10MS(0), _playoutFramesIn10MS(0), _recordingFreq(ALSA_CAPTURE_FREQ), _playoutFreq(ALSA_PLAYOUT_FREQ), _recChannels(ALSA_CAPTURE_CH), _playChannels(ALSA_PLAYOUT_CH), _recordingBuffer(NULL), _playoutBuffer(NULL), _recordingFramesLeft(0), _playoutFramesLeft(0), _initialized(false), _recording(false), _playing(false), _recIsInitialized(false), _playIsInitialized(false), _recordingDelay(0), _playoutDelay(0) { memset(_oldKeyState, 0, sizeof(_oldKeyState)); RTC_LOG(LS_INFO) << __FUNCTION__ << " created"; } // ---------------------------------------------------------------------------- // AudioDeviceLinuxALSA - dtor // ---------------------------------------------------------------------------- AudioDeviceLinuxALSA::~AudioDeviceLinuxALSA() { RTC_LOG(LS_INFO) << __FUNCTION__ << " destroyed"; Terminate(); // Clean up the recording buffer and playout buffer. if (_recordingBuffer) { delete[] _recordingBuffer; _recordingBuffer = NULL; } if (_playoutBuffer) { delete[] _playoutBuffer; _playoutBuffer = NULL; } } void AudioDeviceLinuxALSA::AttachAudioBuffer(AudioDeviceBuffer* audioBuffer) { rtc::CritScope lock(&_critSect); _ptrAudioBuffer = audioBuffer; // Inform the AudioBuffer about default settings for this implementation. // Set all values to zero here since the actual settings will be done by // InitPlayout and InitRecording later. _ptrAudioBuffer->SetRecordingSampleRate(0); _ptrAudioBuffer->SetPlayoutSampleRate(0); _ptrAudioBuffer->SetRecordingChannels(0); _ptrAudioBuffer->SetPlayoutChannels(0); } int32_t AudioDeviceLinuxALSA::ActiveAudioLayer( AudioDeviceModule::AudioLayer& audioLayer) const { audioLayer = AudioDeviceModule::kLinuxAlsaAudio; return 0; } AudioDeviceGeneric::InitStatus AudioDeviceLinuxALSA::Init() { rtc::CritScope lock(&_critSect); // Load libasound if (!AlsaSymbolTable.Load()) { // Alsa is not installed on this system RTC_LOG(LS_ERROR) << "failed to load symbol table"; return InitStatus::OTHER_ERROR; } if (_initialized) { return InitStatus::OK; } #if defined(WEBRTC_USE_X11) // Get X display handle for typing detection _XDisplay = XOpenDisplay(NULL); if (!_XDisplay) { RTC_LOG(LS_WARNING) << "failed to open X display, typing detection will not work"; } #endif _initialized = true; return InitStatus::OK; } int32_t AudioDeviceLinuxALSA::Terminate() { if (!_initialized) { return 0; } rtc::CritScope lock(&_critSect); _mixerManager.Close(); // RECORDING if (_ptrThreadRec) { rtc::PlatformThread* tmpThread = _ptrThreadRec.release(); _critSect.Leave(); tmpThread->Stop(); delete tmpThread; _critSect.Enter(); } // PLAYOUT if (_ptrThreadPlay) { rtc::PlatformThread* tmpThread = _ptrThreadPlay.release(); _critSect.Leave(); tmpThread->Stop(); delete tmpThread; _critSect.Enter(); } #if defined(WEBRTC_USE_X11) if (_XDisplay) { XCloseDisplay(_XDisplay); _XDisplay = NULL; } #endif _initialized = false; _outputDeviceIsSpecified = false; _inputDeviceIsSpecified = false; return 0; } bool AudioDeviceLinuxALSA::Initialized() const { return (_initialized); } int32_t AudioDeviceLinuxALSA::InitSpeaker() { rtc::CritScope lock(&_critSect); if (_playing) { return -1; } char devName[kAdmMaxDeviceNameSize] = {0}; GetDevicesInfo(2, true, _outputDeviceIndex, devName, kAdmMaxDeviceNameSize); return _mixerManager.OpenSpeaker(devName); } int32_t AudioDeviceLinuxALSA::InitMicrophone() { rtc::CritScope lock(&_critSect); if (_recording) { return -1; } char devName[kAdmMaxDeviceNameSize] = {0}; GetDevicesInfo(2, false, _inputDeviceIndex, devName, kAdmMaxDeviceNameSize); return _mixerManager.OpenMicrophone(devName); } bool AudioDeviceLinuxALSA::SpeakerIsInitialized() const { return (_mixerManager.SpeakerIsInitialized()); } bool AudioDeviceLinuxALSA::MicrophoneIsInitialized() const { return (_mixerManager.MicrophoneIsInitialized()); } int32_t AudioDeviceLinuxALSA::SpeakerVolumeIsAvailable(bool& available) { bool wasInitialized = _mixerManager.SpeakerIsInitialized(); // Make an attempt to open up the // output mixer corresponding to the currently selected output device. if (!wasInitialized && InitSpeaker() == -1) { // If we end up here it means that the selected speaker has no volume // control. available = false; return 0; } // Given that InitSpeaker was successful, we know that a volume control // exists available = true; // Close the initialized output mixer if (!wasInitialized) { _mixerManager.CloseSpeaker(); } return 0; } int32_t AudioDeviceLinuxALSA::SetSpeakerVolume(uint32_t volume) { return (_mixerManager.SetSpeakerVolume(volume)); } int32_t AudioDeviceLinuxALSA::SpeakerVolume(uint32_t& volume) const { uint32_t level(0); if (_mixerManager.SpeakerVolume(level) == -1) { return -1; } volume = level; return 0; } int32_t AudioDeviceLinuxALSA::MaxSpeakerVolume(uint32_t& maxVolume) const { uint32_t maxVol(0); if (_mixerManager.MaxSpeakerVolume(maxVol) == -1) { return -1; } maxVolume = maxVol; return 0; } int32_t AudioDeviceLinuxALSA::MinSpeakerVolume(uint32_t& minVolume) const { uint32_t minVol(0); if (_mixerManager.MinSpeakerVolume(minVol) == -1) { return -1; } minVolume = minVol; return 0; } int32_t AudioDeviceLinuxALSA::SpeakerMuteIsAvailable(bool& available) { bool isAvailable(false); bool wasInitialized = _mixerManager.SpeakerIsInitialized(); // Make an attempt to open up the // output mixer corresponding to the currently selected output device. // if (!wasInitialized && InitSpeaker() == -1) { // If we end up here it means that the selected speaker has no volume // control, hence it is safe to state that there is no mute control // already at this stage. available = false; return 0; } // Check if the selected speaker has a mute control _mixerManager.SpeakerMuteIsAvailable(isAvailable); available = isAvailable; // Close the initialized output mixer if (!wasInitialized) { _mixerManager.CloseSpeaker(); } return 0; } int32_t AudioDeviceLinuxALSA::SetSpeakerMute(bool enable) { return (_mixerManager.SetSpeakerMute(enable)); } int32_t AudioDeviceLinuxALSA::SpeakerMute(bool& enabled) const { bool muted(0); if (_mixerManager.SpeakerMute(muted) == -1) { return -1; } enabled = muted; return 0; } int32_t AudioDeviceLinuxALSA::MicrophoneMuteIsAvailable(bool& available) { bool isAvailable(false); bool wasInitialized = _mixerManager.MicrophoneIsInitialized(); // Make an attempt to open up the // input mixer corresponding to the currently selected input device. // if (!wasInitialized && InitMicrophone() == -1) { // If we end up here it means that the selected microphone has no volume // control, hence it is safe to state that there is no mute control // already at this stage. available = false; return 0; } // Check if the selected microphone has a mute control // _mixerManager.MicrophoneMuteIsAvailable(isAvailable); available = isAvailable; // Close the initialized input mixer // if (!wasInitialized) { _mixerManager.CloseMicrophone(); } return 0; } int32_t AudioDeviceLinuxALSA::SetMicrophoneMute(bool enable) { return (_mixerManager.SetMicrophoneMute(enable)); } // ---------------------------------------------------------------------------- // MicrophoneMute // ---------------------------------------------------------------------------- int32_t AudioDeviceLinuxALSA::MicrophoneMute(bool& enabled) const { bool muted(0); if (_mixerManager.MicrophoneMute(muted) == -1) { return -1; } enabled = muted; return 0; } int32_t AudioDeviceLinuxALSA::StereoRecordingIsAvailable(bool& available) { rtc::CritScope lock(&_critSect); // If we already have initialized in stereo it's obviously available if (_recIsInitialized && (2 == _recChannels)) { available = true; return 0; } // Save rec states and the number of rec channels bool recIsInitialized = _recIsInitialized; bool recording = _recording; int recChannels = _recChannels; available = false; // Stop/uninitialize recording if initialized (and possibly started) if (_recIsInitialized) { StopRecording(); } // Try init in stereo; _recChannels = 2; if (InitRecording() == 0) { available = true; } // Stop/uninitialize recording StopRecording(); // Recover previous states _recChannels = recChannels; if (recIsInitialized) { InitRecording(); } if (recording) { StartRecording(); } return 0; } int32_t AudioDeviceLinuxALSA::SetStereoRecording(bool enable) { if (enable) _recChannels = 2; else _recChannels = 1; return 0; } int32_t AudioDeviceLinuxALSA::StereoRecording(bool& enabled) const { if (_recChannels == 2) enabled = true; else enabled = false; return 0; } int32_t AudioDeviceLinuxALSA::StereoPlayoutIsAvailable(bool& available) { rtc::CritScope lock(&_critSect); // If we already have initialized in stereo it's obviously available if (_playIsInitialized && (2 == _playChannels)) { available = true; return 0; } // Save rec states and the number of rec channels bool playIsInitialized = _playIsInitialized; bool playing = _playing; int playChannels = _playChannels; available = false; // Stop/uninitialize recording if initialized (and possibly started) if (_playIsInitialized) { StopPlayout(); } // Try init in stereo; _playChannels = 2; if (InitPlayout() == 0) { available = true; } // Stop/uninitialize recording StopPlayout(); // Recover previous states _playChannels = playChannels; if (playIsInitialized) { InitPlayout(); } if (playing) { StartPlayout(); } return 0; } int32_t AudioDeviceLinuxALSA::SetStereoPlayout(bool enable) { if (enable) _playChannels = 2; else _playChannels = 1; return 0; } int32_t AudioDeviceLinuxALSA::StereoPlayout(bool& enabled) const { if (_playChannels == 2) enabled = true; else enabled = false; return 0; } int32_t AudioDeviceLinuxALSA::MicrophoneVolumeIsAvailable(bool& available) { bool wasInitialized = _mixerManager.MicrophoneIsInitialized(); // Make an attempt to open up the // input mixer corresponding to the currently selected output device. if (!wasInitialized && InitMicrophone() == -1) { // If we end up here it means that the selected microphone has no volume // control. available = false; return 0; } // Given that InitMicrophone was successful, we know that a volume control // exists available = true; // Close the initialized input mixer if (!wasInitialized) { _mixerManager.CloseMicrophone(); } return 0; } int32_t AudioDeviceLinuxALSA::SetMicrophoneVolume(uint32_t volume) { return (_mixerManager.SetMicrophoneVolume(volume)); return 0; } int32_t AudioDeviceLinuxALSA::MicrophoneVolume(uint32_t& volume) const { uint32_t level(0); if (_mixerManager.MicrophoneVolume(level) == -1) { RTC_LOG(LS_WARNING) << "failed to retrive current microphone level"; return -1; } volume = level; return 0; } int32_t AudioDeviceLinuxALSA::MaxMicrophoneVolume(uint32_t& maxVolume) const { uint32_t maxVol(0); if (_mixerManager.MaxMicrophoneVolume(maxVol) == -1) { return -1; } maxVolume = maxVol; return 0; } int32_t AudioDeviceLinuxALSA::MinMicrophoneVolume(uint32_t& minVolume) const { uint32_t minVol(0); if (_mixerManager.MinMicrophoneVolume(minVol) == -1) { return -1; } minVolume = minVol; return 0; } int16_t AudioDeviceLinuxALSA::PlayoutDevices() { return (int16_t)GetDevicesInfo(0, true); } int32_t AudioDeviceLinuxALSA::SetPlayoutDevice(uint16_t index) { if (_playIsInitialized) { return -1; } uint32_t nDevices = GetDevicesInfo(0, true); RTC_LOG(LS_VERBOSE) << "number of available audio output devices is " << nDevices; if (index > (nDevices - 1)) { RTC_LOG(LS_ERROR) << "device index is out of range [0," << (nDevices - 1) << "]"; return -1; } _outputDeviceIndex = index; _outputDeviceIsSpecified = true; return 0; } int32_t AudioDeviceLinuxALSA::SetPlayoutDevice( AudioDeviceModule::WindowsDeviceType /*device*/) { RTC_LOG(LS_ERROR) << "WindowsDeviceType not supported"; return -1; } int32_t AudioDeviceLinuxALSA::PlayoutDeviceName( uint16_t index, char name[kAdmMaxDeviceNameSize], char guid[kAdmMaxGuidSize]) { const uint16_t nDevices(PlayoutDevices()); if ((index > (nDevices - 1)) || (name == NULL)) { return -1; } memset(name, 0, kAdmMaxDeviceNameSize); if (guid != NULL) { memset(guid, 0, kAdmMaxGuidSize); } return GetDevicesInfo(1, true, index, name, kAdmMaxDeviceNameSize); } int32_t AudioDeviceLinuxALSA::RecordingDeviceName( uint16_t index, char name[kAdmMaxDeviceNameSize], char guid[kAdmMaxGuidSize]) { const uint16_t nDevices(RecordingDevices()); if ((index > (nDevices - 1)) || (name == NULL)) { return -1; } memset(name, 0, kAdmMaxDeviceNameSize); if (guid != NULL) { memset(guid, 0, kAdmMaxGuidSize); } return GetDevicesInfo(1, false, index, name, kAdmMaxDeviceNameSize); } int16_t AudioDeviceLinuxALSA::RecordingDevices() { return (int16_t)GetDevicesInfo(0, false); } int32_t AudioDeviceLinuxALSA::SetRecordingDevice(uint16_t index) { if (_recIsInitialized) { return -1; } uint32_t nDevices = GetDevicesInfo(0, false); RTC_LOG(LS_VERBOSE) << "number of availiable audio input devices is " << nDevices; if (index > (nDevices - 1)) { RTC_LOG(LS_ERROR) << "device index is out of range [0," << (nDevices - 1) << "]"; return -1; } _inputDeviceIndex = index; _inputDeviceIsSpecified = true; return 0; } // ---------------------------------------------------------------------------- // SetRecordingDevice II (II) // ---------------------------------------------------------------------------- int32_t AudioDeviceLinuxALSA::SetRecordingDevice( AudioDeviceModule::WindowsDeviceType /*device*/) { RTC_LOG(LS_ERROR) << "WindowsDeviceType not supported"; return -1; } int32_t AudioDeviceLinuxALSA::PlayoutIsAvailable(bool& available) { available = false; // Try to initialize the playout side with mono // Assumes that user set num channels after calling this function _playChannels = 1; int32_t res = InitPlayout(); // Cancel effect of initialization StopPlayout(); if (res != -1) { available = true; } else { // It may be possible to play out in stereo res = StereoPlayoutIsAvailable(available); if (available) { // Then set channels to 2 so InitPlayout doesn't fail _playChannels = 2; } } return res; } int32_t AudioDeviceLinuxALSA::RecordingIsAvailable(bool& available) { available = false; // Try to initialize the recording side with mono // Assumes that user set num channels after calling this function _recChannels = 1; int32_t res = InitRecording(); // Cancel effect of initialization StopRecording(); if (res != -1) { available = true; } else { // It may be possible to record in stereo res = StereoRecordingIsAvailable(available); if (available) { // Then set channels to 2 so InitPlayout doesn't fail _recChannels = 2; } } return res; } int32_t AudioDeviceLinuxALSA::InitPlayout() { int errVal = 0; rtc::CritScope lock(&_critSect); if (_playing) { return -1; } if (!_outputDeviceIsSpecified) { return -1; } if (_playIsInitialized) { return 0; } // Initialize the speaker (devices might have been added or removed) if (InitSpeaker() == -1) { RTC_LOG(LS_WARNING) << "InitSpeaker() failed"; } // Start by closing any existing wave-output devices // if (_handlePlayout != NULL) { LATE(snd_pcm_close)(_handlePlayout); _handlePlayout = NULL; _playIsInitialized = false; if (errVal < 0) { RTC_LOG(LS_ERROR) << "Error closing current playout sound device, error: " << LATE(snd_strerror)(errVal); } } // Open PCM device for playout char deviceName[kAdmMaxDeviceNameSize] = {0}; GetDevicesInfo(2, true, _outputDeviceIndex, deviceName, kAdmMaxDeviceNameSize); RTC_LOG(LS_VERBOSE) << "InitPlayout open (" << deviceName << ")"; errVal = LATE(snd_pcm_open)(&_handlePlayout, deviceName, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); if (errVal == -EBUSY) // Device busy - try some more! { for (int i = 0; i < 5; i++) { SleepMs(1000); errVal = LATE(snd_pcm_open)(&_handlePlayout, deviceName, SND_PCM_STREAM_PLAYBACK, SND_PCM_NONBLOCK); if (errVal == 0) { break; } } } if (errVal < 0) { RTC_LOG(LS_ERROR) << "unable to open playback device: " << LATE(snd_strerror)(errVal) << " (" << errVal << ")"; _handlePlayout = NULL; return -1; } _playoutFramesIn10MS = _playoutFreq / 100; if ((errVal = LATE(snd_pcm_set_params)( _handlePlayout, #if defined(WEBRTC_ARCH_BIG_ENDIAN) SND_PCM_FORMAT_S16_BE, #else SND_PCM_FORMAT_S16_LE, // format #endif SND_PCM_ACCESS_RW_INTERLEAVED, // access _playChannels, // channels _playoutFreq, // rate 1, // soft_resample ALSA_PLAYOUT_LATENCY // 40*1000 //latency required overall latency // in us )) < 0) { /* 0.5sec */ _playoutFramesIn10MS = 0; RTC_LOG(LS_ERROR) << "unable to set playback device: " << LATE(snd_strerror)(errVal) << " (" << errVal << ")"; ErrorRecovery(errVal, _handlePlayout); errVal = LATE(snd_pcm_close)(_handlePlayout); _handlePlayout = NULL; return -1; } errVal = LATE(snd_pcm_get_params)(_handlePlayout, &_playoutBufferSizeInFrame, &_playoutPeriodSizeInFrame); if (errVal < 0) { RTC_LOG(LS_ERROR) << "snd_pcm_get_params: " << LATE(snd_strerror)(errVal) << " (" << errVal << ")"; _playoutBufferSizeInFrame = 0; _playoutPeriodSizeInFrame = 0; } else { RTC_LOG(LS_VERBOSE) << "playout snd_pcm_get_params buffer_size:" << _playoutBufferSizeInFrame << " period_size :" << _playoutPeriodSizeInFrame; } if (_ptrAudioBuffer) { // Update webrtc audio buffer with the selected parameters _ptrAudioBuffer->SetPlayoutSampleRate(_playoutFreq); _ptrAudioBuffer->SetPlayoutChannels(_playChannels); } // Set play buffer size _playoutBufferSizeIn10MS = LATE(snd_pcm_frames_to_bytes)(_handlePlayout, _playoutFramesIn10MS); // Init varaibles used for play if (_handlePlayout != NULL) { _playIsInitialized = true; return 0; } else { return -1; } return 0; } int32_t AudioDeviceLinuxALSA::InitRecording() { int errVal = 0; rtc::CritScope lock(&_critSect); if (_recording) { return -1; } if (!_inputDeviceIsSpecified) { return -1; } if (_recIsInitialized) { return 0; } // Initialize the microphone (devices might have been added or removed) if (InitMicrophone() == -1) { RTC_LOG(LS_WARNING) << "InitMicrophone() failed"; } // Start by closing any existing pcm-input devices // if (_handleRecord != NULL) { int errVal = LATE(snd_pcm_close)(_handleRecord); _handleRecord = NULL; _recIsInitialized = false; if (errVal < 0) { RTC_LOG(LS_ERROR) << "Error closing current recording sound device, error: " << LATE(snd_strerror)(errVal); } } // Open PCM device for recording // The corresponding settings for playout are made after the record settings char deviceName[kAdmMaxDeviceNameSize] = {0}; GetDevicesInfo(2, false, _inputDeviceIndex, deviceName, kAdmMaxDeviceNameSize); RTC_LOG(LS_VERBOSE) << "InitRecording open (" << deviceName << ")"; errVal = LATE(snd_pcm_open)(&_handleRecord, deviceName, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK); // Available modes: 0 = blocking, SND_PCM_NONBLOCK, SND_PCM_ASYNC if (errVal == -EBUSY) // Device busy - try some more! { for (int i = 0; i < 5; i++) { SleepMs(1000); errVal = LATE(snd_pcm_open)(&_handleRecord, deviceName, SND_PCM_STREAM_CAPTURE, SND_PCM_NONBLOCK); if (errVal == 0) { break; } } } if (errVal < 0) { RTC_LOG(LS_ERROR) << "unable to open record device: " << LATE(snd_strerror)(errVal); _handleRecord = NULL; return -1; } _recordingFramesIn10MS = _recordingFreq / 100; if ((errVal = LATE(snd_pcm_set_params)(_handleRecord, #if defined(WEBRTC_ARCH_BIG_ENDIAN) SND_PCM_FORMAT_S16_BE, // format #else SND_PCM_FORMAT_S16_LE, // format #endif SND_PCM_ACCESS_RW_INTERLEAVED, // access _recChannels, // channels _recordingFreq, // rate 1, // soft_resample ALSA_CAPTURE_LATENCY // latency in us )) < 0) { // Fall back to another mode then. if (_recChannels == 1) _recChannels = 2; else _recChannels = 1; if ((errVal = LATE(snd_pcm_set_params)(_handleRecord, #if defined(WEBRTC_ARCH_BIG_ENDIAN) SND_PCM_FORMAT_S16_BE, // format #else SND_PCM_FORMAT_S16_LE, // format #endif SND_PCM_ACCESS_RW_INTERLEAVED, // access _recChannels, // channels _recordingFreq, // rate 1, // soft_resample ALSA_CAPTURE_LATENCY // latency in us )) < 0) { _recordingFramesIn10MS = 0; RTC_LOG(LS_ERROR) << "unable to set record settings: " << LATE(snd_strerror)(errVal) << " (" << errVal << ")"; ErrorRecovery(errVal, _handleRecord); errVal = LATE(snd_pcm_close)(_handleRecord); _handleRecord = NULL; return -1; } } errVal = LATE(snd_pcm_get_params)(_handleRecord, &_recordingBuffersizeInFrame, &_recordingPeriodSizeInFrame); if (errVal < 0) { RTC_LOG(LS_ERROR) << "snd_pcm_get_params " << LATE(snd_strerror)(errVal) << " (" << errVal << ")"; _recordingBuffersizeInFrame = 0; _recordingPeriodSizeInFrame = 0; } else { RTC_LOG(LS_VERBOSE) << "capture snd_pcm_get_params, buffer_size:" << _recordingBuffersizeInFrame << ", period_size:" << _recordingPeriodSizeInFrame; } if (_ptrAudioBuffer) { // Update webrtc audio buffer with the selected parameters _ptrAudioBuffer->SetRecordingSampleRate(_recordingFreq); _ptrAudioBuffer->SetRecordingChannels(_recChannels); } // Set rec buffer size and create buffer _recordingBufferSizeIn10MS = LATE(snd_pcm_frames_to_bytes)(_handleRecord, _recordingFramesIn10MS); if (_handleRecord != NULL) { // Mark recording side as initialized _recIsInitialized = true; return 0; } else { return -1; } return 0; } int32_t AudioDeviceLinuxALSA::StartRecording() { if (!_recIsInitialized) { return -1; } if (_recording) { return 0; } _recording = true; int errVal = 0; _recordingFramesLeft = _recordingFramesIn10MS; // Make sure we only create the buffer once. if (!_recordingBuffer) _recordingBuffer = new int8_t[_recordingBufferSizeIn10MS]; if (!_recordingBuffer) { RTC_LOG(LS_ERROR) << "failed to alloc recording buffer"; _recording = false; return -1; } // RECORDING _ptrThreadRec.reset(new rtc::PlatformThread( RecThreadFunc, this, "webrtc_audio_module_capture_thread")); _ptrThreadRec->Start(); _ptrThreadRec->SetPriority(rtc::kRealtimePriority); errVal = LATE(snd_pcm_prepare)(_handleRecord); if (errVal < 0) { RTC_LOG(LS_ERROR) << "capture snd_pcm_prepare failed (" << LATE(snd_strerror)(errVal) << ")\n"; // just log error // if snd_pcm_open fails will return -1 } errVal = LATE(snd_pcm_start)(_handleRecord); if (errVal < 0) { RTC_LOG(LS_ERROR) << "capture snd_pcm_start err: " << LATE(snd_strerror)(errVal); errVal = LATE(snd_pcm_start)(_handleRecord); if (errVal < 0) { RTC_LOG(LS_ERROR) << "capture snd_pcm_start 2nd try err: " << LATE(snd_strerror)(errVal); StopRecording(); return -1; } } return 0; } int32_t AudioDeviceLinuxALSA::StopRecording() { { rtc::CritScope lock(&_critSect); if (!_recIsInitialized) { return 0; } if (_handleRecord == NULL) { return -1; } // Make sure we don't start recording (it's asynchronous). _recIsInitialized = false; _recording = false; } if (_ptrThreadRec) { _ptrThreadRec->Stop(); _ptrThreadRec.reset(); } rtc::CritScope lock(&_critSect); _recordingFramesLeft = 0; if (_recordingBuffer) { delete[] _recordingBuffer; _recordingBuffer = NULL; } // Stop and close pcm recording device. int errVal = LATE(snd_pcm_drop)(_handleRecord); if (errVal < 0) { RTC_LOG(LS_ERROR) << "Error stop recording: " << LATE(snd_strerror)(errVal); return -1; } errVal = LATE(snd_pcm_close)(_handleRecord); if (errVal < 0) { RTC_LOG(LS_ERROR) << "Error closing record sound device, error: " << LATE(snd_strerror)(errVal); return -1; } // Check if we have muted and unmute if so. bool muteEnabled = false; MicrophoneMute(muteEnabled); if (muteEnabled) { SetMicrophoneMute(false); } // set the pcm input handle to NULL _handleRecord = NULL; return 0; } bool AudioDeviceLinuxALSA::RecordingIsInitialized() const { return (_recIsInitialized); } bool AudioDeviceLinuxALSA::Recording() const { return (_recording); } bool AudioDeviceLinuxALSA::PlayoutIsInitialized() const { return (_playIsInitialized); } int32_t AudioDeviceLinuxALSA::StartPlayout() { if (!_playIsInitialized) { return -1; } if (_playing) { return 0; } _playing = true; _playoutFramesLeft = 0; if (!_playoutBuffer) _playoutBuffer = new int8_t[_playoutBufferSizeIn10MS]; if (!_playoutBuffer) { RTC_LOG(LS_ERROR) << "failed to alloc playout buf"; _playing = false; return -1; } // PLAYOUT _ptrThreadPlay.reset(new rtc::PlatformThread( PlayThreadFunc, this, "webrtc_audio_module_play_thread")); _ptrThreadPlay->Start(); _ptrThreadPlay->SetPriority(rtc::kRealtimePriority); int errVal = LATE(snd_pcm_prepare)(_handlePlayout); if (errVal < 0) { RTC_LOG(LS_ERROR) << "playout snd_pcm_prepare failed (" << LATE(snd_strerror)(errVal) << ")\n"; // just log error // if snd_pcm_open fails will return -1 } return 0; } int32_t AudioDeviceLinuxALSA::StopPlayout() { { rtc::CritScope lock(&_critSect); if (!_playIsInitialized) { return 0; } if (_handlePlayout == NULL) { return -1; } _playing = false; } // stop playout thread first if (_ptrThreadPlay) { _ptrThreadPlay->Stop(); _ptrThreadPlay.reset(); } rtc::CritScope lock(&_critSect); _playoutFramesLeft = 0; delete[] _playoutBuffer; _playoutBuffer = NULL; // stop and close pcm playout device int errVal = LATE(snd_pcm_drop)(_handlePlayout); if (errVal < 0) { RTC_LOG(LS_ERROR) << "Error stop playing: " << LATE(snd_strerror)(errVal); } errVal = LATE(snd_pcm_close)(_handlePlayout); if (errVal < 0) RTC_LOG(LS_ERROR) << "Error closing playout sound device, error: " << LATE(snd_strerror)(errVal); // set the pcm input handle to NULL _playIsInitialized = false; _handlePlayout = NULL; RTC_LOG(LS_VERBOSE) << "handle_playout is now set to NULL"; return 0; } int32_t AudioDeviceLinuxALSA::PlayoutDelay(uint16_t& delayMS) const { delayMS = (uint16_t)_playoutDelay * 1000 / _playoutFreq; return 0; } bool AudioDeviceLinuxALSA::Playing() const { return (_playing); } // ============================================================================ // Private Methods // ============================================================================ int32_t AudioDeviceLinuxALSA::GetDevicesInfo(const int32_t function, const bool playback, const int32_t enumDeviceNo, char* enumDeviceName, const int32_t ednLen) const { // Device enumeration based on libjingle implementation // by <NAME> at Google Inc. const char* type = playback ? "Output" : "Input"; // dmix and dsnoop are only for playback and capture, respectively, but ALSA // stupidly includes them in both lists. const char* ignorePrefix = playback ? "dsnoop:" : "dmix:"; // (ALSA lists many more "devices" of questionable interest, but we show them // just in case the weird devices may actually be desirable for some // users/systems.) int err; int enumCount(0); bool keepSearching(true); // From Chromium issue 95797 // Loop through the sound cards to get Alsa device hints. // Don't use snd_device_name_hint(-1,..) since there is a access violation // inside this ALSA API with libasound.so.2.0.0. int card = -1; while (!(LATE(snd_card_next)(&card)) && (card >= 0) && keepSearching) { void** hints; err = LATE(snd_device_name_hint)(card, "pcm", &hints); if (err != 0) { RTC_LOG(LS_ERROR) << "GetDevicesInfo - device name hint error: " << LATE(snd_strerror)(err); return -1; } enumCount++; // default is 0 if ((function == FUNC_GET_DEVICE_NAME || function == FUNC_GET_DEVICE_NAME_FOR_AN_ENUM) && enumDeviceNo == 0) { strcpy(enumDeviceName, "default"); err = LATE(snd_device_name_free_hint)(hints); if (err != 0) { RTC_LOG(LS_ERROR) << "GetDevicesInfo - device name free hint error: " << LATE(snd_strerror)(err); } return 0; } for (void** list = hints; *list != NULL; ++list) { char* actualType = LATE(snd_device_name_get_hint)(*list, "IOID"); if (actualType) { // NULL means it's both. bool wrongType = (strcmp(actualType, type) != 0); free(actualType); if (wrongType) { // Wrong type of device (i.e., input vs. output). continue; } } char* name = LATE(snd_device_name_get_hint)(*list, "NAME"); if (!name) { RTC_LOG(LS_ERROR) << "Device has no name"; // Skip it. continue; } // Now check if we actually want to show this device. if (strcmp(name, "default") != 0 && strcmp(name, "null") != 0 && strcmp(name, "pulse") != 0 && strncmp(name, ignorePrefix, strlen(ignorePrefix)) != 0) { // Yes, we do. char* desc = LATE(snd_device_name_get_hint)(*list, "DESC"); if (!desc) { // Virtual devices don't necessarily have descriptions. // Use their names instead. desc = name; } if (FUNC_GET_NUM_OF_DEVICE == function) { RTC_LOG(LS_VERBOSE) << "Enum device " << enumCount << " - " << name; } if ((FUNC_GET_DEVICE_NAME == function) && (enumDeviceNo == enumCount)) { // We have found the enum device, copy the name to buffer. strncpy(enumDeviceName, desc, ednLen); enumDeviceName[ednLen - 1] = '\0'; keepSearching = false; // Replace '\n' with '-'. char* pret = strchr(enumDeviceName, '\n' /*0xa*/); // LF if (pret) *pret = '-'; } if ((FUNC_GET_DEVICE_NAME_FOR_AN_ENUM == function) && (enumDeviceNo == enumCount)) { // We have found the enum device, copy the name to buffer. strncpy(enumDeviceName, name, ednLen); enumDeviceName[ednLen - 1] = '\0'; keepSearching = false; } if (keepSearching) ++enumCount; if (desc != name) free(desc); } free(name); if (!keepSearching) break; } err = LATE(snd_device_name_free_hint)(hints); if (err != 0) { RTC_LOG(LS_ERROR) << "GetDevicesInfo - device name free hint error: " << LATE(snd_strerror)(err); // Continue and return true anyway, since we did get the whole list. } } if (FUNC_GET_NUM_OF_DEVICE == function) { if (enumCount == 1) // only default? enumCount = 0; return enumCount; // Normal return point for function 0 } if (keepSearching) { // If we get here for function 1 and 2, we didn't find the specified // enum device. RTC_LOG(LS_ERROR) << "GetDevicesInfo - Could not find device name or numbers"; return -1; } return 0; } int32_t AudioDeviceLinuxALSA::InputSanityCheckAfterUnlockedPeriod() const { if (_handleRecord == NULL) { RTC_LOG(LS_ERROR) << "input state has been modified during unlocked period"; return -1; } return 0; } int32_t AudioDeviceLinuxALSA::OutputSanityCheckAfterUnlockedPeriod() const { if (_handlePlayout == NULL) { RTC_LOG(LS_ERROR) << "output state has been modified during unlocked period"; return -1; } return 0; } int32_t AudioDeviceLinuxALSA::ErrorRecovery(int32_t error, snd_pcm_t* deviceHandle) { int st = LATE(snd_pcm_state)(deviceHandle); RTC_LOG(LS_VERBOSE) << "Trying to recover from " << ((LATE(snd_pcm_stream)(deviceHandle) == SND_PCM_STREAM_CAPTURE) ? "capture" : "playout") << " error: " << LATE(snd_strerror)(error) << " (" << error << ") (state " << st << ")"; // It is recommended to use snd_pcm_recover for all errors. If that function // cannot handle the error, the input error code will be returned, otherwise // 0 is returned. From snd_pcm_recover API doc: "This functions handles // -EINTR (4) (interrupted system call), -EPIPE (32) (playout overrun or // capture underrun) and -ESTRPIPE (86) (stream is suspended) error codes // trying to prepare given stream for next I/O." /** Open */ // SND_PCM_STATE_OPEN = 0, /** Setup installed */ // SND_PCM_STATE_SETUP, /** Ready to start */ // SND_PCM_STATE_PREPARED, /** Running */ // SND_PCM_STATE_RUNNING, /** Stopped: underrun (playback) or overrun (capture) detected */ // SND_PCM_STATE_XRUN,= 4 /** Draining: running (playback) or stopped (capture) */ // SND_PCM_STATE_DRAINING, /** Paused */ // SND_PCM_STATE_PAUSED, /** Hardware is suspended */ // SND_PCM_STATE_SUSPENDED, // ** Hardware is disconnected */ // SND_PCM_STATE_DISCONNECTED, // SND_PCM_STATE_LAST = SND_PCM_STATE_DISCONNECTED // snd_pcm_recover isn't available in older alsa, e.g. on the FC4 machine // in Sthlm lab. int res = LATE(snd_pcm_recover)(deviceHandle, error, 1); if (0 == res) { RTC_LOG(LS_VERBOSE) << "Recovery - snd_pcm_recover OK"; if ((error == -EPIPE || error == -ESTRPIPE) && // Buf underrun/overrun. _recording && LATE(snd_pcm_stream)(deviceHandle) == SND_PCM_STREAM_CAPTURE) { // For capture streams we also have to repeat the explicit start() // to get data flowing again. int err = LATE(snd_pcm_start)(deviceHandle); if (err != 0) { RTC_LOG(LS_ERROR) << "Recovery - snd_pcm_start error: " << err; return -1; } } if ((error == -EPIPE || error == -ESTRPIPE) && // Buf underrun/overrun. _playing && LATE(snd_pcm_stream)(deviceHandle) == SND_PCM_STREAM_PLAYBACK) { // For capture streams we also have to repeat the explicit start() to get // data flowing again. int err = LATE(snd_pcm_start)(deviceHandle); if (err != 0) { RTC_LOG(LS_ERROR) << "Recovery - snd_pcm_start error: " << LATE(snd_strerror)(err); return -1; } } return -EPIPE == error ? 1 : 0; } else { RTC_LOG(LS_ERROR) << "Unrecoverable alsa stream error: " << res; } return res; } // ============================================================================ // Thread Methods // ============================================================================ bool AudioDeviceLinuxALSA::PlayThreadFunc(void* pThis) { return (static_cast<AudioDeviceLinuxALSA*>(pThis)->PlayThreadProcess()); } bool AudioDeviceLinuxALSA::RecThreadFunc(void* pThis) { return (static_cast<AudioDeviceLinuxALSA*>(pThis)->RecThreadProcess()); } bool AudioDeviceLinuxALSA::PlayThreadProcess() { if (!_playing) return false; int err; snd_pcm_sframes_t frames; snd_pcm_sframes_t avail_frames; Lock(); // return a positive number of frames ready otherwise a negative error code avail_frames = LATE(snd_pcm_avail_update)(_handlePlayout); if (avail_frames < 0) { RTC_LOG(LS_ERROR) << "playout snd_pcm_avail_update error: " << LATE(snd_strerror)(avail_frames); ErrorRecovery(avail_frames, _handlePlayout); UnLock(); return true; } else if (avail_frames == 0) { UnLock(); // maximum tixe in milliseconds to wait, a negative value means infinity err = LATE(snd_pcm_wait)(_handlePlayout, 2); if (err == 0) { // timeout occured // RTC_LOG(LS_VERBOSE) << "playout snd_pcm_wait timeout"; } return true; } if (_playoutFramesLeft <= 0) { UnLock(); _ptrAudioBuffer->RequestPlayoutData(_playoutFramesIn10MS); Lock(); _playoutFramesLeft = _ptrAudioBuffer->GetPlayoutData(_playoutBuffer); assert(_playoutFramesLeft == _playoutFramesIn10MS); } if (static_cast<uint32_t>(avail_frames) > _playoutFramesLeft) avail_frames = _playoutFramesLeft; int size = LATE(snd_pcm_frames_to_bytes)(_handlePlayout, _playoutFramesLeft); frames = LATE(snd_pcm_writei)( _handlePlayout, &_playoutBuffer[_playoutBufferSizeIn10MS - size], avail_frames); if (frames < 0) { RTC_LOG(LS_VERBOSE) << "playout snd_pcm_writei error: " << LATE(snd_strerror)(frames); _playoutFramesLeft = 0; ErrorRecovery(frames, _handlePlayout); UnLock(); return true; } else { assert(frames == avail_frames); _playoutFramesLeft -= frames; } UnLock(); return true; } bool AudioDeviceLinuxALSA::RecThreadProcess() { if (!_recording) return false; int err; snd_pcm_sframes_t frames; snd_pcm_sframes_t avail_frames; int8_t buffer[_recordingBufferSizeIn10MS]; Lock(); // return a positive number of frames ready otherwise a negative error code avail_frames = LATE(snd_pcm_avail_update)(_handleRecord); if (avail_frames < 0) { RTC_LOG(LS_ERROR) << "capture snd_pcm_avail_update error: " << LATE(snd_strerror)(avail_frames); ErrorRecovery(avail_frames, _handleRecord); UnLock(); return true; } else if (avail_frames == 0) { // no frame is available now UnLock(); // maximum time in milliseconds to wait, a negative value means infinity err = LATE(snd_pcm_wait)(_handleRecord, ALSA_CAPTURE_WAIT_TIMEOUT); // add by cgb // if (err == 0) // timeout occured // RTC_LOG(LS_VERBOSE) << "capture snd_pcm_wait timeout"; return true; } if (static_cast<uint32_t>(avail_frames) > _recordingFramesLeft) avail_frames = _recordingFramesLeft; frames = LATE(snd_pcm_readi)(_handleRecord, buffer, avail_frames); // frames to be written if (frames < 0) { RTC_LOG(LS_ERROR) << "capture snd_pcm_readi error: " << LATE(snd_strerror)(frames); ErrorRecovery(frames, _handleRecord); UnLock(); return true; } else if (frames > 0) { assert(frames == avail_frames); int left_size = LATE(snd_pcm_frames_to_bytes)(_handleRecord, _recordingFramesLeft); int size = LATE(snd_pcm_frames_to_bytes)(_handleRecord, frames); memcpy(&_recordingBuffer[_recordingBufferSizeIn10MS - left_size], buffer, size); _recordingFramesLeft -= frames; if (!_recordingFramesLeft) { // buf is full _recordingFramesLeft = _recordingFramesIn10MS; // store the recorded buffer (no action will be taken if the // #recorded samples is not a full buffer) _ptrAudioBuffer->SetRecordedBuffer(_recordingBuffer, _recordingFramesIn10MS); // calculate delay _playoutDelay = 0; _recordingDelay = 0; if (_handlePlayout) { err = LATE(snd_pcm_delay)(_handlePlayout, &_playoutDelay); // returned delay in frames if (err < 0) { // TODO(xians): Shall we call ErrorRecovery() here? _playoutDelay = 0; RTC_LOG(LS_ERROR) << "playout snd_pcm_delay: " << LATE(snd_strerror)(err); } } err = LATE(snd_pcm_delay)(_handleRecord, &_recordingDelay); // returned delay in frames if (err < 0) { // TODO(xians): Shall we call ErrorRecovery() here? _recordingDelay = 0; RTC_LOG(LS_ERROR) << "capture snd_pcm_delay: " << LATE(snd_strerror)(err); } // TODO(xians): Shall we add 10ms buffer delay to the record delay? _ptrAudioBuffer->SetVQEData(_playoutDelay * 1000 / _playoutFreq, _recordingDelay * 1000 / _recordingFreq); _ptrAudioBuffer->SetTypingStatus(KeyPressed()); // Deliver recorded samples at specified sample rate, mic level etc. // to the observer using callback. UnLock(); _ptrAudioBuffer->DeliverRecordedData(); Lock(); } } UnLock(); return true; } bool AudioDeviceLinuxALSA::KeyPressed() const { #if defined(WEBRTC_USE_X11) char szKey[32]; unsigned int i = 0; char state = 0; if (!_XDisplay) return false; // Check key map status XQueryKeymap(_XDisplay, szKey); // A bit change in keymap means a key is pressed for (i = 0; i < sizeof(szKey); i++) state |= (szKey[i] ^ _oldKeyState[i]) & szKey[i]; // Save old state memcpy((char*)_oldKeyState, (char*)szKey, sizeof(_oldKeyState)); return (state != 0); #else return false; #endif } } // namespace webrtc
<gh_stars>1-10 /******************************************************************************* * Copyright Searchbox - http://www.searchbox.com * * 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.searchbox.core.engine; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Configurable; import com.searchbox.core.SearchElement; import com.searchbox.core.dm.Collection; import com.searchbox.core.search.AbstractSearchCondition; @Configurable public abstract class AbstractSearchEngine<Q, R> implements SearchEngine<Q, R> { private static final Logger LOGGER = LoggerFactory .getLogger(AbstractSearchEngine.class); protected String name; protected String description; protected Class<Q> queryClass; protected Class<R> responseClass; protected AbstractSearchEngine(Class<Q> queryClass, Class<R> responseClass) { this.queryClass = queryClass; this.responseClass = responseClass; } protected AbstractSearchEngine(String name, Class<Q> queryClass, Class<R> responseClass) { this.name = name; this.queryClass = queryClass; this.responseClass = responseClass; } @Override public Class<Q> getQueryClass() { return this.queryClass; } @Override public Class<R> getResponseClass() { return this.responseClass; } @Override public abstract Q newQuery(Collection collection); @Override public List<SearchElement> getSupportedElements() { return null; } @Override public Boolean supportsElement(SearchElement element) { // FIXME check if searchegine can actually use Element return true; } @Override public Boolean supportsCondition(AbstractSearchCondition condition) { // TODO Auto-generated method stub return true; } @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public void setQueryClass(Class<Q> queryClass) { this.queryClass = queryClass; } protected void setResponseClass(Class<R> responseClass) { this.responseClass = responseClass; } }
<filename>src/types/OrderByDir.ts import { Constants } from '../constants'; export const OrderByDirs = [ Constants.ORDER_BY_DIR.ASC, Constants.ORDER_BY_DIR.DESC ] as const; export type OrderByDir = typeof OrderByDirs[number];
import java.util.Map; public class ChunkStatusHelper { public static String getParentStatus(Map<String, String> chunkStatuses, String statusName) { if (chunkStatuses.containsKey(statusName)) { String parentStatus = chunkStatuses.get(statusName); return parentStatus != null ? parentStatus : "No parent status"; } else { return "No parent status"; } } public static void main(String[] args) { Map<String, String> chunkStatuses = Map.of( "spawn", "light", "heightmaps", "spawn", "full", "heightmaps" ); String statusName = "full"; System.out.println(getParentStatus(chunkStatuses, statusName)); // Output: heightmaps } }
#!/bin/sh # /** # * Copyright (c) 2013-Now http://jeesite.com All rights reserved. # * # * Author: ThinkGem@163.com # * # */ echo "" echo "[信息] 打包Web工程,并运行Web工程。" echo "" # 打包Web工程(开始) cd .. mvn clean package spring-boot:repackage -Dmaven.test.skip=true -U cd target # 打包Web工程(结束) # 根据情况修改 web.jar 为您的 jar 包名称 mkdir web cp web.war ./web cd web jar -xvf web.war cd WEB-INF exec ./startup.sh
#!/usr/bin/env osascript # Returns the current playing song in iTunes for OSX tell application "System Events" set process_list to (name of every process) end tell if process_list contains "iTunes" then tell application "iTunes" if player state is playing then set track_name to name of current track set artist_name to artist of current track # set album_name to album of current track set trim_length to 40 set now_playing to "♫ " & artist_name & " - " & track_name if length of now_playing is less than trim_length then set now_playing_trim to now_playing else set now_playing_trim to characters 1 thru trim_length of now_playing as string end if end if end tell end if
/* * 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 org.apache.jena.permissions.graph.impl; import java.util.Map; import java.util.Map.Entry; import org.apache.jena.permissions.graph.SecuredPrefixMapping; import org.apache.jena.permissions.impl.ItemHolder; import org.apache.jena.permissions.impl.SecuredItemImpl; import org.apache.jena.shared.AuthenticationRequiredException; import org.apache.jena.shared.PrefixMapping; import org.apache.jena.shared.ReadDeniedException; import org.apache.jena.shared.UpdateDeniedException; import org.apache.jena.shared.impl.PrefixMappingImpl; /** * Implementation of SecuredPrefixMapping to be used by a SecuredItemInvoker * proxy. */ public class SecuredPrefixMappingImpl extends SecuredItemImpl implements SecuredPrefixMapping { // the item holder that holds this SecuredPrefixMapping private final ItemHolder<PrefixMapping, SecuredPrefixMapping> holder; /** * Constructor * * @param graph * The Secured graph this mapping is for. * @param holder * The item holder that will contain this SecuredPrefixMapping. */ SecuredPrefixMappingImpl(final SecuredGraphImpl graph, final ItemHolder<PrefixMapping, SecuredPrefixMapping> holder) { super(graph, holder); this.holder = holder; } @Override public String expandPrefix(final String prefixed) throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().expandPrefix(prefixed); } @Override public Map<String, String> getNsPrefixMap() throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().getNsPrefixMap(); } @Override public String getNsPrefixURI(final String prefix) throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().getNsPrefixURI(prefix); } @Override public String getNsURIPrefix(final String uri) throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().getNsURIPrefix(uri); } @Override public SecuredPrefixMapping lock() throws UpdateDeniedException, AuthenticationRequiredException { checkUpdate(); holder.getBaseItem().lock(); return holder.getSecuredItem(); } @Override public String qnameFor(final String uri) throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().qnameFor(uri); } @Override public SecuredPrefixMapping removeNsPrefix(final String prefix) throws UpdateDeniedException, AuthenticationRequiredException { checkUpdate(); holder.getBaseItem().removeNsPrefix(prefix); return holder.getSecuredItem(); } @Override public boolean samePrefixMappingAs(final PrefixMapping other) throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().samePrefixMappingAs(other); } @Override public SecuredPrefixMapping setNsPrefix(final String prefix, final String uri) throws UpdateDeniedException, AuthenticationRequiredException { checkUpdate(); holder.getBaseItem().setNsPrefix(prefix, uri); return holder.getSecuredItem(); } @Override public SecuredPrefixMapping setNsPrefixes(final Map<String, String> map) throws UpdateDeniedException, AuthenticationRequiredException { checkUpdate(); holder.getBaseItem().setNsPrefixes(map); return holder.getSecuredItem(); } @Override public SecuredPrefixMapping setNsPrefixes(final PrefixMapping other) throws UpdateDeniedException, AuthenticationRequiredException { checkUpdate(); holder.getBaseItem().setNsPrefixes(other); return holder.getSecuredItem(); } @Override public String shortForm(final String uri) throws ReadDeniedException, AuthenticationRequiredException { checkRead(); return holder.getBaseItem().shortForm(uri); } @Override public SecuredPrefixMapping withDefaultMappings(final PrefixMapping map) throws UpdateDeniedException, AuthenticationRequiredException { // mapping only updates if there are map entries to add. Since this gets // called // when we are doing deep triple checks while writing we need to attempt // the // update only if there are new updates to add. PrefixMapping m = holder.getBaseItem(); PrefixMappingImpl pm = new PrefixMappingImpl(); for (Entry<String, String> e : map.getNsPrefixMap().entrySet()) { if (m.getNsPrefixURI(e.getKey()) == null && m.getNsURIPrefix(e.getValue()) == null) { pm.setNsPrefix(e.getKey(), e.getValue()); } } if (!pm.getNsPrefixMap().isEmpty()) { checkUpdate(); holder.getBaseItem().withDefaultMappings(pm); } return holder.getSecuredItem(); } }
<reponame>SAP-samples/yaaS-implicit-grant<gh_stars>0 /* * [y] SAP Hybris */ $(document).ready(function(){ $("#one_post").click(function(){ jQuery.ajax( { url: 'https://api.us.yaas.io/hybris/product/v2/<projectid>/products', //replace <projectid> with the Identifier type: 'GET', contentType:"application/json", beforeSend : function( xhr ) { var id = "Bearer " + $('#token').html(); xhr.setRequestHeader( "Authorization", id); xhr.setRequestHeader("Content-Type", "application/json"); }, success: function(response) { $('#get_response').html("Success!\n" + JSON.stringify(response,null,2)); } } ); }); });
<filename>seal/src/main/java/cn/rongcloud/im/ui/activity/SetLanguageActivity.java<gh_stars>0 package cn.rongcloud.im.ui.activity; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.TaskStackBuilder; import android.view.View; import android.widget.ImageView; import java.util.Locale; import cn.rongcloud.im.App; import cn.rongcloud.im.R; import io.rong.common.RLog; import io.rong.imkit.RongConfigurationManager; import io.rong.imkit.utilities.LangUtils.RCLocale; import io.rong.imlib.RongIMClient; public class SetLanguageActivity extends BaseActivity implements View.OnClickListener { private final String TAG = SetLanguageActivity.class.getSimpleName(); private RCLocale originalLocale; private RCLocale selectedLocale; private ImageView chineseCheckbox; private ImageView englishCheckbox; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_set_language); setTitle(R.string.setting_language); findViewById(R.id.ll_chinese).setOnClickListener(SetLanguageActivity.this); findViewById(R.id.ll_english).setOnClickListener(SetLanguageActivity.this); chineseCheckbox = (ImageView) findViewById(R.id.img_chinese_checkbox); englishCheckbox = (ImageView) findViewById(R.id.img_english_checkbox); originalLocale = RongConfigurationManager.getInstance().getAppLocale(this); if (originalLocale == RCLocale.LOCALE_CHINA) { selectLocale(RCLocale.LOCALE_CHINA); } else if (originalLocale == RCLocale.LOCALE_US) { selectLocale(RCLocale.LOCALE_US); } else { //auto值则以系统为标准设定 Locale systemLocale = RongConfigurationManager.getInstance().getSystemLocale(); if (systemLocale.getLanguage().equals(Locale.CHINESE.getLanguage())) { originalLocale = RCLocale.LOCALE_CHINA; selectLocale(RCLocale.LOCALE_CHINA); } else if (systemLocale.getLanguage().equals(Locale.ENGLISH.getLanguage())) { originalLocale = RCLocale.LOCALE_US; selectLocale(RCLocale.LOCALE_US); } else { originalLocale = RCLocale.LOCALE_CHINA; selectLocale(RCLocale.LOCALE_CHINA); } } } private void selectLocale(RCLocale locale) { if (locale == RCLocale.LOCALE_CHINA) { englishCheckbox.setImageDrawable(null); chineseCheckbox.setImageResource(R.drawable.ic_checkbox_full); selectedLocale = RCLocale.LOCALE_CHINA; } else if (locale == RCLocale.LOCALE_US) { chineseCheckbox.setImageDrawable(null); englishCheckbox.setImageResource(R.drawable.ic_checkbox_full); selectedLocale = RCLocale.LOCALE_US; } } @Override public void onClick(View v) { if (v.getId() == R.id.ll_chinese) { selectLocale(RCLocale.LOCALE_CHINA); changeLanguageAndRestart(selectedLocale); } else if (v.getId() == R.id.ll_english) { selectLocale(RCLocale.LOCALE_US); changeLanguageAndRestart(selectedLocale); } } private void changeLanguageAndRestart(RCLocale selectedLocale){ if( selectedLocale == originalLocale) return; if (selectedLocale == RCLocale.LOCALE_CHINA) { RongConfigurationManager.getInstance().switchLocale(RCLocale.LOCALE_CHINA, this); App.updateApplicationLanguage(); setPushLanguage(RongIMClient.PushLanguage.ZH_CN); } else if(selectedLocale == RCLocale.LOCALE_US) { RongConfigurationManager.getInstance().switchLocale(RCLocale.LOCALE_US, this); App.updateApplicationLanguage(); setPushLanguage(RongIMClient.PushLanguage.EN_US); } backToSettingActivity(); } private void setPushLanguage(final RongIMClient.PushLanguage language) { RongIMClient.getInstance().setPushLanguage(language, new RongIMClient.OperationCallback() { @Override public void onSuccess() { //设置成功也存起来 RongConfigurationManager.getInstance().setPushLanguage(SetLanguageActivity.this, language); } @Override public void onError(RongIMClient.ErrorCode errorCode) { RLog.e(TAG, getString(R.string.setting_push_language_error)); } }); } private void backToSettingActivity() { Intent mainActivity = new Intent(SetLanguageActivity.this, MainActivity.class); mainActivity.putExtra(MainActivity.INITIAL_TAB_INDEX, MainActivity.TAB_ME_INDEX); Intent settLanguageActivity = new Intent(SetLanguageActivity.this, SetLanguageActivity.class); TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(SetLanguageActivity.this); taskStackBuilder.addNextIntent(mainActivity); taskStackBuilder.addNextIntent(settLanguageActivity); taskStackBuilder.startActivities(); overridePendingTransition(0, 0); } }
const search = (arr, query) => { // Convert the query to lower case query = query.toLowerCase(); // Filter the array const results = arr.filter(obj => { const values = Object.values(obj); return values.some(value => value.toLowerCase().includes(query)); }); return results; }; const arr = [ { name: "Honda CR-V", color: "blue", price: 32000 }, { name: "Toyota Corolla", color: "red", price: 22000 }, { name: "Ford Mustang", color: "yellow", price: 70000 }, ] const res = search(arr, 'car'); console.log(res); // [{ name: "Honda CR-V", color: "blue", price: 32000 }, { name: "Toyota Corolla", color: "red", price: 22000 }]
crossroad install glib2 glib-networking crossroad meson . build-cross ninja -C build-cross
#!/bin/bash echo "Starting timeline!" ${HADOOP_HOME}/bin/yarn --config ${HADOOP_CONF_DIR} timelineserver
# Source this script to setup the runtime environment on cori export OMP_NUM_THREADS=32 export KMP_BLOCKTIME=1 export KMP_AFFINITY="granularity=fine,compact,1,0" export HDF5_USE_FILE_LOCKING=FALSE module load tensorflow/intel-2.2.0-py37 module list
public class Fibonacci { static int fibonacci(int n) { if (n <= 1) return n; return fibonacci(n-1) + fibonacci(n-2); } public static void main (String args[]) { int accept_val; System.out.println("Please enter the number for which you want to find Fibonacci number: "); Scanner sc = new Scanner(System.in); accept_val = sc.nextInt(); System.out.println("Fibonacci number of " + accept_val + " is " + fibonacci(accept_val)); } }
<filename>public/js/datatables.js jQuery(function () { $("#dataTable").DataTable({ language: { url: `/locales/es.json`, }, }); });
def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n - 1) + fibonacci(n - 2) for i in range(0, n + 1): print(fibonacci(i))
#!/bin/bash FN="ChAMPdata_2.14.1.tar.gz" URLS=( "https://bioconductor.org/packages/3.8/data/experiment/src/contrib/ChAMPdata_2.14.1.tar.gz" "https://bioarchive.galaxyproject.org/ChAMPdata_2.14.1.tar.gz" "https://depot.galaxyproject.org/software/bioconductor-champdata/bioconductor-champdata_2.14.1_src_all.tar.gz" ) MD5="4bf780ba771b8bee8639aecacc014243" # Use a staging area in the conda dir rather than temp dirs, both to avoid # permission issues as well as to have things downloaded in a predictable # manner. STAGING=$PREFIX/share/$PKG_NAME-$PKG_VERSION-$PKG_BUILDNUM mkdir -p $STAGING TARBALL=$STAGING/$FN SUCCESS=0 for URL in ${URLS[@]}; do curl $URL > $TARBALL [[ $? == 0 ]] || continue # Platform-specific md5sum checks. if [[ $(uname -s) == "Linux" ]]; then if md5sum -c <<<"$MD5 $TARBALL"; then SUCCESS=1 break fi else if [[ $(uname -s) == "Darwin" ]]; then if [[ $(md5 $TARBALL | cut -f4 -d " ") == "$MD5" ]]; then SUCCESS=1 break fi fi fi done if [[ $SUCCESS != 1 ]]; then echo "ERROR: post-link.sh was unable to download any of the following URLs with the md5sum $MD5:" printf '%s\n' "${URLS[@]}" exit 1 fi # Install and clean up R CMD INSTALL --library=$PREFIX/lib/R/library $TARBALL rm $TARBALL rmdir $STAGING
def rotate_up(cube_state): """Rotates the Up layer of a cube Counter-clockwise (when viewed from the Red side). Args: cube_state (list): The cube state of a mixed up cube. Returns: list: The cube state with the Up layer rotated """ temp_state = cube_state.copy() temp_state[0] = cube_state[2] temp_state[1] = cube_state[0] temp_state[2] = cube_state[3] temp_state[3] = cube_state[1] temp_state[4] = cube_state[6] temp_state[6] = cube_state[5] temp_state[5] = cube_state[7] temp_state[7] = cube_state[4] temp_state[8] = cube_state[10] temp_state[10] = cube_state[9] temp_state[9] = cube_state[11] temp_state[11] = cube_state[8] return temp_state
import { useMemo } from 'react' import { Currency, NATIVE } from '@sushiswap/core-sdk' import { SupportedChainId } from 'constants/chains' import useWeb3React from './useWeb3' export default function useNativeCurrency(): Currency { const { chainId } = useWeb3React() return useMemo( () => chainId ? NATIVE[chainId] : // display mainnet when not connected NATIVE[SupportedChainId.MAINNET], [chainId] ) }
using System; using System.Net; using System.Net.Mail; using System.Text; public class ForgotPasswordViewModel { private const int TokenLength = 10; public void SendPasswordResetEmail(string userEmail) { string token = GenerateRandomToken(TokenLength); string resetLink = $"https://example.com/resetpassword?token={token}"; // Send email with the password reset link SendEmail(userEmail, resetLink); } private string GenerateRandomToken(int length) { const string chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; var random = new Random(); var token = new StringBuilder(length); for (int i = 0; i < length; i++) { token.Append(chars[random.Next(chars.Length)]); } return token.ToString(); } private void SendEmail(string userEmail, string resetLink) { string senderEmail = "noreply@example.com"; string senderPassword = "yourEmailPassword"; MailMessage mail = new MailMessage(senderEmail, userEmail); SmtpClient client = new SmtpClient("smtp.example.com"); mail.Subject = "Password Reset Request"; mail.Body = $"Click the following link to reset your password: {resetLink}"; client.Port = 587; client.Credentials = new NetworkCredential(senderEmail, senderPassword); client.EnableSsl = true; try { client.Send(mail); } catch (Exception ex) { Console.WriteLine("Error sending email: " + ex.Message); } } }
/* * Copyright 2014-2018 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.dbflute.logic.generate.language.typemapping; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.apache.torque.engine.database.model.TypeMap; import org.dbflute.util.DfCollectionUtil; /** * @author jflute */ public class DfLanguageTypeMappingJava implements DfLanguageTypeMapping { // =================================================================================== // Definition // ========== protected static final Map<String, String> DEFAULT_EMPTY_MAP = DfCollectionUtil.newLinkedHashMap(); protected static final String JAVA_NATIVE_BIGDECIMAL = "java.math.BigDecimal"; protected static final List<String> _stringList = newArrayList("String"); protected static final List<String> _numberList; static { _numberList = newArrayList("Byte", "Short", "Integer", "Long", "Float", "Double", "BigDecimal", "BigInteger"); } // #date_parade protected static final List<String> _dateList = newArrayList("LocalDate", "LocalDateTime", "LocalTime", "Date", "Time", "Timestamp"); protected static final List<String> _booleanList = newArrayList("Boolean"); protected static final List<String> _binaryList = newArrayList("byte[]"); @SafeVarargs protected static <ELEMENT> ArrayList<ELEMENT> newArrayList(ELEMENT... elements) { return DfCollectionUtil.newArrayList(elements); } // =================================================================================== // Type Mapping // ============ public Map<String, String> getJdbcToJavaNativeMap() { // Java native types are defined in TypeMap as default type // so this returns empty (this is special handling for Java) return DEFAULT_EMPTY_MAP; } // =================================================================================== // Native Suffix List // ================== public List<String> getStringList() { return _stringList; } public List<String> getNumberList() { return _numberList; } public List<String> getDateList() { return _dateList; } public List<String> getBooleanList() { return _booleanList; } public List<String> getBinaryList() { return _binaryList; } // =================================================================================== // Small Adjustment // ================ public String getSequenceJavaNativeType() { return JAVA_NATIVE_BIGDECIMAL; } public String getDefaultNumericJavaNativeType() { return JAVA_NATIVE_BIGDECIMAL; } public String getDefaultDecimalJavaNativeType() { return JAVA_NATIVE_BIGDECIMAL; } public String getJdbcTypeOfUUID() { return TypeMap.UUID; // [UUID Headache]: The reason why UUID type has not been supported yet on JDBC. } public String switchParameterBeanTestValueType(String plainTypeName) { return plainTypeName; } public String convertToImmutableJavaNativeType(String javaNative) { return javaNative; } public String convertToImmutableJavaNativeDefaultValue(String immutableJavaNative) { return "null"; } public String convertToJavaNativeValueFromImmutable(String immutableJavaNative, String javaNative, String variable) { return variable; } }
import argparse import os def rename_files(directory, prefix): if not os.path.exists(directory): print(f"Error: Directory '{directory}' does not exist.") return files = [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))] if not files: print(f"No files to rename in directory '{directory}'.") return for index, file in enumerate(files, start=1): filename, extension = os.path.splitext(file) new_filename = f"{prefix}_{index}{extension}" os.rename(os.path.join(directory, file), os.path.join(directory, new_filename)) print(f"Renamed '{file}' to '{new_filename}'") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Rename files in a directory with a specified prefix and sequential numbers.") parser.add_argument("-d", "--directory", default=os.getcwd(), help="Path to the directory containing the files to be renamed") parser.add_argument("-p", "--prefix", default="file", help="Prefix to be used for renaming the files") args = parser.parse_args() rename_files(args.directory, args.prefix)
#!/bin/sh if [ $1 = "beat" ] ; then celery -A app_celery.celery_app beat --loglevel=INFO --scheduler django_celery_beat.schedulers:DatabaseScheduler else celery -A app_celery.celery_app worker -P threads --concurrency=4 --loglevel=INFO --without-gossip --without-mingle --without-heartbeat -Ofair fi
<filename>comercial_vue/router/router.js import VueRouter from 'vue-router' import auth from '../auth/auth.js' import Dashboard from '../core/inicio/Dashboard.vue' import Login from '../core/login/Login.vue' /* importar rutas */ import products from '../components/dashboard/products/routes/' import services from '../components/dashboard/services/routes/' import users from '../components/dashboard/users/routes/' import collaborators from '../components/dashboard/collaborators/routes/' import gastos from '../components/dashboard/gastos_generales/routes/' import sms from '../components/dashboard/messages/routes/' // import testrutas from '../component/testrutas' /* importar rutas */ const globlalRoutes = [ ...route('/login', Login), ...route('/dashboard', Dashboard, { Auth: true }), ...products, ...services, ...users, ...collaborators, ...gastos, ...sms ] const routes = [ ...globlalRoutes ] const router = new VueRouter({ routes }) function route(path, component = Default, meta = {}) { return [{ path, component, meta }] } router.beforeEach((to, from, next) => { if (to.meta.Auth) { const authUser = localStorage.getItem('role') if (!auth.authenticated()) { next({ path: '/login', query: { redirect: to.fullPath } }) } else if (to.meta.req_user) { (authUser == 2) ? next() : next('/404') } else if (to.meta.req_admin) { (authUser == 1) ? next() : next('/404') } else if (to.meta.req_admin_or_user) { (authUser == 1 || authUser == 2 ) ? next() : next('/404') } else { next() } } else { next() } }) export default router
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; var _normalize = require('./normalize'); var _normalize2 = _interopRequireDefault(_normalize); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var write = function write(path, value, data) { if (path === '') { return value; } var location = (0, _normalize2.default)(path); var copy = _extends({}, data); var target = copy; var i = void 0; for (i = 0; i < location.length - 1; i++) { if (target[location[i]] === undefined) { target[location[i]] = {}; } else { target[location[i]] = _extends({}, target[location[i]]); } target = target[location[i]]; } target[location[i]] = value; return copy; }; exports.default = write;
// 11050. 이항 계수 1 // 2019.05.22 // 수학 #include<iostream> using namespace std; // 팩토리얼을 재귀로 구함 int Factorial(int num) { if (num == 1 || num == 0) { return 1; } else { return Factorial(num - 1) * num; } } int main() { int n, k; cin >> n >> k; // 이항계수 공식 사용하여 출력 cout << Factorial(n) / (Factorial(k) * Factorial(n - k)) << endl; return 0; }
/** * Calculate the total amount given an array of price items */ const calculateTotalAmount = (prices) => { let total = 0; prices.forEach(price => { total += price; }); return total; }; calculateTotalAmount([2.5, 5.5, 10.25]); // 18.25
<reponame>alterem/smartCityService package com.zhcs.dao; import com.zhcs.entity.BasissettingEntity; //***************************************************************************** /** * <p>Title:BasissettingDao</p> * <p>Description: 基础设置</p> * <p>Copyright: Copyright (c) 2017</p> * <p>Company: 深圳市智慧城市管家信息科技有限公司 </p> * @author 刘晓东 - Alter * @version v1.0 2017年2月23日 */ //***************************************************************************** public interface BasissettingDao extends BaseDao<BasissettingEntity> { String queryId(); }
package com.github.piedpiper.node.rest; import com.github.piedpiper.node.NodeInput; import com.mashape.unirest.http.Unirest; import com.mashape.unirest.request.HttpRequestWithBody; public class RESTPutHandler extends BaseBodyRestHandler { @Override protected HttpRequestWithBody getRequestWithBody(NodeInput input) throws Exception { return Unirest.put(getUrl(input)); } }
import { Module } from '@nestjs/common'; import { GatewayController } from './gateway.controller'; import { GatewayService } from './gateway.service'; import { ClientGrpcProxy, ClientsModule } from '@nestjs/microservices'; import { resolve } from 'path'; class ErrorHandlingProxy extends ClientGrpcProxy { protected serializeResponse(response: any): any { console.log('RESPONSEEEEE'); return super.serializeResponse(response); } protected serializeError(err: any): any { console.log('ERRORRRRRR'); return super.serializeError(err); } } @Module({ imports: [ ClientsModule.register([ { name: 'mservice', customClass: ErrorHandlingProxy, options: { url: 'localhost:50052', package: 'mservice', protoPath: resolve(__dirname, '../../mservice/mservice.proto'), }, }, ]), ], controllers: [GatewayController], providers: [GatewayService], }) export class GatewayModule {}
def find_GCD(x, y): bound = min(x, y) gcd_list = [] for i in range(1, bound+1): if (x % i == 0) and (y % i == 0): gcd_list.append(i) return gcd_list
import subprocess def execute_commands_from_file(file_path): try: with open(file_path, 'r') as file: commands = file.readlines() for command in commands: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) output, error = process.communicate() if process.returncode != 0: print(f"Error executing command: {command.strip()}. Error: {error.decode('utf-8')}") else: print(f"Command executed successfully: {command.strip()}. Output: {output.decode('utf-8')}") except FileNotFoundError: print(f"File {file_path} not found.") except Exception as e: print(f"An error occurred: {e}") # Example usage execute_commands_from_file('terminal_configs.sh')
MAIN_ROOT=$PWD/../../.. KALDI_ROOT=$MAIN_ROOT/tools/kaldi export PATH=$PWD/utils/:$KALDI_ROOT/tools/openfst/bin:$KALDI_ROOT/tools/sctk/bin:$PWD:$PATH [ ! -f $KALDI_ROOT/tools/config/common_path.sh ] && echo >&2 "The standard file $KALDI_ROOT/tools/config/common_path.sh is not present -> Exit!" && exit 1 . $KALDI_ROOT/tools/config/common_path.sh export LC_ALL=C export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:$MAIN_ROOT/tools/chainer_ctc/ext/warp-ctc/build export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/lib64:/usr/local/cuda/extras/CUPTI/lib64 export LIBRARY_PATH=$LIBRARY_PATH:/usr/local/cuda/lib64 . $MAIN_ROOT/tools/activate_python.sh export PATH=$MAIN_ROOT/utils:$MAIN_ROOT/espnet/bin:$PATH export OMP_NUM_THREADS=1 # NOTE(kan-bayashi): Use UTF-8 in Python to avoid UnicodeDecodeError when LC_ALL=C export PYTHONIOENCODING=UTF-8 export PYTHONPATH=$MAIN_ROOT:$PYTHONPATH
#!/bin/bash mix ecto.setup mix phx.server
<reponame>TeKraft/smle import { Component } from '@angular/core'; import { TypedModelComponent } from '../base/TypedModelComponent'; import { AbstractAllowedValues } from '../../../model/swe/AbstractAllowedValues'; @Component({ selector: 'swe-abstract-allowed-values', templateUrl: './AbstractAllowedValuesComponent.html' }) export class AbstractAllowedValuesComponent extends TypedModelComponent<AbstractAllowedValues> { protected createModel(): AbstractAllowedValues { return undefined; } }
/** * @license Copyright (c) 2003-2021, CKSource - <NAME>. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ /* globals ClassicEditor, console, window, document */ import { CS_CONFIG } from '@ckeditor/ckeditor5-cloud-services/tests/_utils/cloud-services-config'; ClassicEditor .create( document.querySelector( '#snippet-custom-heading-elements' ), { cloudServices: CS_CONFIG, heading: { options: [ { model: 'paragraph', title: 'Paragraph', class: 'ck-heading_paragraph' }, { model: 'heading1', view: 'h1', title: 'Heading 1', class: 'ck-heading_heading1' }, { model: 'heading2', view: 'h2', title: 'Heading 2', class: 'ck-heading_heading2' }, { model: 'headingFancy', view: { name: 'h2', classes: 'fancy' }, title: 'Heading 2 (fancy)', class: 'ck-heading_heading2_fancy', converterPriority: 'high' } ] }, ui: { viewportOffset: { top: window.getViewportTopOffsetConfig() } } } ) .then( editor => { window.editor = editor; } ) .catch( err => { console.error( err.stack ); } );
#!/bin/bash # Script to gnerate file meta data report read -p "Enter directory path : " PATH exec find $PATH -type f -exec du -h {} \+ > report.txt
#!/usr/bin/env bash set -e docker build --pull -t node_docs --build-arg NODE_VERSION='latest' . docker run \ -e CI=true \ --rm node_docs \ /bin/bash \ -c './script/build_docs.sh apm-agent-nodejs ./docs ./build'
import { DocumentDefinition } from 'mongoose'; import { IUser } from '../interfaces'; import UserModel from '../models/User.model'; import bcrypt from 'bcrypt'; /** * @param {IUser} userData * @returns {Document} User document */ export const insertUser = async (userData: DocumentDefinition<IUser>) => { return await UserModel.create(userData) .then(async (user) => { await user.generateAuthToken(); return user; }) .catch((error) => { throw new Error(error.message); }); } /** * @todo create @function getUsers to fetch all the users in the system */ /** * @todo create @function updateUser to update a user in the system * @param userId @type string * @param updateData @type DocumentDefinition<IUser> */ /** * @todo create @function deleteUser to delete the user * @param userId @type string */
#!/bin/bash mkdir -p $IROOT/.pip_cache export PIP_DOWNLOAD_CACHE=$IROOT/.pip_cache fw_depends python3 $IROOT/py3/bin/pip3 install --install-option="--prefix=${IROOT}/py3" -r $TROOT/requirements.txt
<reponame>vesense/incubator-streampipes /* * 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 org.apache.streampipes.manager.template; import org.apache.streampipes.model.SpDataStream; import org.apache.streampipes.model.pipeline.Pipeline; import org.apache.streampipes.model.staticproperty.StaticProperty; import org.apache.streampipes.model.template.PipelineTemplateDescription; import org.apache.streampipes.model.template.PipelineTemplateInvocation; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class PipelineTemplateInvocationGenerator { private SpDataStream spDataStream; private PipelineTemplateDescription pipelineTemplateDescription; public PipelineTemplateInvocationGenerator(SpDataStream dataStream, PipelineTemplateDescription pipelineTemplateDescription) { this.spDataStream = dataStream; this.pipelineTemplateDescription = pipelineTemplateDescription; } public PipelineTemplateInvocation generateInvocation() { Pipeline pipeline = new PipelineGenerator(spDataStream.getElementId(), pipelineTemplateDescription, "test").makePipeline(); PipelineTemplateInvocation pipelineTemplateInvocation = new PipelineTemplateInvocation(); pipelineTemplateInvocation.setStaticProperties(collectStaticProperties(pipeline)); pipelineTemplateInvocation.setDataSetId(spDataStream.getElementId()); //pipelineTemplateInvocation.setPipelineTemplateDescription(pipelineTemplateDescription); pipelineTemplateInvocation.setPipelineTemplateId(pipelineTemplateDescription.getPipelineTemplateId()); return pipelineTemplateInvocation; } private List<StaticProperty> collectStaticProperties(Pipeline pipeline) { List<StaticProperty> staticProperties = new ArrayList<>(); pipeline.getSepas().forEach(pe -> { pe.getStaticProperties().forEach(sp -> sp.setInternalName(pe.getDOM() + sp.getInternalName())); staticProperties.addAll(pe.getStaticProperties()); }); pipeline.getActions().forEach(pe -> { pe.getStaticProperties().forEach(sp -> sp.setInternalName(pe.getDOM() + sp.getInternalName())); staticProperties.addAll(pe.getStaticProperties()); }); // Not sure what it does // staticProperties // .stream() // .filter(sp -> sp instanceof MappingPropertyUnary) // .forEach(mp -> ((MappingPropertyUnary) mp) // .setSelectedProperty(((MappingPropertyUnary) mp) // .getMapsFromOptions() // .get(0))); return staticProperties; } private List<StaticProperty> filter(List<StaticProperty> staticProperties) { return staticProperties .stream() // TODO fix (predefined is always true //.filter(sp -> !(sp instanceof MappingProperty)) .filter(sp -> !(sp.isPredefined())) .collect(Collectors.toList()); } }
<gh_stars>1-10 import { updateDoc, doc, getDoc } from "firebase/firestore"; import { db } from "../../lib/firebase"; export default async function handler(req, res) { //Get the Data first const da = await getDoc(doc(db, "users", req.body.id)); const dData = da.data(); //Firestore query const dNotif = dData[req.body.nestedName]; dNotif[req.body.fieldName] = req.body.value; await updateDoc(doc(db, "users", req.body.id), { notifications: dNotif }); //Return JSON res.status(200).json({ status: "OK", data: dNotif, }); }
<filename>api/src/main/java/com/example/demo/model/AddressDto.java /** * This file was generated by the JPA Modeler */ package com.example.demo.model; import lombok.Getter; import lombok.Setter; import java.io.Serializable; import java.util.List; /** * @author dzni0816 */ @Getter @Setter public class AddressDto implements Serializable { private String id; private String addressLine; private String city; private String country; private String postalCode; private String modifiedDate; private List<CustomerDto> customers1; private List<LocationDto> locations; }
def has_cycle(head): slow = head fast = head while (slow and fast and fast.next): slow = slow.next fast = fast.next.next if slow == fast: return True return False
require 'rails_helper' RSpec.describe UsersController, type: :controller do let(:new_user_attributes) do { name: "TestName", email: "<EMAIL>", password: "password", password_confirmation: "password" } end describe "GET new" do it "returns http success" do get :new expect(response).to have_http_status(:success) end it "instantiates a new user" do get :new expect(assigns(:user)).to_not be_nil end end describe "POST create" do it "returns an http redirect" do post :create, params: { user: new_user_attributes } expect(response).to have_http_status(:redirect) end it "creates a new user" do expect{ post :create, params: { user: new_user_attributes } }.to change(User, :count).by(1) end it "sets user name correctly" do post :create, params: { user: new_user_attributes } expect(assigns(:user).name).to eq new_user_attributes[:name] end it "sets user email correctly" do post :create, params: { user: new_user_attributes } expect(assigns(:user).email).to eq new_user_attributes[:email] end it "sets user password correctly" do post :create, params: { user: new_user_attributes } expect(assigns(:user).password).to eq new_user_attributes[:password] end it "sets user password confirmation correctly" do post :create, params: { user: new_user_attributes } expect(assigns(:user).password_confirmation).to eq new_user_attributes[:password_confirmation] end it "logs the user in after sign up" do post :create, params: { user: new_user_attributes } expect(session[:user_id]).to eq assigns(:user).id end end describe "not signed in" do let(:factory_user) { create(:user) } before do post :create, params: { user: new_user_attributes } end it "returns http success" do get :show, params: { id: factory_user.id } expect(response).to have_http_status(:success) end it "renders the show view" do get :show, params: { id: factory_user.id } expect(response).to render_template :show end it "assigns factory_user to @user" do get :show, params: { id: factory_user.id } expect(assigns(:user)).to eq(factory_user) end end end
/* * @Author: 拆家大主教 * @Date: 2021-09-05 14:30:26 * @Last Modified by: 拆家大主教 * @Last Modified time: 2021-09-08 17:01:47 */ ;function Life() { let _this = this; let FIRST_2 = true; // 初始两天 let is_BRANCH = false; // 支线 let NEW = true; // 新生 let DAT = []; let BRANCH_DAT = []; let TLT = []; let TLT_used = []; let EVT = []; let ACH = null; let CHR = null; let STR = null; let EMQ = null; let SPR = null; let MRK = null; this.Init = function() { FIRST_2 = true; is_BRANCH = false; TLT_used = []; NEW = true; DAT = [-1]; //! [1016] BRANCH_DAT = [0]; TLT = []; EVT = []; //! [10152,10268, 10267] ACH = 0; CHR = 0; STR = 0; EMQ = 0; SPR = 0; MRK = 4; } this.Check_talent_exclusive = function(dic) { let is_ok = true; dic.forEach(id => { talents_dic[id].exclusive?.forEach(value => { if (dic.includes(value)) { is_ok = false; } }) }); return is_ok; } this.Set_talent = function(dic) { TLT = dic; console.log(TLT); TLT.forEach(id => { if(!talents_dic[id].condition) { ACH += talents_dic[id].effect?. ACH || 0; CHR += talents_dic[id].effect?. CHR || 0; STR += talents_dic[id].effect?. STR || 0; EMQ += talents_dic[id].effect?. EMQ || 0; SPR += talents_dic[id].effect?. SPR || 0; TLT_used.push(id); } }); } this.Set_choice = function(dic) { ACH += dic.ACH; CHR += dic.CHR; STR += dic.STR; EMQ += dic.EMQ; } this.Cal_Date = function(valueTime){ let startDate = "2020/9/1"; let date = new Date(startDate); let newDate = new Date(date.getFullYear(), date.getMonth(), date.getDate() + valueTime); let year2 = newDate.getFullYear(); let month2 = newDate.getMonth() + 1; let day2 = newDate.getDate(); return year2 + "/" + month2 + "/" + day2; } this.Next = function(id) { let is_ask_for = !!id; let add_date = FIRST_2 ? 1 : Math.ceil(Math.random() * 11); // 高考完毕,进行跳转 add_date = (EVT.contains([10268, 10267]) && !is_BRANCH) ? (1019 - Number(DAT[0])) : add_date; // 支线特判 10296-走进树人堂事件 EVT.contains([10269]) ? ( (is_BRANCH = true) && (date_dic["*"] = date_dic["BRANCH"]) ) : null; DAT[0] == 2 ? FIRST_2 = false : null id = id || String( (date_dic[DAT[0] + add_date] || date_dic["*"]) .event[ Math.floor( Math.random() * (date_dic[DAT[0] + add_date] || date_dic["*"]) .event.length ) ] ).slice(0,5) let item = events_dic[id]; if(!is_ask_for && !this.Check(item)) { return this.Next(); } !is_ask_for ? DAT[0] += add_date : null; // 支线时间+1 is_BRANCH && (BRANCH_DAT[0]++); let text = ""; this.Record(item); text += this.Talent(item); text += item.event; //text += item.postEvent || ""; //this.Record(item); text += this.Branch(item); (MRK < 1 && DAT[0] && !is_ask_for && item.id !== 99999 && !is_BRANCH) ? text += this.Next("30000").text : null return { date: is_BRANCH ? "SRT事纪" + BRANCH_DAT[0] : this.Cal_Date(DAT[0]), text: text, expel: MRK < 1 } } this.Check = function(item) { //console.log(item.id); if(item.NoRandom) {return false;} let exclude = item.exclude ? item.exclude .replace(/\?/g, ".contains(") .replace(/\]/g, "])") .replace(/\&/g, "##") .replace(/\|/g, "&&") .replace(/##/g, "||") .replace(/\!/g, ".notContains(") : false; let include = item.include ? item.include .replace(/\?/g, ".contains(") .replace(/\]/g, "])") .replace(/\&/g, "&&") .replace(/\|/g, "||") .replace(/\!/g, ".notContains(") : true //console.log(item.id,"exclude",exclude,"\ninclude",include); //console.log(DAT,item.id,eval(exclude),eval(include)); //console.log(item.id, eval(exclude), eval(include)); return !eval(exclude) && eval(include) } this.Record = function(item) { EVT.push(item.id); ACH += item.effect ?. ACH || 0; CHR += item.effect ?. CHR || 0; STR += item.effect ?. STR || 0; EMQ += item.effect ?. EMQ || 0; SPR += item.effect ?. SPR || 0; MRK += item.effect ?. MRK || 0; //console.log("ACH",ACH,"CHR",CHR,"STR",STR,"EMQ",EMQ,"SPR",SPR); } this.Branch = function(item) { let _return = ""; if(item.branch) { item.branch.reverse(); item.branch.forEach(branch => { let condition = branch.split(":")[0] .replace(/\?/g, ".contains(") .replace(/\]/g, "])") .replace(/\&/g, "&&") .replace(/\|/g, "||") .replace(/\!/g, ".notContains(") if(eval(condition)) { _return = this.Next( branch.split(":")[1] ).text; } }); } return _return; } this.Talent = function() { let _return = ""; TLT.forEach(id => { let condition = talents_dic[id].condition ?. replace(/\?/g, ".contains(") .replace(/\]/g, "])") .replace(/\&/g, "&&") .replace(/\|/g, "||") .replace(/\!/g, ".notContains(") || false; if( eval(condition) && !TLT_used.includes(id) ) { ACH += talents_dic[id].effect?. ACH || 0; CHR += talents_dic[id].effect?. CHR || 0; STR += talents_dic[id].effect?. STR || 0; EMQ += talents_dic[id].effect?. EMQ || 0; SPR += talents_dic[id].effect?. SPR || 0; TLT_used.push(id); _return += "天赋【" + talents_dic[id].name + "】发动:" + talents_dic[id].description + "<br />"; } }); return _return; } this.Get_summary = function() { return { DAT: DAT[0], ACH: ACH, CHR: CHR, STR: STR, EMQ: EMQ, SPR: SPR, MRK: MRK } } }
# Generated by Django 3.0.2 on 2020-01-26 07:11 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cases', '0005_auto_20200122_2041'), ] operations = [ migrations.AlterField( model_name='case', name='comment', field=models.CharField(help_text='Comment for this case.', max_length=256, verbose_name='Comment'), ), migrations.AlterField( model_name='case', name='name', field=models.CharField(help_text="Case's name.", max_length=256, verbose_name='Name'), ), ]
<reponame>waymobetta/coindrop import React from 'react' import PropTypes from 'prop-types' import LayoutConnect from '../components/LayoutConnect' import SEO from '../components/seo' import { withStyles } from '@material-ui/core/styles' import Paper from '@material-ui/core/Paper' import Grid from '@material-ui/core/Grid' import Button from '@material-ui/core/Button' import Typography from '@material-ui/core/Typography' import Stepper from '@material-ui/core/Stepper' import Step from '@material-ui/core/Step' import StepLabel from '@material-ui/core/StepLabel' import StepOne from '../components/steps/StepOne' import StepTwo from '../components/steps/StepTwo' // import StepFive from '../components/steps/stepFive' import StepThree from '../components/steps/StepThree' // import StepFour from '../components/steps/StepFour' import StepFinal from '../components/steps/StepFinal' import theme from '../components/theme' import { Link, navigate } from 'gatsby' import classNames from 'classnames' const styles = () => ({ root: { flexGrow: 1, height: 'calc(100vh - 84px)', }, connectGrid: { height: 'calc(100vh - 84px)', textAlign: 'center', }, paper: { textAlign: 'center', color: theme.palette.text.secondary, padding: '40px 20px 30px 20px', borderRadius: '67px', minHeight: 400, maxWidth: 540, margin: 'auto', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center', position: 'relative', ...theme.boxShadow, }, paperSorry: { textAlign: 'center', color: theme.palette.text.secondary, padding: '40px 100px 30px 100px', borderRadius: '67px', maxWidth: 540, margin: 'auto', display: 'flex', flexDirection: 'column', justifyContent: 'space-around', alignItems: 'center', position: 'relative', ...theme.boxShadow, height: 300, }, grow: { flexGrow: 1, }, footer: { backgroundColor: '#272B2F', height: 200, }, subGrid: {}, firstStepGrid: { marginTop: 140, [theme.breakpoints.down('xs')]: { marginTop: 60, }, }, stepLabel: { padding: 0, height: 10, width: 10, }, stepper: { width: 144, margin: '0px auto', }, stepIcon: { fill: '#ccc', width: 16, height: 16, }, stepIconActive: { fill: '#D74EFF', width: 16, height: 16, }, stepIconText: { display: 'none', }, stepTitle: { fontSize: 40, color: '#FFFFFF', fontWeight: 500, }, }) function getSteps() { return [ 'Welcome', 'Connect Accounts', 'Connect Accounts', 'Verification Code', ] } class Connect extends React.Component { constructor(props) { super(props) this.state = { activeStep: 0, skipped: new Set(), selectedPlatform: '', verified: true, canClaimEther: true, } } isStepOptional = step => step === 0 getStepContent = step => { switch (step) { case 0: return <StepOne onClick={this.handleNext} /> case 1: return <StepTwo onClick={this.handleNext} /> case 2: return ( <StepThree onClick={this.handleNext} /> ) case 3: navigate( "dashboard/tasks/", { state: { ftu: true }, } ) return // return ( // <StepFour // onClick={this.handleVerify} // selectedPlatform={this.state.selectedPlatform} // canClaimEther={this.state.canClaimEther} // /> // ) default: return 'Unknown step' } } getStepTitle = step => { switch (step) { case 0: return '' case 1: return 'Connect Accounts' case 2: return 'Connect Accounts' case 3: return 'Almost Done' default: return '' } } handleSelection = selection => { const { activeStep } = this.state let { skipped } = this.state if (this.isStepSkipped(activeStep)) { skipped = new Set(skipped.values()) skipped.delete(activeStep) } this.setState({ activeStep: activeStep + 1, skipped, selectedPlatform: selection, }) } handleNext = () => { const { activeStep } = this.state let { skipped } = this.state this.setState({ activeStep: activeStep + 1, skipped, }) } handleVerify = () => { const { activeStep } = this.state // We will return verification response here this.setState({ activeStep: activeStep + 1, verified: true, }) } handleBack = () => { this.setState(state => ({ activeStep: state.activeStep - 1, })) } handleSkip = () => { const { activeStep } = this.state if (!this.isStepOptional(activeStep)) { // You probably want to guard against something like this, // it should never occur unless someone's actively trying to break something. throw new Error("You can't skip a step that isn't optional.") } this.setState(state => { const skipped = new Set(state.skipped.values()) skipped.add(activeStep) return { activeStep: state.activeStep + 1, skipped, } }) } handleReset = () => { this.setState({ activeStep: 0, }) } tryAgain = () => { this.setState({ activeStep: 2, }) } isStepSkipped(step) { return this.state.skipped.has(step) } render() { const { classes } = this.props const steps = getSteps() const { activeStep, canClaimEther, verified } = this.state const finalStep = activeStep === steps.length return ( <LayoutConnect canClaimEther={canClaimEther} verified={verified} finalStep={finalStep} activeStep={activeStep} > <SEO title="Home" keywords={['coinDrop', 'application', 'react']} /> <div className={classes.root}> <Grid container spacing={0} justify="center" alignItems="flex-start" className={classes.connectGrid} > <Grid item xs={10} sm={8} md={6} className={classNames( activeStep === 0 && classes.firstStepGrid, classes.subGrid )} > <Typography variant="h6" gutterBottom align="center" classes={{ root: classes.stepTitle }} > {this.getStepTitle(activeStep)} </Typography> <React.Fragment> {activeStep === steps.length ? ( <React.Fragment> {verified ? ( <StepFinal verified canClaimEther={canClaimEther} /> ) : ( <Paper className={classes.paperSorry} elevation={10} > <React.Fragment> <Typography variant="h2" gutterBottom align="center" > Sorry! </Typography> <Typography variant="subtitle2" gutterBottom align="center" > It seems that there was a problem and we couldn´t connect your account. </Typography> <Button variant="outlined" color="primary" onClick={this.tryAgain} > Try Again </Button> </React.Fragment> </Paper> )} </React.Fragment> ) : ( <Paper className={classes.paper} elevation={0} > <React.Fragment> {this.getStepContent(activeStep)} <Stepper activeStep={activeStep} classes={{ root: classes.stepper, }} > {steps.map((label, index) => { const props = {} if ( this.isStepSkipped( index ) ) { props.completed = false } return ( <Step key={label} {...props} > <StepLabel classes={{ root: classes.stepLabel, }} StepIconProps={{ classes: { root: classes.stepIcon, active: classes.stepIconActive, text: classes.stepIconText, completed: classes.stepIconActive, }, }} /> </Step> ) })} </Stepper> </React.Fragment> </Paper> )} {activeStep === 0 && ( <Link className={classes.itemLink} activeClassName="active" to="dashboard/home/" > <Button variant="text" color="primary"> Not Now </Button> </Link> )} </React.Fragment> </Grid> </Grid> </div> </LayoutConnect> ) } } Connect.propTypes = { classes: PropTypes.object.isRequired, } export default withStyles(styles)(Connect)
// Copyright 2019 SAP SE // // 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 recon import ( "time" "github.com/prometheus/client_golang/prometheus" ) // This value is overwritten in unit tests. var IsTest = false // TaskOpts holds common parameters that are used by all recon tasks. type TaskOpts struct { PathToExecutable string HostTimeout int CtxTimeout time.Duration } // GetTaskExitCodeGaugeVec returns a *prometheus.GaugeVec for use with recon tasks. func GetTaskExitCodeGaugeVec(r prometheus.Registerer) *prometheus.GaugeVec { gaugeVec := prometheus.NewGaugeVec( prometheus.GaugeOpts{ Name: "swift_recon_task_exit_code", Help: "The exit code for a Swift Recon query execution.", }, []string{"query"}, ) r.MustRegister(gaugeVec) return gaugeVec }
#!/usr/bin/env bash bash ./.travis/scripts/import-signing-key.sh echo 'Deploying artifacts' bash ./.travis/scripts/deploy-to-sonatype-ossrh.sh echo 'Deployed artifacts'
<?php namespace app\api\model; use think\Model; class Image extends BaseModel { protected $visible = ['url']; public function getImageDimensions($imageUrl) { $dimensions = getimagesize($imageUrl); return ['width' => $dimensions[0], 'height' => $dimensions[1]]; } }
package com.lothrazar.cyclicmagic.block.buttondoorbell; import java.util.List; import com.lothrazar.cyclicmagic.IContent; import com.lothrazar.cyclicmagic.data.IHasRecipe; import com.lothrazar.cyclicmagic.guide.GuideCategory; import com.lothrazar.cyclicmagic.registry.BlockRegistry; import com.lothrazar.cyclicmagic.registry.RecipeRegistry; import com.lothrazar.cyclicmagic.registry.SoundRegistry; import com.lothrazar.cyclicmagic.util.Const; import com.lothrazar.cyclicmagic.util.UtilChat; import com.lothrazar.cyclicmagic.util.UtilSound; import net.minecraft.block.BlockButton; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.item.crafting.IRecipe; import net.minecraft.util.EnumFacing; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.AxisAlignedBB; import net.minecraft.util.math.BlockPos; import net.minecraft.world.IBlockAccess; import net.minecraft.world.World; import net.minecraftforge.common.config.Configuration; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; public class BlockDoorbell extends BlockButton implements IHasRecipe, IContent { private static final double SIXLRG = 0.6875D; private static final double THREELRG = 0.255D; private static final double THREE_SMALL = 0.3125D; private static final double SIX = 0.745D; protected static final AxisAlignedBB AABB_DOWN_OFF = new AxisAlignedBB(THREE_SMALL, 0.875D, THREELRG, SIXLRG, 1.0D, SIX); protected static final AxisAlignedBB AABB_UP_OFF = new AxisAlignedBB(THREE_SMALL, 0.0D, THREELRG, SIXLRG, 0.125D, SIX); protected static final AxisAlignedBB AABB_NORTH_OFF = new AxisAlignedBB(THREE_SMALL, THREELRG, 0.875D, SIXLRG, SIX, 1.0D); protected static final AxisAlignedBB AABB_SOUTH_OFF = new AxisAlignedBB(THREE_SMALL, THREELRG, 0.0D, SIXLRG, SIX, 0.125D); protected static final AxisAlignedBB AABB_WEST_OFF = new AxisAlignedBB(0.875D, THREELRG, THREE_SMALL, 1.0D, SIX, SIXLRG); protected static final AxisAlignedBB AABB_EAST_OFF = new AxisAlignedBB(0.0D, THREELRG, THREE_SMALL, 0.125D, SIX, SIXLRG); protected static final AxisAlignedBB AABB_DOWN_ON = new AxisAlignedBB(THREE_SMALL, 0.9375D, THREELRG, SIXLRG, 1.0D, SIX); protected static final AxisAlignedBB AABB_UP_ON = new AxisAlignedBB(THREE_SMALL, 0.0D, THREELRG, SIXLRG, 0.0625D, SIX); protected static final AxisAlignedBB AABB_NORTH_ON = new AxisAlignedBB(THREE_SMALL, THREELRG, 0.9375D, SIXLRG, SIX, 1.0D); protected static final AxisAlignedBB AABB_SOUTH_ON = new AxisAlignedBB(THREE_SMALL, THREELRG, 0.0D, SIXLRG, SIX, 0.0625D); protected static final AxisAlignedBB AABB_WEST_ON = new AxisAlignedBB(0.9375D, THREELRG, THREE_SMALL, 1.0D, SIX, SIXLRG); protected static final AxisAlignedBB AABB_EAST_ON = new AxisAlignedBB(0.0D, THREELRG, THREE_SMALL, 0.0625D, SIX, SIXLRG); public BlockDoorbell() { super(false); } @Override public void register() { BlockRegistry.registerBlock(this, "doorbell_simple", GuideCategory.BLOCK); } private boolean enabled; @Override public boolean enabled() { return enabled; } @Override public void syncConfig(Configuration config) { enabled = config.getBoolean("doorbell", Const.ConfigCategory.content, true, Const.ConfigCategory.contentDefaultText); } @Override public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return 0; } @Override public int getStrongPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side) { return 0; } @Override public boolean canProvidePower(IBlockState state) { return false; } @Override @SideOnly(Side.CLIENT) public void addInformation(ItemStack stack, World playerIn, List<String> tooltip, net.minecraft.client.util.ITooltipFlag advanced) { tooltip.add(UtilChat.lang(this.getTranslationKey() + ".tooltip")); } @Override protected void playClickSound(EntityPlayer player, World worldIn, BlockPos pos) { UtilSound.playSound(player, pos, SoundRegistry.doorbell_mikekoenig, SoundCategory.BLOCKS, 0.5F); } @Override protected void playReleaseSound(World worldIn, BlockPos pos) {} @Override public AxisAlignedBB getBoundingBox(IBlockState state, IBlockAccess source, BlockPos pos) { EnumFacing enumfacing = state.getValue(FACING); boolean flag = state.getValue(POWERED).booleanValue(); switch (enumfacing) { case EAST: return flag ? AABB_EAST_ON : AABB_EAST_OFF; case WEST: return flag ? AABB_WEST_ON : AABB_WEST_OFF; case SOUTH: return flag ? AABB_SOUTH_ON : AABB_SOUTH_OFF; case NORTH: default: return flag ? AABB_NORTH_ON : AABB_NORTH_OFF; case UP: return flag ? AABB_UP_ON : AABB_UP_OFF; case DOWN: return flag ? AABB_DOWN_ON : AABB_DOWN_OFF; } } @Override public IRecipe addRecipe() { return RecipeRegistry.addShapedOreRecipe(new ItemStack(this), "b ", " n", 'b', Blocks.WOODEN_BUTTON, 'n', Blocks.NOTEBLOCK); } }
<?php $number1 = 5; $number2 = 10; if($number1 > $number2){ echo $number1; } else { echo $number2; } ?>
<filename>src/application/store/index.js //3rd party - redux and saga dependencies import createSagaMiddleWare from 'redux-saga'; import { createStore, applyMiddleware, compose } from 'redux'; //Application Imports import sagas from '../sagas'; import { reducers } from '../state'; const sagaMiddleWare = createSagaMiddleWare(); var store; //In development - expose redux to redux dev tools and assign the store to the window for debugging if (process.env.NODE_ENV === 'development') { const composeEnhancers = window && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose; store = createStore( reducers, composeEnhancers( applyMiddleware(sagaMiddleWare) ) ) window.store = store; } else { store = createStore( reducers, applyMiddleware(sagaMiddleWare) ) } sagaMiddleWare.run(sagas); export default store;
package evilcraft.items; import evilcraft.api.config.ItemConfig; /** * Config for the {@link InvertedPotentia}. * @author rubensworks * */ public class InvertedPotentiaConfig extends ItemConfig { /** * The unique instance. */ public static InvertedPotentiaConfig _instance; /** * Make a new instance. */ public InvertedPotentiaConfig() { super( true, "invertedPotentia", null, InvertedPotentia.class ); } }
<reponame>raiden101/eda let mongoose = require("mongoose"); let Schema = mongoose.Schema; const exam_morn_schema = new Schema({ date: Date, total_slot: Number, selected_members: { type: [String], defaut: [] } }); const morn_exams = mongoose.model("morn_exam", exam_morn_schema); module.exports = morn_exams;
import java.util.List; public class GetRoundsServerResource extends ServerResource implements GetRoundsResource { @Inject private RoundManager roundManager; @Inject private MyEntityManager entityManager; public ListRoundsResult getRounds(GymkhanaRequest request) { List<Round> rounds = roundManager.getRounds(); // Retrieve the list of rounds using RoundManager ListRoundsResult result = new ListRoundsResult(rounds); // Create a ListRoundsResult using the retrieved rounds return result; // Return the ListRoundsResult } }
<reponame>vaniot-s/sentry import React from 'react'; import styled from '@emotion/styled'; import {t} from 'app/locale'; import space from 'app/styles/space'; import {Deploy} from 'app/types'; import Tag from 'app/views/settings/components/tag'; import Link from 'app/components/links/link'; import {IconOpen} from 'app/icons'; import {stringifyQueryObject} from 'app/utils/tokenizeSearch'; import overflowEllipsis from 'app/styles/overflowEllipsis'; type Props = { deploy: Deploy; orgSlug?: string; version?: string; className?: string; }; const DeployBadge = ({deploy, orgSlug, version, className}: Props) => { const shouldLinkToIssues = !!orgSlug && !!version; const badge = ( <Badge className={className}> <Label>{deploy.environment}</Label> {shouldLinkToIssues && <Icon size="xs" />} </Badge> ); if (!shouldLinkToIssues) { return badge; } return ( <Link to={{ pathname: `/organizations/${orgSlug}/issues/`, query: { project: null, environment: deploy.environment, query: stringifyQueryObject({ query: [], release: [version!], }), }, }} title={t('Open in Issues')} > {badge} </Link> ); }; const Badge = styled(Tag)` background-color: ${p => p.theme.gray700}; color: ${p => p.theme.white}; font-size: ${p => p.theme.fontSizeSmall}; align-items: center; height: 20px; `; const Label = styled('span')` max-width: 100px; line-height: 20px; ${overflowEllipsis} `; const Icon = styled(IconOpen)` margin-left: ${space(0.5)}; flex-shrink: 0; `; export default DeployBadge;
import vtk x = [ -1.22396, -1.17188, -1.11979, -1.06771, -1.01562, -0.963542, -0.911458, -0.859375, -0.807292, -0.755208, -0.703125, -0.651042, -0.598958, -0.546875, -0.494792, -0.442708, -0.390625, -0.338542, -0.286458, -0.234375, -0.182292, -0.130209, -0.078125, -0.026042, 0.0260415, 0.078125, 0.130208, 0.182291, 0.234375, 0.286458, 0.338542, 0.390625, 0.442708, 0.494792, 0.546875, 0.598958, 0.651042, 0.703125, 0.755208, 0.807292, 0.859375, 0.911458, 0.963542, 1.01562, 1.06771, 1.11979, 1.17188] y = [ -1.25, -1.17188, -1.09375, -1.01562, -0.9375, -0.859375, -0.78125, -0.703125, -0.625, -0.546875, -0.46875, -0.390625, -0.3125, -0.234375, -0.15625, -0.078125, 0, 0.078125, 0.15625, 0.234375, 0.3125, 0.390625, 0.46875, 0.546875, 0.625, 0.703125, 0.78125, 0.859375, 0.9375, 1.01562, 1.09375, 1.17188, 1.25] z = [ 0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.75, 0.8, 0.9, 1, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.75, 1.8, 1.9, 2, 2.1, 2.2, 2.3, 2.4, 2.5, 2.6, 2.7, 2.75, 2.8, 2.9, 3, 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.75, 3.8, 3.9] # Create a rectilinear grid by defining three arrays specifying the # coordinates in the x-y-z directions. xCoords = vtk.vtkFloatArray() for i in x: xCoords.InsertNextValue(i) yCoords = vtk.vtkFloatArray() for i in y: yCoords.InsertNextValue(i) zCoords = vtk.vtkFloatArray() for i in z: zCoords.InsertNextValue(i) # The coordinates are assigned to the rectilinear grid. Make sure that # the number of values in each of the XCoordinates, YCoordinates, # and ZCoordinates is equal to what is defined in SetDimensions(). # rgrid = vtk.vtkRectilinearGrid() rgrid.SetDimensions(len(x), len(y), len(z)) rgrid.SetXCoordinates(xCoords) rgrid.SetYCoordinates(yCoords) rgrid.SetZCoordinates(zCoords) # Extract a plane from the grid to see what we've got. plane = vtk.vtkRectilinearGridGeometryFilter() plane.SetInputData(rgrid) plane.SetExtent(0, 46, 16, 16, 0, 43) rgridMapper = vtk.vtkPolyDataMapper() rgridMapper.SetInputConnection(plane.GetOutputPort()) wireActor = vtk.vtkActor() wireActor.SetMapper(rgridMapper) wireActor.GetProperty().SetRepresentationToWireframe() wireActor.GetProperty().SetColor(0, 0, 0) # Create the usual rendering stuff. renderer = vtk.vtkRenderer() renWin = vtk.vtkRenderWindow() renWin.AddRenderer(renderer) iren = vtk.vtkRenderWindowInteractor() iren.SetRenderWindow(renWin) renderer.AddActor(wireActor) renderer.SetBackground(1, 1, 1) renderer.ResetCamera() renderer.GetActiveCamera().Elevation(60.0) renderer.GetActiveCamera().Azimuth(30.0) renderer.GetActiveCamera().Zoom(1.0) renWin.SetSize(300, 300) # interact with data renWin.Render() iren.Start()
<reponame>mhs1314/allPay<filename>qht-modules/qht-api/src/main/java/com/qht/rest/AccountController.java<gh_stars>0 package com.qht.rest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.qht.biz.AccountBiz; import com.qht.entity.Account; @Controller @RequestMapping("account") public class AccountController extends APIBaseController<AccountBiz,Account>{ }
<filename>AtividadesSpringBoot/AtividadeHelloObjetivos/src/main/java/com/example/demo/controller/objetivosController.java package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/Objetivos") public class objetivosController { @GetMapping public String Objetivos() { return "Aprender a utilizar SpringBoot/SpringTool/MySQL direito"; } }
def merge_arrays(arr1, arr2): # Get the length of two arrays m = len(arr1) n = len(arr2) # Create an array to store the merged array mergedArray = [0] * (m + n) # Initialize two index values to keep track of # current index in first and second arrays i = 0 # for 1st array j = 0 # for 2nd array k = 0 # for merged array # Merge the smaller elements from both arrays # into merged array while i < m and j < n: # Pick the smaller element and put it into the # merged array if arr1[i] < arr2[j]: mergedArray[k] = arr1[i] i += 1 else: mergedArray[k] = arr2[j] j += 1 k += 1 # Copy the remaining elements of first array # into merged array while i < m: mergedArray[k] = arr1[i] i += 1 k += 1 # Copy the remaining elements of second array # into merged array while j < n: mergedArray[k] = arr2[j] j += 1 k += 1 return mergedArray arr1 = [1, 3, 5, 7] arr2 = [2, 4, 6, 8] mergedArray = merge_arrays(arr1, arr2) print(mergedArray)
<gh_stars>0 <!-- Copyright 2020 Kansaneläkelaitos 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 fi.kela.kanta.cda; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.configuration.Configuration; import org.apache.commons.configuration.ConfigurationException; import org.apache.commons.configuration.PropertiesConfiguration; public class MaarittelyKonfiguraatio { final private Map<String, MaarittelyLuokka> maarittelyt; /** * @param templateId * @return * @throws HL7Exception */ public MaarittelyLuokka haeMaarittelyLuokka(List<String> templateIds, String code) { MaarittelyLuokka luokka = MaarittelyLuokka.PUUTTUU; if ( (templateIds == null) || templateIds.isEmpty() ) { return luokka; } for (String templateId : templateIds) { MaarittelyLuokka seuraava = haeMaarittelyLuokka(templateId, code); if ( seuraava == MaarittelyLuokka.EI_TUETTU ) { return MaarittelyLuokka.EI_TUETTU; } else if ( seuraava == MaarittelyLuokka.TULEVA ) { if ( luokka == MaarittelyLuokka.PUUTTUU || luokka == MaarittelyLuokka.VANHA || luokka == MaarittelyLuokka.NYKYINEN ) { luokka = seuraava; } } else if ( seuraava == MaarittelyLuokka.VANHA ) { if ( luokka == MaarittelyLuokka.PUUTTUU || luokka == MaarittelyLuokka.NYKYINEN ) { luokka = seuraava; } } else if ( seuraava == MaarittelyLuokka.NYKYINEN && luokka == MaarittelyLuokka.PUUTTUU ) { luokka = seuraava; } } return luokka; } private MaarittelyLuokka haeMaarittelyLuokka(String templateId, String code) { if ( (templateId == null) || "".equals(templateId) ) { return MaarittelyLuokka.PUUTTUU; } if ( maarittelyt.containsKey(templateId + "..." + code) ) { return maarittelyt.get(templateId + "..." + code); } else if ( maarittelyt.containsKey(templateId) ) { return maarittelyt.get(templateId); } else { maarittelyt.put(templateId, MaarittelyLuokka.EI_TUETTU); return MaarittelyLuokka.EI_TUETTU; } } /** * @return */ public static MaarittelyKonfiguraatio lueKonfiguraatio() throws ConfigurationException { return new MaarittelyKonfiguraatio(); } @SuppressWarnings("unchecked") private MaarittelyKonfiguraatio() throws ConfigurationException { maarittelyt = new HashMap<String, MaarittelyLuokka>(); try { Configuration config = new PropertiesConfiguration("cda_template.properties"); Iterator<String> templateIds = (Iterator<String>) config.getKeys(); while (templateIds.hasNext()) { kasitteleTyyppi(config, templateIds.next()); } } catch (ConfigurationException e) { throw e; } } private void kasitteleTyyppi(Configuration config, String templateId) { MaarittelyLuokka luokka = MaarittelyLuokka.VANHA; for (String token : config.getStringArray(templateId)) { if ( (token == null) || "".equals(token) ) { continue; } token = token.trim().toUpperCase(); if ( "NYKYINEN".equals(token) ) { luokka = MaarittelyLuokka.NYKYINEN; } else if ( "TULEVA".equals(token) ) { luokka = MaarittelyLuokka.TULEVA; } else if ( "VANHA".equals(token) ) { luokka = MaarittelyLuokka.VANHA; } else if ( "EI_TUETTU".equals(token) ) { luokka = MaarittelyLuokka.EI_TUETTU; } else if ( "*".equals(token) ) { kasitteleKoodi(templateId, luokka); } else { kasitteleKoodi(templateId + "..." + token, luokka); } } } private void kasitteleKoodi(String templateIdKoodi, MaarittelyLuokka luokka) { if ( maarittelyt.containsKey(templateIdKoodi) ) { MaarittelyLuokka vanha = maarittelyt.get(templateIdKoodi); if ( vanha == MaarittelyLuokka.VANHA ) { maarittelyt.put(templateIdKoodi, luokka); } else if ( luokka == MaarittelyLuokka.EI_TUETTU ) { maarittelyt.put(templateIdKoodi, luokka); } else if ( (vanha == MaarittelyLuokka.TULEVA) && (luokka == MaarittelyLuokka.NYKYINEN) ) { maarittelyt.put(templateIdKoodi, luokka); } } else { maarittelyt.put(templateIdKoodi, luokka); } } }
// Add JQuery <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script> // Search keyword var query = "Hello World"; // Executing search and redirect to the search result page $(document).ready(function () { window.location.replace('https://www.google.com/search?q=' + query); });
#include "program.h" #include <memory> #include <stdexcept> #include "costs.h" #include "crypto_utils.h" #include "operator_lookup.h" #include "utils.h" namespace chia { uint8_t const MAX_SINGLE_BYTE = 0x7F; uint8_t const CONS_BOX_MARKER = 0xFF; /** * ============================================================================= * CLVMObject * ============================================================================= */ CLVMObject::CLVMObject(NodeType type) : type_(type) {} CLVMObject_Atom::CLVMObject_Atom(Bytes bytes) : CLVMObject(NodeType::Atom), bytes_(std::move(bytes)) {} Bytes CLVMObject_Atom::GetBytes() const { return bytes_; } CLVMObject_Pair::CLVMObject_Pair(CLVMObjectPtr first, CLVMObjectPtr second) : CLVMObject(NodeType::Pair), first_(first), second_(second) {} CLVMObjectPtr CLVMObject_Pair::GetFirstNode() const { return first_; } CLVMObjectPtr CLVMObject_Pair::GetSecondNode() const { return second_; } Bytes Atom(CLVMObjectPtr obj) { if (obj->GetNodeType() != NodeType::Atom) { throw std::runtime_error("it's not an ATOM"); } auto atom = static_cast<CLVMObject_Atom*>(obj.get()); return atom->GetBytes(); } std::tuple<CLVMObjectPtr, CLVMObjectPtr> Pair(CLVMObjectPtr obj) { if (obj->GetNodeType() != NodeType::Pair) { throw std::runtime_error("it's not a PAIR"); } auto pair = static_cast<CLVMObject_Pair*>(obj.get()); return std::make_tuple(pair->GetFirstNode(), pair->GetSecondNode()); } CLVMObjectPtr First(CLVMObjectPtr obj) { if (obj->GetNodeType() != NodeType::Pair) { throw std::runtime_error("it's not a PAIR"); } auto pair = static_cast<CLVMObject_Pair*>(obj.get()); return pair->GetFirstNode(); } CLVMObjectPtr Rest(CLVMObjectPtr obj) { if (obj->GetNodeType() != NodeType::Pair) { throw std::runtime_error("it's not a PAIR"); } auto pair = static_cast<CLVMObject_Pair*>(obj.get()); return pair->GetSecondNode(); } bool IsNull(CLVMObjectPtr obj) { if (obj->GetNodeType() != NodeType::Atom) { return false; } CLVMObject_Atom* atom = static_cast<CLVMObject_Atom*>(obj.get()); Bytes bytes = atom->GetBytes(); return bytes.empty(); } int ListLen(CLVMObjectPtr list) { int count{0}; while (list->GetNodeType() == NodeType::Pair) { ++count; std::tie(std::ignore, list) = Pair(list); } return count; } /** * ============================================================================= * Op: SExp * ============================================================================= */ CLVMObjectPtr ToSExp(Bytes bytes) { return CLVMObjectPtr(new CLVMObject_Atom(std::move(bytes))); } CLVMObjectPtr ToSExp(CLVMObjectPtr first, CLVMObjectPtr second) { return CLVMObjectPtr(new CLVMObject_Pair(first, second)); } CLVMObjectPtr ToTrue() { return ToSExp(utils::ByteToBytes('\1')); } CLVMObjectPtr ToFalse() { return ToSExp(Bytes()); } bool ListP(CLVMObjectPtr obj) { return obj->GetNodeType() == NodeType::Pair; } int ArgsLen(CLVMObjectPtr obj) { int len{0}; while (obj->GetNodeType() == NodeType::Pair) { auto [a, r] = Pair(obj); if (a->GetNodeType() != NodeType::Atom) { throw std::runtime_error("requires in args"); } // Next len += Atom(a).size(); obj = r; } return len; } std::tuple<bool, Bytes, CLVMObjectPtr> ArgsNext(CLVMObjectPtr obj) { if (obj->GetNodeType() != NodeType::Pair) { return std::make_tuple(false, Bytes(), CLVMObjectPtr()); } auto [b, next] = Pair(obj); Bytes bytes = Atom(b); return std::make_tuple(true, bytes, next); } std::tuple<Cost, CLVMObjectPtr> MallocCost(Cost cost, CLVMObjectPtr atom) { return std::make_tuple(cost + Atom(atom).size() * MALLOC_COST_PER_BYTE, atom); } std::vector<std::tuple<Int, int>> ListInts(CLVMObjectPtr args) { ArgsIter iter(args); std::vector<std::tuple<Int, int>> res; while (!iter.IsEof()) { int l; Int r = iter.NextInt(&l); res.push_back(std::make_tuple(r, l)); } return res; } std::vector<Bytes> ListBytes(CLVMObjectPtr args) { std::vector<Bytes> res; ArgsIter iter(args); while (!iter.IsEof()) { res.push_back(iter.Next()); } return res; } /** * ============================================================================= * SExp Stream * ============================================================================= */ namespace stream { class OpStack; using Op = std::function<void(OpStack&, ValStack&, StreamReadFunc&)>; class OpStack : public Stack<Op> {}; class StreamReader { public: explicit StreamReader(Bytes const& bytes) : bytes_(bytes) {} Bytes operator()(int size) const { Bytes res; int read_size = std::min<std::size_t>(size, bytes_.size() - pos_); if (read_size == 0) { return res; } res.resize(read_size); memcpy(res.data(), bytes_.data() + pos_, read_size); pos_ += read_size; return res; } private: Bytes const& bytes_; mutable int pos_{0}; }; CLVMObjectPtr AtomFromStream(StreamReadFunc f, uint8_t b) { if (b == 0x80) { return ToSExp(Bytes()); } if (b <= MAX_SINGLE_BYTE) { return ToSExp(utils::ByteToBytes(b)); } int bit_count{0}; int bit_mask{0x80}; while (b & bit_mask) { bit_count += 1; b &= 0xff ^ bit_mask; bit_mask >>= 1; } Bytes size_blob = utils::ByteToBytes(b); if (bit_count > 1) { Bytes b = f(bit_count - 1); if (b.size() != bit_count - 1) { throw std::runtime_error("bad encoding"); } size_blob = utils::ConnectBuffers(size_blob, b); } uint64_t size = Int(size_blob).ToUInt(); // TODO The size might overflow if (size >= 0x400000000) { throw std::runtime_error("blob too large"); } Bytes blob = f(size); if (blob.size() != size) { throw std::runtime_error("bad encoding"); } return ToSExp(blob); } void OpCons(OpStack& op_stack, ValStack& val_stack, StreamReadFunc& f) { auto right = val_stack.Pop(); auto left = val_stack.Pop(); val_stack.Push(ToSExp(left, right)); } void OpReadSExp(OpStack& op_stack, ValStack& val_stack, StreamReadFunc& f) { Bytes blob = f(1); if (blob.empty()) { throw std::runtime_error("bad encoding"); } uint8_t b = blob[0]; if (b == CONS_BOX_MARKER) { op_stack.Push(OpCons); op_stack.Push(OpReadSExp); op_stack.Push(OpReadSExp); return; } val_stack.Push(AtomFromStream(f, b)); } CLVMObjectPtr SExpFromStream(ReadStreamFunc f) { OpStack op_stack; op_stack.Push(OpReadSExp); ValStack val_stack; while (!op_stack.IsEmpty()) { auto func = op_stack.Pop(); func(op_stack, val_stack, f); } return val_stack.Pop(); } } // namespace stream /** * ============================================================================= * Tree hash * ============================================================================= */ namespace tree_hash { class OpStack; using Op = std::function<void(Stack<CLVMObjectPtr>&, OpStack&)>; class OpStack : public Stack<Op> {}; Bytes32 SHA256TreeHash( CLVMObjectPtr sexp, std::vector<Bytes> const& precalculated = std::vector<Bytes>()) { Op handle_pair = [](ValStack& sexp_stack, OpStack& op_stack) { auto p0 = sexp_stack.Pop(); auto p1 = sexp_stack.Pop(); Bytes prefix = utils::ByteToBytes('\2'); sexp_stack.Push(ToSExp(utils::bytes_cast<32>(crypto_utils::MakeSHA256( utils::ConnectBuffers(prefix, Atom(p0), Atom(p1)))))); }; Op roll = [](ValStack& sexp_stack, OpStack& op_stack) { auto p0 = sexp_stack.Pop(); auto p1 = sexp_stack.Pop(); sexp_stack.Push(p0); sexp_stack.Push(p1); }; Op handle_sexp = [&handle_sexp, &handle_pair, &roll, &precalculated]( ValStack& sexp_stack, OpStack& op_stack) { auto sexp = sexp_stack.Pop(); if (sexp->GetNodeType() == NodeType::Pair) { auto [p0, p1] = Pair(sexp); sexp_stack.Push(p0); sexp_stack.Push(p1); op_stack.Push(handle_pair); op_stack.Push(handle_sexp); op_stack.Push(roll); op_stack.Push(handle_sexp); } else { Bytes atom = Atom(sexp); auto i = std::find(std::begin(precalculated), std::end(precalculated), atom); Bytes r; if (i != std::end(precalculated)) { r = atom; } else { Bytes prefix = utils::ByteToBytes('\1'); r = utils::bytes_cast<32>( crypto_utils::MakeSHA256(utils::ConnectBuffers(prefix, atom))); } sexp_stack.Push(ToSExp(r)); } }; ValStack sexp_stack; sexp_stack.Push(sexp); OpStack op_stack; op_stack.Push(handle_sexp); while (!op_stack.IsEmpty()) { auto op = op_stack.Pop(); op(sexp_stack, op_stack); } assert(!sexp_stack.IsEmpty()); auto res = sexp_stack.Pop(); assert(sexp_stack.IsEmpty()); assert(res->GetNodeType() == NodeType::Atom); return utils::bytes_cast<32>(Atom(res)); } } // namespace tree_hash /** * ============================================================================= * Program * ============================================================================= */ Program Program::ImportFromBytes(Bytes const& bytes) { Program prog; prog.sexp_ = stream::SExpFromStream(stream::StreamReader(bytes)); return prog; } Program Program::LoadFromFile(std::string_view file_path) { std::string prog_hex = utils::LoadHexFromFile(file_path); Bytes prog_bytes = utils::BytesFromHex(prog_hex); return ImportFromBytes(prog_bytes); } Bytes32 Program::GetTreeHash() { return tree_hash::SHA256TreeHash(sexp_); } uint8_t MSBMask(uint8_t byte) { byte |= byte >> 1; byte |= byte >> 2; byte |= byte >> 4; return (byte + 1) >> 1; } namespace run { class OpStack; using Op = std::function<int(OpStack&, ValStack&)>; class OpStack : public Stack<Op> {}; std::tuple<int, CLVMObjectPtr> RunProgram(CLVMObjectPtr program, CLVMObjectPtr args, OperatorLookup const& operator_lookup, Cost max_cost) { auto traverse_path = [](CLVMObjectPtr sexp, CLVMObjectPtr env) -> std::tuple<int, CLVMObjectPtr> { Cost cost{PATH_LOOKUP_BASE_COST}; cost += PATH_LOOKUP_COST_PER_LEG; if (IsNull(sexp)) { return std::make_tuple(cost, CLVMObjectPtr()); } Bytes b = Atom(sexp); int end_byte_cursor{0}; while (end_byte_cursor < b.size() && b[end_byte_cursor] == 0) { ++end_byte_cursor; } cost += end_byte_cursor * PATH_LOOKUP_COST_PER_ZERO_BYTE; if (end_byte_cursor == b.size()) { return std::make_tuple(cost, CLVMObjectPtr()); } int end_bitmask = MSBMask(b[end_byte_cursor]); int byte_cursor = b.size() - 1; int bitmask = 0x01; while (byte_cursor > end_byte_cursor || bitmask < end_bitmask) { if (env->GetNodeType() != NodeType::Pair) { throw std::runtime_error("path into atom {env}"); } auto [first, rest] = Pair(env); env = (b[byte_cursor] & bitmask) ? rest : first; cost += PATH_LOOKUP_COST_PER_LEG; bitmask <<= 1; if (bitmask == 0x100) { --byte_cursor; bitmask = 0x01; } } return std::make_tuple(cost, env); }; Op swap_op, cons_op, eval_op, apply_op; swap_op = [&apply_op](OpStack& op_stack, ValStack& val_stack) -> int { auto v2 = val_stack.Pop(); auto v1 = val_stack.Pop(); val_stack.Push(v2); val_stack.Push(v1); return 0; }; cons_op = [](OpStack& op_stack, ValStack& val_stack) -> int { auto v1 = val_stack.Pop(); auto v2 = val_stack.Pop(); val_stack.Push(ToSExp(v1, v2)); return 0; }; eval_op = [traverse_path, &operator_lookup, &apply_op, &cons_op, &eval_op, &swap_op](OpStack& op_stack, ValStack& val_stack) -> int { auto [sexp, args] = Pair(val_stack.Pop()); if (sexp->GetNodeType() != NodeType::Pair) { auto [cost, r] = traverse_path(sexp, args); val_stack.Push(r); return cost; } auto [opt, sexp_rest] = Pair(sexp); if (opt->GetNodeType() == NodeType::Pair) { auto [new_opt, must_be_nil] = Pair(opt); if (new_opt->GetNodeType() == NodeType::Pair || !IsNull(must_be_nil)) { throw std::runtime_error("syntax X must be lone atom"); } auto new_operand_list = sexp_rest; val_stack.Push(new_opt); val_stack.Push(new_operand_list); op_stack.Push(apply_op); return APPLY_COST; } Bytes op = Atom(opt); auto operand_list = sexp_rest; if (op == operator_lookup.QUOTE_ATOM) { val_stack.Push(operand_list); return QUOTE_COST; } op_stack.Push(apply_op); val_stack.Push(opt); while (!IsNull(operand_list)) { auto [_, r] = Pair(operand_list); val_stack.Push(ToSExp(_, args)); op_stack.Push(cons_op); op_stack.Push(eval_op); op_stack.Push(swap_op); operand_list = r; } val_stack.Push(CLVMObjectPtr()); return 1; }; apply_op = [&operator_lookup, &eval_op](OpStack& op_stack, ValStack& val_stack) -> int { auto operand_list = val_stack.Pop(); auto opt = val_stack.Pop(); if (opt->GetNodeType() == NodeType::Pair) { throw std::runtime_error("internal error"); } Bytes op = Atom(opt); if (op == operator_lookup.APPLY_ATOM) { if (ListLen(operand_list) != 2) { throw std::runtime_error("apply requires exactly 2 parameters"); } auto [new_program, r] = Pair(operand_list); CLVMObjectPtr new_args; std::tie(new_args, std::ignore) = Pair(r); val_stack.Push(ToSExp(new_program, new_args)); op_stack.Push(eval_op); return APPLY_COST; } auto [additional_cost, r] = operator_lookup(op, operand_list); val_stack.Push(r); return additional_cost; }; OpStack op_stack; op_stack.Push(eval_op); ValStack val_stack; val_stack.Push(ToSExp(program, args)); Cost cost{0}; while (!op_stack.IsEmpty()) { auto f = op_stack.Pop(); cost += f(op_stack, val_stack); if (max_cost && cost > max_cost) { throw std::runtime_error("cost exceeded"); } } return std::make_tuple(cost, val_stack.GetLast()); } } // namespace run std::tuple<int, CLVMObjectPtr> Program::Run( CLVMObjectPtr args, OperatorLookup const& operator_lookup, Cost max_cost) { return run::RunProgram(sexp_, args, operator_lookup, max_cost); } } // namespace chia
// -!- C++ -!- ////////////////////////////////////////////////////////////// // // System : // Module : // Object Name : $RCSfile$ // Revision : $Revision$ // Date : $Date$ // Author : $Author$ // Created By : <NAME> // Created : Sun Feb 17 15:35:50 2019 // Last Modified : <190219.1354> // // Description // // Notes // // History // ///////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2019 <NAME> D/B/A Deepwoods Software // 51 Locke Hill Road // Wendell, MA 01379-9728 // // 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., 675 Mass Ave, Cambridge, MA 02139, USA. // // // ////////////////////////////////////////////////////////////////////////////// static const char rcsid[] = "@(#) : $Id$"; #include "PWMTest.hxx" #include "utils/ConfigUpdateListener.hxx" #include "utils/ConfigUpdateService.hxx" #include "openlcb/EventService.hxx" ConfigUpdateListener::UpdateAction ConfiguredPWMConsumer::apply_configuration(int fd, bool initial_load, BarrierNotifiable *done) { AutoNotify n(done); openlcb::EventId cfg_pwm_zero_event = config.event_pwm_zero().read(fd); openlcb::EventId cfg_pwm_one_event = config.event_pwm_one().read(fd); openlcb::EventId cfg_pwm_two_event = config.event_pwm_two().read(fd); openlcb::EventId cfg_pwm_three_event = config.event_pwm_three().read(fd); openlcb::EventId cfg_pwm_four_event = config.event_pwm_four().read(fd); openlcb::EventId cfg_pwm_five_event = config.event_pwm_five().read(fd); openlcb::EventId cfg_pwm_six_event = config.event_pwm_six().read(fd); openlcb::EventId cfg_pwm_seven_event = config.event_pwm_seven().read(fd); openlcb::EventId cfg_pwm_eight_event = config.event_pwm_eight().read(fd); openlcb::EventId cfg_pwm_nine_event = config.event_pwm_nine().read(fd); openlcb::EventId cfg_pwm_ten_event = config.event_pwm_ten().read(fd); period = config.pwm_period().read(fd); pwm_->set_period(period); zero_duty = config.pwm_zero().read(fd); one_duty = config.pwm_one().read(fd); two_duty = config.pwm_two().read(fd); three_duty = config.pwm_three().read(fd); four_duty = config.pwm_four().read(fd); five_duty = config.pwm_five().read(fd); six_duty = config.pwm_six().read(fd); seven_duty = config.pwm_seven().read(fd); eight_duty = config.pwm_eight().read(fd); nine_duty = config.pwm_nine().read(fd); ten_duty = config.pwm_ten().read(fd); if (cfg_pwm_zero_event != pwm_zero_event || cfg_pwm_one_event != pwm_one_event || cfg_pwm_two_event != pwm_two_event || cfg_pwm_three_event != pwm_three_event || cfg_pwm_four_event != pwm_four_event || cfg_pwm_five_event != pwm_five_event || cfg_pwm_six_event != pwm_six_event || cfg_pwm_seven_event != pwm_seven_event || cfg_pwm_eight_event != pwm_eight_event || cfg_pwm_nine_event != pwm_nine_event || cfg_pwm_ten_event != pwm_ten_event) { if (!initial_load) unregister_handler(); pwm_zero_event = cfg_pwm_zero_event; pwm_one_event = cfg_pwm_one_event; pwm_two_event = cfg_pwm_two_event; pwm_three_event = cfg_pwm_three_event; pwm_four_event = cfg_pwm_four_event; pwm_five_event = cfg_pwm_five_event; pwm_six_event = cfg_pwm_six_event; pwm_seven_event = cfg_pwm_seven_event; pwm_eight_event = cfg_pwm_eight_event; pwm_nine_event = cfg_pwm_nine_event; pwm_ten_event = cfg_pwm_ten_event; register_handler(); return REINIT_NEEDED; // Causes events identify. } return UPDATED; } void ConfiguredPWMConsumer::factory_reset(int fd) { config.description().write(fd,""); CDI_FACTORY_RESET(config.pwm_period); CDI_FACTORY_RESET(config.pwm_zero); CDI_FACTORY_RESET(config.pwm_one); CDI_FACTORY_RESET(config.pwm_two); CDI_FACTORY_RESET(config.pwm_three); CDI_FACTORY_RESET(config.pwm_four); CDI_FACTORY_RESET(config.pwm_five); CDI_FACTORY_RESET(config.pwm_six); CDI_FACTORY_RESET(config.pwm_seven); CDI_FACTORY_RESET(config.pwm_eight); CDI_FACTORY_RESET(config.pwm_nine); CDI_FACTORY_RESET(config.pwm_ten); } void ConfiguredPWMConsumer::handle_event_report(const EventRegistryEntry &entry, EventReport *event, BarrierNotifiable *done) { if (event->event == pwm_zero_event) { pwm_->set_duty(zero_duty); } else if (event->event == pwm_one_event) { pwm_->set_duty(one_duty); } else if (event->event == pwm_two_event) { pwm_->set_duty(two_duty); } else if (event->event == pwm_three_event) { pwm_->set_duty(three_duty); } else if (event->event == pwm_four_event) { pwm_->set_duty(four_duty); } else if (event->event == pwm_five_event) { pwm_->set_duty(five_duty); } else if (event->event == pwm_six_event) { pwm_->set_duty(six_duty); } else if (event->event == pwm_seven_event) { pwm_->set_duty(seven_duty); } else if (event->event == pwm_eight_event) { pwm_->set_duty(eight_duty); } else if (event->event == pwm_nine_event) { pwm_->set_duty(nine_duty); } else if (event->event == pwm_ten_event) { pwm_->set_duty(ten_duty); } done->notify(); } void ConfiguredPWMConsumer::handle_identify_global(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { if (event->dst_node && event->dst_node != node_) { done->notify(); } SendAllConsumersIdentified(event,done); done->maybe_done(); } void ConfiguredPWMConsumer::SendAllConsumersIdentified(openlcb::EventReport* event, BarrierNotifiable* done) { openlcb::Defs::MTI mti_zero = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_one = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_two = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_three = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_four = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_five = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_six = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_seven = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_eight = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_nine = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID, mti_ten = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID; uint32_t current_duty_cycle = /* pwm_->get_duty() */ 0; if (current_duty_cycle == zero_duty) { mti_zero = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == one_duty) { mti_one = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == two_duty) { mti_two = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == three_duty) { mti_three = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == four_duty) { mti_four = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == five_duty) { mti_five = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == six_duty) { mti_six = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == seven_duty) { mti_seven = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == eight_duty) { mti_eight = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == nine_duty) { mti_nine = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (current_duty_cycle == ten_duty) { mti_ten = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } write_helpers[0].WriteAsync(node_,mti_zero, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_zero_event), done->new_child()); write_helpers[1].WriteAsync(node_,mti_one, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_one_event), done->new_child()); write_helpers[2].WriteAsync(node_,mti_two, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_two_event), done->new_child()); write_helpers[3].WriteAsync(node_,mti_three, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_three_event), done->new_child()); write_helpers[4].WriteAsync(node_,mti_four, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_four_event), done->new_child()); write_helpers[5].WriteAsync(node_,mti_five, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_five_event), done->new_child()); write_helpers[6].WriteAsync(node_,mti_six, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_six_event), done->new_child()); write_helpers[7].WriteAsync(node_,mti_seven, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_seven_event), done->new_child()); write_helpers[8].WriteAsync(node_,mti_eight, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_eight_event), done->new_child()); write_helpers[9].WriteAsync(node_,mti_nine, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_nine_event), done->new_child()); write_helpers[10].WriteAsync(node_,mti_ten, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(pwm_ten_event), done->new_child()); } void ConfiguredPWMConsumer::handle_identify_consumer(const EventRegistryEntry &registry_entry, EventReport *event, BarrierNotifiable *done) { SendConsumerIdentified(event,done); done->maybe_done(); } void ConfiguredPWMConsumer::SendConsumerIdentified(openlcb::EventReport* event, BarrierNotifiable* done) { openlcb::Defs::MTI mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_INVALID; uint32_t current_duty_cycle = /* pwm_->get_duty() */ 0; if (event->event == pwm_zero_event && current_duty_cycle == zero_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_one_event && current_duty_cycle == one_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_two_event && current_duty_cycle == two_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_three_event && current_duty_cycle == three_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_four_event && current_duty_cycle == four_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_five_event && current_duty_cycle == five_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_six_event && current_duty_cycle == six_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_seven_event && current_duty_cycle == seven_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_eight_event && current_duty_cycle == eight_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_nine_event && current_duty_cycle == nine_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else if (event->event == pwm_ten_event && current_duty_cycle == ten_duty) { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_VALID; } else { mti = openlcb::Defs::MTI_CONSUMER_IDENTIFIED_UNKNOWN; } event->event_write_helper<1>()->WriteAsync(node_, mti, openlcb::WriteHelper::global(), openlcb::eventid_to_buffer(event->event), done->new_child()); } void ConfiguredPWMConsumer::register_handler() { openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_zero_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_one_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_two_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_three_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_four_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_five_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_six_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_seven_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_eight_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_nine_event),0); openlcb::EventRegistry::instance()->register_handler( openlcb::EventRegistryEntry(this,pwm_ten_event),0); } void ConfiguredPWMConsumer::unregister_handler() { openlcb::EventRegistry::instance()->unregister_handler(this); }
#!/bin/bash # # This script will duplicate an installed clusterdeployment for testing purposes. # The duplicated cluster will have a generated name that starts with the name # of the original clusterdeployment followed by "-dup" # set -e usage(){ echo "Usage: $0 [CLUSTERDEPLOYMENT_NAMESPACE/]CLUSTERDEPLOYMENT_NAME [COUNT]" exit 1 } # Get the name and namespace for the clusterdeployment to duplicate. CD_NAME_ARG=${1?missing ClusterDeployment name} CD_NAME_ARR=(${CD_NAME_ARG//// }) case ${#CD_NAME_ARR[@]} in 1) CD_NAME=${CD_NAME_ARR[0]} ;; 2) CD_NAMESPACE=${CD_NAME_ARR[0]} CD_NAME=${CD_NAME_ARR[1]} ;; *) echo "Could not determine namespace and name of ClusterDeployment" usage ;; esac # Get the duplication count COUNT=${2:-1} if [[ "${COUNT}" -le 0 ]] then echo "COUNT must be a positive integer: ${COUNT}" usage exit 1 fi echo "Duplicating ${CD_NAMESPACE}${CD_NAMESPACE:+/}${CD_NAME} ${COUNT} times" # Argument to supply to oc commands to provide the namespace. This is empty if # the user did not specify a namespace. NAMESPACE_ARG="${CD_NAMESPACE:+--namespace }${CD_NAMESPACE}" # Get the clusterdeployment to duplicate. CD=$(oc get cd ${NAMESPACE_ARG} ${CD_NAME} -ojson) # Ensure that the cluster has been installed. if [ "$(echo ${CD} | jq .spec.installed)" != "true" ] then echo "Cluster is not installed" exit 1 fi # Get the clusterprovision to duplicate. PROV=$(oc get clusterprovision ${NAMESPACE_ARG} $(echo ${CD} | jq -r .status.provision.name) -ojson) # Create the json for the new clusterdeployment. NEW_CD=$(echo ${CD} | jq \ 'del(.status) | .metadata|={ "namespace":.namespace, "generateName":.name, "labels":{"hive.openshift.io/duplicated-from":.name}} | .metadata.generateName|=.+"-dup-" | .spec.installed=true | .spec.manageDNS=false | .spec.preserveOnDelete=true | .spec.certificateBundles[]?.generate=false') # Create the json for the new clusterprovision, without the name or UID of the clusterdeployment. NEW_PROV_BASE=$(echo ${PROV} | jq \ 'del(.status) | .metadata|={ "namespace":.namespace, "ownerReferences":(.ownerReferences | select(.[].controller=true)), "labels":{"hive.openshift.io/duplicated-from":.name}} | .spec.stage="complete" | del(.spec.podSpec) | del(.spec.attempt)') for (( i=0; i<${COUNT}; i++ )) do # Create the new clusterdeployment, and save the name of the new clusterdeployment. CD_CREATE_OUTPUT=$(echo $NEW_CD | oc create -f -) echo ${CD_CREATE_OUTPUT} CD_CREATE_OUTPUT_ARR=(${CD_CREATE_OUTPUT//// }) NEW_CD_NAME=${CD_CREATE_OUTPUT_ARR[1]} # Get the UID of the new clusterdeployment. NEW_CD_UID=$(oc get cd ${NAMESPACE_ARG} ${NEW_CD_NAME} -ojsonpath={.metadata.uid}) # Fill out the clusterdeployment name and UID for the new clusterprovision. NEW_PROV=$(echo ${NEW_PROV_BASE} | jq \ --arg name "${NEW_CD_NAME}" \ --arg cd_uid "${NEW_CD_UID}" \ '.metadata.name=$name | .metadata.ownerReferences[0].name=$name | .metadata.ownerReferences[0].uid=$cd_uid | .metadata.labels|=.+{"hive.openshift.io/cluster-deployment-name": $name}') # Create the new clusterprovision. echo $NEW_PROV | oc create -f - done
/* * smart-doc * * Copyright (C) 2018-2020 smart-doc * * 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.power.doc.utils; import com.power.common.util.CollectionUtil; import com.power.common.util.StringUtil; import com.power.doc.constants.DocAnnotationConstants; import com.power.doc.constants.DocValidatorAnnotationEnum; import com.power.doc.constants.ValidatorAnnotations; import com.power.doc.model.DocJavaField; import com.thoughtworks.qdox.model.*; import com.thoughtworks.qdox.model.expression.AnnotationValue; import com.thoughtworks.qdox.model.expression.AnnotationValueList; import com.thoughtworks.qdox.model.expression.Expression; import com.thoughtworks.qdox.model.expression.TypeRef; import com.thoughtworks.qdox.model.impl.DefaultJavaField; import com.thoughtworks.qdox.model.impl.DefaultJavaParameterizedType; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.*; /** * Handle JavaClass * * @author yu 2019/12/21. */ public class JavaClassUtil { /** * Get fields * * @param cls1 The JavaClass object * @param counter Recursive counter * @param addedFields added fields,Field deduplication * @return list of JavaField */ public static List<DocJavaField> getFields(JavaClass cls1, int counter, Set<String> addedFields) { List<DocJavaField> fieldList = new ArrayList<>(); if (null == cls1) { return fieldList; } else if ("Object".equals(cls1.getSimpleName()) || "Timestamp".equals(cls1.getSimpleName()) || "Date".equals(cls1.getSimpleName()) || "Locale".equals(cls1.getSimpleName()) || "ClassLoader".equals(cls1.getSimpleName()) || JavaClassValidateUtil.isMap(cls1.getFullyQualifiedName())) { return fieldList; } else { String className = cls1.getFullyQualifiedName(); if (cls1.isInterface() && !JavaClassValidateUtil.isCollection(className) && !JavaClassValidateUtil.isMap(className)) { List<JavaMethod> methods = cls1.getMethods(); for (JavaMethod javaMethod : methods) { String methodName = javaMethod.getName(); int paramSize = javaMethod.getParameters().size(); boolean enable = false; if (methodName.startsWith("get") && !"get".equals(methodName) && paramSize == 0) { methodName = StringUtil.firstToLowerCase(methodName.substring(3, methodName.length())); enable = true; } else if (methodName.startsWith("is") && !"is".equals(methodName) && paramSize == 0) { methodName = StringUtil.firstToLowerCase(methodName.substring(2, methodName.length())); enable = true; } if (!enable) { continue; } addedFields.add(methodName); String comment = javaMethod.getComment(); JavaField javaField = new DefaultJavaField(javaMethod.getReturns(), methodName); DocJavaField docJavaField = DocJavaField.builder() .setJavaField(javaField) .setComment(comment) .setDocletTags(javaMethod.getTags()) .setAnnotations(javaMethod.getAnnotations()); fieldList.add(docJavaField); } } // ignore enum parent class if (!cls1.isEnum()) { JavaClass parentClass = cls1.getSuperJavaClass(); fieldList.addAll(getFields(parentClass, counter, addedFields)); List<JavaType> implClasses = cls1.getImplements(); for (JavaType type : implClasses) { JavaClass javaClass = (JavaClass) type; fieldList.addAll(getFields(javaClass, counter, addedFields)); } } List<DocJavaField> docJavaFields = new ArrayList<>(); for (JavaField javaField : cls1.getFields()) { String fieldName = javaField.getName(); if (addedFields.contains(fieldName)) { continue; } addedFields.add(fieldName); docJavaFields.add(DocJavaField.builder().setComment(javaField.getComment()).setJavaField(javaField)); } fieldList.addAll(docJavaFields); } return fieldList; } /** * get enum value * * @param javaClass enum class * @param formDataEnum is return method * @return Object */ public static Object getEnumValue(JavaClass javaClass, boolean formDataEnum) { List<JavaField> javaFields = javaClass.getEnumConstants(); List<JavaMethod> methodList = javaClass.getMethods(); int annotation = 0; for (JavaMethod method : methodList) { if (method.getAnnotations().size() > 0) { annotation = 1; break; } } Object value = null; int index = 0; for (JavaField javaField : javaFields) { String simpleName = javaField.getType().getSimpleName(); StringBuilder valueBuilder = new StringBuilder(); valueBuilder.append("\"").append(javaField.getName()).append("\"").toString(); if (!JavaClassValidateUtil.isPrimitive(simpleName) && index < 1) { if (!CollectionUtil.isEmpty(javaField.getEnumConstantArguments())) { value = javaField.getEnumConstantArguments().get(0); } else { value = valueBuilder.toString(); } } index++; } return value; } public static String getEnumParams(JavaClass javaClass) { List<JavaField> javaFields = javaClass.getEnumConstants(); StringBuilder stringBuilder = new StringBuilder(); for (JavaField javaField : javaFields) { List<Expression> exceptions = javaField.getEnumConstantArguments(); stringBuilder.append(javaField.getName()); //如果枚举值不为空 if (!CollectionUtil.isEmpty(exceptions)) { stringBuilder.append(" -("); for (int i = 0; i < exceptions.size(); i++) { stringBuilder.append(exceptions.get(i)); if (i != exceptions.size() - 1) { stringBuilder.append(","); } } stringBuilder.append(")"); } stringBuilder.append("<br/>"); } return stringBuilder.toString(); } /** * Get annotation simpleName * * @param annotationName annotationName * @return String */ public static String getAnnotationSimpleName(String annotationName) { return getClassSimpleName(annotationName); } /** * Get className * * @param className className * @return String */ public static String getClassSimpleName(String className) { if (className.contains(".")) { int index = className.lastIndexOf("."); className = className.substring(index + 1, className.length()); } if (className.contains("[")) { int index = className.indexOf("["); className = className.substring(0, index); } return className; } /** * get Actual type * * @param javaClass JavaClass * @return JavaClass */ public static JavaClass getActualType(JavaClass javaClass) { return getActualTypes(javaClass).get(0); } /** * get Actual type list * * @param javaClass JavaClass * @return JavaClass */ public static List<JavaClass> getActualTypes(JavaClass javaClass) { if (null == javaClass) { return new ArrayList<>(0); } List<JavaClass> javaClassList = new ArrayList<>(); List<JavaType> actualTypes = ((DefaultJavaParameterizedType) javaClass).getActualTypeArguments(); actualTypes.forEach(javaType -> { JavaClass actualClass = (JavaClass) javaType; javaClassList.add(actualClass); }); return javaClassList; } /** * Obtain Validate Group classes * * @param annotations the annotations of controller method param * @return the group annotation value */ public static List<String> getParamGroupJavaClass(List<JavaAnnotation> annotations) { if (CollectionUtil.isEmpty(annotations)) { return new ArrayList<>(0); } List<String> javaClassList = new ArrayList<>(); List<String> validates = DocValidatorAnnotationEnum.listValidatorAnnotations(); for (JavaAnnotation javaAnnotation : annotations) { List<AnnotationValue> annotationValueList = getAnnotationValues(validates, javaAnnotation); addGroupClass(annotationValueList, javaClassList); } return javaClassList; } /** * Obtain Validate Group classes * * @param javaAnnotation the annotation of controller method param * @return the group annotation value */ public static List<String> getParamGroupJavaClass(JavaAnnotation javaAnnotation) { if (Objects.isNull(javaAnnotation)) { return new ArrayList<>(0); } List<String> javaClassList = new ArrayList<>(); List<String> validates = DocValidatorAnnotationEnum.listValidatorAnnotations(); List<AnnotationValue> annotationValueList = getAnnotationValues(validates, javaAnnotation); addGroupClass(annotationValueList, javaClassList); String simpleAnnotationName = javaAnnotation.getType().getValue(); // add default group if (javaClassList.size() == 0 && JavaClassValidateUtil.isJSR303Required(simpleAnnotationName)) { javaClassList.add("javax.validation.groups.Default"); } return javaClassList; } /** * 通过name获取类标签的value * * @param cls 类 * @param tagName 需要获取的标签name * @param checkComments 检查注释 * @return 类标签的value * @author songhaozhi */ public static String getClassTagsValue(final JavaClass cls, final String tagName, boolean checkComments) { if (StringUtil.isNotEmpty(tagName)) { StringBuilder result = new StringBuilder(); List<DocletTag> tags = cls.getTags(); for (int i = 0; i < tags.size(); i++) { if (!tagName.equals(tags.get(i).getName())) { continue; } String value = tags.get(i).getValue(); if (StringUtil.isEmpty(value) && checkComments) { throw new RuntimeException("ERROR: #" + cls.getName() + "() - bad @" + tagName + " javadoc from " + cls.getName() + ", must be add comment if you use it."); } if (tagName.equals(tags.get(i).getName())) { if (i != 0) { result.append(","); } result.append(value); } } return result.toString(); } return null; } /** * Get Map of final field and value * * @param clazz Java class * @return Map * @throws IllegalAccessException IllegalAccessException */ public static Map<String, String> getFinalFieldValue(Class<?> clazz) throws IllegalAccessException { String className = getClassSimpleName(clazz.getName()); Field[] fields = clazz.getDeclaredFields(); Map<String, String> constants = new HashMap<>(); for (Field field : fields) { boolean isFinal = Modifier.isFinal(field.getModifiers()); if (isFinal) { String name = field.getName(); constants.put(className + "." + name, String.valueOf(field.get(null))); } } return constants; } private static void addGroupClass(List<AnnotationValue> annotationValueList, List<String> javaClassList) { if (CollectionUtil.isEmpty(annotationValueList)) { return; } for (int i = 0; i < annotationValueList.size(); i++) { TypeRef annotationValue = (TypeRef) annotationValueList.get(i); DefaultJavaParameterizedType annotationValueType = (DefaultJavaParameterizedType) annotationValue.getType(); javaClassList.add(annotationValueType.getGenericCanonicalName()); } } private static List<AnnotationValue> getAnnotationValues(List<String> validates, JavaAnnotation javaAnnotation) { List<AnnotationValue> annotationValueList = null; String simpleName = javaAnnotation.getType().getValue(); if (simpleName.equalsIgnoreCase(ValidatorAnnotations.VALIDATED)) { if (Objects.nonNull(javaAnnotation.getProperty(DocAnnotationConstants.VALUE_PROP))) { AnnotationValue v = javaAnnotation.getProperty(DocAnnotationConstants.VALUE_PROP); if (v instanceof AnnotationValueList) { annotationValueList = ((AnnotationValueList) v).getValueList(); } if (v instanceof TypeRef) { annotationValueList = new ArrayList<>(); annotationValueList.add(v); } } } else if (validates.contains(simpleName)) { if (Objects.nonNull(javaAnnotation.getProperty(DocAnnotationConstants.GROUP_PROP))) { AnnotationValue v = javaAnnotation.getProperty(DocAnnotationConstants.GROUP_PROP); if (v instanceof AnnotationValueList) { annotationValueList = ((AnnotationValueList) v).getValueList(); } if (v instanceof TypeRef) { annotationValueList = new ArrayList<>(); annotationValueList.add(v); } } } return annotationValueList; } }
import { sonarTypes } from "../constants/action-types" const initialState = ({ sonarToken: localStorage.getItem('sonarToken') ? localStorage.getItem('sonarToken') : null, username: localStorage.getItem('sonarUsername') ? localStorage.getItem('sonarUsername') : null, projects: [], measure: null, }) export const sonarReducer = (state = initialState, action) => { switch(action.type){ case(sonarTypes.SONAR_LOGIN): return { ...state, username: action.payload } case(sonarTypes.SONAR_CLEAN): return { ...state, projects: [] } case(sonarTypes.SET_SONAR_TOKEN): return { ...state, sonarToken: action.payload } case(sonarTypes.SONAR_SET_PROJECTS): return { ...state, projects: [ ...state.projects , action.payload] } default: return state; } }
package io.opensphere.core.viewer.control; import java.awt.event.InputEvent; import io.opensphere.core.math.Vector2i; import io.opensphere.core.math.Vector3d; import io.opensphere.core.util.MathUtil; import io.opensphere.core.util.ref.VolatileReference; import io.opensphere.core.viewer.impl.DynamicViewer; import io.opensphere.core.viewer.impl.Viewer2D; import io.opensphere.core.viewer.impl.Viewer2D.ViewerPosition2D; /** * Translate raw mouse events into viewer movements. */ @SuppressWarnings("PMD.GodClass") public class Viewer2DControlTranslator extends AbstractViewerControlTranslator { /** * The amount zoom input is multiplied by to determine the change in scale. */ private static final double ZOOM_FACTOR = .05; /** True when the controls are enabled and false when they are not. */ private boolean myControlEnabled = true; /** * Construct a Viewer2DControlTranslator. * * @param viewer The viewer to manipulate. */ public Viewer2DControlTranslator(VolatileReference<DynamicViewer> viewer) { super(viewer); } @Override public boolean canAdjustViewer(Vector2i from, Vector2i to) { return true; } @Override public void compoundMoveAxisDrag(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundMoveAxisEnd(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundMoveAxisStart(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundViewPitchDrag(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundViewPitchEnd(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundViewPitchStart(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundViewYawDrag(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundViewYawEnd(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void compoundViewYawStart(InputEvent event) { // Not Applicable to this map type (2d) } @Override public synchronized void moveView(double deltaX, double deltaY) { if (!myControlEnabled) { return; } ViewerPosition2D viewPosition = getViewer().getPosition(); double modelWidth = getViewer().getModelWidth(); double modelHeight = getViewer().getModelHeight(); double stretchFactor = getViewer().getStretchFactor(); Vector3d location = new Vector3d( viewPosition.getLocation().getX() - deltaX / getViewer().getViewportWidth() * modelWidth / (stretchFactor > 1. ? stretchFactor : 1.) / getViewer().getScale(), viewPosition.getLocation().getY() + deltaY / getViewer().getViewportHeight() * modelHeight * (stretchFactor < 1. ? stretchFactor : 1.) / getViewer().getScale(), 0.); getViewer().setPosition(new ViewerPosition2D(location, getViewer().getScale())); } @Override public void moveView(Vector2i from, Vector2i to) { if (!myControlEnabled) { return; } int dx = to.getX() - from.getX(); int dy = to.getY() - from.getY(); moveView(dx, dy); } @Override public void moveViewAxes(double deltaX, double deltaY) { } @Override public void moveViewAxes(Vector2i from, Vector2i to) { } @Override public void moveYawAxis(double deltaX, double deltaY) { } @Override public void moveYawAxis(Vector2i from, Vector2i to) { } @Override public void pitchView(double angleRads) { } @Override public void pitchView(Vector2i from, Vector2i to) { } @Override public void pitchViewDown(InputEvent event) { pitchView(1f); } @Override public void pitchViewUp(InputEvent event) { pitchView(-1f); } @Override public void resetView(InputEvent event) { // Not Applicable to this map type (2d) } @Override public void rollView(double angleRads) { } @Override public void rollView(Vector2i from, Vector2i to) { } @Override public void rollViewLeft(InputEvent event) { rollView(1f); } @Override public void rollViewRight(InputEvent event) { rollView(-1f); } @Override public void setControlEnabled(boolean enable) { myControlEnabled = enable; } @Override public void spinOnAxis(double angleRads) { // Not implemented for this map type } @Override public void spinOnAxis(double angleRads, Vector3d spinAxis) { // Not implemented for this map type } @Override public void viewDown(InputEvent event, boolean microMovement) { if (!myControlEnabled) { return; } int yMove = microMovement ? -1 : -10; moveView(new Vector2i(0, 0), new Vector2i(0, yMove)); } @Override public void viewLeft(InputEvent event, boolean microMovement) { if (!myControlEnabled) { return; } int xMove = microMovement ? 1 : 10; moveView(new Vector2i(0, 0), new Vector2i(xMove, 0)); } @Override public void viewRight(InputEvent event, boolean microMovement) { if (!myControlEnabled) { return; } int xMove = microMovement ? -1 : -10; moveView(new Vector2i(0, 0), new Vector2i(xMove, 0)); } @Override public void viewUp(InputEvent event, boolean microMovement) { if (!myControlEnabled) { return; } int yMove = microMovement ? 1 : 10; moveView(new Vector2i(0, 0), new Vector2i(0, yMove)); } @Override public void yawView(double angleRads) { } @Override public void yawView(Vector2i from, Vector2i to) { } @Override public void yawViewLeft(InputEvent event) { yawView(-1f); } @Override public void yawViewRight(InputEvent event) { yawView(1f); } @Override public void zoomView(double amount) { if (!myControlEnabled) { return; } double newScale = getViewer().getScale() * Math.pow(2, amount * ZOOM_FACTOR); if (Math.abs(newScale - getViewer().getScale()) > MathUtil.DBL_EPSILON) { ViewerPosition2D viewPosition = getViewer().getPosition(); getViewer().setPosition(new ViewerPosition2D(viewPosition.getLocation(), newScale)); } } @Override protected Viewer2D getViewer() { return (Viewer2D)super.getViewer(); } }
<reponame>MickaelSERENO/SciVis_Android package com.sereno.vfv.Data; import android.graphics.Bitmap; import com.sereno.vfv.Data.Annotation.DrawableAnnotationPosition; import com.sereno.view.AnnotationCanvasData; import com.sereno.vfv.Data.TF.TransferFunction; import java.util.ArrayList; import java.util.List; public class SubDataset implements TransferFunction.ITransferFunctionListener { public static final int VISIBILITY_PUBLIC = 1; public static final int VISIBILITY_PRIVATE = 0; public static final int TRANSFER_FUNCTION_NONE = 0; public static final int TRANSFER_FUNCTION_GTF = 1; public static final int TRANSFER_FUNCTION_TGTF = 2; public static final int TRANSFER_FUNCTION_MERGE = 3; /** Callback interface called when the SubDataset is modified*/ public interface ISubDatasetListener { /** Method called when a new rotation on the current SubDataset is performed * @param dataset the dataset being rotated * @param quaternion the quaternion rotation*/ void onRotationEvent(SubDataset dataset, float[] quaternion); /** Method called when a translation on the current SubDataset is performed * @param dataset the dataset being rotated * @param position the new 3D position*/ void onPositionEvent(SubDataset dataset, float[] position); /** Method called when a new scaling on the current SubDataset is performed * @param dataset the dataset being rotated * @param scale the new scaling factors*/ void onScaleEvent(SubDataset dataset, float[] scale); /** Method called when a new snapshot on the current SubDataset is performed * @param dataset the dataset creating a new snapshot * @param snapshot the snapshot created*/ void onSnapshotEvent(SubDataset dataset, Bitmap snapshot); /** Method called when a new canvas annotation has been added to this SubDataset * @param dataset the dataset receiving a new annotation * @param annotation the annotation added*/ void onAddCanvasAnnotation(SubDataset dataset, AnnotationCanvasData annotation); /** Method called when a SubDataset is being removed * @param dataset the subdataset being removed*/ void onRemove(SubDataset dataset); /** Method called when a canvas annotation is being removed from the SubDataset * @param dataset the dataset bound to the annotation * @param annotation the annotation being removed*/ void onRemoveCanvasAnnotation(SubDataset dataset, AnnotationCanvasData annotation); /** Method called when the SubDataset transfer function has been updated * @param dataset the dataset that has been updated*/ void onUpdateTF(SubDataset dataset); /** Method called when the headset ID locking this SubDataset has changed * @param dataset the dataset calling this method * @param headsetID the new headset ID. -1 == no headset ID*/ void onSetCurrentHeadset(SubDataset dataset, int headsetID); /** Method called when the headset ID owning this SubDataset has changed * @param dataset the dataset calling this method * @param headsetID the new headset ID. -1 == public SubDataset*/ void onSetOwner(SubDataset dataset, int headsetID); /** Method called when the modificability status of this SubDataset has changed * @param dataset the dataset calling this method * @param status true if the subdataset can be modified, false otherwise*/ void onSetCanBeModified(SubDataset dataset, boolean status); /** Method called when the visibility of map associated to subdataset instance has changed * @param dataset the dataset calling this method * @param visibility the new visibility (true == visible, false == invisible)*/ void onSetMapVisibility(SubDataset dataset, boolean visibility); /** Method called when the volumetric mask associated to a SubDataset has changed * @param dataset the dataset calling this method*/ void onSetVolumetricMask(SubDataset dataset); /** Method called when a DrawableAnnotationPosition has been added to a subdataset * @param dataset the object calling this method * @param pos the drawable object added to this subdataset*/ void onAddDrawableAnnotationPosition(SubDataset dataset, DrawableAnnotationPosition pos); /** Method called when the depth clipping value has been set * @param dataset the object calling this method * @param minClipping the new min depth clipping value (clamped between 0.0f and 1.0f) * @param maxClipping the new max depth clipping value (clamped between 0.0f and 1.0f)*/ void onSetDepthClipping(SubDataset dataset, float minClipping, float maxClipping); /** Method called when the subdataset group this subdataset belongs to has changed * @param dataset the object calling this method * @param group the new subdataset group owning this subdataset*/ void onSetSubDatasetGroup(SubDataset dataset, SubDatasetGroup group); /** Method called when the subdataset name has changed * @param dataset the object calling this method * @param name the new name to apply*/ void onRename(SubDataset dataset, String name); } /** The native C++ handle*/ protected long m_ptr; /** The parent dataset*/ private Dataset m_parent; /** The subdataset group this subdataset belongs to*/ private SubDatasetGroup m_sdg = null; /** List of listeners bound to this SubDataset*/ private List<ISubDatasetListener> m_listeners = new ArrayList<>(); /** List of canvas annotations bound to this SubDataset*/ private List<AnnotationCanvasData> m_annotationCanvases = new ArrayList<>(); /** List of registered positional annotations bound to this SubDataset*/ private List<DrawableAnnotationPosition> m_annotationPositions = new ArrayList<>(); /** The current headset owning this subdataset. -1 == public subDataset*/ private int m_ownerHeadsetID = -1; /** The current headset modifying this subdataset. -1 == no one is modifying this subdataset*/ private int m_currentHeadsetID = -1; /** The current transfer function this object uses*/ private TransferFunction m_tf = null; /** Tells whether this application can modify or not this SubDataset*/ private boolean m_canBeModified = true; /** Is the map activaed? Works only for VTK Datasets*/ private boolean m_mapActivated = true; /** Constructor. Link the Java object with the C++ native SubDataset object * @param ptr the native C++ pointer * @param parent the java object Dataset parent * @param ownerID the headset ID owning this SubDataset. -1 == public SubDataset*/ public SubDataset(long ptr, Dataset parent, int ownerID) { m_ptr = ptr; m_parent = parent; m_ownerHeadsetID = ownerID; setTransferFunction(null); } @Override public Object clone() { if(m_ptr == 0) return null; return new SubDataset(nativeClone(m_ptr), m_parent, m_ownerHeadsetID); } /** Create a new SubDataset from basic information. It still needs to be attached to the parent afterward * @param parent the parent of this SubDataset * @param id the ID of this SubDataset * @param name the name of this SubDataset * @param ownerID the headset ID owning this SubDataset. -1 == public SubDataset * @return the newly created SubDataset. It is not automatically added to the parent though.*/ static public SubDataset createNewSubDataset(Dataset parent, int id, String name, int ownerID) { return new SubDataset(nativeCreateNewSubDataset(parent.getPtr(), id, name), parent, ownerID); } /** Add a new callback Listener * @param listener the listener to call for new events*/ public void addListener(ISubDatasetListener listener) { m_listeners.add(listener); } /** Remove an old callback Listener * @param listener the listener to remove from the list*/ public void removeListener(ISubDatasetListener listener) { m_listeners.remove(listener); } /** Tells whether this SubDataset is in a valid state or not * @return true if in a valid state, false otherwise*/ public boolean isValid() { if(m_ptr == 0) return false; return nativeIsValid(m_ptr); } /** Get a snapshot of this SubDataset in the main rendering object * @return the snapshot of the subdataset*/ public Bitmap getSnapshot() { if(m_ptr == 0) return null; return nativeGetSnapshot(m_ptr); } /** Get the rotation quaternion components. In order: w, i, j, k * @return the rotation quaternion components*/ public float[] getRotation() { if(m_ptr == 0) return null; return nativeGetRotation(m_ptr); } /** Get the 3D position components. In order: x, y, z * @return the position quaternion components*/ public float[] getPosition() { if(m_ptr == 0) return null; return nativeGetPosition(m_ptr); } /** Get the 3D scaling components. In order: x, y, z * @return the 3D scaling components*/ public float[] getScale() { if(m_ptr == 0) return null; return nativeGetScale(m_ptr); } /** Get the max depth clipping value clamped between 0.0f (totally clipped) and 1.0f (no clipping at all) * @return the depth clipping value*/ public float getMaxDepthClipping() { if(m_ptr == 0) return -1; return nativeGetMaxDepthClipping(m_ptr); } /** Get the min depth clipping value clamped between 0.0f (totally clipped) and 1.0f (no clipping at all) * @return the depth clipping value*/ public float getMinDepthClipping() { if(m_ptr == 0) return -1; return nativeGetMinDepthClipping(m_ptr); } /** Set the depth clipping value. Values are clamped between 0.0f (totally clipped) and 1.0f (no clipping at all) * @param d the max depth clipping value. */ public void setDepthClipping(float min, float max) { if(m_ptr == 0) return; else if(min != getMinDepthClipping() || max != getMaxDepthClipping()) { nativeSetDepthClipping(m_ptr, min, max); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetDepthClipping(this, min, max); } } /** Get the native pointer of the SubDataset * @return the native pointer*/ public long getNativePtr() { return m_ptr; } /** Function called frm C++ code when a new snapshot has been created * @param bmp the new bitmap snapshot*/ public void onSnapshotEvent(Bitmap bmp) { for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSnapshotEvent(this, bmp); } /** Set the rotation of this SubDataset * @param quaternion the new rotation to apply (w, x, y, z)*/ public void setRotation(float[] quaternion) { if(m_ptr == 0) return; nativeSetRotation(m_ptr, quaternion); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onRotationEvent(this, quaternion); } /** Set the position of this SubDataset * @param position the new position to apply*/ public void setPosition(float[] position) { if(m_ptr == 0) return; nativeSetPosition(m_ptr, position); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onPositionEvent(this, position); } /** Set the scaling of this SubDataset * @param scale the new scale to apply*/ public void setScale(float[] scale) { if(m_ptr == 0) return; nativeSetScale(m_ptr, scale); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onScaleEvent(this, scale); } public void setVolumetricMask(byte[] mask) { if(m_ptr == 0) return; nativeSetVolumetricMask(m_ptr, mask); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetVolumetricMask(this); } /** Reset the volumetric mask to false*/ public void resetVolumetricMask() { if(m_ptr == 0) return; nativeResetVolumetricMask(m_ptr); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetVolumetricMask(this); } /** Enable/Disable the volumetric mask * @param b true to enable the volumetric mask, false otherwise*/ public void enableVolumetricMask(boolean b) { if(m_ptr == 0) return; nativeEnableVolumetricMask(m_ptr, b); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetVolumetricMask(this); } /** Get whether the volumetric mask is enabled or not * @return true if yes, false otherwise*/ public boolean isVolumetricMaskEnabled() { return nativeIsVolumetricMaskEnabled(m_ptr); } /** Get the SubDataset name * @return the SubDataset name*/ public String getName() { if(m_ptr == 0) return ""; return nativeGetName(m_ptr); } /** Set the SubDataset name * @param name the new name to apply*/ public void setName(String name) { if(m_ptr == 0) return; if(!name.equals(getName())) { nativeSetName(m_ptr, name); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onRename(this, name); } } /** Get the SubDataset ID * @return the SubDataset ID*/ public int getID() { if(m_ptr == 0) return -1; return nativeGetID(m_ptr); } /** Get the parent dataset * @return the parent dataset*/ public Dataset getParent() {return m_parent;} /** Get the ID of the Headset owning this SubDataset. -1 == public SubDataset * @return the headset ID as defined by the application (server)*/ public int getOwnerID() {return m_ownerHeadsetID;} /** Get the boolean status telling whether or not this SubDataset can be modified by this client * @return true if yes, false otherwise. Pay attention that this variable is regarding this SubDataset states on the running server*/ public boolean getCanBeModified() {return m_canBeModified;} /** Set the boolean status telling whether or not this SubDataset can be modified by this client * @param value true if yes, false otherwise. Pay attention that this variable is regarding this SubDataset states on the running server*/ public void setCanBeModified(boolean value) { if (value != m_canBeModified) { m_canBeModified = value; for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetCanBeModified(this, value); } } /** Set the headset ID currently modifying/locking this subdataset * @param hmdID the headset ID to use. -1 == no owner*/ public void setCurrentHeadset(int hmdID) { if(hmdID != m_currentHeadsetID) { m_currentHeadsetID = hmdID; for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetCurrentHeadset(this, hmdID); } } /** Set the ID of the Headset owning this SubDataset. -1 == public SubDataset * @param id the new headset ID as defined by the application (server)*/ public void setOwnerID(int id) { if(id != m_ownerHeadsetID) { m_ownerHeadsetID = id; for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetOwner(this, id); } } /** Get the headset ID currently modifying/locking this subdataset * @return the current headset ID locking this subdataset. -1 == no owner*/ public int getCurrentHeadset() { return m_currentHeadsetID; } /** Set the transfer function to use for this object. * @param tf the model transfer function to use*/ public void setTransferFunction(TransferFunction tf) { int tfType = SubDataset.TRANSFER_FUNCTION_NONE; if(m_tf != tf) { if(m_tf != null) m_tf.removeListener(this); if(tf != null) tf.addListener(this); } long tfPtr = 0; if(tf != null) { tfType = tf.getType(); tfPtr = tf.getNativeTransferFunction(); } nativeSetTF(m_ptr, tfType, tfPtr); m_tf = tf; for (int j = 0; j < m_listeners.size(); j++) m_listeners.get(j).onUpdateTF(this); } /** Get the bound transfer function to this SubDataset * @return the transfer function being used*/ public TransferFunction getTransferFunction() { return m_tf; } /** Get the type of the bound transfer function to this SubDataset * @return the transfer function type being used. Return TRANSFER_FUNCTION_NONE is getTransferFunction() == null*/ public int getTransferFunctionType() { if(m_tf != null) return m_tf.getType(); return SubDataset.TRANSFER_FUNCTION_NONE; } /** Add a new annotation * @param annot the annotation to add*/ public void addAnnotation(AnnotationCanvasData annot) { m_annotationCanvases.add(annot); for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onAddCanvasAnnotation(this, annot); } /** Get the list of annotations * @return the list of annotations. Please, do not modify the list (list item can however be modified)*/ public List<AnnotationCanvasData> getAnnotations() { return m_annotationCanvases; } /** unlink the SubDataset*/ public void inRemoving() { /* Remove the annotation*/ while(m_annotationCanvases.size() > 0) removeCanvasAnnotation(m_annotationCanvases.get(m_annotationCanvases.size()-1)); Object[] listeners = m_listeners.toArray(); //Do a copy because on "onRemove", objects may want to get removed from the list of listeners for(int i = 0; i < listeners.length; i++) ((ISubDatasetListener)listeners[i]).onRemove(this); m_ptr = 0; } /** Remove a canvas annotation from this SubDataset * @param annot the annotation to remove. This function does nothing if the annotation cannot be found*/ public void removeCanvasAnnotation(AnnotationCanvasData annot) { if(m_annotationCanvases.contains(annot)) { for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onRemoveCanvasAnnotation(this, annot); m_annotationCanvases.remove(annot); } } /** Set whether or not the map rendered below the 3D visualization in the headset should be rendered or not * @param visible true if yes, false otherwise*/ public void setMapVisibility(boolean visible) { if(visible != m_mapActivated) { m_mapActivated = visible; for(int i = 0; i < m_listeners.size(); i++) m_listeners.get(i).onSetMapVisibility(this, visible); } } /** Get whether or not the map rendered below the 3D visualization in the headset should be rendered or not * @return visible true if yes, false otherwise*/ public boolean getMapVisibility() { return m_mapActivated; } /** Link an Drawable AnnotationPosition to this object * @param pos the drawable to link with*/ public void addAnnotationPosition(DrawableAnnotationPosition pos) { m_annotationPositions.add(pos); nativeAddAnnotationPosition(m_ptr, pos.getPtr()); for(ISubDatasetListener l : m_listeners) l.onAddDrawableAnnotationPosition(this, pos); } /** Get the list of all linked drawable AnnotationPosition objects * @return a list of DrawableAnnotationPosition link to this SubDataset*/ public List<DrawableAnnotationPosition> getAnnotationPositions() { return m_annotationPositions; } void setSubDatasetGroup(SubDatasetGroup sdg) { if(m_sdg != null) m_sdg.removeSubDataset(this); m_sdg = sdg; } public SubDatasetGroup getSubDatasetGroup() { return m_sdg; } public void finalize() { if(m_ptr == 0) return; nativeDelPtr(m_ptr); } @Override public void onUpdateTransferFunction(TransferFunction tf) { setTransferFunction(tf); } /** Create a new SubDataset native C++ ptr * @param datasetPtr the dataset native C++ pointer * @param id the SubDataset ID * @param name the SubDataset name*/ private static native long nativeCreateNewSubDataset(long datasetPtr, int id, String name); /** Free the resources allocated for the native C++ pointer data * @param ptr the native C++ pointer data to free*/ private native void nativeDelPtr(long ptr); /** Native code clonning a current SubDataset * @param ptr the native pointer to clone * @return the new native pointer cloned*/ private native int nativeClone(long ptr); /** Native code telling is this SubDataset is in a valid state * @param ptr the native pointer * @return true if in a valid state, false otherwise*/ private native boolean nativeIsValid(long ptr); /** Native code to get a snapshot of this SubDataset in the main rendering object * @param ptr the native pointer * @return the snapshot of the subdataset*/ private native Bitmap nativeGetSnapshot(long ptr); /** Get the rotation quaternion components. In order: w, i, j, k * @param ptr the native pointer * @return the rotation quaternion components*/ private native float[] nativeGetRotation(long ptr); /** Set the rotation quaternion components. In order: w, i, j, k * @param ptr the native pointer * @param q the quaternion rotation*/ private native void nativeSetRotation(long ptr, float[] q); /** Get the 3D position components. In order: x, y, z * @param ptr the native pointer * @return the 3D position vector*/ private native float[] nativeGetPosition(long ptr); /** Set the 3D position components. In order: x, y, z * @param ptr the native pointer * @param p the 3D position vector*/ private native void nativeSetPosition(long ptr, float[] p); /** Get the 3D scale components. In order: x, y, z * @param ptr the native pointer * @return the 3D scale vector*/ private native float[] nativeGetScale(long ptr); /** Set the 3D scale components. In order: x, y, z * @param ptr the native pointer * @param s the 3D scale vector*/ private native void nativeSetScale(long ptr, float[] s); /** Set the transfer function model of the native C++ SD object * @param ptr the native pointer * @param tfType the new transfer function type * @param tfPtr the transfer function ptr to apply*/ private native void nativeSetTF(long ptr, int tfType, long tfPtr); /** Set the volumetric mask of the native C++ SD object * @param ptr the native pointer * @param mask the new mask to apply*/ private native void nativeSetVolumetricMask(long ptr, byte[] mask); /** Reset the volumetric mask of the native C++ SD object to false * @param ptr the native pointer*/ private native void nativeResetVolumetricMask(long ptr); /** Enable/Disable the volumetric mask of the native C++ SD object * @param ptr the native pointer * @param isEnabled true to enable the volumetric mask, false otherwise*/ private native void nativeEnableVolumetricMask(long ptr, boolean isEnabled); /** Get the min depth clipping value used on the native C++ SD object * @param ptr the native pointer*/ private native float nativeGetMinDepthClipping(long ptr); /** Get the max depth clipping value used on the native C++ SD object * @param ptr the native pointer*/ private native float nativeGetMaxDepthClipping(long ptr); /** Set the depth clipping value to use for the native C++ SD object * @param ptr the native pointer * @param min the new min depth clipping value to apply * @param max the new max depth clipping value to apply*/ private native void nativeSetDepthClipping(long ptr, float min, float max); /** Native code to set the Gaussian Transfer Function ranges * pIDs, minVals, and maxVals should be coherent (same size and correspond to each one) * @param ptr the native pointer * @param tfType the transfer function type * @param pIDs the list of pIDs * @param centers the list of centers normalized * @param scales the list of scales normalized*/ private native void nativeSetGTFRanges(long ptr, int tfType, int[] pIDs, float[] centers, float[] scales); /** Native code to get the SubDataset name * @param ptr the native pointer * @return the SubDataset name*/ private native String nativeGetName(long ptr); /** Native code to set the SubDataset name * @param ptr the native pointer * @param name the new SubDataset name*/ private native void nativeSetName(long ptr, String name); /** Native code to get the SubDataset ID * @param ptr the native pointer * @return the SubDataset id*/ private native int nativeGetID(long ptr); /** Native code to add an annotation position object * @param ptr the native pointer of the subdataset * @param annotPtr a std::shared<DrawableAnnotationPosition> (or derived) native C++ pointer*/ private native void nativeAddAnnotationPosition(long ptr, long annotPtr); private native boolean nativeIsVolumetricMaskEnabled(long ptr); }
package ar.com.tandilweb.ApiServer.rests; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import ar.com.tandilweb.ApiServer.dataTypesObjects.friends.FriendList; import ar.com.tandilweb.ApiServer.dataTypesObjects.friends.FriendRequests; import ar.com.tandilweb.ApiServer.dataTypesObjects.generic.GeneralResponse; import ar.com.tandilweb.ApiServer.dataTypesObjects.generic.ValidationException; import ar.com.tandilweb.ApiServer.transport.FriendsAdapter; @RestController @RequestMapping("/friends") public class Friends { @Autowired FriendsAdapter friendsAdapter; @RequestMapping(path="", method=RequestMethod.GET) public ResponseEntity<FriendList> getFriends() { FriendList out = new FriendList(); try { out.friends = friendsAdapter.getFriends(0); // from ME out.operationSuccess = true; return new ResponseEntity<FriendList>(out, HttpStatus.OK); } catch (ValidationException e) { out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = e.getIdECode(); return new ResponseEntity<FriendList>(out, HttpStatus.BAD_REQUEST); } catch (Exception e) { out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = -1; return new ResponseEntity<FriendList>(out, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(path="/{id}", method=RequestMethod.DELETE) public ResponseEntity<GeneralResponse> deleteFriends(@PathVariable("id") int friendID) { try { if(friendID <= 0) { throw new ValidationException(1, "Invalid friend id"); } friendsAdapter.deleteFriend(0, friendID); GeneralResponse out = new GeneralResponse(); out.operationSuccess = true; return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (ValidationException e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = e.getIdECode(); return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (Exception e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = -1; return new ResponseEntity<GeneralResponse>(out, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(path="/requests", method=RequestMethod.GET) public ResponseEntity<FriendRequests> getFriendsRequest() { FriendRequests out = new FriendRequests(); try { out.requests = friendsAdapter.getFriendRequests(0); // from ME return new ResponseEntity<FriendRequests>(out, HttpStatus.OK); } catch (ValidationException e) { out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = e.getIdECode(); return new ResponseEntity<FriendRequests>(out, HttpStatus.BAD_REQUEST); } catch (Exception e) { out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = -1; return new ResponseEntity<FriendRequests>(out, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(path="/requests/{id}", method=RequestMethod.DELETE) public ResponseEntity<GeneralResponse> rejectFriendsRequest(@PathVariable("id") int userID) { try { if(userID <= 0) { throw new ValidationException(1, "Invalid request id"); } friendsAdapter.deleteFriend(0, userID); GeneralResponse out = new GeneralResponse(); out.operationSuccess = true; return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (ValidationException e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = e.getIdECode(); return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (Exception e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = -1; return new ResponseEntity<GeneralResponse>(out, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(path="/requests/{id}", method=RequestMethod.PUT) public ResponseEntity<GeneralResponse> acceptFriendsRequest(@PathVariable("id") int requestID) { try { if(requestID <= 0) { throw new ValidationException(1, "Invalid request id"); } friendsAdapter.acceptRequest(0, requestID); GeneralResponse out = new GeneralResponse(); out.operationSuccess = true; return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (ValidationException e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = e.getIdECode(); return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (Exception e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = -1; return new ResponseEntity<GeneralResponse>(out, HttpStatus.INTERNAL_SERVER_ERROR); } } @RequestMapping(path="/requests/{id}", method=RequestMethod.POST) public ResponseEntity<GeneralResponse> sendFriendsRequest(@PathVariable("id") int userID) { try { if(userID <= 0) { throw new ValidationException(1, "Invalid user id"); } friendsAdapter.sendRequest(0, userID); GeneralResponse out = new GeneralResponse(); out.operationSuccess = true; return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (ValidationException e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = e.getIdECode(); return new ResponseEntity<GeneralResponse>(out, HttpStatus.BAD_REQUEST); } catch (Exception e) { GeneralResponse out = new GeneralResponse(); out.operationSuccess = false; out.errorDescription = e.getMessage(); out.errorCode = -1; return new ResponseEntity<GeneralResponse>(out, HttpStatus.INTERNAL_SERVER_ERROR); } } }
package bd.edu.daffodilvarsity.classmanager.otherclasses; import com.google.firebase.Timestamp; public class BookedClassDetailsUser { private String roomNo = ""; private String time = ""; private String teacherInitial = ""; private String teacherEmail = ""; private Timestamp reservationDate; private String dayOfWeek = ""; private Timestamp timeWhenUserBooked; private String uid = ""; private String program = ""; private String docId; private String shift; private String section; private String courseCode; private float priority; public BookedClassDetailsUser() { } public String getRoomNo() { return roomNo; } public void setRoomNo(String roomNo) { this.roomNo = roomNo; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public String getTeacherInitial() { return teacherInitial; } public void setTeacherInitial(String teacherInitial) { this.teacherInitial = teacherInitial; } public String getDayOfWeek() { return dayOfWeek; } public String getTeacherEmail() { return teacherEmail; } public void setTeacherEmail(String teacherEmail) { this.teacherEmail = teacherEmail; } public void setDayOfWeek(String dayOfWeek) { this.dayOfWeek = dayOfWeek; } public Timestamp getTimeWhenUserBooked() { return timeWhenUserBooked; } public void setTimeWhenUserBooked(Timestamp timeWhenUserBooked) { this.timeWhenUserBooked = timeWhenUserBooked; } public Timestamp getReservationDate() { return reservationDate; } public void setReservationDate(Timestamp reservationDate) { this.reservationDate = reservationDate; } public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getDocId() { return docId; } public void setDocId(String docId) { this.docId = docId; } public String getShift() { return shift; } public void setShift(String shift) { this.shift = shift; } public String getSection() { return section; } public void setSection(String section) { this.section = section; } public String getCourseCode() { return courseCode; } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } public float getPriority() { return priority; } public void setPriority(float priority) { this.priority = priority; } public String getProgram() { return program; } public void setProgram(String program) { this.program = program; } }
import styled from 'styled-components'; import { Link } from 'gatsby'; export const Button = styled(Link)` background: ${props => props.primary ? '#F26A2e' : '#077BF1'}; white-space: nowrap; padding: ${props => props.big ? '16px 40px' : '10px 32px'}; color: #fff; font-size: ${props => props.big ? '20px' : '16px'}; outline: none; border: none; min-width: 100px; cursor: pointer; text-decoration: none; transition: .5s !important; border-radius: ${props => props.round ? '50px' : 'none'}; &:hover { background: ${props => props.primary ? '#077BF1' : '#F26A2e'}; transform: translateY(-2px); } `
<gh_stars>0 package com.example.zhongweikang.beijingnew.utils; import android.graphics.Bitmap; import android.os.Handler; import android.util.Log; /** * 圖片緩存类放法 */ public class BitmapCacheUtils { /*1 根據地址去內存中取圖片, * 2 根據URL 去本地種取, * 3.最後去網絡中取,取到后發送給主縣城中顯示,同時向內存中存一份,本地存一份 * * */ private NetCacheUtils mNetCacheUtils; // 网络请求对象 private LocalCacehUtils mLocalCacheUtils; // 本地缓存对象 private MemoryCacheUtils memoryCacheUtils; // 内存缓存对象 public BitmapCacheUtils(Handler handler) { // 夠造方法,初始換網絡請求的同時,傳給它handler memoryCacheUtils=new MemoryCacheUtils(); mLocalCacheUtils = new LocalCacehUtils(); // 实例化本地缓存对象 mNetCacheUtils = new NetCacheUtils(handler, mLocalCacheUtils,memoryCacheUtils); // 实例化网络缓存对象 } public Bitmap getBitmapFromUrl(String url, int position) { // 得到圖片的地址 /* 先根据URl,去内存中取,如果取到直接返回*/ Bitmap bm=memoryCacheUtils.getBitmapMemory(url); if (bm!=null){ Log.d("memory","从内存总获取"); return bm; } /* 首先得到本地缓存中的缓存*/ bm = mLocalCacheUtils.getBitmaoFromLocal(url); if (bm != null) { Log.d("loacal", "从本地取得的照片"); return bm; // 一return 下面的网络请求得到的图片不会再质走了 } /*如果获取本地缓存中的方法得不到缓存,在进行网络得到缓存*/ mNetCacheUtils.getBitmapFromNet(url, position); // 這個方法中調用網絡請求中的方法,同時將圖片地址傳給它 return null; } }
package io.opensphere.merge.controller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.util.List; import org.easymock.EasyMock; import org.easymock.EasyMockSupport; import org.junit.Test; import io.opensphere.core.datafilter.columns.ColumnMappingController; import io.opensphere.core.util.collections.New; import io.opensphere.mantle.data.DataTypeInfo; import io.opensphere.mantle.data.element.DataElement; import io.opensphere.mantle.data.util.DataElementLookupUtils; import io.opensphere.merge.algorithm.Col; /** * Unit test for {@link ColumnMappingSupport}. */ public class ColumnMappingSupportTest { /** * The layer 1 columns. */ private static final List<String> ourType1Columns = New.list("USER_NAME", "PLACE_COUNTRY", "TEXT"); /** * The layer 2 columns. */ private static final List<String> ourType2Columns = New.list("TRUNCATED", "EMBERSGEOCODE_COUNTRY", "TEXT"); /** * The test layer key. */ private static final String ourTypeKey1 = "twitter"; /** * Another test layer key. */ private static final String ourTypeKey2 = "embers"; /** * Tests the column match function. */ @Test public void testColumnMatch() { EasyMockSupport support = new EasyMockSupport(); DataElementLookupUtils lookup = support.createMock(DataElementLookupUtils.class); ColumnMappingController mapper = createMapper(support); List<Col> layer1Columns = createColumns(support, ourTypeKey1, ourType1Columns); List<Col> layer2Columns = createColumns(support, ourTypeKey2, ourType2Columns); support.replayAll(); ColumnMappingSupport mappingSupport = new ColumnMappingSupport(lookup, mapper); int i = 0; for (Col layer1Column : layer1Columns) { int j = 0; for (Col layer2Column : layer2Columns) { String joinedName = mappingSupport.columnMatch(layer1Column, layer2Column); if (i == 1 && j == 1 || i == 2 && j == 2) { assertNotNull(joinedName); } else { assertNull(joinedName); } j++; } i++; } support.verifyAll(); } /** * Tests get records. */ @Test public void testGetRecords() { EasyMockSupport support = new EasyMockSupport(); ColumnMappingController mapper = support.createMock(ColumnMappingController.class); DataTypeInfo type = support.createMock(DataTypeInfo.class); List<DataElement> elements = createElements(support); DataElementLookupUtils lookup = createLookup(support, type, elements); support.replayAll(); ColumnMappingSupport mappingSupport = new ColumnMappingSupport(lookup, mapper); assertEquals(elements, mappingSupport.getRecords(type)); support.verifyAll(); } /** * Creates the columns for test. * * @param support Used to create a mock. * @param typeKey The layer. * @param columnNames The column names. * @return The columns. */ private List<Col> createColumns(EasyMockSupport support, String typeKey, List<String> columnNames) { DataTypeInfo dataType = support.createMock(DataTypeInfo.class); EasyMock.expect(dataType.getTypeKey()).andReturn(typeKey).atLeastOnce(); List<Col> columns = New.list(); for (String columnName : columnNames) { Col column = new Col(); column.name = columnName; column.owner = dataType; columns.add(column); } return columns; } /** * Creates mocked data elements. * * @param support Used to create the mock. * @return The data elements. */ private List<DataElement> createElements(EasyMockSupport support) { DataElement element = support.createMock(DataElement.class); return New.list(element); } /** * Creates a mocked {@link DataElementLookupUtils}. * * @param support Used to create the mock. * @param type The expected type. * @param elements The elements to return. * @return The mocked class. */ private DataElementLookupUtils createLookup(EasyMockSupport support, DataTypeInfo type, List<DataElement> elements) { DataElementLookupUtils lookup = support.createMock(DataElementLookupUtils.class); EasyMock.expect(lookup.getDataElements(EasyMock.eq(type))).andReturn(elements); return lookup; } /** * Creates an easy mocked mapper. * * @param support Used to create the mock. * @return The mocked mapper. */ private ColumnMappingController createMapper(EasyMockSupport support) { ColumnMappingController mapper = support.createMock(ColumnMappingController.class); EasyMock.expect(mapper.getDefinedColumn(EasyMock.cmpEq(ourTypeKey1), EasyMock.isA(String.class))) .andAnswer(this::getDefinedColumnAnswer).atLeastOnce(); EasyMock.expect(mapper.getDefinedColumn(EasyMock.cmpEq(ourTypeKey2), EasyMock.isA(String.class))) .andAnswer(this::getDefinedColumnAnswer).atLeastOnce(); return mapper; } /** * The answer to the getDefinedColumn mocked call. * * @return The mapped column name, or null if not mapped. */ private String getDefinedColumnAnswer() { String definedColumn = null; String typeKey = EasyMock.getCurrentArguments()[0].toString(); String column = EasyMock.getCurrentArguments()[1].toString(); if (ourTypeKey1.equals(typeKey)) { assertTrue(ourType1Columns.contains(column)); } else { assertTrue(ourType2Columns.contains(column)); } if (column.endsWith("_COUNTRY")) { definedColumn = "COUNTRY"; } return definedColumn; } }
package com.lai.mtc.mvp.utlis; import android.support.v4.app.Fragment; import com.trello.rxlifecycle2.LifecycleProvider; import com.trello.rxlifecycle2.LifecycleTransformer; import com.trello.rxlifecycle2.android.ActivityEvent; import org.reactivestreams.Publisher; import io.reactivex.Flowable; import io.reactivex.FlowableTransformer; import io.reactivex.Observable; import io.reactivex.ObservableSource; import io.reactivex.ObservableTransformer; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.schedulers.Schedulers; /** * @author Lai * @time 2017/9/18 17:32 * @describe describe */ public class RxUtlis { /** * 统一线程处理 * * @param <T> * @return */ public static <T> ObservableTransformer<T, T> bind(final Fragment mLifecycleProvider) { final LifecycleProvider<ActivityEvent> lifecycleProvider = (LifecycleProvider<ActivityEvent>) mLifecycleProvider; return new ObservableTransformer<T, T>() { @Override public ObservableSource<T> apply(Observable<T> upstream) { return upstream.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()).compose(lifecycleProvider.<T>bindToLifecycle()); } }; } public static <T> ObservableTransformer<T, T> toMain() { return new ObservableTransformer<T, T>() { @Override public ObservableSource<T> apply(Observable<T> upstream) { return upstream.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; } public static <T> FlowableTransformer<T, T> toFlowableMain() { return new FlowableTransformer<T, T>() { @Override public Publisher<T> apply(Flowable<T> upstream) { return upstream.subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); } }; } public interface Lifecycle{ <T> LifecycleTransformer<T> bindToLifecycle(); } public static <T> ObservableTransformer<T, T> handler(final Lifecycle lifecycle) { return new ObservableTransformer<T, T>() { @Override public ObservableSource<T> apply(Observable<T> upstream) { return upstream.compose(RxUtlis.<T>toMain()).compose(lifecycle.<T>bindToLifecycle()); } }; } }
import _ from 'lodash' import { nanoid } from 'nanoid' import { SerializedChatter } from 'libs/Chatter' /** * RegExp used to identify a valid action text. */ const TextRegExp = /^[\w\W]+$/ /** * RegExp used to identify a valid action name. */ const NameRegExp = /^[\w\- ]+$/ /** * RegExp used to identify a valid action recipient. */ const RecipientRegExp = /^[\w]{3,}$/ /** * Types of action available. */ export enum ActionType { Say = 'Say', Whisper = 'Whisper', Prepare = 'Prepare', Open = 'Open URL', } /** * Action class. */ export default class Action implements Serializable<SerializedAction> { /** * Validates an action. * @param editing - Defines if we're editing or creating a new action. * @param type - The current type. * @param name - The name to validate. * @param text - The text to validate. * @param recipient - The recipient to validate. * @return The validation state. */ public static validate(editing: boolean, type: ActionType, text: string, name: string, recipient?: string) { const isWhisperAction = type === ActionType.Whisper const textValid = Action.validateValue(editing, text, TextRegExp) const nameValid = Action.validateValue(editing, name, NameRegExp) const recipientValid = isWhisperAction && !_.isNil(recipient) ? Action.validateValue(editing, recipient, RecipientRegExp) : true const textAndNameValid = textValid && nameValid const valid = isWhisperAction ? textAndNameValid && recipientValid : textAndNameValid return { name: nameValid, recipient: recipientValid, text: textValid, valid } } /** * Parses an action text and replace placeholders. * @param action - The action to parse. * @param placeholders - Available placholders. * @return The parsed action text. */ public static parse(action: SerializedAction, replacements: ActionReplacement) { const compiledTemplate = _.template(action.text) return compiledTemplate(replacements) } /** * Validates an action value. * @param editing - Defines if we're editing or creating a new action. * @param value - The value to validate. * @param regexp - The regexp used to validate. * @return `true` when the value is valid. */ private static validateValue(editing: boolean, value: string, regexp: RegExp) { const valid = regexp.test(value) return editing ? value.length > 0 && valid : valid } /** * Creates a new action instance. * @class * @param type - The action type. * @param name - The action name. * @param text - The action text. * @param [recipient] - The action recipient. * @param [id] - The action id. */ constructor( private type: ActionType, private name: string, private text: string, private recipient?: string, private id = nanoid() ) {} /** * Serializes an action. * @return The serialized action. */ public serialize() { return { id: this.id, name: this.name, recipient: this.type === ActionType.Whisper ? this.recipient : undefined, text: this.text, type: this.type, } } /** * Validate the current action instance. * @return The validation state. */ public validate() { return Action.validate(false, this.type, this.text, this.name, this.recipient) } } /** * Action placeholders. */ export enum ActionPlaceholder { Username = 'username', Channel = 'channel', } /** * Action placeholders replacement values.. */ type ActionReplacement = Record<ActionPlaceholder, string> /** * Serialized action. */ export type SerializedAction = { id: string name: string text: string type: ActionType recipient?: string } /** * Action handler. */ export type ActionHandler = (action: SerializedAction, chatter: Optional<SerializedChatter>) => void
<filename>client/components/allMovies.js import React from 'react' import {getAllMoviesThunk, getFeaturedMoviesThunk} from '../store/movies' import {connect} from 'react-redux' import SingleMovie from './singleMovie' class DisconnectedAllMovies extends React.Component { componentDidMount() { const genre = this.props.match.params.genre if (!genre || genre === 'featured') { this.props.getFeaturedMovies() } else { this.props.getMovies( genre[0].toUpperCase() + genre.slice(1).toLowerCase() ) } } render() { return ( <div className="container is-fluid"> <div className="columns is-multiline"> {this.props.movies.map(movie => { return <SingleMovie key={movie.id} movie={movie} /> })} </div> </div> ) } } const mapStateToProps = state => { return { movies: state.movies.allMovies, selectedGenre: state.movies.selectedGenre } } const mapDispatchToProps = dispatch => { return { getMovies: genre => dispatch(getAllMoviesThunk(genre)), getFeaturedMovies: () => dispatch(getFeaturedMoviesThunk()) } } const AllMovies = connect(mapStateToProps, mapDispatchToProps)( DisconnectedAllMovies ) export default AllMovies
<gh_stars>0 function openWork(evt,workName){ var i,worklinks,workcontent; workcontent=document.getElementsByClassName("work-tab-content"); for(i=0;i<workcontent.length;i++){ workcontent[i].style.display = "none"; } worklinks = document.getElementsByClassName("work-tab-links"); for(i=0;i<worklinks.length;i++){ worklinks[i].className=worklinks[i].className.replace("active", ""); } document.getElementById(workName).style.display="flex"; evt.currentTarget.className+=" active "; } document.getElementById("defaultOpen").click();
# function to find the longest common substring def find_longest_common_substring(string1, string2): # find the length of the two strings str1_len = len(string1) str2_len = len(string2) # initialize a 2-dimensional array LCS = [[0 for x in range(str2_len+1)] for y in range(str1_len+1)] # find the longest common substring for i in range(str1_len+1): for j in range(str2_len+1): if(i == 0 or j == 0): LCS[i][j] = 0 elif(string1[i-1] == string2[j-1]): LCS[i][j] = LCS[i-1][j-1] + 1 else: LCS[i][j] = 0 # find the maximum element in the matrix max = 0 for i in range(str1_len+1): for j in range(str2_len+1): if(max < LCS[i][j]): max = LCS[i][j] # return the longest common substring return max
<reponame>ahmed82/fabric-bdls // Copyright IBM Corp. All Rights Reserved. // // SPDX-License-Identifier: Apache-2.0 // package consensus import ( "time" "github.com/pkg/errors" ) // Configuration defines the parameters needed in order to create an instance of Consensus. type Configuration struct { // SelfID is the identifier of the node. SelfID uint64 // RequestBatchMaxCount is the maximal number of requests in a batch. // A request batch that reaches this count is proposed immediately. RequestBatchMaxCount uint64 // RequestBatchMaxBytes is the maximal total size of requests in a batch, in bytes. // This is also the maximal size of a request. A request batch that reaches this size is proposed immediately. RequestBatchMaxBytes uint64 // RequestBatchMaxInterval is the maximal time interval a request batch is waiting before it is proposed. // A request batch is accumulating requests until RequestBatchMaxInterval had elapsed from the time the batch was // first created (i.e. the time the first request was added to it), or until it is of count RequestBatchMaxCount, // or total size RequestBatchMaxBytes, which ever happens first. RequestBatchMaxInterval time.Duration // IncomingMessageBufferSize is the size of the buffer holding incoming messages before they are processed. IncomingMessageBufferSize uint64 // RequestPoolSize is the number of pending requests retained by the node. // The RequestPoolSize is recommended to be at least double (x2) the RequestBatchMaxCount. RequestPoolSize uint64 // RequestForwardTimeout is started from the moment a request is submitted, and defines the interval after which a // request is forwarded to the leader. RequestForwardTimeout time.Duration // RequestComplainTimeout is started when RequestForwardTimeout expires, and defines the interval after which the // node complains about the view leader. RequestComplainTimeout time.Duration // RequestAutoRemoveTimeout is started when RequestComplainTimeout expires, and defines the interval after which // a request is removed (dropped) from the request pool. RequestAutoRemoveTimeout time.Duration // ViewChangeResendInterval defined the interval in which the ViewChange message is resent. ViewChangeResendInterval time.Duration // ViewChangeTimeout is started when a node first receives a quorum of ViewChange messages, and defines the // interval after which the node will try to initiate a view change with a higher view number. ViewChangeTimeout time.Duration // LeaderHeartbeatTimeout is the interval after which, if nodes do not receive a "sign of life" from the leader, // they complain on the current leader and try to initiate a view change. A sign of life is either a heartbeat // or a message from the leader. LeaderHeartbeatTimeout time.Duration // LeaderHeartbeatCount is the number of heartbeats per LeaderHeartbeatTimeout that the leader should emit. // The heartbeat-interval is equal to: LeaderHeartbeatTimeout/LeaderHeartbeatCount. LeaderHeartbeatCount uint64 // NumOfTicksBehindBeforeSyncing is the number of follower ticks where the follower is behind the leader // by one sequence before starting a sync NumOfTicksBehindBeforeSyncing uint64 // CollectTimeout is the interval after which the node stops listening to StateTransferResponse messages, // stops collecting information about view metadata from remote nodes. CollectTimeout time.Duration // SyncOnStart is a flag indicating whether a sync is required on startup. SyncOnStart bool // SpeedUpViewChange is a flag indicating whether a node waits for only f+1 view change messages to join // the view change (hence speeds up the view change process), or it waits for a quorum before joining. // Waiting only for f+1 is considered less safe. SpeedUpViewChange bool } // DefaultConfig contains reasonable values for a small cluster that resides on the same geography (or "Region"), but // possibly on different availability zones within the geography. It is assumed that the typical latency between nodes, // and between clients to nodes, is approximately 10ms. // Set the SelfID. var DefaultConfig = Configuration{ RequestBatchMaxCount: 100, RequestBatchMaxBytes: 10 * 1024 * 1024, RequestBatchMaxInterval: 50 * time.Millisecond, IncomingMessageBufferSize: 200, RequestPoolSize: 400, RequestForwardTimeout: 2 * time.Second, RequestComplainTimeout: 20 * time.Second, RequestAutoRemoveTimeout: 3 * time.Minute, ViewChangeResendInterval: 5 * time.Second, ViewChangeTimeout: 20 * time.Second, LeaderHeartbeatTimeout: time.Minute, LeaderHeartbeatCount: 10, NumOfTicksBehindBeforeSyncing: 10, CollectTimeout: time.Second, SyncOnStart: false, SpeedUpViewChange: false, } func (c Configuration) Validate() error { if !(c.SelfID > 0) { return errors.Errorf("SelfID is lower than or equal to zero") } if !(c.RequestBatchMaxCount > 0) { return errors.Errorf("RequestBatchMaxCount should be greater than zero") } if !(c.RequestBatchMaxBytes > 0) { return errors.Errorf("RequestBatchMaxBytes should be greater than zero") } if !(c.RequestBatchMaxInterval > 0) { return errors.Errorf("RequestBatchMaxInterval should be greater than zero") } if !(c.IncomingMessageBufferSize > 0) { return errors.Errorf("IncomingMessageBufferSize should be greater than zero") } if !(c.RequestPoolSize > 0) { return errors.Errorf("RequestPoolSize should be greater than zero") } if !(c.RequestForwardTimeout > 0) { return errors.Errorf("RequestForwardTimeout should be greater than zero") } if !(c.RequestComplainTimeout > 0) { return errors.Errorf("RequestComplainTimeout should be greater than zero") } if !(c.RequestAutoRemoveTimeout > 0) { return errors.Errorf("RequestAutoRemoveTimeout should be greater than zero") } if !(c.ViewChangeResendInterval > 0) { return errors.Errorf("ViewChangeResendInterval should be greater than zero") } if !(c.ViewChangeTimeout > 0) { return errors.Errorf("ViewChangeTimeout should be greater than zero") } if !(c.LeaderHeartbeatTimeout > 0) { return errors.Errorf("LeaderHeartbeatTimeout should be greater than zero") } if !(c.LeaderHeartbeatCount > 0) { return errors.Errorf("LeaderHeartbeatCount should be greater than zero") } if !(c.NumOfTicksBehindBeforeSyncing > 0) { return errors.Errorf("NumOfTicksBehindBeforeSyncing should be greater than zero") } if !(c.CollectTimeout > 0) { return errors.Errorf("CollectTimeout should be greater than zero") } if c.RequestBatchMaxCount > c.RequestBatchMaxBytes { return errors.Errorf("RequestBatchMaxCount is bigger than RequestBatchMaxBytes") } if c.RequestForwardTimeout > c.RequestComplainTimeout { return errors.Errorf("RequestForwardTimeout is bigger than RequestComplainTimeout") } if c.RequestComplainTimeout > c.RequestAutoRemoveTimeout { return errors.Errorf("RequestComplainTimeout is bigger than RequestAutoRemoveTimeout") } if c.ViewChangeResendInterval > c.ViewChangeTimeout { return errors.Errorf("ViewChangeResendInterval is bigger than ViewChangeTimeout") } return nil }
#!/bin/bash -l # Runs a spades assembly. Run with no options for usage. # Author: Lee Katz <lkatz@cdc.gov> #Example: (for f in *R1_001.fastq.gz; do b=`basename $f _R1.fastq.gz`; r=`sed 's/R1/R2/' <<< $f`; qsub -N spades$b -o ./assemblies/log/b.spades.log ~/bin/launch_SPAdes_v3.11.0.sh $f $r ./assemblies/$b.spades3.11 ./assemblies/$b; done;) #$ -S /bin/bash #$ -pe smp 4-16 #$ -cwd -V #$ -o spades.log #$ -j y #$ -N SPAdes3.11.0 #$ -q all.q forward=$1 reverse=$2 out=$3 fastaOut=$4 source /etc/profile.d/modules.sh scriptname=$(basename $0); if [ "$out" == "" ]; then echo "Usage: $scriptname reads.1.fastq.gz reads.2.fastq.gz output/ [out.fasta]" echo " if out.fasta is given, then the output directory will be removed and the scaffolds.fasta file will be saved" exit 1; fi; module load SPAdes/3.11.0 if [ $? -gt 0 ]; then echo "unable to load spades 3.11.0"; exit 1; fi; NSLOTS=${NSLOTS:=1} COMMAND="spades.py -1 $forward -2 $reverse --careful -o $out -t $NSLOTS" echo "$scriptname: $COMMAND" $COMMAND if [ $? -gt 0 ]; then echo "problem with spades 3.11.0"; exit 1; fi; if [ "$fastaOut" != "" ]; then cp -v "$out/scaffolds.fasta" $fastaOut if [ $? -gt 0 ]; then echo "problem with copying $out/scaffolds.fasta => $fastaOut"; exit 1; fi; rm -rf "$out"; if [ $? -gt 0 ]; then echo "problem with removing the directory $out"; exit 1; fi; fi
module.exports = { testMatch: ['<rootDir>/src/**/*.test.ts'], moduleFileExtensions: ['js', 'ts', 'json', 'vue'], setupFilesAfterEnv: ['<rootDir>/src/config/jest/plugins.ts'], moduleNameMapper: { '^@/(.*)$': '<rootDir>/src/$1', }, transform: { '^.+\\.ts$': 'ts-jest', '^.+\\.vue$': 'vue-jest', } }
import React, { useState, useEffect } from 'react'; import { List, SearchBar } from 'react-native-elements'; import { View, Text } from 'react-native'; const App = () => { const [products, setProducts] = useState([]); const [filter, setFilter] = useState(''); useEffect(() => { fetch('http://products-website.com/products') .then(response => response.json()) .then(products => setProducts(products)); }, []); const searchProducts = (filter) => { setFilter(filter); let filteredProducts = products.filter(product => product.price <= filter); setProducts(filteredProducts); } return ( <View> <SearchBar placeholder="Filter by price..." onChangeText={searchProducts} value={filter} /> {products.length > 0 ? <List containerStyle={{ marginBottom: 20 }}> {products.map((product, i) => ( <List.Item key={i} title={product.name} onPress={() => navigation.navigate('Product Details', {product})} /> ))} </List> : <Text>No products are available.</Text> } </View> ) }; export default App;
/* * 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 ed.biodare2.backend.security.dao; import ed.biodare2.backend.security.BioDare2User; import ed.biodare2.backend.security.dao.db.UserToken; import java.time.LocalDateTime; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; /** * * @author tzielins */ public interface UserTokenRep extends JpaRepository<UserToken, String> { Optional<UserToken> findByToken(String token); List<UserToken> findByExpiringBefore(LocalDateTime date); List<UserToken> findByUser(BioDare2User user); }
<gh_stars>100-1000 import * as React from 'react'; import styles from '@patternfly/react-styles/css/components/DualListSelector/dual-list-selector'; import { css } from '@patternfly/react-styles'; import formStyles from '@patternfly/react-styles/css/components/FormControl/form-control'; import { DualListSelectorTree, DualListSelectorTreeItemData } from './DualListSelectorTree'; import { getUniqueId } from '../../helpers'; import { DualListSelectorListWrapper } from './DualListSelectorListWrapper'; import { DualListSelectorContext, DualListSelectorPaneContext } from './DualListSelectorContext'; import { DualListSelectorList } from './DualListSelectorList'; export interface DualListSelectorPaneProps { /** Additional classes applied to the dual list selector pane. */ className?: string; /** A dual list selector list or dual list selector tree to be rendered in the pane. */ children?: React.ReactNode; /** Flag indicating if this pane is the chosen pane. */ isChosen?: boolean; /** Status to display above the pane. */ status?: string; /** Title of the pane. */ title?: React.ReactNode; /** A search input placed above the list at the top of the pane, before actions. */ searchInput?: React.ReactNode; /** Actions to place above the pane. */ actions?: React.ReactNode[]; /** Id of the pane. */ id?: string; /** @hide Options to list in the pane. */ options?: React.ReactNode[]; /** @hide Options currently selected in the pane. */ selectedOptions?: string[] | number[]; /** @hide Callback for when an option is selected. Optionally used only when options prop is provided. */ onOptionSelect?: ( e: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent, index: number, isChosen: boolean, id?: string, itemData?: any, parentData?: any ) => void; /** @hide Callback for when a tree option is checked. Optionally used only when options prop is provided. */ onOptionCheck?: ( evt: React.MouseEvent | React.ChangeEvent<HTMLInputElement> | React.KeyboardEvent, isChecked: boolean, itemData: DualListSelectorTreeItemData ) => void; /** @hide Flag indicating a dynamically built search bar should be included above the pane. */ isSearchable?: boolean; /** Flag indicating whether the component is disabled. */ isDisabled?: boolean; /** Callback for search input. To be used when isSearchable is true. */ onSearch?: (event: React.ChangeEvent<HTMLInputElement>) => void; /** @hide A callback for when the search input value for changes. To be used when isSearchable is true. */ onSearchInputChanged?: (value: string, event: React.FormEvent<HTMLInputElement>) => void; /** @hide Filter function for custom filtering based on search string. To be used when isSearchable is true. */ filterOption?: (option: React.ReactNode, input: string) => boolean; /** @hide Accessible label for the search input. To be used when isSearchable is true. */ searchInputAriaLabel?: string; /** @hide Callback for updating the filtered options in DualListSelector. To be used when isSearchable is true. */ onFilterUpdate?: (newFilteredOptions: React.ReactNode[], paneType: string, isSearchReset: boolean) => void; } export const DualListSelectorPane: React.FunctionComponent<DualListSelectorPaneProps> = ({ isChosen = false, className = '', status = '', actions, searchInput, children, onOptionSelect, onOptionCheck, title = '', options = [] as React.ReactNode[], selectedOptions = [], isSearchable = false, searchInputAriaLabel = '', onFilterUpdate, onSearchInputChanged, filterOption, id = getUniqueId('dual-list-selector-pane'), isDisabled = false, ...props }: DualListSelectorPaneProps) => { const [input, setInput] = React.useState(''); const { isTree } = React.useContext(DualListSelectorContext); // only called when search input is dynamically built const onChange = (e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value; let filtered; if (isTree) { filtered = (options as DualListSelectorTreeItemData[]) .map(opt => Object.assign({}, opt)) .filter(item => filterInput(item as DualListSelectorTreeItemData, newValue)); } else { filtered = options.filter(option => { if (displayOption(option)) { return option; } }); } onFilterUpdate(filtered, isChosen ? 'chosen' : 'available', newValue === ''); if (onSearchInputChanged) { onSearchInputChanged(newValue, e); } setInput(newValue); }; // only called when options are passed via options prop and isTree === true const filterInput = (item: DualListSelectorTreeItemData, input: string): boolean => { if (filterOption) { return filterOption(item, input); } else { if (item.text.toLowerCase().includes(input.toLowerCase()) || input === '') { return true; } } if (item.children) { return ( (item.children = item.children.map(opt => Object.assign({}, opt)).filter(child => filterInput(child, input))) .length > 0 ); } }; // only called when options are passed via options prop and isTree === false const displayOption = (option: React.ReactNode) => { if (filterOption) { return filterOption(option, input); } else { return option .toString() .toLowerCase() .includes(input.toLowerCase()); } }; return ( <div className={css(styles.dualListSelectorPane, isChosen ? styles.modifiers.chosen : 'pf-m-available', className)} {...props} > {title && ( <div className={css(styles.dualListSelectorHeader)}> <div className="pf-c-dual-list-selector__title"> <div className={css(styles.dualListSelectorTitleText)}>{title}</div> </div> </div> )} {(actions || searchInput || isSearchable) && ( <div className={css(styles.dualListSelectorTools)}> {(isSearchable || searchInput) && ( <div className={css(styles.dualListSelectorToolsFilter)}> {searchInput ? ( searchInput ) : ( <input className={css(formStyles.formControl, formStyles.modifiers.search)} type="search" onChange={isDisabled ? undefined : onChange} aria-label={searchInputAriaLabel} disabled={isDisabled} /> )} </div> )} {actions && <div className={css(styles.dualListSelectorToolsActions)}>{actions}</div>} </div> )} {status && ( <div className={css(styles.dualListSelectorStatus)}> <div className={css(styles.dualListSelectorStatusText)} id={`${id}-status`}> {status} </div> </div> )} <DualListSelectorPaneContext.Provider value={{ isChosen }}> {!isTree && ( <DualListSelectorListWrapper aria-labelledby={`${id}-status`} options={options} selectedOptions={selectedOptions} onOptionSelect={( e: React.MouseEvent | React.ChangeEvent | React.KeyboardEvent, index: number, id: string ) => onOptionSelect(e, index, isChosen, id)} displayOption={displayOption} id={`${id}-list`} isDisabled={isDisabled} > {children} </DualListSelectorListWrapper> )} {isTree && ( <DualListSelectorListWrapper aria-labelledby={`${id}-status`} id={`${id}-list`}> {options.length > 0 ? ( <DualListSelectorList> <DualListSelectorTree data={ isSearchable ? (options as DualListSelectorTreeItemData[]) .map(opt => Object.assign({}, opt)) .filter(item => filterInput(item as DualListSelectorTreeItemData, input)) : (options as DualListSelectorTreeItemData[]) } onOptionCheck={onOptionCheck} id={`${id}-tree`} isDisabled={isDisabled} /> </DualListSelectorList> ) : ( children )} </DualListSelectorListWrapper> )} </DualListSelectorPaneContext.Provider> </div> ); }; DualListSelectorPane.displayName = 'DualListSelectorPane';
$ go run funciones-variadicas.go [1 2] 3 [1 2 3] 6 [1 2 3 4] 10 # Otro aspecto clave de las funciones en Go es # su habilidad de generar closures, lo cual # veremos a continuación.
<filename>src/main/java/br/com/controle/financeiro/model/exception/NotFoundException.java<gh_stars>1-10 package br.com.controle.financeiro.model.exception; public class NotFoundException extends RuntimeException { public NotFoundException(Long id) { super("Could not find resource with" + id); } public NotFoundException(String message) { super(message); } }