repo_name
stringlengths
6
101
path
stringlengths
4
300
text
stringlengths
7
1.31M
Pittor052/SoftUni-Studies
FirstStepsInPython/Fundamentals/Lab/Lists Basics/04. Search.py
<filename>FirstStepsInPython/Fundamentals/Lab/Lists Basics/04. Search.py # # 01 solution using 2 lists and 1 for loop # lines = int(input()) # key = input() # word_list = [] # found_match = [] # for _ in range(lines): # words = input() # word_list.append(words) # if key in words: # found_match.append(words) # print(word_list) # print(found_match) # 02 solution using 1 list and 2 for loops lines = int(input()) key = input() word_list = [] for _ in range(lines): words = input() word_list.append(words) print(word_list) for i in range(len(word_list) - 1, -1, -1): element = word_list[i] if key not in element: word_list.remove(element) print(word_list)
toomuchsalt/ONE-1
runtime/onert/core/include/ir/OperandIndexSequence.h
<filename>runtime/onert/core/include/ir/OperandIndexSequence.h /* * Copyright (c) 2018 Samsung Electronics Co., Ltd. All Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef __ONERT_MODEL_OPERAND_INDEX_SEQUENCE_H__ #define __ONERT_MODEL_OPERAND_INDEX_SEQUENCE_H__ #include <initializer_list> #include <vector> #include "ir/Index.h" namespace onert { namespace ir { class OperandIndexSequence { public: OperandIndexSequence(void) = default; OperandIndexSequence(std::initializer_list<OperandIndex> list); OperandIndexSequence(std::initializer_list<int32_t> list); OperandIndexSequence(std::initializer_list<uint32_t> list); public: void append(const OperandIndex &index) { _set.emplace_back(index); } void append(const OperandIndexSequence &l) { _set.insert(_set.end(), l.begin(), l.end()); } public: uint32_t size() const { return static_cast<uint32_t>(_set.size()); } const OperandIndex &at(IOIndex set_index) const { return _set.at(set_index.value()); } const OperandIndex &at(uint32_t index) const { return _set.at(index); } bool contains(const OperandIndex &index) const; void replace(const OperandIndex &from, const OperandIndex &to); public: OperandIndexSequence operator+(const OperandIndexSequence &other) const; public: std::vector<OperandIndex>::const_iterator begin(void) const { return _set.begin(); } std::vector<OperandIndex>::const_iterator end(void) const { return _set.end(); } // Standard c++ uses `cbegin` for const_iterator and `begin` for mutable iterator. // However, our project uses `begin` for const_iterator in several data structures. // Thus, I introduced `mbegin` for mutable iterator. std::vector<OperandIndex>::iterator mbegin(void) { return _set.begin(); } std::vector<OperandIndex>::iterator mend(void) { return _set.end(); } private: std::vector<OperandIndex> _set; }; } // namespace ir } // namespace onert #endif // __ONERT_MODEL_OPERAND_INDEX_SET_H__
shulthz/gwallet
plugins/blinded/receiveblindtransfer.cpp
#include "include/receiveblindtransfer.hpp" #include "../include/panels/cli.hpp" #include <panels/commands.hpp> ReceiveBlindTransfer::ReceiveBlindTransfer(GWallet* gwallet) { p_GWallet = gwallet; InitWidgetsFromXRC((wxWindow *)p_GWallet); SetScrollRate(1,1); Connect(wxID_OK, wxEVT_COMMAND_BUTTON_CLICKED, wxCommandEventHandler(ReceiveBlindTransfer::OnOk)); } void ReceiveBlindTransfer::OnOk(wxCommandEvent& WXUNUSED(event)) { if(!Validate()) return; const auto _confirmation_receipt = confirmation_receipt->GetValue().ToStdString(); const auto _opt_from = opt_from->GetValue().ToStdString(); const auto _opt_memo = opt_memo->GetValue().ToStdString(); auto _cli = false; if(cli->IsChecked()) _cli = true; std::stringstream command; command << "receive_blind_transfer " << _confirmation_receipt << " \"" << _opt_from << "\" \"" << _opt_memo << "\""; if(_cli) { p_GWallet->panels.p_cli->DoCommand(command.str()); return; } else { const fc::variants line_variants = fc::json::variants_from_string(command.str()); const auto command_name = line_variants[0].get_string(); auto arguments_variants = fc::variants(line_variants.begin() + 1, line_variants.end()); try { const auto result_obj = p_GWallet->bitshares.wallet_cli->receive_call(p_GWallet->bitshares.api_id, command_name, arguments_variants); const auto blind_confirm = result_obj.as<graphene::wallet::blind_confirmation>(GRAPHENE_MAX_NESTED_OBJECTS); new ReceiveBlindTransferResponse(p_GWallet, blind_confirm); } catch (fc::exception &e) { p_GWallet->OnError(this, e.to_detail_string()); return; } } } ReceiveBlindTransferResponse::ReceiveBlindTransferResponse(GWallet* gwallet, wxAny any_response) { InitWidgetsFromXRC((wxWindow *)gwallet); SetScrollRate(1,1); gwallet->panels.p_commands->DoSignedTranactionResponse(response_tree, any_response.As<graphene::wallet::blind_confirmation>().trx); gwallet->panels.p_commands->notebook->AddPage(this, _("Receive blind transfer response"), true); }
wilfredwilly/springboot-learn-by-example
chapter-03/conditional/src/test/java/com/sivalabs/demo/ConditionalTest.java
/** * */ package com.sivalabs.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import java.util.List; /** * @author Siva * */ @RunWith(SpringRunner.class) @ContextConfiguration(classes=AppConfig.class) public class ConditionalTest { @Autowired private UserDAO userDAO; @Test public void test_get_all_usernames() { List<String> userNames = userDAO.getAllUserNames(); System.err.println(userNames); } }
bravedragon623/react-frontend-ico-dashboard
src/redux/modules/auth/signIn.js
import { from } from 'seamless-immutable'; import { createReducer, createSubmitAction, createAction } from '../../../utils/actions'; export const INIT_SIGN_IN = 'auth/signIn/INIT_SIGN_IN'; export const VERIFY_SIGN_IN = 'auth/signIn/VERIFY_SIGN_IN'; export const CHANGE_STEP = 'auth/signIn/CHANGE_STEP'; export const RESET_STORE = 'auth/signIn/RESET_STORE'; export const initSignIn = createSubmitAction(INIT_SIGN_IN); export const verifySignIn = createSubmitAction(VERIFY_SIGN_IN); export const changeStep = createAction(CHANGE_STEP); export const resetStore = createAction(RESET_STORE); const initialState = from({ step: 'initSignIn', fetching: false, accessToken: '', verification: { verificationId: '', method: '' } }); export default createReducer({ [initSignIn.REQUEST]: (state) => ( state.merge({ fetching: true }) ), [initSignIn.SUCCESS]: (state, { payload }) => ( state.merge({ fetching: false, accessToken: payload.accessToken, verification: { verificationId: payload.verification.verificationId, method: payload.verification.method } }) ), [initSignIn.FAILURE]: (state) => ( state.merge({ fetching: false }) ), [verifySignIn.REQUEST]: (state) => ( state.merge({ fetching: true }) ), [verifySignIn.SUCCESS]: (state) => ( state.merge({ fetching: false }) ), [verifySignIn.FAILURE]: (state) => ( state.merge({ fetching: false }) ), [CHANGE_STEP]: (state, { payload }) => ( state.merge({ step: payload }) ), [RESET_STORE]: (state) => ( state.merge(initialState) ) }, initialState);
dog-days/webpack-launcher
packages/webpack-launcher/bin/webpack-launcher-serve-build.js
#!/usr/bin/env node 'use strict'; require('../scripts/serveBuild.js');
marcinseweryn/Health-Center
HealthCenter/src/main/java/com/github/marcinseweryn/controllers/HomeController.java
package com.github.marcinseweryn.controllers; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.mvc.support.RedirectAttributes; import com.github.marcinseweryn.model.Patient; import com.github.marcinseweryn.model.User; import com.github.marcinseweryn.service.EmailService; import com.github.marcinseweryn.service.UserService; @Controller public class HomeController { @Autowired private EmailService emailService; @Autowired private UserService userService; @RequestMapping(value = "/", method = RequestMethod.GET) public String home() { return "main/home"; } @RequestMapping(value = "/login", method = RequestMethod.GET) public String login(){ return "main/login"; } @RequestMapping(value = "/forgot-account", method = RequestMethod.GET) public String forgotPasswordFirstStepGet(){ return "main/forgot-account"; } @RequestMapping(value = "/forgot-account", method = RequestMethod.POST) public String forgotPasswordFirstStepPost(@RequestParam String email, RedirectAttributes redirectAttributes){ String code = emailService.forgottenLoginDataFirstStep(email); redirectAttributes.addFlashAttribute("status", code); if(!code.equals("incorrectEmail")){ redirectAttributes.addFlashAttribute("email", email); return "redirect:/forgot-account-2"; } return "redirect:/forgot-account-information"; } @RequestMapping(value = "/forgot-account-2", method = RequestMethod.GET) public String forgotPasswordSecondStepGet(@ModelAttribute("status") String code, Model model, @ModelAttribute("email") String email, RedirectAttributes redirectAttributes){ if(code.equals("")){ // block refresh return "redirect:/"; } model.addAttribute("code", code); model.addAttribute("email", email); return "main/forgot-account-2"; } @RequestMapping(value = "/forgot-account-2", method = RequestMethod.POST) public String forgotPasswordSecondStepPost(@RequestParam String email, @RequestParam String enteredCode, @RequestParam String code, RedirectAttributes redirectAttributes){ String status; if(code.equals(enteredCode)){ User user = userService.findUserByEmail(email); emailService.forgottenLoginDataSecondStep(email, user); status = "correctCode"; }else{ status = "incorrectCode"; } redirectAttributes.addFlashAttribute("status", status); return "redirect:/forgot-account-information"; } @RequestMapping(value = "/forgot-account-information", method = RequestMethod.GET) public String forgotAccountInformationGet(@ModelAttribute("status") String status, Model model){ if(status.equals("")){ // block refresh return "redirect:/"; } model.addAttribute("status", status); return "main/forgot-account-information"; } @RequestMapping(value = "/registration", method = RequestMethod.GET) public String registration(Model model){ model.addAttribute("patient", new Patient()); return "main/registration"; } @RequestMapping(value = "/registration", method = RequestMethod.POST) public String register(@Valid Patient patient, Errors errors, RedirectAttributes redirectAttributes){ if(errors.hasErrors()){ return "main/registration"; } // patient.setRole("ROLE_PATIENT"); // userService.addUser(patient); // // User user = userService.findUsers(patient).get(0); // String ID = user.getID().toString(); // redirectAttributes.addFlashAttribute("accountNumber", ID); return "redirect:/registration-completed"; } @RequestMapping(value = "/registration-completed", method = RequestMethod.GET) public String registrationCompleted(Model model, @ModelAttribute("accountNumber") String ID){ if(!ID.equals("")){ model.addAttribute("accountNumber", ID); return "main/registration-completed"; } return "main/home"; } @RequestMapping(value = "/information", method = RequestMethod.GET) public String information(){ return "main/information"; } @RequestMapping(value = "/aboutUs", method = RequestMethod.GET) public String aboutUs(){ return "main/aboutUs"; } @RequestMapping(value = "/403", method = RequestMethod.GET) public String error403(){ return "errors/403"; } }
propainter/cdap
cdap-app-fabric/src/test/java/io/cdap/cdap/internal/app/runtime/monitor/proxy/ServiceSocksProxyTest.java
/* * Copyright © 2019 <NAME>, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package io.cdap.cdap.internal.app.runtime.monitor.proxy; import io.cdap.cdap.common.discovery.ResolvingDiscoverable; import io.cdap.common.http.HttpRequestConfig; import io.cdap.common.http.HttpRequests; import io.cdap.common.http.HttpResponse; import io.cdap.http.NettyHttpService; import org.apache.twill.common.Cancellable; import org.apache.twill.discovery.Discoverable; import org.apache.twill.discovery.InMemoryDiscoveryService; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.net.Authenticator; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.ProxySelector; import java.net.SocketAddress; import java.net.SocketException; import java.net.URI; import java.net.URL; import java.util.Collections; import java.util.List; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * Unit tests for {@link ServiceSocksProxy}. */ public class ServiceSocksProxyTest { private static final Logger LOG = LoggerFactory.getLogger(ServiceSocksProxy.class); private static final String USER = "test"; private static final String PASS = "<PASSWORD>"; // Username and password used by the Authenticator private static String authUser = USER; private static String authPass = <PASSWORD>; private static Authenticator authenticator; private static InMemoryDiscoveryService discoveryService; private static NettyHttpService httpService; private static ServiceSocksProxy proxyServer; private static ProxySelector defaultProxySelector; @BeforeClass public static void init() throws Exception { // Start a HTTP service for hosting services to test httpService = NettyHttpService.builder("test") .setHttpHandlers(new TestHandler()) .build(); httpService.start(); LOG.info("Http service started on {}", httpService.getBindAddress()); // Register discovery discoveryService = new InMemoryDiscoveryService(); discoveryService.register(ResolvingDiscoverable.of((new Discoverable("test-service", httpService.getBindAddress())))); proxyServer = new ServiceSocksProxy(discoveryService, (user, pass) -> USER.equals(user) && PASS.equals(pass)); proxyServer.startAndWait(); defaultProxySelector = ProxySelector.getDefault(); // Set the proxy for URLConnection Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyServer.getBindAddress()); ProxySelector.setDefault(new ProxySelector() { @Override public List<Proxy> select(URI uri) { return Collections.singletonList(proxy); } @Override public void connectFailed(URI uri, SocketAddress sa, IOException ioe) { LOG.error("Connect failed {} {}", uri, sa, ioe); } }); authenticator = new Authenticator() { @Override protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(authUser, authPass.toCharArray()); } }; Authenticator.setDefault(authenticator); } @AfterClass public static void finish() throws Exception { Authenticator.setDefault(null); ProxySelector.setDefault(defaultProxySelector); proxyServer.stopAndWait(); httpService.stop(); } @Test public void testGet() throws Exception { URL url = new URL("http://test-service/ping"); HttpResponse response = HttpRequests.execute(io.cdap.common.http.HttpRequest.get(url).build()); Assert.assertEquals(200, response.getResponseCode()); } @Test public void testPost() throws Exception { URL url = new URL("http://test-service/echo"); String body = "Echo body"; HttpResponse response = HttpRequests.execute( io.cdap.common.http.HttpRequest.post(url) .withBody(body) .build()); Assert.assertEquals(200, response.getResponseCode()); Assert.assertEquals(body, response.getResponseBodyAsString()); } @Test (expected = IOException.class) public void testTimeout() throws Exception { // Connect to a service that is not discoverable URL url = new URL("http://not-exist/ping"); HttpRequests.execute(io.cdap.common.http.HttpRequest.get(url).build(), new HttpRequestConfig(500, 10000)); } @Test public void testDelayRegister() throws Exception { URL url = new URL("http://test-service-2/ping"); // Delay the service registration by 2 seconds. ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(); ScheduledFuture<Cancellable> future = scheduler.schedule( () -> discoveryService.register(ResolvingDiscoverable.of(new Discoverable("test-service-2", httpService.getBindAddress()))), 2, TimeUnit.SECONDS); try { HttpResponse response = HttpRequests.execute(io.cdap.common.http.HttpRequest.get(url).build(), new HttpRequestConfig(5000, 5000)); Assert.assertEquals(200, response.getResponseCode()); } finally { future.get(5, TimeUnit.SECONDS).cancel(); } } @Test (expected = SocketException.class) public void testAuthFailure() throws Exception { String oldPass = authPass; authPass += "<PASSWORD>"; Cancellable cancellable = discoveryService.register( ResolvingDiscoverable.of(new Discoverable("test-auth-failure", httpService.getBindAddress()))); try { // Use a different hostname to make sure the connection is not getting reused. Otherwise it may not have auth // failure as intended URL url = new URL("http://test-auth-failure/ping"); HttpRequests.execute(io.cdap.common.http.HttpRequest.get(url).build()); } finally { cancellable.cancel(); authPass = oldPass; } } @Test (expected = SocketException.class) public void testNoAuth() throws Exception { Authenticator.setDefault(null); Cancellable cancellable = discoveryService.register( ResolvingDiscoverable.of(new Discoverable("test-no-auth", httpService.getBindAddress()))); try { // Use a different hostname to make sure the connection is not getting reused. Otherwise it may not have auth // failure as intended URL url = new URL("http://test-no-auth/ping"); HttpRequests.execute(io.cdap.common.http.HttpRequest.get(url).build()); } finally { cancellable.cancel(); Authenticator.setDefault(authenticator); } } }
dearbornlavern/zos
pkg/stubs/version_monitor_stub.go
package stubs import ( "context" semver "github.com/blang/semver" zbus "github.com/threefoldtech/zbus" ) type VersionMonitorStub struct { client zbus.Client module string object zbus.ObjectID } func NewVersionMonitorStub(client zbus.Client) *VersionMonitorStub { return &VersionMonitorStub{ client: client, module: "identityd", object: zbus.ObjectID{ Name: "monitor", Version: "0.0.1", }, } } func (s *VersionMonitorStub) Version(ctx context.Context) (<-chan semver.Version, error) { ch := make(chan semver.Version) recv, err := s.client.Stream(ctx, s.module, s.object, "Version") if err != nil { return nil, err } go func() { defer close(ch) for event := range recv { var obj semver.Version if err := event.Unmarshal(&obj); err != nil { panic(err) } ch <- obj } }() return ch, nil }
pdeljanov/Ayane
include/Ayane/SampleFormats.h
<reponame>pdeljanov/Ayane<filename>include/Ayane/SampleFormats.h /* * * Copyright (c) 2013 <NAME>. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. * */ #ifndef AYANE_SAMPLEFORMATS_H_ #define AYANE_SAMPLEFORMATS_H_ #include "Ayane/Attributes.h" #include <cstdint> #include <cmath> /* * Clamping functions from FFMPEG's libavcodec. Supplemented * with signed 24 bit integer clamping. */ static inline uint8_t clip_uint8( int in ) { if ( in & ( ~0xFF ) ) return ( -in ) >> 31; else return (uint8_t)in; } static inline int8_t clip_int8( int in ) { if ( ( in + 0x80 ) & ~0xFF ) return ( in >> 31 ) ^ 0x7F; else return (int8_t)in; } static inline uint16_t clip_uint16( int in ) { if ( in & ( ~0xFFFF ) ) return ( -in )>>31; else return (uint16_t)in; } static inline int16_t clip_int16( int in ) { if ( ( in + 0x8000 ) & ~0xFFFF ) return ( in >> 31 ) ^ 0x7FFF; else return (int16_t)in; } static inline int32_t clip_int24( int in ) { if ( ( in + 0x800000 ) & ~0xFFFFFF ) return ( in >> 31 ) ^ 0x7FFFFF; else return (int32_t)in; } static inline int32_t clip_int32( int64_t in ) { if ( ( in + 0x80000000u ) & ~0xFFFFFFFFul ) return ( in >> 63 ) ^ 0x7FFFFFFF; else return (int32_t)in; } namespace Ayane { class RawBuffer; /** Enumeration of supported sample format data types. */ typedef enum { /** Unsigned 8bit integer sample format. */ kUInt8 = 0, /** Signed 16bit integer sample format. */ kInt16, /** Signed 24bit integer sample format. */ kInt24, /** Signed 32bit integer sample format. */ kInt32, /** 32bit floating point sample format. */ kFloat32, /** 64bit floating point sample format. */ kFloat64 } SampleFormat; /** Data type for a signed 32bit integer sample. */ typedef int32_t SampleInt32; /** Data type for a signed 24bit integer sample. */ typedef int32_t SampleInt24; /** Data type for a signed 16bit sample. */ typedef int16_t SampleInt16; /** Data type for an unsigned 8bit sample. */ typedef uint16_t SampleUInt8; /** Data type for a 32bit floating point sample. */ typedef float SampleFloat32; /** Data type for a 64bit floating point sample. */ typedef double SampleFloat64; /** Data type that should be used when representing a sample rate. */ typedef unsigned int SampleRate; class SampleFormats { public: typedef struct { /** Friendly name. */ const char *name; /** The size of the sample in memory. */ unsigned int stride; /** The actual size of the sample. */ unsigned int formatSize; /** The actual number of bits contained in one sample. */ unsigned int numBits; } Descriptor; /** Retreives information about the specified sample format. */ static const Descriptor &about( SampleFormat format ) { return descriptorTable[format]; } /** * Converts a sample of InSampleType to OutSampleType. */ template< typename InSampleType, typename OutSampleType > static force_inline OutSampleType convertSample( InSampleType ); /** * Converts many samples of InSampleType to OutSampleType. */ template< typename InSampleType, typename OutSampleType > static void convertMany( InSampleType *no_overlap src, OutSampleType *no_overlap dest, int count ) { for( int i = 0; i < count; ++i ) { dest[i] = SampleFormats::convertSample<InSampleType, OutSampleType>(src[i]); } } /** * Converts many samples of InSampleType to OutSampleType with a * custom source buffer stride. */ template< typename InSampleType, typename OutSampleType > static void convertMany(InSampleType *no_overlap src, int srcStride, OutSampleType *no_overlap dest, int count ) { OutSampleType *end = dest + count; while( dest != end ) { *dest = SampleFormats::convertSample<InSampleType, OutSampleType>(*src); src += srcStride; ++dest; } } /** * Converts many samples of InSampleType to OutSampleType with a * custom destination buffer stride. */ template< typename InSampleType, typename OutSampleType > static void convertMany(InSampleType *no_overlap src, OutSampleType *no_overlap dest, int destStride, int count ) { InSampleType *end = src + count; while( src != end ) { *dest = SampleFormats::convertSample<InSampleType, OutSampleType>(*src); ++src; dest += destStride; } } private: // Format descriptor table. // Printable Name, In Memory Size, Actual Size (bytes), Bit Width static constexpr Descriptor descriptorTable[] = { { "UInt8" , sizeof(SampleUInt8) , 1, 8 }, { "Int16" , sizeof(SampleInt16) , 2, 16 }, { "Int24" , sizeof(SampleInt24) , 3, 24 }, { "Int32" , sizeof(SampleInt32) , 4, 32 }, { "Float32", sizeof(SampleFloat32), 4, 32 }, { "Float64", sizeof(SampleFloat64), 8, 64 } }; }; /* --- SampleFormats::convertSample(...) Specializations --- */ /* SampleUInt8 convertSample(...) specializations */ template<> force_inline SampleUInt8 SampleFormats::convertSample( SampleUInt8 si ) { return si; } template<> force_inline SampleInt16 SampleFormats::convertSample( SampleUInt8 si ) { return (si - 0x80) << 8; } template<> force_inline SampleInt32 SampleFormats::convertSample( SampleUInt8 si ) { return (si - 0x80) << 24; } template<> force_inline SampleFloat32 SampleFormats::convertSample( SampleUInt8 si ) { return (si - 0x80) * (1.0f / (1<<7)); } template<> force_inline SampleFloat64 SampleFormats::convertSample( SampleUInt8 si ) { return (si - 0x80) * (1.0 / (1<<7)); } /* SampleInt16 convertSample(...) specializations */ template<> force_inline SampleUInt8 SampleFormats::convertSample( SampleInt16 si ) { return (si >> 8) + 0x80; } template<> force_inline SampleInt16 SampleFormats::convertSample( SampleInt16 si ) { return si; } template<> force_inline SampleInt32 SampleFormats::convertSample( SampleInt16 si ) { return (si) << 16; } template<> force_inline SampleFloat32 SampleFormats::convertSample( SampleInt16 si ) { return (si) * (1.0f / (1<<15)); } template<> force_inline SampleFloat64 SampleFormats::convertSample( SampleInt16 si ) { return (si) * (1.0 / (1<<15)); } /* SampleInt32 convertSample(...) specializations */ template<> force_inline SampleUInt8 SampleFormats::convertSample( SampleInt32 si ) { return (si >> 24 ) + 0x80; } template<> force_inline SampleInt16 SampleFormats::convertSample( SampleInt32 si ) { return (si) >> 16; } template<> force_inline SampleInt32 SampleFormats::convertSample( SampleInt32 si ) { return si; } template<> force_inline SampleFloat32 SampleFormats::convertSample( SampleInt32 si ) { return (si) * (1.0f / (1u<<31)); } template<> force_inline SampleFloat64 SampleFormats::convertSample( SampleInt32 si ) { return (si) * (1.0 / (1u<<31)); } /* SampleFloat32 convertSample(...) specializations */ template<> force_inline SampleUInt8 SampleFormats::convertSample( SampleFloat32 si ) { return clip_uint8( lrintf(si * (1<<7) ) + 0x80); } template<> force_inline SampleInt16 SampleFormats::convertSample( SampleFloat32 si ) { return clip_int16( lrintf(si * (1<<15)) ); } template<> force_inline SampleInt32 SampleFormats::convertSample( SampleFloat32 si ) { return clip_int32( llrintf(si * (1u<<31)) ); } template<> force_inline SampleFloat32 SampleFormats::convertSample( SampleFloat32 si ) { return si; } template<> force_inline SampleFloat64 SampleFormats::convertSample( SampleFloat32 si ) { return si; } /* SampleFloat64 convertSample(...) specializations */ template<> force_inline SampleUInt8 SampleFormats::convertSample( SampleFloat64 si ) { return clip_uint8( lrint(si * (1<<7)) + 0x80 ); } template<> force_inline SampleInt16 SampleFormats::convertSample( SampleFloat64 si ) { return clip_int16( lrint(si * (1<<15)) ); } template<> force_inline SampleInt32 SampleFormats::convertSample( SampleFloat64 si ) { return clip_int32( llrint(si * (1u<<31)) ); } template<> force_inline SampleFloat32 SampleFormats::convertSample( SampleFloat64 si ) { return si; } template<> force_inline SampleFloat64 SampleFormats::convertSample( SampleFloat64 si ) { return si; } } #endif
ranwise/djangochannel
backend/api/v2/courses/serializers.py
from rest_framework import serializers from backend.courses.models import Course, Category class ListCategoryCourseSerializer(serializers.ModelSerializer): """Сериализация списка категорий курсов""" class Meta: model = Category fields = ("id", "title", "slug") class ListCourseSerializer(serializers.ModelSerializer): """Сериализация списка курсов""" class Meta: model = Course fields = ("id", "title", "description", "date_start", "date_end", "get_absolute_url") class DetailCourseSerializer(serializers.ModelSerializer): """Сериализация описания курса""" is_student = serializers.SerializerMethodField() def get_is_student(self, obj): """Проверка является ли юзер студентом курса""" if self.context.get("request", None): if self.context['request'].user in self.instance.students.all(): return True class Meta: model = Course exclude = ("students", "test_in_course")
yanaspaula/rdf4j
core/spin/src/main/java/org/eclipse/rdf4j/spin/function/spif/Cast.java
/******************************************************************************* * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/org/documents/edl-v10.php. *******************************************************************************/ package org.eclipse.rdf4j.spin.function.spif; import org.eclipse.rdf4j.model.IRI; import org.eclipse.rdf4j.model.Literal; import org.eclipse.rdf4j.model.Value; import org.eclipse.rdf4j.model.ValueFactory; import org.eclipse.rdf4j.model.vocabulary.SPIF; import org.eclipse.rdf4j.query.algebra.evaluation.ValueExprEvaluationException; import org.eclipse.rdf4j.query.algebra.evaluation.function.BinaryFunction; import org.eclipse.rdf4j.query.algebra.evaluation.function.Function; import org.eclipse.rdf4j.query.algebra.evaluation.function.FunctionRegistry; public class Cast extends BinaryFunction { @Override public String getURI() { return SPIF.CAST_FUNCTION.toString(); } @Override protected Value evaluate(ValueFactory valueFactory, Value arg1, Value arg2) throws ValueExprEvaluationException { if (!(arg1 instanceof Literal)) { throw new ValueExprEvaluationException("First argument must be a literal"); } if (!(arg2 instanceof IRI)) { throw new ValueExprEvaluationException("Second argument must be a datatype"); } Literal value = (Literal) arg1; IRI targetDatatype = (IRI) arg2; Function func = FunctionRegistry.getInstance().get(targetDatatype.stringValue()).orElse(null); return (func != null) ? func.evaluate(valueFactory, value) : valueFactory.createLiteral(value.getLabel(), targetDatatype); } }
Morpheus-compiler/polycube
src/services/pcn-katran/src/MaglevBase.cpp
/* * 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; version 2 of the License. * * 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., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "MaglevBase.h" #include "MurmurHash3.h" namespace katran { namespace { constexpr uint32_t kHashSeed0 = 0; constexpr uint32_t kHashSeed1 = 2307; constexpr uint32_t kHashSeed2 = 42; constexpr uint32_t kHashSeed3 = 2718281828; } // namespace void MaglevBase::genMaglevPermutation( std::vector<uint32_t>& permutation, const Endpoint& endpoint, const uint32_t pos, const uint32_t ring_size) { auto offset_hash = MurmurHash3_x64_64(endpoint.hash, kHashSeed2, kHashSeed0); auto offset = offset_hash % ring_size; auto skip_hash = MurmurHash3_x64_64(endpoint.hash, kHashSeed3, kHashSeed1); auto skip = (skip_hash % (ring_size - 1)) + 1; permutation[2 * pos] = offset; permutation[2 * pos + 1] = skip; } } // namespace katran
ilaotan/sumk
src/main/java/org/yx/db/sql/DBSettings.java
<reponame>ilaotan/sumk<gh_stars>0 /** * Copyright (C) 2016 - 2030 youtongluan. * * 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.yx.db.sql; import org.yx.conf.AppInfo; import org.yx.log.Logs; public final class DBSettings { private static boolean FAIL_IF_PROPERTY_NOT_MAPPED; private static boolean FROM_CACHE; private static boolean TO_CACHE; private static int MAX_LOG_PARAM_LENGTH; private static int LIMIT_AS_NO_LIMIT; private static int UNION_LOG_TIME; private static boolean UNION_LOG_ENABLE; private static int DEBUG_LOG_SPEND_TIME; private static String CUSTOM_DB_NAME; public static int debugLogSpendTime() { return DEBUG_LOG_SPEND_TIME; } public static int unionLogTime() { return UNION_LOG_TIME; } public static boolean isUnionLogEnable() { return UNION_LOG_ENABLE; } public static boolean failIfPropertyNotMapped() { return FAIL_IF_PROPERTY_NOT_MAPPED; } public static boolean fromCache() { return FROM_CACHE; } public static boolean toCache() { return TO_CACHE; } public static int asNoLimit() { return LIMIT_AS_NO_LIMIT; } public static int maxSqlParamLength() { return MAX_LOG_PARAM_LENGTH; } public static String customDbName() { return CUSTOM_DB_NAME; } public static synchronized void init() { if (LIMIT_AS_NO_LIMIT > 0) { return; } if (customDbName() == null) { CUSTOM_DB_NAME = AppInfo.get("sumk.db.default", null); } AppInfo.addObserver(info -> { try { FAIL_IF_PROPERTY_NOT_MAPPED = AppInfo.getBoolean("sumk.db.failIfPropertyNotMapped", true); FROM_CACHE = AppInfo.getBoolean("sumk.db.fromCache", true); TO_CACHE = AppInfo.getBoolean("sumk.db.toCache", true); LIMIT_AS_NO_LIMIT = AppInfo.getInt("sumk.db.asnolimit", 5000); MAX_LOG_PARAM_LENGTH = AppInfo.getInt("sumk.sql.param.maxlength", 5000); UNION_LOG_TIME = AppInfo.getInt("sumk.unionlog.sql.time", 0); UNION_LOG_ENABLE = AppInfo.getBoolean("sumk.unionlog.sql.enable", true); DEBUG_LOG_SPEND_TIME = AppInfo.getInt("sumk.sql.debug.spendTime", 100); } catch (Exception e) { Logs.db().info(e.getMessage(), e); } }); } }
olgadanylova/ios-SDK
SDK/watchos/backendless/include/ReferenceCache.h
// // ReferenceCache.h // backendlessAPI /* * ********************************************************************************************************************* * * BACKENDLESS.COM CONFIDENTIAL * * ******************************************************************************************************************** * * Copyright 2018 BACKENDLESS.COM. All Rights Reserved. * * NOTICE: All information contained herein is, and remains the property of Backendless.com and its suppliers, * if any. The intellectual and technical concepts contained herein are proprietary to Backendless.com and its * suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret * or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden * unless prior written permission is obtained from Backendless.com. * * ******************************************************************************************************************** */ #import <Foundation/Foundation.h> @interface ReferenceCache : NSObject -(void)reset; -(void)addObject:(id)obj; -(void)addString:(NSString *)obj; -(int)getStringId:(NSString *)obj; -(int)getObjectId:(id)obj; -(int)getId:(id)obj; @end
FedericoCampanozzi/HotLineCesena2
app/src/main/java/hotlinecesena/model/inventory/Inventory.java
package hotlinecesena.model.inventory; import java.util.Optional; import hotlinecesena.model.entities.actors.Actor; import hotlinecesena.model.entities.items.Item; import hotlinecesena.model.entities.items.Weapon; /** * * Models an inventory for {@link Actor}s which may contain weapons and items. * */ public interface Inventory { /** * Adds a given quantity of an {@link Item} to this inventory. * @param item the {@code Item} to be added. * @param quantity quantity of the item to be added. */ void add(Item item, int quantity); /** * Returns the quantity of a given {@link Item} present in this inventory. * @param item the item to look for in this inventory * @return the quantity of the given item that this inventory is holding. */ int getQuantityOf(Item item); /** * Returns the weapon currently equipped in this inventory. * @return an {@link Optional} containing the equipped weapon, if * present, otherwise returns an empty optional. */ Optional<Weapon> getWeapon(); /** * Handles reloading for the currently equipped weapon. */ void reloadWeapon(); /** * Makes the actor equip the next weapon. */ void switchToNextWeapon(); /** * Makes the actor equip the previous weapon. */ void switchToPreviousWeapon(); /** * Checks to see if the reload action for the equipped weapon is currently ongoing. * @return {@code true} if this inventory is currently reloading the equipped * weapon, {@code false} otherwise. */ boolean isReloading(); /** * Updates features of this inventory that depend on time. * @param timeElapsed the time elapsed since the last update. */ void update(double timeElapsed); }
TamaraAbells/okuna-api
openbook_auth/migrations/0028_user_uuid.py
# Generated by Django 2.2b1 on 2019-03-11 16:51 from django.db import migrations, models import uuid def create_uuid(apps, schema_editor): User = apps.get_model('openbook_auth', 'User') for user in User.objects.all(): user.uuid = uuid.uuid4() user.save() class Migration(migrations.Migration): dependencies = [ ('openbook_auth', '0027_auto_20190311_1432'), ] operations = [ migrations.AddField( model_name='user', name='uuid', field=models.UUIDField(default=uuid.uuid4, editable=False), ), migrations.RunPython(create_uuid), ]
jpan127/RJD-MP3
SJone/firmware/mp3/L5_Application/drivers/uart.hpp
<gh_stars>0 #pragma once #include "FreeRTOS.h" #include "LPC17xx.h" #include "semphr.h" #include "singleton_template.hpp" #define DEFAULT_BAUDRATE (9600) // Interrupt Enable Bits #define IER_RBR_BIT (1 << 0) // RBR interrupt enable #define IER_THRE_BIT (1 << 1) // THRE interrupt enable #define IER_RX_LSR_BIT (1 << 2) // RX line status interrupt enable // Interrupt Status Bits #define IIR_RX_LSR_BIT (0x3 << 1) // RX line status error #define IIR_RXREADY_BIT (1 << 2) // RX data available #define IIR_TIO_BIT (0x3 << 2) // Character time out indication #define IIR_THRE_BIT (1 << 1) // THRE // LCR Divisor Latch Access Bit #define LCR_DLAB_BIT (1 << 7) // Disable before configuration // Line Status Register bits #define LSR_RDR_BIT (1 << 0) // Set when RX FIFO is not empty #define LSR_OE_BIT (1 << 1) // Overrun flag, means new data is lost #define LSR_PE_BIT (1 << 2) // Parity error #define LSR_FE_BIT (1 << 3) // Framing error, incorrect stop bit, unsynchronized #define LSR_BI_BIT (1 << 4) // Break interrupt #define LSR_THRE_BIT (1 << 5) // Transmit holding register empty #define LSR_TEMT_BIT (1 << 6) // Both THR and TSR (Transmit Shift Register) are empty #define LSR_RXFE_BIT (1 << 7) // RBR contains an error (framing, parity, break interrupt) // Not using UART0 or UART1 typedef enum { UART_PORT2 = 2, UART_PORT3 = 3 } uart_port_t; typedef enum { POLLING, INTERRUPT } uart_mode_t; // Global Variables extern SemaphoreHandle_t UartSem; extern "C" { void UART2_IRQHandler(); void UART3_IRQHandler(); } class Uart { public: // UART0: TX: P0.2 RX: P0.3 // UART2: TX: P0.10 RX: P0.11 // UART3: TX: P0.0 RX: P0.1 // Initializes registers and configures baud rate void Init(uint32_t baud_rate=DEFAULT_BAUDRATE); // Checks if TX buffer is empty bool TxAvailable(); // Send string // @param buffer : pre-allocated buffer // @param buffer_size : size of pre-allocated buffer void SendString(uint8_t *buffer, size_t buffer_size); void SendString(const char *buffer, size_t buffer_size); // Send byte bool SendByte(uint8_t byte); // Checks if anything waiting in RX buffer bool RxAvailable(); // Receive string // @param buffer : pre-allocated buffer // @param buffer_size : size of pre-allocated buffer // @return : size of buffer filled size_t ReceiveString(uint8_t *buffer, size_t buffer_size); // Receive byte bool ReceiveByte(uint8_t *byte, uint32_t timeout_ms); protected: // Constructor Uart(uart_port_t port); // Member variables uart_port_t Port; LPC_UART_TypeDef *UartPtr; IRQn_Type IRQPtr; }; class Uart2 : public Uart, public SingletonTemplate <Uart2> { private: Uart2() : Uart(UART_PORT2) { // Empty } friend class SingletonTemplate <Uart2>; }; class Uart3 : public Uart, public SingletonTemplate <Uart3> { private: Uart3() : Uart(UART_PORT3) { // Empty } friend class SingletonTemplate <Uart3>; }; /*////////////////////////////////////////////////////////////////////////////////////////////////// [RBR] Receiver Buffer Register : Contains the next received character to be read. [THR] Transmit Holding Register : Contains the next to be transmitted character. [DLL] Divisor Latch LSB : LSB of baud rate divisor value. [DLM] Divisor Latch MSB : MSB of baud rate divisor value. [IER] Interrupt Enable Register : Contains enable bits for UART interrupts. [IIR] Interrupt ID Register : Identifies which interrupts are pending. [FCR] FIFO Control Register : Controls UART FIFO usage and modes. [LCR] Line Control Register : Contains controls for frame formatting + break generation. [LSR] Line Status Register : Contains flags for tx/rx status, line errors. [SCR] Scratch Pad Register : 8-bit temp storage for software. [ACR] Auto-baud Control Register : Contains controls for auto-baud feature. [ICR] IrDA Control Register : Enables/configures IrDA mode. [FDR] Fractional Divider Register : Generates clock input for baud rate divider. [TER] Transmit Enable Register : Turns off UART transmitter for use with software control. *///////////////////////////////////////////////////////////////////////////////////////////////////
WortNils/similarityComparator
sansa-query/sansa-query-spark/src/main/scala/net/sansa_stack/query/spark/ontop/JDBCDatabaseGenerator.scala
<filename>sansa-query/sansa-query-spark/src/main/scala/net/sansa_stack/query/spark/ontop/JDBCDatabaseGenerator.scala package net.sansa_stack.query.spark.ontop import java.sql.{Connection, SQLException} import net.sansa_stack.rdf.common.partition.core.{RdfPartitionStateDefault, RdfPartitioner} import net.sansa_stack.rdf.common.partition.schema._ import org.apache.spark.sql.catalyst.ScalaReflection import org.apache.spark.sql.types.StructType import scala.reflect.runtime.universe.typeOf /** * Setup the JDBC database needed for the Ontop metadata extraction. * * @author <NAME> */ object JDBCDatabaseGenerator { val logger = com.typesafe.scalalogging.Logger(JDBCDatabaseGenerator.getClass) // mapping from partition type to H2 database type private val partitionType2DatabaseType = Map( typeOf[SchemaStringLong] -> "LONG", typeOf[SchemaStringDouble] -> "DOUBLE", typeOf[SchemaStringFloat] -> "FLOAT", typeOf[SchemaStringDecimal] -> "DECIMAL", typeOf[SchemaStringBoolean] -> "BOOLEAN", typeOf[SchemaStringString] -> "VARCHAR(255)", typeOf[SchemaStringDate] -> "DATE", typeOf[SchemaStringTimestamp] -> "TIMESTAMP" ) // .map(e => (typeOf[e._1.type], e._2)) /** * Generates the tables per partitions for the database at the given connection. * * @param connection the database connection * @param partitions the partitions */ def generateTables(connection: Connection, partitioner: RdfPartitioner[RdfPartitionStateDefault], partitions: Set[RdfPartitionStateDefault], blankNodeStrategy: BlankNodeStrategy.Value = BlankNodeStrategy.Table): Unit = { try { val stmt = connection.createStatement() stmt.executeUpdate("DROP ALL OBJECTS") partitions.foreach { p => val name = SQLUtils.createTableName(p, blankNodeStrategy) // val sparkSchema = ScalaReflection.schemaFor(p.layout.schema).dataType.asInstanceOf[StructType] val schema = partitioner.determineLayout(p).schema val sparkSchema = ScalaReflection.schemaFor(schema).dataType.asInstanceOf[StructType] logger.trace(s"creating table for property ${p.predicate} with Spark schema $sparkSchema and layout ${schema}") p match { case RdfPartitionStateDefault(subjectType, predicate, objectType, datatype, langTagPresent, lang) => val s = objectType match { case 0|1 => s"CREATE TABLE IF NOT EXISTS ${SQLUtils.escapeTablename(name)} (" + "s varchar(255) NOT NULL," + "o varchar(255) NOT NULL" + ")" case 2 => if (schema == typeOf[SchemaStringStringLang]) { s"CREATE TABLE IF NOT EXISTS ${SQLUtils.escapeTablename(name)} (" + "s varchar(255) NOT NULL," + "o varchar(255) NOT NULL," + "l varchar(10)" + ")" } else { if (schema == typeOf[SchemaStringStringType]) { s"CREATE TABLE IF NOT EXISTS ${SQLUtils.escapeTablename(name)} (" + "s varchar(255) NOT NULL," + "o varchar(255) NOT NULL," + "t varchar(255) NOT NULL" + ")" } else { val colType = partitionType2DatabaseType.get(schema) if (colType.isDefined) { s""" |CREATE TABLE IF NOT EXISTS ${SQLUtils.escapeTablename(name)} ( |s varchar(255) NOT NULL, |o ${colType.get} NOT NULL) |""".stripMargin } else { logger.error(s"Error: couldn't create H2 table for property $predicate with schema $schema") "" } } } case _ => logger.error("TODO: bnode H2 SQL table for Ontop mappings") "" } logger.debug(s) stmt.addBatch(s) case _ => logger.error(s"wrong partition type: ${p}") } } // stmt.addBatch(s"CREATE TABLE IF NOT EXISTS triples (" + // "s varchar(255) NOT NULL," + // "p varchar(255) NOT NULL," + // "o varchar(255) NOT NULL" + // ")") val numTables = stmt.executeBatch().length logger.debug(s"created $numTables tables") } catch { case e: SQLException => logger.error("Error occurred when creating in-memory H2 database", e) } connection.commit() } }
apache/uima-ruta
ruta-maven-plugin/src/it/multimodule/main/src/test/java/org/apache/uima/ruta/maven/OneEngineTest.java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.uima.ruta.maven; import java.io.File; import static org.junit.Assert.*; import org.apache.uima.UIMAFramework; import org.apache.uima.analysis_engine.AnalysisEngine; import org.apache.uima.analysis_engine.AnalysisEngineDescription; import org.apache.uima.cas.CAS; import org.apache.uima.cas.Type; import org.apache.uima.cas.text.AnnotationFS; import org.apache.uima.cas.text.AnnotationIndex; import org.apache.uima.util.XMLInputSource; import org.junit.Test; public class OneEngineTest { @Test public void test() throws Exception{ File descDirectory = new File("target/generated-sources/ruta/descriptor"); File aeFile1 = new File(descDirectory, "my/package/one/OneEngine.xml"); assertTrue(aeFile1.exists()); File tsFile1 = new File(descDirectory, "my/package/one/OneTypeSystem.xml"); assertTrue(tsFile1.exists()); AnalysisEngineDescription aed = UIMAFramework.getXMLParser().parseAnalysisEngineDescription(new XMLInputSource(aeFile1)); AnalysisEngine ae = UIMAFramework.produceAnalysisEngine(aed); CAS cas = ae.newCAS(); cas.setDocumentText("This is a test."); ae.process(cas); Type type1 = cas.getTypeSystem().getType("my.package.one.One.Type1"); AnnotationIndex<AnnotationFS> ai1 = cas.getAnnotationIndex(type1); assertEquals(1, ai1.size()); assertEquals("This", ai1.iterator().next().getCoveredText()); Type type2 = cas.getTypeSystem().getType("my.package.two.Two.Type2"); AnnotationIndex<AnnotationFS> ai2 = cas.getAnnotationIndex(type2); assertEquals(1, ai2.size()); assertEquals("This", ai2.iterator().next().getCoveredText()); Type type3 = cas.getTypeSystem().getType("my.package.three.Three.Type3"); AnnotationIndex<AnnotationFS> ai3 = cas.getAnnotationIndex(type3); assertEquals(1, ai3.size()); assertEquals("This", ai3.iterator().next().getCoveredText()); cas.release(); } }
DFE-Digital/get-help-with-tech
spec/controllers/support/schools/headteacher_controller_spec.rb
require 'rails_helper' RSpec.describe Support::Schools::HeadteacherController, type: :controller do let(:non_support_third_line_user) { create(:user, is_support: true, role: 'no') } let(:support_third_line_user) { create(:support_user, :third_line) } let!(:school) { create(:school) } describe '#edit' do context 'non support third line users' do before { sign_in_as non_support_third_line_user } specify do expect { get :edit, params: { school_urn: school.urn } }.to be_forbidden_for(non_support_third_line_user) end end context 'support third line users' do before do sign_in_as support_third_line_user end context 'when the school has no contacts at all' do before { get :edit, params: { school_urn: school.urn } } specify { expect(response).to be_successful } it 'exposes a blank form to create the headteacher contact of the school' do expect(assigns(:form)).to be_a(Support::School::ChangeHeadteacherForm) expect(assigns(:form).school).to eq(school) expect(assigns(:form).email_address).to be_nil expect(assigns(:form).full_name).to be_nil expect(assigns(:form).id).to be_nil expect(assigns(:form).phone_number).to be_nil expect(assigns(:form).role).to be_nil expect(assigns(:form).title).to be_nil end end context 'when the school has a non-headteacher contact' do let!(:contact) { create(:school_contact, :contact, school: school) } before { get :edit, params: { school_urn: school.urn } } specify { expect(response).to be_successful } it 'exposes a form initialized to set the contact as the headteacher of the school' do expect(assigns(:form).school).to eq(school) expect(assigns(:form).email_address).to eq(contact.email_address) expect(assigns(:form).full_name).to eq(contact.full_name) expect(assigns(:form).id).to eq(contact.id) expect(assigns(:form).phone_number).to eq(contact.phone_number) expect(assigns(:form).role).to eq(contact.role) expect(assigns(:form).title).to eq(contact.title) end end context 'when the school has a headteacher contact' do let!(:headteacher) { create(:school_contact, :headteacher, school: school) } before { get :edit, params: { school_urn: school.urn } } specify { expect(response).to be_successful } it 'exposes a form initialized to update the details of the headteacher of the school' do expect(assigns(:form).school).to eq(school) expect(assigns(:form).email_address).to eq(headteacher.email_address) expect(assigns(:form).full_name).to eq(headteacher.full_name) expect(assigns(:form).id).to eq(headteacher.id) expect(assigns(:form).phone_number).to eq(headteacher.phone_number) expect(assigns(:form).role).to eq(headteacher.role) expect(assigns(:form).title).to eq(headteacher.title) end end end end describe '#update' do let(:full_name) { Faker::Name.unique.name } let(:email_address) { Faker::Internet.unique.email } let(:id) { Faker::Number.unique.between(from: 1000, to: 100_000) } let(:phone_number) { Faker::PhoneNumber.phone_number } let(:title) { Faker::Lorem.sentence } let(:params) do { school_urn: school.urn, support_school_change_headteacher_form: { email_address: email_address, full_name: full_name, id: id, phone_number: phone_number, title: title, }, } end context 'non support third line users' do before { sign_in_as non_support_third_line_user } specify do expect { patch :update, params: params }.to be_forbidden_for(non_support_third_line_user) end end context 'support third line users' do before do sign_in_as support_third_line_user patch :update, params: params end context 'when the headteacher can be updated' do it 'redirects back to school' do expect(response).to redirect_to(support_school_path(school)) end it 'shows a successful change message to the user' do expect(flash[:success]).to eq("#{school.name}'s headteacher details updated") end end context 'when the headteacher cannot be updated for some reason' do let(:email_address) {} it 'display again the form with some errors' do expect(assigns(:form).errors).not_to be_empty end end end end end
maltewirz/code-challenges
src/code-challenges/codewars/5KYU/sumPairs/test_sum_pairs.py
from sum_pairs import sum_pairs import unittest class Test(unittest.TestCase): def test_1(self): result = sum_pairs([4, 3, 2, 3, 4], 6) self.assertEqual(result, [4, 2]) def test_2(self): result = sum_pairs([10, 5, 2, 3, 7, 5], 10) self.assertEqual(result, [3, 7]) if __name__ == "__main__": unittest.main()
Teagum/chainsaddiction
src/chainsaddiction/utils/tests/runtest.c
<gh_stars>0 #include "unittest.h" #include "test-utils.h" int main (void) { SETUP; RUN_TEST (test__local_decoding); RUN_TEST (test__global_decoding); EVALUATE; }
your-code-is-my-property/celloverflow
src/firebase/helpers/questionHelper.js
<gh_stars>1-10 import { firestore, timestamp } from '../firebase'; export const saveQuestionToFirestore = (questionData) => { return new Promise((resolve, reject) => { const questionRef = firestore.collection('questions'); questionRef.add({ ...questionData, votes: 0, voters: {}, createdAt: timestamp.now() }) .then(resolve) .catch(reject) }); } export const getAllQuestions = (username) => { return new Promise((resolve, reject) => { const questionRef = !username ? firestore.collection('questions') : firestore.collection('questions').where('username', '==', username); questionRef.get().then(document => { const allQuestions = document.docs.map(doc => { return { ...doc.data(), id: doc?.id, } }); resolve(allQuestions) }).catch(err => { console.log(err); reject(); }) }); } export const getQuestionById = (questionId) => { return new Promise((resolve, reject) => { const questionRef = firestore.collection('questions').doc(questionId); questionRef.get().then(question => { if (!question.exists) reject(); resolve({ ...question.data(), id: question.id }) }).catch(err => { console.log(err) reject() }); }); } export const deleteQuestion = (questionId) => { return new Promise((resolve, reject) => { const questionRef = firestore.collection('questions').doc(questionId); const answersRef = firestore.collection('answers').doc(questionId).collection('answers'); questionRef.delete().then(resolve).catch(err => { console.log(err) reject() }); try { answersRef.get().then(collection => { collection.docs.map(doc => doc.ref.delete()); }); } catch (err) { console.log(err); } }); } export const voteQuestion = (questionId, votes, voters) => { return new Promise((resolve, reject) => { const questionRef = firestore.collection('questions').doc(questionId); questionRef.update({ votes, voters }).then(resolve).catch(err => { console.log(err) reject() }); }); }
Zix13/capital-components
src/fss-icons/forum_128.js
<reponame>Zix13/capital-components "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _react = _interopRequireDefault(require("react")); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _extends() { _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; }; return _extends.apply(this, arguments); } var SvgComponent = function SvgComponent(props) { return _react.default.createElement("svg", _extends({ viewBox: "0 0 128 128" }, props), _react.default.createElement("path", { d: "M109.937 18.06C101.254 9.373 89.254 4 76 4 62.746 4 50.746 9.373 42.062 18.06 33.375 26.746 28 38.746 28 52c0 4.163.531 8.202 1.528 12.054A23.433 23.433 0 0 0 28 64a23.929 23.929 0 0 0-16.969 7.031A23.918 23.918 0 0 0 4 88c0 7.016 2.687 13.371 7.031 17.969L28 124v-12a23.929 23.929 0 0 0 16.969-7.031 23.952 23.952 0 0 0 6.453-11.741A47.751 47.751 0 0 0 76 100v24l33.937-36.064C118.625 78.74 124 66.033 124 52c0-13.254-5.375-25.254-14.063-33.94zm-2.913 67.134L80 113.913V96h-4c-8.663 0-16.94-2.495-24.021-7.131.009-.289.021-.578.021-.869a23.922 23.922 0 0 0-7.031-16.969 23.982 23.982 0 0 0-11.107-6.307A44.137 44.137 0 0 1 32 52c0-11.751 4.578-22.8 12.892-31.112C53.199 12.577 64.247 8 76 8s22.801 4.577 31.109 12.889C115.422 29.2 120 40.249 120 52c0 12.549-4.606 24.336-12.976 33.194z" }), _react.default.createElement("circle", { cx: 76, cy: 52, r: 6 }), _react.default.createElement("circle", { cx: 96, cy: 52, r: 6 }), _react.default.createElement("circle", { cx: 56, cy: 52, r: 6 })); }; var _default = SvgComponent; exports.default = _default;
kyupid/oopinspring
workspace_springjava/paradise/src/main/java/com/heaven/mvc/board/controller/BoardController.java
package com.heaven.mvc.board.controller; import javax.validation.Valid; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; 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.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; import com.heaven.mvc.board.domain.BoardVO; import com.heaven.mvc.board.service.BoardService; @Controller @SessionAttributes("boardVO") public class BoardController { @Autowired private BoardService boardService; public BoardService getBoardService() { return boardService; } public void setBoardService(BoardService boardService) { this.boardService = boardService; } @RequestMapping(value = "/board/list") public String list(Model model) { model.addAttribute("boardList", boardService.list()); return "/board/list"; } @RequestMapping(value = "/board/read/{seq}") public String read(Model model, @PathVariable int seq) { model.addAttribute("boardVO", boardService.read(seq)); return "/board/read"; } @RequestMapping(value = "/board/write", method = RequestMethod.GET) public String write(Model model) { model.addAttribute("boardVO", new BoardVO()); return "/board/write"; } @RequestMapping(value = "/board/write", method = RequestMethod.POST) public String write(@Valid BoardVO boardVO, BindingResult bindingResult, SessionStatus sessionStatus) { if (bindingResult.hasErrors()) { return "/board/write"; } else { boardService.write(boardVO); sessionStatus.setComplete(); return "redirect:/board/list"; } } @RequestMapping(value = "/board/edit", method = RequestMethod.GET) public String edit(@ModelAttribute BoardVO boardVO) { return "/board/edit"; } @RequestMapping(value = "/board/edit", method = RequestMethod.POST) public String edit(@Valid @ModelAttribute BoardVO boardVO, BindingResult result, int pwd, SessionStatus sessionStatus, Model model) { if (result.hasErrors()) { return "/board/edit"; } else { if (boardVO.getPassword() == pwd) { boardService.edit(boardVO); sessionStatus.setComplete(); return "redirect:/board/list"; } model.addAttribute("msg", "비밀번호가 일치하지 않습니다."); return "/board/edit"; } } @RequestMapping(value = "/board/delete/{seq}", method = RequestMethod.GET) public String delete(@PathVariable int seq, Model model) { model.addAttribute("seq", seq); return "/board/delete"; } @RequestMapping(value = "/board/delete", method = RequestMethod.POST) public String delete(int seq, int pwd, Model model) { int rowCount; BoardVO boardVO = new BoardVO(); boardVO.setSeq(seq); boardVO.setPassword(<PASSWORD>); rowCount = boardService.delete(boardVO); if (rowCount == 0) { model.addAttribute("seq", seq); model.addAttribute("msg", "비밀번호가 일치하지 않습니다."); return "/board/delete"; } else { return "redirect:/board/list"; } } @RequestMapping(value = "/test") @ResponseBody public String test(String name, int age) { return "<h1>" + name + age + "</h1>"; } }
softicar/platform
platform-common/src/main/java/com/softicar/platform/common/io/reader/IManagedReader.java
<gh_stars>1-10 package com.softicar.platform.common.io.reader; import com.softicar.platform.common.io.writer.ManagedWriter; import java.io.Closeable; import java.io.Reader; import java.util.Collection; /** * An {@link IManagedReader} is similar to a {@link Reader} but does not * implement {@link Closeable} or {@link AutoCloseable}. * <p> * The life-cycle of the underlying {@link Reader} is managed outside the scope * of the {@link ManagedReader}. * * @author <NAME> */ public interface IManagedReader { /** * Reads characters from this {@link IManagedReader} into the given buffer. * * @param buffer * the buffer array (never <i>null</i>) * @return the number of characters read; -1 indicates the end of this * {@link IManagedReader} */ int read(char[] buffer); /** * Reads all lines from this {@link IManagedReader}. * * @return all lines of text (never <i>null</i>) */ Collection<String> readLines(); /** * Reads all remaining text from this {@link IManagedReader}. * * @return all remaining text (never <i>null</i>) */ default String readAll() { StringBuilder builder = new StringBuilder(); new ManagedWriter(builder).write(this); return builder.toString(); } }
RippeR37/GLUL
src/GLUL/GUI/Events/TextInput.cpp
#include <GLUL/GUI/Events/TextInput.h> namespace GLUL { namespace GUI { namespace Event { TextInput::TextInput(const std::string& text) : text(text) { } } } }
dnadeau4/HELICS-src
src/helics/core/ipc/IpcBlockingPriorityQueueImpl.cpp
<reponame>dnadeau4/HELICS-src /* Copyright © 2017-2018, Battelle Memorial Institute; Lawrence Livermore National Security, LLC; Alliance for Sustainable Energy, LLC All rights reserved. See LICENSE file and DISCLAIMER for more details. */ #pragma once #include "IpcBlockingPriorityQueueImpl.hpp" #include <algorithm> #include <boost/interprocess/sync/scoped_lock.hpp> namespace helics { namespace ipc { namespace detail { dataBlock::dataBlock (unsigned char *newBlock, size_t blockSize) {} void dataBlock::swap (dataBlock &other) noexcept {} bool dataBlock::isSpaceAvaialble (int sz) const {} bool dataBlock::push (const unsigned char *block, int blockSize) {} int dataBlock::next_data_size () const {} int dataBlock::pop(unsigned char *block) {} /** reverse the order in which the data will be extracted*/ void dataBlock::reverse () {} using namespace boost::interprocess; /** default constructor*/ IpcBlockingPriorityQueueImpl::IpcBlockingPriorityQueueImpl (void *dataBlock, size_t blockSize) {} /** clear the queue*/ void IpcBlockingPriorityQueueImpl::clear () { scoped_lock<interprocess_mutex> pullLock (m_pullLock); // first pullLock scoped_lock<interprocess_mutex> pushLock (m_pushLock); // second pushLock pullData.clear (); pushData.clear (); //TODO add the priority block queueEmptyFlag = true; } /** push an element onto the queue val the value to push on the queue */ void IpcBlockingPriorityQueueImpl::push (const unsigned char *data, size_t size) // forwarding reference { scoped_lock<interprocess_mutex> pushLock (m_pushLock); // only one lock on this branch if (!pushData.empty ()) { pushData.push (data,size); } else { scoped_lock<interprocess_mutex> conditionLock (m_conditionLock); if (queueEmptyFlag) { queueEmptyFlag = false; conditionLock.unlock (); // release the push lock so we don't get a potential deadlock condition pushLock.unlock (); //all locks released //no lock the pulllock scoped_lock<interprocess_mutex> pullLock (m_pullLock); conditionLock.lock (); queueEmptyFlag = false; //reset the queueEmptyflag conditionLock.unlock (); if (pullData.empty ()) { pullData.push (data, size); // pullLock.unlock (); condition_empty.notify_all (); } else { pushLock.lock (); pushData.push (data, size); } } else { pushData.push (data, size); } } } /** push an element onto the queue val the value to push on the queue */ template <class Z> void pushPriority (Z &&val) // forwarding reference { bool expEmpty = true; if (queueEmptyFlag.compare_exchange_strong (expEmpty, false)) { std::unique_lock<std::mutex> pullLock (m_pullLock); // first pullLock queueEmptyFlag = false; // need to set the flag again just in case after we get the lock priorityQueue.push (std::forward<Z> (val)); // pullLock.unlock (); condition.notify_all (); } else { std::unique_lock<std::mutex> pullLock (m_pullLock); priorityQueue.push (std::forward<Z> (val)); expEmpty = true; if (queueEmptyFlag.compare_exchange_strong (expEmpty, false)) { condition.notify_all (); } } } /** construct on object in place on the queue */ template <class... Args> void emplace (Args &&... args) { std::unique_lock<std::mutex> pushLock (m_pushLock); // only one lock on this branch if (!pushElements.empty ()) { pushElements.emplace_back (std::forward<Args> (args)...); } else { bool expEmpty = true; if (queueEmptyFlag.compare_exchange_strong (expEmpty, false)) { // release the push lock so we don't get a potential deadlock condition pushLock.unlock (); std::unique_lock<std::mutex> pullLock (m_pullLock); // first pullLock queueEmptyFlag = false; // need to set the flag again after we get the lock if (pullElements.empty ()) { pullElements.emplace_back (std::forward<Args> (args)...); // pullLock.unlock (); condition.notify_all (); } else { pushLock.lock (); pushElements.emplace_back (std::forward<Args> (args)...); } } else { pushElements.emplace_back (std::forward<Args> (args)...); expEmpty = true; if (queueEmptyFlag.compare_exchange_strong (expEmpty, false)) { condition.notify_all (); } } } } /** emplace an element onto the priority queue val the value to push on the queue */ template <class... Args> void emplacePriority (Args &&... args) { bool expEmpty = true; if (queueEmptyFlag.compare_exchange_strong (expEmpty, false)) { std::unique_lock<std::mutex> pullLock (m_pullLock); // first pullLock queueEmptyFlag = false; // need to set the flag again just in case after we get the lock priorityQueue.emplace (std::forward<Args> (args)...); // pullLock.unlock (); condition.notify_all (); } else { std::unique_lock<std::mutex> pullLock (m_pullLock); priorityQueue.emplace (std::forward<Args> (args)...); expEmpty = true; if (queueEmptyFlag.compare_exchange_strong (expEmpty, false)) { condition.notify_all (); } } } /** try to peek at an object without popping it from the stack @details only available for copy assignable objects @return an optional object with an object of type T if available */ template <typename = std::enable_if<std::is_copy_assignable<T>::value>> stx::optional<T> try_peek () const { std::lock_guard<std::mutex> lock (m_pullLock); if (!priorityQueue.empty ()) { return priorityQueue.front (); } if (pullElements.empty ()) { return stx::nullopt; } auto t = pullElements.back (); return t; } /** try to pop an object from the queue @return an optional containing the value if successful the optional will be empty if there is no element in the queue */ stx::optional<T> try_pop (); /** blocking call to wait on an object from the stack*/ T pop () { T actval; auto val = try_pop (); while (!val) { std::unique_lock<std::mutex> pullLock (m_pullLock); // get the lock then wait if (!priorityQueue.empty ()) { actval = std::move (priorityQueue.front ()); priorityQueue.pop (); return actval; } if (!pullElements.empty ()) // make sure we are actually empty; { actval = std::move (pullElements.back ()); pullElements.pop_back (); return actval; } condition.wait (pullLock); // now wait if (!priorityQueue.empty ()) { actval = std::move (priorityQueue.front ()); priorityQueue.pop (); return actval; } if (!pullElements.empty ()) // check for spurious wake-ups { actval = std::move (pullElements.back ()); pullElements.pop_back (); return actval; } pullLock.unlock (); val = try_pop (); } // move the value out of the optional actval = std::move (*val); return actval; } /** blocking call to wait on an object from the stack with timeout*/ stx::optional<T> pop (std::chrono::milliseconds timeout) { auto val = try_pop (); while (!val) { std::unique_lock<std::mutex> pullLock (m_pullLock); // get the lock then wait if (!priorityQueue.empty ()) { val = std::move (priorityQueue.front ()); priorityQueue.pop (); break; } if (!pullElements.empty ()) // make sure we are actually empty; { val = std::move (pullElements.back ()); pullElements.pop_back (); break; } auto res = condition.wait_for (pullLock, timeout); // now wait if (!priorityQueue.empty ()) { val = std::move (priorityQueue.front ()); priorityQueue.pop (); break; } if (!pullElements.empty ()) // check for spurious wake-ups { val = std::move (pullElements.back ()); pullElements.pop_back (); break; } pullLock.unlock (); val = try_pop (); if (res == std::cv_status::timeout) { break; } } // move the value out of the optional return val; } /** blocking call that will call the specified functor if the queue is empty @param callOnWaitFunction an nullary functor that will be called if the initial query does not return a value @details after calling the function the call will check again and if still empty will block and wait. */ template <typename Functor> T pop (Functor callOnWaitFunction) { auto val = try_pop (); while (!val) // may be spurious so make sure actually have a value { callOnWaitFunction (); std::unique_lock<std::mutex> pullLock (m_pullLock); // first pullLock if (!priorityQueue.empty ()) { auto actval = std::move (priorityQueue.front ()); priorityQueue.pop (); return actval; } if (!pullElements.empty ()) { // the callback may fill the queue or it may have been filled in the meantime auto actval = std::move (pullElements.back ()); pullElements.pop_back (); return actval; } condition.wait (pullLock); // need to check again to handle spurious wake-up if (!priorityQueue.empty ()) { auto actval = std::move (priorityQueue.front ()); priorityQueue.pop (); return actval; } if (!pullElements.empty ()) { auto actval = std::move (pullElements.back ()); pullElements.pop_back (); return actval; } pullLock.unlock (); val = try_pop (); } return std::move (*val); } /** check whether there are any elements in the queue because this is meant for multi-threaded applications this may or may not have any meaning depending on the number of consumers */ bool empty () const; }; template <typename T> stx::optional<T> BlockingPriorityQueue<T>::try_pop () { std::lock_guard<std::mutex> pullLock (m_pullLock); // first pullLock if (!priorityQueue.empty ()) { stx::optional<T> val (std::move (priorityQueue.front ())); priorityQueue.pop (); return val; } if (pullElements.empty ()) { std::unique_lock<std::mutex> pushLock (m_pushLock); // second pushLock if (!pushElements.empty ()) { // on the off chance the queue got out of sync std::swap (pushElements, pullElements); pushLock.unlock (); // we can free the push function to accept more elements after the swap call; std::reverse (pullElements.begin (), pullElements.end ()); stx::optional<T> val (std::move (pullElements.back ())); // do it this way to allow movable only types pullElements.pop_back (); if (pullElements.empty ()) { pushLock.lock (); // second pushLock if (!pushElements.empty ()) // more elements could have been added { // this is the potential for slow operations std::swap (pushElements, pullElements); // we can free the push function to accept more elements after the swap call; pushLock.unlock (); std::reverse (pullElements.begin (), pullElements.end ()); } else { queueEmptyFlag = true; } } return val; } queueEmptyFlag = true; return {}; // return the empty optional } stx::optional<T> val (std::move (pullElements.back ())); // do it this way to allow movable only types pullElements.pop_back (); if (pullElements.empty ()) { std::unique_lock<std::mutex> pushLock (m_pushLock); // second pushLock if (!pushElements.empty ()) { // this is the potential for slow operations std::swap (pushElements, pullElements); // we can free the push function to accept more elements after the swap call; pushLock.unlock (); std::reverse (pullElements.begin (), pullElements.end ()); } else { queueEmptyFlag = true; } } return val; } template <typename T> bool BlockingPriorityQueue<T>::empty () const { return queueEmptyFlag; } } // namespace detail } // namespace ipc } // namespace helics
Hower91/Apache-C-Standard-Library-4.2.x
include/loc/_messages.h
<filename>include/loc/_messages.h /*************************************************************************** * * _messages.h - definition of the std::messages class templates * * This is an internal header file used to implement the C++ Standard * Library. It should never be #included directly by a program. * * $Id: //stdlib/dev/include/loc/_messages.h#29 $ * *************************************************************************** * * Copyright (c) 1994-2005 Quovadx, Inc., acting through its Rogue Wave * Software division. 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. * **************************************************************************/ #ifndef _RWSTD_LOC_MESSAGES_H_INCLUDED #define _RWSTD_LOC_MESSAGES_H_INCLUDED #if __GNUG__ >= 3 # pragma GCC system_header #endif // gcc >= 3 #include <string> #include <loc/_facet.h> #include <loc/_codecvt.h> #include <loc/_locale.h> #include <rw/_defs.h> _RWSTD_NAMESPACE (__rw) { int __rw_cat_open (const _STD::string&, const _V3_LOCALE::locale&); const char* __rw_get_message (int, int, int); const _V3_LOCALE::locale& __rw_get_locale (int); void __rw_cat_close (int); } // namespace __rw _RWSTD_NAMESPACE (_V3_LOCALE) { struct _RWSTD_EXPORT messages_base { typedef int catalog; }; // 172.16.31.10 _EXPORT template <class _CharT> class messages: public _RW::__rw_facet, public messages_base { public: typedef _CharT char_type; typedef basic_string<char_type, char_traits<char_type>, allocator<char_type> > string_type; _EXPLICIT messages (_RWSTD_SIZE_T __refs = 0) : _RW::__rw_facet (__refs), messages_base () { } catalog open (const string& __fun, const locale& __loc) const { return do_open (__fun, __loc); } string_type get (catalog __c, int __set, int __msgid, const string_type& __df) const { return do_get (__c, __set, __msgid, __df); } void close (catalog __c) const { do_close (__c); } static _RW::__rw_facet_id id; protected: virtual catalog do_open (const string& __fun, const locale&__loc) const { return _RW::__rw_cat_open (__fun, __loc); } virtual string_type do_get (catalog, int, int, const string_type&) const; virtual void do_close (catalog __cat) const { _RW::__rw_cat_close (__cat); } }; #ifndef _RWSTD_NO_SPECIALIZED_FACET_ID _RWSTD_SPECIALIZED_CLASS _RW::__rw_facet_id messages<char>::id; # ifndef _RWSTD_NO_WCHAR_T _RWSTD_SPECIALIZED_CLASS _RW::__rw_facet_id messages<wchar_t>::id; # endif // _RWSTD_NO_WCHAR_T #endif // _RWSTD_NO_SPECIALIZED_FACET_ID // 172.16.58.3 template <class _CharT> class messages_byname: public messages<_CharT> { char _C_namebuf [32]; public: _EXPLICIT messages_byname (const char *__name, _RWSTD_SIZE_T __refs = 0) : messages<_CharT>(__refs) { this->_C_set_name (__name, _C_namebuf, sizeof _C_namebuf); } }; } // namespace _V3_LOCALE #if _RWSTD_DEFINE_TEMPLATE_FIRST (_MESSAGES) # include <loc/_messages.cc> #endif // _RWSTD_DEFINE_TEMPLATE_FIRST (MESSAGES) _RWSTD_NAMESPACE (_V3_LOCALE) { #if _RWSTD_INSTANTIATE (_MESSAGES, _CHAR) _RWSTD_INSTANTIATE_1 (class _RWSTD_EXPORT messages<char>); #endif // _RWSTD_INSTANTIATE (_MESSAGES, _CHAR) #if _RWSTD_INSTANTIATE (_MESSAGES, _WCHAR_T) _RWSTD_INSTANTIATE_1 (class _RWSTD_EXPORT messages<wchar_t>); #endif // _RWSTD_INSTANTIATE (_MESSAGES, _WCHAR_T) } // namespace _V3_LOCALE #if _RWSTD_DEFINE_TEMPLATE_LAST (_MESSAGES) # include <loc/_messages.cc> #endif // _RWSTD_DEFINE_TEMPLATE_LAST (MESSAGES) #endif // _RWSTD_LOC_MESSAGES_H_INCLUDED
ZibraMax/FEM
FEM/Elements/Element.py
<reponame>ZibraMax/FEM<gh_stars>1-10 """Element class """ import numpy as np from typing import Tuple, Callable class Element(): """Generates a generic element. Args: coords (np.ndarray): Vertical coordinates matrix _coords (np.ndarray): Vertical coordinates matrix for graphical interfaces gdl (np.ndarray): Degree of freedom matrix. Each row is a variable. border (bool): True if the element is part of the border domain of another element. """ def __init__(self, coords: np.ndarray, _coords: np.ndarray, gdl: np.ndarray, border: bool = False) -> None: """Generates a generic element. Args: coords (np.ndarray): Vertical coordinates matrix _coords (np.ndarray): Vertical coordinates matrix for graphical interfaces gdl (np.ndarray): Degree of freedom matrix. Each row is a variable. border (bool): True if the element is part of the border domain of another element. """ self.coords = coords self._coords = _coords self.border = border self.gdl = gdl self.gdlm = [] for i in range(len(self.gdl)): for j in range(len(self.gdl[i])): self.gdlm.append(self.gdl[i, j]) self.n = int(len(self.gdl)*len(self.gdl[0])) self.properties = {'load_x': [], 'load_y': []} self.intBorders = False if not self.border: # TODO Esta vaina debería eliminarse. # Los elementos no tienen porque guardar. # Sus matrices y vectores. Esto gasta memoria. # Las matrices y vectores solo se estan usando para ensamblar y # eso se puede hacer directamente al calcular las matrices. self.Ke = np.zeros([self.n, self.n]) self.Fe = np.zeros([self.n, 1]) self.Ue = np.zeros(self.gdl.shape) self.Qe = np.zeros([self.n, 1]) @classmethod def description(self): """Creates the elemetn description Returns: str: Description of the element """ return '' def restartMatrix(self): """Sets all element matrices and vectors to 0 state """ if not self.border: self.Ke[:, :] = 0.0 self.Fe[:, :] = 0.0 self.Ue[:, :] = 0.0 self.Qe[:, :] = 0.0 def T(self, z: np.ndarray) -> np.ndarray: """Give the global coordinates of given natural coordiantes over element Args: z (np.ndarray): Natural coordinates matrix Returns: np.ndarray: Global coordinates matrix """ p = self.psis(z) return p@self.coords, p def TS(self, z): """Returns the transformation of a given set of points in the element. This method is used for border elements Args: z (np.ndarray): Natural coordinates matrix Returns: np.ndarray: Global coordinates matrix """ return self.s0+self.dir*self.T(z)[0] def inverseMapping(self, x0: np.ndarray, n: int = 100) -> np.ndarray: """Give the natural coordinates of given global coordinates over elements using Newton's method Args: x0(np.ndarray): Global coordinates matrix n(int, optional): Máximun number of iterations. Defaults to 100. Returns: np.ndarray: Natural coordinates matrix """ tol = 1*10**(-6) zi = np.zeros(x0.shape)+0.1 for _ in range(n): xi = x0 - self.T(zi)[0].T _J = np.linalg.inv(self.J(zi)[0]) xi = xi.T xi = xi.reshape(list(xi.shape)+[1]) dz = _J@xi zi += dz[:, :, 0].T if np.max(np.abs(dz)) < tol: break return zi def J(self, z: np.ndarray) -> np.ndarray: """Calculate the jacobian matrix over a set of natural coordinates Args: z(np.ndarray): Natural coordinates matrix Returns: np.ndarray: Jacobian's matrices """ dpsis = self.dpsis(z).T return dpsis @ self.coords, dpsis def giveSolution(self, SVSolution: bool = False, domain: str = 'domain') -> np.ndarray: """Calculate the interpolated solution over element domain Args: SVSolution(bool, optional): To calculate second variable solutions. Defaults to False. Returns: np.ndarray: Arrays of coordinates, solutions and second variables solutions. """ # TODO hacer una comprobación de frontera para evitar errores _z = self.domain if domain == 'gauss-points': _z = self.Z _x, _p = self.T(_z.T) if SVSolution: j, dpz = self.J(_z.T) # TODO Revisar con Reddy dpx = np.linalg.inv(j) @ dpz # print((self.Ue @ np.transpose(dpx,axes=[0,2,1])).shape) # TODO REVISAR VS return _x, self.Ue@_p.T, self.Ue @ np.transpose(dpx, axes=[0, 2, 1]) return _x, self.Ue@_p.T def giveSolutionPoint(self, Z: np.ndarray, SVSolution: bool = False) -> np.ndarray: """Calculate the interpolated solution over given set of points Args: Z(np.ndarray): Natural coordintas to extract the solution SVSolution(bool, optional): To calculate second variable solution. Defaults to False. Returns: np.ndarray: Arrays of coordinates, solutions and second variables solutions. """ # TODO hacer una comprobación de frontera para evitar errores _x, _p = self.T(Z) if SVSolution: j, dpz = self.J(Z) # TODO Revisar con Reddy dpx = np.linalg.inv(j) @ dpz # TODO REVISAR VS return _x, self.Ue@_p.T, self.Ue @ np.transpose(dpx, axes=[0, 2, 1]) return _x, self.Ue@_p.T def setUe(self, U: np.ndarray) -> None: """Assing element local solution Args: U(np.ndarray): Global solution """ # TODO hacer una comprobación de frontera para evitar errores for i in range(len(self.gdl)): self.Ue[i] = U[np.ix_(self.gdl[i])].flatten() n = len(self._coords) m = len(self.gdl) self._Ueg = self.Ue[np.ix_(np.linspace( 0, m-1, m).astype(int), np.linspace(0, n-1, n).astype(int))] self._Ueg = np.array(self._Ueg.T.tolist()+[self._Ueg.T[0].tolist()]) def integrate(self, f: Callable) -> float: """Calculate the integral of f function over element domain Args: f(function): Function to be integrated Returns: float: Integral value """ integral = 0 for w, z in zip(self.W, self.Z): integral += f(z)*w return integral
valdisxp1/scapegoat
src/test/scala/com/sksamuel/scapegoat/inspections/collections/ReverseTakeReverseTest.scala
package com.sksamuel.scapegoat.inspections.collections import com.sksamuel.scapegoat.InspectionTest class ReverseTakeReverseTest extends InspectionTest { override val inspections = Seq(new ReverseTakeReverse) "ReverseTakeReverse" - { "should report warning" in { val code = """class Test { List(1,2,3).reverse.take(2).reverse Array(1,2,3).reverse.take(1).reverse } """.stripMargin compileCodeSnippet(code) compiler.scapegoat.feedback.warnings.size shouldBe 2 } } }
gmzorz/MiniRT
sources/buffer/write_color_at.c
/* ************************************************************************** */ /* */ /* :::::::: */ /* write_color_at.c :+: :+: */ /* +:+ */ /* By: goosterl <<EMAIL>> +#+ */ /* +#+ */ /* Created: 2020/11/23 15:28:48 by goosterl #+# #+# */ /* Updated: 2021/04/12 14:07:44 by goosterl ######## odam.nl */ /* */ /* ************************************************************************** */ #include <color.h> #include <buffer.h> void write_color_at(t_buffer *buf, const int u, const int v, const t_rgb color) { char *location; location = get_addr_loc(buf, u, v); *(unsigned int *)location = rgb_to_data(vec3_clamp(color, 0, 1)); }
sulmanweb/social-api
spec/graphql/mutations/users/follow_user_spec.rb
require 'rails_helper' module Mutations module Users RSpec.describe FollowUser, type: :request do describe '.resolve' do it 'current user will follow the given user' do user1 = FactoryBot.create(:user) user2 = FactoryBot.create(:user) session = FactoryBot.create(:session, user_id: user1.id) headers = sign_in_test_headers(session) variables = {id: user2.id} post '/graphql', params: {query: query, variables: variables.to_json}, headers: headers json = JSON.parse(response.body) data = json['data']['followUser']['success'] expect(data).to be_truthy end end def query ' mutation($id: ID!) { followUser(id: $id) { success } } ' end end end end
archaim/ember-flexberry
tests/unit/utils/run-after-test.js
<filename>tests/unit/utils/run-after-test.js import Ember from 'ember'; import { module, test } from 'qunit'; import runAfter from 'ember-flexberry/utils/run-after'; module('Unit | Utility | run-after'); test('possible condition', function(assert) { const done = assert.async(); let counter = 0; const condition = () => ++counter === 5; runAfter(null, condition, () => { assert.strictEqual(counter, 5, `The 'condition' is called five times.`); done(); }); }); test('impossible condition', function(assert) { const onerror = Ember.onerror; const done = assert.async(); let error; let counter = 0; let conditionCalled = false; Ember.onerror = (e) => { error = e; }; runAfter(null, () => { conditionCalled = true; throw new Error('Impossible condition.'); }, () => ++counter); runAfter(null, () => conditionCalled, () => { Ember.onerror = onerror; assert.strictEqual(counter, 0, `The 'handler' is not called.`); assert.strictEqual(error.message, 'Impossible condition.', 'Condition complete.'); done(); }); }); test('validate context', function(assert) { const done = assert.async(); const context = {}; const condition = function() { assert.ok(this === context, `The 'condition' is called with correct context.`); return true; }; const handler = function() { assert.ok(this === context, `The 'handler' is called with correct context.`); done(); }; runAfter(context, condition, handler); });
zakkudo/translation-static-analyzer
__mocks__/filesystem.js
<filename>__mocks__/filesystem.js<gh_stars>0 const AboutPage = ` export default class AboutPage extends Component { static get title() { return __('About'); } static get template() { return <div>{{__('Search')}} Welcome to the about page!</div>'; } }; `.trim(); const EmptyPage = ``.trim(); const SearchPage = ` export default class SearchPage extends Component { static get title() { return __('Search'); } static get template() { return '{{__('invalid''string')}} {{__p('menuitem', 'Search')}} <div>{{__n('%d result', '%d results', 2)}}</div> {{__np('footer', '%d view', '%d views', 23)}}'; } }; `.trim(); const Application = ` export default class Application extends Component { static get title() { return __('Application'); } }; `.trim(); const EmptyKeysPage = ` export default class Application extends Component { static get title() { return __('') + __n('') + __np('') + __p(''); } }; `.trim(); module.exports = { 'src/pages/Search/index.js': SearchPage, 'src/pages/About/index.js': AboutPage, 'src/pages/Empty/index.js': EmptyPage, 'src/pages/EmptyKeys/index.js': EmptyKeysPage, 'src/test.js': EmptyPage, 'src/index.js': Application, './locales/existing.json': JSON.stringify({ "Search": {"default": "検索"}, "test unused key": {"default": "test value"}, "Application": {"default": "アプリケーション"}, }), 'src/pages/About/.locales/existing.json': JSON.stringify({}), 'src/pages/Search/.locales/existing.json': JSON.stringify({'Search': ''}), };
eflows4hpc/compss
compss/runtime/resources/commons/src/main/java/es/bsc/compss/types/resources/MasterResourceImpl.java
<filename>compss/runtime/resources/commons/src/main/java/es/bsc/compss/types/resources/MasterResourceImpl.java /* * Copyright 2002-2021 Barcelona Supercomputing Center (www.bsc.es) * * 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 es.bsc.compss.types.resources; import es.bsc.compss.COMPSsConstants; import es.bsc.compss.api.COMPSsRuntime; import es.bsc.compss.comm.Comm; import es.bsc.compss.comm.CommAdaptor; import es.bsc.compss.loader.LoaderAPI; import es.bsc.compss.types.COMPSsMaster; import es.bsc.compss.types.uri.MultiURI; import java.util.HashMap; import java.util.Map; public class MasterResourceImpl extends DynamicMethodWorker implements MasterResource { /** * Creates a new Master Resource. */ public MasterResourceImpl() { super(COMPSsMaster.getMasterName(), // Master name new MethodResourceDescription(), // Master resource description new COMPSsMaster(null), // Master COMPSs node 0, // limit of tasks 0, // Limit of GPU tasks 0, // Limit of FPGA tasks 0, // Limit of OTHER tasks new HashMap<>()// Shared disks ); } /** * Returns the COMPSs base log directory. * * @return The COMPSs base log directory. */ public String getCOMPSsLogBaseDirPath() { return ((COMPSsMaster) this.getNode()).getCOMPSsLogBaseDirPath(); } @Override public String getWorkingDirectory() { return ((COMPSsMaster) this.getNode()).getWorkingDirectory(); } public String getUserExecutionDirPath() { return ((COMPSsMaster) this.getNode()).getUserExecutionDirPath(); } @Override public String getAppLogDirPath() { return ((COMPSsMaster) this.getNode()).getAppLogDirPath(); } @Override public String getTempDirPath() { return ((COMPSsMaster) this.getNode()).getTempDirPath(); } @Override public String getJobsDirPath() { return ((COMPSsMaster) this.getNode()).getJobsDirPath(); } @Override public String getWorkersDirPath() { return ((COMPSsMaster) this.getNode()).getWorkersDirPath(); } @Override public void setInternalURI(MultiURI u) { for (CommAdaptor adaptor : Comm.getAdaptors().values()) { adaptor.completeMasterURI(u); } } @Override public ResourceType getType() { return ResourceType.MASTER; } @Override public void retrieveUniqueDataValues() { // All data is kept within the master process. No need to bring to the node any data since it is already there. } @Override public int compareTo(Resource t) { if (t.getType() == ResourceType.MASTER) { return getName().compareTo(t.getName()); } else { return 1; } } @Override public void updateDisks(Map<String, String> sharedDisks) { super.sharedDisks = sharedDisks; } /** * Configures the necessary parameters so tasks executed in the worker are able to detect nested tasks. * * @param runtimeAPI runtimeAPI implementation handling the task execution * @param loader loaderAPI implementation to detect data accesses */ public void setupNestedSupport(COMPSsRuntime runtimeAPI, LoaderAPI loader) { boolean enableNested = Boolean.parseBoolean(System.getProperty(COMPSsConstants.ENABLED_NESTED_TASKS_DETECTION)); if (enableNested) { ((COMPSsMaster) this.getNode()).setRuntimeApi(runtimeAPI); ((COMPSsMaster) this.getNode()).setLoaderApi(loader); } } }
ffpy/SqlPal
sqlpal/src/org/sqlpal/crud/SaveHandler.java
package org.sqlpal.crud; import org.sqlpal.common.ModelField; import org.sqlpal.crud.factory.SqlFactory; import org.sqlpal.manager.FactoryManager; import org.sqlpal.manager.ModelManager; import org.sqlpal.util.EmptyUtils; import org.sqlpal.util.StatementUtils; import com.sun.istack.internal.NotNull; import java.lang.reflect.Field; import java.sql.*; import java.util.ArrayList; import java.util.List; /** * 插入处理类 */ class SaveHandler extends DefaultExecuteCallback<Integer> { private List<ModelField> allFields = new ArrayList<>(); private int insertIndex; // 填充自增字段时的计数器 private List<? extends DataSupport> mModels; /** * 插入记录 * @return 返回插入结果,成功为1,失败为0 * @throws SQLException 数据库错误 */ int save(@NotNull DataSupport model) throws SQLException { List<DataSupport> models = new ArrayList<>(); models.add(model); mModels = models; Integer row = new DataHandler().execute(this, model); mModels = null; return row == null ? 0 : row; } /** * 插入多条记录 * 要同时插入多条记录建议用这个方法,执行速度更快 * @param models 要插入的Model类列表 * @throws SQLException 数据库错误 */ void saveAll(@NotNull List<? extends DataSupport> models) throws SQLException { insertIndex = 0; mModels = models; new DataHandler().executeBatch(this, models); mModels = null; } @Override public PreparedStatement onCreateStatement(Connection connection, DataSupport model) throws SQLException { return connection.prepareStatement(FactoryManager.getSqlFactory().insert(model.getTableName(), allFields), Statement.RETURN_GENERATED_KEYS); } @Override public boolean onGetValues(DataSupport model) throws SQLException { ModelManager.getAllFields(model, allFields); return !EmptyUtils.isEmpty(allFields); } @Override public void onAddValues(PreparedStatement statement) throws SQLException { StatementUtils utils = new StatementUtils(statement); utils.addValues(allFields); } @Override public Integer onExecute(PreparedStatement statement) throws SQLException { int n = statement.executeUpdate(); fillAutoIncrement(statement); return n; } @Override public void onExecuteBatch(PreparedStatement statement) throws SQLException { super.onExecuteBatch(statement); fillAutoIncrement(statement); } /** * 填充自增字段 */ private void fillAutoIncrement(@NotNull Statement stmt) throws SQLException { Class<? extends DataSupport> cls = mModels.get(0).getClass(); String fieldName = ModelManager.getAutoIncrement(cls); if (fieldName == null) return; ResultSet rs = stmt.getGeneratedKeys(); while (rs.next()) { int id = rs.getInt(1); try { Field field = cls.getDeclaredField(fieldName); field.setAccessible(true); field.set(mModels.get(insertIndex++), id); } catch (IllegalAccessException | NoSuchFieldException ignored) { } } } }
jmrico01/WurstScript
de.peeeq.wurstscript/src/main/java/de/peeeq/wurstio/jassinterpreter/providers/RegionProvider.java
package de.peeeq.wurstio.jassinterpreter.providers; import de.peeeq.wurstio.jassinterpreter.mocks.RegionMock; import de.peeeq.wurstscript.intermediatelang.IlConstHandle; import de.peeeq.wurstscript.intermediatelang.interpreter.AbstractInterpreter; public class RegionProvider extends Provider { public RegionProvider(AbstractInterpreter interpreter) { super(interpreter); } public IlConstHandle CreateRegion() { return new IlConstHandle(NameProvider.getRandomName("region"), new RegionMock()); } public void RemoveRegion(IlConstHandle region) { } public void RegionAddRect(IlConstHandle region, IlConstHandle rect) { // TODO } }
RuntimeConverter/RuntimeConverterLaravelJava
laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Faker/namespaces/Guesser/classes/Name.java
<reponame>RuntimeConverter/RuntimeConverterLaravelJava<filename>laravel-converted/src/main/java/com/project/convertedCode/globalNamespace/namespaces/Faker/namespaces/Guesser/classes/Name.java package com.project.convertedCode.globalNamespace.namespaces.Faker.namespaces.Guesser.classes; import com.runtimeconverter.runtime.nativeFunctions.string.function_str_replace; import com.runtimeconverter.runtime.passByReference.PassByReferenceArgs; import com.runtimeconverter.runtime.classes.StaticBaseClass; import com.runtimeconverter.runtime.nativeClasses.Closure; import com.runtimeconverter.runtime.classes.RuntimeClassBase; import com.runtimeconverter.runtime.RuntimeEnv; import com.runtimeconverter.runtime.nativeFunctions.pcre.function_preg_match; import com.runtimeconverter.runtime.ZVal; import com.runtimeconverter.runtime.reflection.ReflectionClassData; import com.runtimeconverter.runtime.annotations.ConvertedParameter; import com.project.convertedCode.globalNamespace.namespaces.Faker.namespaces.Provider.classes.Base; import com.runtimeconverter.runtime.arrays.ZPair; import java.lang.invoke.MethodHandles; import com.runtimeconverter.runtime.interfaces.ContextConstants; import com.runtimeconverter.runtime.classes.NoConstructor; import com.runtimeconverter.runtime.nativeFunctions.string.function_sprintf; import com.runtimeconverter.runtime.annotations.ConvertedMethod; import static com.runtimeconverter.runtime.ZVal.toStringR; import static com.runtimeconverter.runtime.ZVal.toObjectR; import static com.runtimeconverter.runtime.ZVal.assignParameter; /* Converted with The Runtime Converter (runtimeconverter.com) vendor/fzaninotto/faker/src/Faker/Guesser/Name.php */ public class Name extends RuntimeClassBase { public Object generator = null; public Name(RuntimeEnv env, Object... args) { super(env); if (this.getClass() == Name.class) { this.__construct(env, args); } } public Name(NoConstructor n) { super(n); } @ConvertedMethod @ConvertedParameter(index = 0, name = "generator", typeHint = "Faker\\Generator") public Object __construct(RuntimeEnv env, Object... args) { Object generator = assignParameter(args, 0, false); this.generator = generator; return null; } @ConvertedMethod @ConvertedParameter(index = 0, name = "name") @ConvertedParameter( index = 1, name = "size", defaultValue = "NULL", defaultValueType = "constant" ) public Object guessFormat(RuntimeEnv env, Object... args) { ContextConstants runtimeConverterFunctionClassConstants = new ContextConstants() .setDir("/vendor/fzaninotto/faker/src/Faker/Guesser") .setFile("/vendor/fzaninotto/faker/src/Faker/Guesser/Name.php"); int runtimeConverterBreakCount; Object name = assignParameter(args, 0, false); Object size = assignParameter(args, 1, true); if (null == size) { size = ZVal.getNull(); } Object generator = null; name = Base.runtimeStaticObject.toLower(env, name); generator = ZVal.assign(this.generator); if (function_preg_match.f.env(env).call("/^is[_A-Z]/", name).getBool()) { return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("boolean") .value()); } }.use("generator", generator)); } if (function_preg_match.f.env(env).call("/(_a|A)t$/", name).getBool()) { return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("dateTime") .value()); } }.use("generator", generator)); } switch (toStringR(function_str_replace.f.env(env).call("_", "", name).value())) { case "firstname": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("firstName") .value()); } }.use("generator", generator)); case "lastname": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("lastName") .value()); } }.use("generator", generator)); case "username": case "login": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("userName") .value()); } }.use("generator", generator)); case "email": case "emailaddress": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("email") .value()); } }.use("generator", generator)); case "phonenumber": case "phone": case "telephone": case "telnumber": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("phoneNumber") .value()); } }.use("generator", generator)); case "address": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("address") .value()); } }.use("generator", generator)); case "city": case "town": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("city") .value()); } }.use("generator", generator)); case "streetaddress": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("streetAddress") .value()); } }.use("generator", generator)); case "postcode": case "zipcode": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("postcode") .value()); } }.use("generator", generator)); case "state": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("state") .value()); } }.use("generator", generator)); case "county": if (ZVal.equalityCheck( toObjectR(this.generator).accessProp(this, env).name("locale").value(), "en_US")) { return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( function_sprintf .f .env(env) .call( "%s County", toObjectR(generator) .accessProp(this, env) .name("city") .value()) .value()); } }.use("generator", generator)); } return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("state") .value()); } }.use("generator", generator)); case "country": SwitchEnumType2 switchVariable2 = ZVal.getEnum( size, SwitchEnumType2.DEFAULT_CASE, SwitchEnumType2.INTEGER_2, 2, SwitchEnumType2.INTEGER_3, 3, SwitchEnumType2.INTEGER_5, 5, SwitchEnumType2.INTEGER_6, 6); switch (switchVariable2) { case INTEGER_2: return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue( "generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("countryCode") .value()); } }.use("generator", generator)); case INTEGER_3: return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue( "generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("countryISOAlpha3") .value()); } }.use("generator", generator)); case INTEGER_5: case INTEGER_6: return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue( "generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("locale") .value()); } }.use("generator", generator)); case DEFAULT_CASE: return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue( "generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("country") .value()); } }.use("generator", generator)); } ; break; case "locale": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("locale") .value()); } }.use("generator", generator)); case "currency": case "currencycode": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("currencyCode") .value()); } }.use("generator", generator)); case "url": case "website": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("url") .value()); } }.use("generator", generator)); case "company": case "companyname": case "employer": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("company") .value()); } }.use("generator", generator)); case "title": if (ZVal.toBool(ZVal.strictNotEqualityCheck(size, "!==", ZVal.getNull())) && ZVal.toBool(ZVal.isLessThanOrEqualTo(size, "<=", 10))) { return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("title") .value()); } }.use("generator", generator)); } return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("sentence") .value()); } }.use("generator", generator)); case "body": case "summary": case "article": case "description": return ZVal.assign( new Closure( env, runtimeConverterFunctionClassConstants, "Faker\\Guesser", this) { @Override @ConvertedMethod public Object run( RuntimeEnv env, Object thisvar, PassByReferenceArgs runtimePassByReferenceArgs, Object... args) { Object generator = null; generator = this.contextReferences.getCapturedValue("generator"); return ZVal.assign( toObjectR(generator) .accessProp(this, env) .name("text") .value()); } }.use("generator", generator)); } ; return null; } public static final Object CONST_class = "Faker\\Guesser\\Name"; // Runtime Converter Internals // RuntimeStaticCompanion contains static methods // RequestStaticProperties contains static (per-request) properties // ReflectionClassData contains php reflection data used by the runtime library public static class RuntimeStaticCompanion extends StaticBaseClass { private static final MethodHandles.Lookup staticCompanionLookup = MethodHandles.lookup(); } public static final RuntimeStaticCompanion runtimeStaticObject = new RuntimeStaticCompanion(); private static final ReflectionClassData runtimeConverterReflectionData = ReflectionClassData.builder() .setName("Faker\\Guesser\\Name") .setLookup( Name.class, MethodHandles.lookup(), RuntimeStaticCompanion.staticCompanionLookup) .setLocalProperties("generator") .setFilename("vendor/fzaninotto/faker/src/Faker/Guesser/Name.php") .get(); @Override public ReflectionClassData getRuntimeConverterReflectionData() { return runtimeConverterReflectionData; } @Override public Object converterRuntimeCallExtended( RuntimeEnv env, String method, Class<?> caller, PassByReferenceArgs passByReferenceArgs, Object... args) { return RuntimeClassBase.converterRuntimeCallExtendedWithDataStatic( this, runtimeConverterReflectionData, env, method, caller, passByReferenceArgs, args); } private enum SwitchEnumType2 { INTEGER_2, INTEGER_3, INTEGER_5, INTEGER_6, DEFAULT_CASE, UNREACHABLE_CODE_N42 } }
bjerkio/go-tripletex
client/account/account_client.go
// Code generated by go-swagger; DO NOT EDIT. package account // This file was generated by the swagger tool. // Editing this file might prove futile when you re-run the swagger generate command import ( "fmt" "github.com/go-openapi/runtime" "github.com/go-openapi/strfmt" ) // New creates a new account API client. func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService { return &Client{transport: transport, formats: formats} } /* Client for account API */ type Client struct { transport runtime.ClientTransport formats strfmt.Registry } // ClientService is the interface for Client methods type ClientService interface { LedgerAccountListDeleteByIds(params *LedgerAccountListDeleteByIdsParams, authInfo runtime.ClientAuthInfoWriter) error LedgerAccountListPostList(params *LedgerAccountListPostListParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountListPostListCreated, error) LedgerAccountListPutList(params *LedgerAccountListPutListParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountListPutListOK, error) LedgerAccountDelete(params *LedgerAccountDeleteParams, authInfo runtime.ClientAuthInfoWriter) error LedgerAccountGet(params *LedgerAccountGetParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountGetOK, error) LedgerAccountPost(params *LedgerAccountPostParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountPostCreated, error) LedgerAccountPut(params *LedgerAccountPutParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountPutOK, error) LedgerAccountSearch(params *LedgerAccountSearchParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountSearchOK, error) SetTransport(transport runtime.ClientTransport) } /* LedgerAccountListDeleteByIds bs e t a delete multiple accounts */ func (a *Client) LedgerAccountListDeleteByIds(params *LedgerAccountListDeleteByIdsParams, authInfo runtime.ClientAuthInfoWriter) error { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountListDeleteByIdsParams() } _, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccountList_deleteByIds", Method: "DELETE", PathPattern: "/ledger/account/list", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountListDeleteByIdsReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return err } return nil } /* LedgerAccountListPostList bs e t a create several accounts */ func (a *Client) LedgerAccountListPostList(params *LedgerAccountListPostListParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountListPostListCreated, error) { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountListPostListParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccountList_postList", Method: "POST", PathPattern: "/ledger/account/list", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json; charset=utf-8"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountListPostListReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } success, ok := result.(*LedgerAccountListPostListCreated) if ok { return success, nil } // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue msg := fmt.Sprintf("unexpected success response for LedgerAccountList_postList: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } /* LedgerAccountListPutList bs e t a update multiple accounts */ func (a *Client) LedgerAccountListPutList(params *LedgerAccountListPutListParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountListPutListOK, error) { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountListPutListParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccountList_putList", Method: "PUT", PathPattern: "/ledger/account/list", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json; charset=utf-8"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountListPutListReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } success, ok := result.(*LedgerAccountListPutListOK) if ok { return success, nil } // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue msg := fmt.Sprintf("unexpected success response for LedgerAccountList_putList: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } /* LedgerAccountDelete bs e t a delete account */ func (a *Client) LedgerAccountDelete(params *LedgerAccountDeleteParams, authInfo runtime.ClientAuthInfoWriter) error { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountDeleteParams() } _, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccount_delete", Method: "DELETE", PathPattern: "/ledger/account/{id}", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountDeleteReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return err } return nil } /* LedgerAccountGet gets account by ID */ func (a *Client) LedgerAccountGet(params *LedgerAccountGetParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountGetOK, error) { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountGetParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccount_get", Method: "GET", PathPattern: "/ledger/account/{id}", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountGetReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } success, ok := result.(*LedgerAccountGetOK) if ok { return success, nil } // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue msg := fmt.Sprintf("unexpected success response for LedgerAccount_get: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } /* LedgerAccountPost bs e t a create a new account */ func (a *Client) LedgerAccountPost(params *LedgerAccountPostParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountPostCreated, error) { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountPostParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccount_post", Method: "POST", PathPattern: "/ledger/account", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json; charset=utf-8"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountPostReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } success, ok := result.(*LedgerAccountPostCreated) if ok { return success, nil } // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue msg := fmt.Sprintf("unexpected success response for LedgerAccount_post: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } /* LedgerAccountPut bs e t a update account */ func (a *Client) LedgerAccountPut(params *LedgerAccountPutParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountPutOK, error) { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountPutParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccount_put", Method: "PUT", PathPattern: "/ledger/account/{id}", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json; charset=utf-8"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountPutReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } success, ok := result.(*LedgerAccountPutOK) if ok { return success, nil } // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue msg := fmt.Sprintf("unexpected success response for LedgerAccount_put: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } /* LedgerAccountSearch finds accounts corresponding with sent data */ func (a *Client) LedgerAccountSearch(params *LedgerAccountSearchParams, authInfo runtime.ClientAuthInfoWriter) (*LedgerAccountSearchOK, error) { // TODO: Validate the params before sending if params == nil { params = NewLedgerAccountSearchParams() } result, err := a.transport.Submit(&runtime.ClientOperation{ ID: "LedgerAccount_search", Method: "GET", PathPattern: "/ledger/account", ProducesMediaTypes: []string{"application/json"}, ConsumesMediaTypes: []string{"application/json"}, Schemes: []string{"https"}, Params: params, Reader: &LedgerAccountSearchReader{formats: a.formats}, AuthInfo: authInfo, Context: params.Context, Client: params.HTTPClient, }) if err != nil { return nil, err } success, ok := result.(*LedgerAccountSearchOK) if ok { return success, nil } // unexpected success response // safeguard: normally, absent a default response, unknown success responses return an error above: so this is a codegen issue msg := fmt.Sprintf("unexpected success response for LedgerAccount_search: API contract not enforced by server. Client expected to get an error, but got: %T", result) panic(msg) } // SetTransport changes the transport on the client func (a *Client) SetTransport(transport runtime.ClientTransport) { a.transport = transport }
KingCosmic/BardsBalladMobile
src/modals/SideInfo/ChangeClass.js
<reponame>KingCosmic/BardsBalladMobile<gh_stars>0 import React, { Component } from 'react'; import styled from 'styled-components'; import T from '../../components/Text'; const BackDrop = styled.div` position: absolute; top: 0; left: 0; bottom: 0; right: 0; background-color: rgba(0, 0, 0, .6); display: flex; justify-content: center; align-items: center; ` const Container = styled.div` width: 90%; max-height: 60%; background-color: ${props => props.theme.light}; border-radius: 10px; padding: 20px; display: flex; flex-direction: column; align-items: center; ` const Title = styled(T)` color: ${props => props.theme.gold}; font-size: 1.7em; padding-bottom: 15px; ` const Row = styled.div` display: flex; padding: 20px 0; width: 100%; justify-content: space-around; align-items: center; ` const Button = styled(T)` background-color: ${props => props.cancel ? props.theme.red : props.theme.green}; border-radius: 5px; padding: 10px; font-size: 1.3em; text-align: center; width: 40%; ` const Input = styled.input` margin: 0 15px; color: rgba(20, 20, 20, .85); border: none; background: ${props => props.theme.dark}; border: 2px solid ${props => props.theme.middleblack}; padding: 10px; border-radius: 4px; appearance: none; color: ${props => props.theme.gold}; font-size: 1.4em; width: 80%; text-align: center; &:focus { outline: none; } ` class ChangeClass extends Component { constructor(props) { super(props); this.state = { value: props.job } this.handleClass = this.handleClass.bind(this); this.confirmChange = this.confirmChange.bind(this); } handleClass(event) { this.setState({ value: event.target.value }); } confirmChange() { const { requestClose, syncData, characterID } = this.props; const { value } = this.state; requestClose() syncData( characterID, { job: value } ) } render() { const { requestClose } = this.props; const { value } = this.state; return ( <BackDrop onClick={requestClose}> <Container onClick={(e) => e.stopPropagation()}> <Title>Edit Class</Title> <Input defaultValue={value} onChange={this.handleClass} /> <Row> <Button onClick={requestClose} cancel>Cancel</Button> <Button onClick={this.confirmChange}>Confirm</Button> </Row> </Container> </BackDrop> ) } } export default ChangeClass;
rokath/trice
internal/emitter/remoteDisplay_test.go
// Copyright 2020 Thomas.Hoehenleitner [at] seerose.net // Use of this source code is governed by a license that can be found in the LICENSE file. // whitebox test for package emitter. package emitter import ( "fmt" "io/ioutil" "math/rand" "runtime" "strings" "testing" "time" ) func TestDummy(t *testing.T) { } /* // to do: avoid direct call of trice - it fails on github func _TestRemoteDisplay(t *testing.T) { // prepare afn := "testdata/actRemote.log" efn := "testdata/expRemote.log" _ = os.Remove(afn) ipp := randomDynIPPort() name := baseName() p := NewRemoteDisplay(name, "-logfile "+afn, "localhost", ipp) l1 := []string{"This is ", "the 1st ", "line"} l2 := []string{"This is ", "the 2nd ", "line"} p.writeLine(l1) p.writeLine(l2) p.stopServer(0) time.Sleep(100 * time.Millisecond) expLines, expErr := readLines(efn) actLines, actErr := readLines(afn) assert.Equal(t, nil, expErr) assert.Equal(t, nil, actErr) assert.Equal(t, 9, len(expLines)) assert.Equal(t, 9, len(actLines)) assert.Equal(t, expLines[1:], actLines[1:]) _ = os.Remove(afn) } */ func randomDynIPPort() (s string) { rand.Seed(time.Now().UTC().UnixNano()) min := 49152 max := 65535 s = fmt.Sprint(rand.Intn(max-min) + min) return } func readLines(filename string) (lines []string, err error) { content, err := ioutil.ReadFile(filename) stringContent := string(content) if runtime.GOOS == "windows" { stringContent = strings.ReplaceAll(stringContent, "\r\n", "\n") } lines = strings.Split(stringContent, "\n") return }
GotanDev/msgraph-sdk-java
src/main/java/com/microsoft/graph/requests/OnenoteEntityHierarchyModelRequest.java
// Template Source: BaseEntityRequest.java.tt // ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ package com.microsoft.graph.requests; import com.microsoft.graph.http.IRequestBuilder; import com.microsoft.graph.core.ClientException; import com.microsoft.graph.models.OnenoteEntityHierarchyModel; import java.util.Arrays; import java.util.EnumSet; import javax.annotation.Nullable; import javax.annotation.Nonnull; import com.microsoft.graph.core.IBaseClient; import com.microsoft.graph.http.BaseRequest; import com.microsoft.graph.http.HttpMethod; // **NOTE** This file was generated by a tool and any changes will be overwritten. /** * The class for the Onenote Entity Hierarchy Model Request. */ public class OnenoteEntityHierarchyModelRequest extends BaseRequest<OnenoteEntityHierarchyModel> { /** * The request for the OnenoteEntityHierarchyModel * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request * @param responseClass the class of the response */ public OnenoteEntityHierarchyModelRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final Class<? extends OnenoteEntityHierarchyModel> responseClass) { super(requestUrl, client, requestOptions, responseClass); } /** * The request for the OnenoteEntityHierarchyModel * * @param requestUrl the request URL * @param client the service client * @param requestOptions the options for this request */ public OnenoteEntityHierarchyModelRequest(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) { super(requestUrl, client, requestOptions, OnenoteEntityHierarchyModel.class); } /** * Gets the OnenoteEntityHierarchyModel from the service * * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<OnenoteEntityHierarchyModel> getAsync() { return sendAsync(HttpMethod.GET, null); } /** * Gets the OnenoteEntityHierarchyModel from the service * * @return the OnenoteEntityHierarchyModel from the request * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public OnenoteEntityHierarchyModel get() throws ClientException { return send(HttpMethod.GET, null); } /** * Delete this item from the service * * @return a future with the deletion result */ @Nonnull public java.util.concurrent.CompletableFuture<OnenoteEntityHierarchyModel> deleteAsync() { return sendAsync(HttpMethod.DELETE, null); } /** * Delete this item from the service * @return the resulting response if the service returns anything on deletion * * @throws ClientException if there was an exception during the delete operation */ @Nullable public OnenoteEntityHierarchyModel delete() throws ClientException { return send(HttpMethod.DELETE, null); } /** * Patches this OnenoteEntityHierarchyModel with a source * * @param sourceOnenoteEntityHierarchyModel the source object with updates * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<OnenoteEntityHierarchyModel> patchAsync(@Nonnull final OnenoteEntityHierarchyModel sourceOnenoteEntityHierarchyModel) { return sendAsync(HttpMethod.PATCH, sourceOnenoteEntityHierarchyModel); } /** * Patches this OnenoteEntityHierarchyModel with a source * * @param sourceOnenoteEntityHierarchyModel the source object with updates * @return the updated OnenoteEntityHierarchyModel * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public OnenoteEntityHierarchyModel patch(@Nonnull final OnenoteEntityHierarchyModel sourceOnenoteEntityHierarchyModel) throws ClientException { return send(HttpMethod.PATCH, sourceOnenoteEntityHierarchyModel); } /** * Creates a OnenoteEntityHierarchyModel with a new object * * @param newOnenoteEntityHierarchyModel the new object to create * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<OnenoteEntityHierarchyModel> postAsync(@Nonnull final OnenoteEntityHierarchyModel newOnenoteEntityHierarchyModel) { return sendAsync(HttpMethod.POST, newOnenoteEntityHierarchyModel); } /** * Creates a OnenoteEntityHierarchyModel with a new object * * @param newOnenoteEntityHierarchyModel the new object to create * @return the created OnenoteEntityHierarchyModel * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public OnenoteEntityHierarchyModel post(@Nonnull final OnenoteEntityHierarchyModel newOnenoteEntityHierarchyModel) throws ClientException { return send(HttpMethod.POST, newOnenoteEntityHierarchyModel); } /** * Creates a OnenoteEntityHierarchyModel with a new object * * @param newOnenoteEntityHierarchyModel the object to create/update * @return a future with the result */ @Nonnull public java.util.concurrent.CompletableFuture<OnenoteEntityHierarchyModel> putAsync(@Nonnull final OnenoteEntityHierarchyModel newOnenoteEntityHierarchyModel) { return sendAsync(HttpMethod.PUT, newOnenoteEntityHierarchyModel); } /** * Creates a OnenoteEntityHierarchyModel with a new object * * @param newOnenoteEntityHierarchyModel the object to create/update * @return the created OnenoteEntityHierarchyModel * @throws ClientException this exception occurs if the request was unable to complete for any reason */ @Nullable public OnenoteEntityHierarchyModel put(@Nonnull final OnenoteEntityHierarchyModel newOnenoteEntityHierarchyModel) throws ClientException { return send(HttpMethod.PUT, newOnenoteEntityHierarchyModel); } /** * Sets the select clause for the request * * @param value the select clause * @return the updated request */ @Nonnull public OnenoteEntityHierarchyModelRequest select(@Nonnull final String value) { addSelectOption(value); return this; } /** * Sets the expand clause for the request * * @param value the expand clause * @return the updated request */ @Nonnull public OnenoteEntityHierarchyModelRequest expand(@Nonnull final String value) { addExpandOption(value); return this; } }
shawnmullaney/forge
tests/terrain.py
# Copyright (C) 2013-2018 Internet Systems Consortium. # # Permission to use, copy, modify, and distribute this software for any # purpose with or without fee is hereby granted, provided that the above # copyright notice and this permission notice appear in all copies. # # THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SYSTEMS CONSORTIUM # DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL # INTERNET SYSTEMS CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING # FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION # WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. # Author: <NAME> import os import sys import time import logging from shutil import rmtree import subprocess import importlib from Crypto.Random.random import randint from scapy.config import conf from scapy.layers.dhcp6 import DUID_LLT from forge_cfg import world, step from softwaresupport.multi_server_functions import fabric_download_file, make_tarfile, archive_file_name,\ fabric_remove_file_command, fabric_run_command import logging_facility from srv_control import start_srv log = logging.getLogger('forge') values_v6 = {"T1": 0, # IA_NA IA_PD "T2": 0, # IA_NA IA_PD "address": "::", "IA_Address": "::", "prefix": "::", "plen": 0, # prefix; plz remember, to add prefix and prefix length! "preflft": 0, # IA_Address IA_Prefix "validlft": 0, # IA_Address IA_Prefix "enterprisenum": 0, # vendor "vendor_class_data": "", "linkaddr": world.f_cfg.srv_ipv6_addr_global, # relay "peeraddr": world.f_cfg.cli_link_local, # relay "ifaceid": "15", # relay "DUID": None, "FQDN_flags": "", "FQDN_domain_name": "", "address_type": 1, # dhcpv6 mac addr type, option 79 "link_local_mac_addr": world.f_cfg.cli_mac, "remote_id": "", "subscriber_id": "", "ia_id": 0, "ia_pd": 0, "prefval": 1, "elapsedtime": 1, "srvaddr": "::", "statuscode": 0, "statusmsg": "", "reconfigure_msg_type": 5, "reqopts": 7, "paaaddr": "::", "iitype": 0, "iimajor": 0, "iiminor": 0, "archtypes": 1, "erpdomain": "", "user_class_data": ""} srv_values_v6 = {"T1": 1000, "T2": 2000, "preferred-lifetime": 3000, "valid-lifetime": 4000, "prefix": "3000::", "prefix-len": 64, "timer": 10, "dst_addr": ()} values_dns = {"qname": "", "qtype": "", "qclass": ""} # times values, plz do not change this. # there is a test step to do this server_times_v6 = {"renew-timer": 1000, "rebind-timer": 2000, "preferred-lifetime": 3000, "valid-lifetime": 4000, "rapid-commit": False # yes that little odd, but let us keep it that way, # rapid-commit it's only option that is used # only in server configuration } server_times_v4 = {"renew-timer": 1000, "rebind-timer": 2000, "valid-lifetime": 4000} values_v4 = {"ciaddr": "0.0.0.0", "yiaddr": "0.0.0.0", "siaddr": "0.0.0.0", "giaddr": "0.0.0.0", "htype": 1, "broadcastBit": False, "hops": 0, "chaddr": None, "FQDN_flags": "", "FQDN_domain_name": ""} # we should consider transfer most of functions to separate v4 and v6 files # TODO: make separate files after branch merge def _set_values(): # this function is called after each message send. if world.f_cfg.proto == "v6": world.cfg["values"] = values_v6.copy() world.cfg["server_times"] = server_times_v6.copy() # reset values to 'default for scenario' world.cfg["values"]["cli_duid"] = world.cfg["cli_duid"] world.cfg["values"]["server_id"] = "" world.cfg["values"]["ia_id"] = world.cfg["ia_id"] world.cfg["values"]["ia_pd"] = world.cfg["ia_pd"] else: world.cfg["values"] = values_v4.copy() world.cfg["server_times"] = server_times_v4.copy() world.set_values = _set_values def client_id(mac): world.cfg["cli_duid"] = DUID_LLT(timeval = int(time.time()), lladdr = mac) if "values" in world.cfg: world.cfg["values"]["cli_duid"] = world.cfg["cli_duid"] def ia_id(): world.cfg["ia_id"] = randint(1, 99999) if "values" in world.cfg: world.cfg["values"]["ia_id"] = world.cfg["ia_id"] def ia_pd(): world.cfg["ia_pd"] = randint(1, 99999) if "values" in world.cfg: world.cfg["values"]["ia_pd"] = world.cfg["ia_pd"] def _v4_initialize(): # Setup scapy for v4 # conf.iface = IFACE conf.checkIPaddr = False # DHCPv4 is sent from 0.0.0.0, so response matching may confuse scapy world.cfg["srv4_addr"] = world.f_cfg.srv4_addr world.cfg["rel4_addr"] = world.f_cfg.rel4_addr world.cfg["giaddr4"] = world.f_cfg.giaddr4 world.cfg["space"] = "dhcp4" world.cfg["source_port"] = 68 world.cfg["destination_port"] = 67 world.cfg["source_IP"] = "0.0.0.0" world.cfg["destination_IP"] = "255.255.255.255" world.dhcp_enable = True def _v6_initialize(): world.dhcp_enable = True # RFC 3315 define two addresess: # All_DHCP_Relay_Agents_and_Servers = fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:2 # All DHCP_Servers fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:3. world.cfg["address_v6"] = "fd00:a516:7c1b:17cd:6d81:2137:bd2a:2c5b:2" world.cfg["cli_link_local"] = world.f_cfg.cli_link_local world.cfg["unicast"] = False world.cfg["relay"] = False world.cfg["space"] = "dhcp6" world.cfg["source_port"] = 546 world.cfg["destination_port"] = 547 # Setup scapy for v6 conf.iface6 = world.f_cfg.iface conf.use_pcap = True # those values should be initialized once each test # if you are willing to change it use 'client set value' steps client_id(world.f_cfg.cli_mac) ia_id() ia_pd() def _dns_initialize(): world.cfg["dns_iface"] = world.f_cfg.dns_iface world.cfg["dns4_addr"] = world.f_cfg.dns4_addr world.cfg["dns6_addr"] = world.f_cfg.dns6_addr world.cfg["dns_port"] = world.f_cfg.dns_port world.dns_enable = True def _define_software(dhcp_version): # unfortunately we have to do this every single time world.cfg["dhcp_under_test"] = "" world.cfg["dns_under_test"] = "" for name in world.f_cfg.software_under_test: if name in world.f_cfg.dhcp_used: world.cfg["dhcp_under_test"] = name.replace('6', '4') if dhcp_version == 'v4' else name.replace('4', '6') # world.cfg["dns_under_test"] = "" elif name in world.f_cfg.dns_used: world.cfg["dns_under_test"] = name # world.cfg["dhcp_under_test"] = "" def declare_all(dhcp_version=None): world.climsg = [] # Message(s) to be sent world.srvmsg = [] # Server's response(s) world.rlymsg = [] # Server's response(s) Relayed by Relay Agent world.tmpmsg = [] # container for temporary stored messages world.cliopts = [] # Option(s) to be included in the next message sent world.relayopts = [] # option(s) to be included in Relay Forward message. world.rsoo = [] # List of relay-supplied-options world.savedmsg = {0: []} # Saved option(s) world.define = [] # temporary define variables proto = dhcp_version if dhcp_version else world.f_cfg.proto world.proto = world.f_cfg.proto = proto world.oro = None world.vendor = [] world.iaad = [] world.iapd = [] world.opts = [] world.subopts = [] world.message_fields = [] world.subnet_add = True world.control_channel = None # last received response from any communication channel world.cfg = {} world.f_cfg.multiple_tested_servers = [world.f_cfg.mgmt_address] # dictionary that will keep multiple configs for various servers # mainly for testing multiple kea servers in the single test, # multiple servers has to be configured exactly identical. # supported only for Kea servers world.configClass = None # list that will keep configuration class from which mysql/postgres/netconf # configuration script will be generated # in future it's designed to clear JSON configuration process as well world.configString = "" world.cfg['leases'] = os.path.join(world.f_cfg.software_install_path, 'var/lib/kea/kea-leases%s.csv' % world.proto[1]) world.cfg['kea_logs'] = os.path.join(world.f_cfg.software_install_path + '/var/log/kea.log') world.cfg["dhcp_log_file"] = "~/none_file" world.loops = {"active": False, "save_leases_details": False} world.scapy_verbose = 99 world.dns_enable = False world.dhcp_enable = False world.ddns_enable = False world.ctrl_enable = False world.fuzzing = False # clear tmp DB values to use default from configuration world.f_cfg.db_type = world.f_cfg.db_type_bk world.f_cfg.db_host = world.f_cfg.db_host_bk world.f_cfg.db_name = world.f_cfg.db_name_bk world.f_cfg.db_passwd = world.f_cfg.db_passwd_bk world.f_cfg.db_user = world.f_cfg.db_user_bk <EMAIL> def test_start(): """ Server starting before testing """ # clear tests results if os.path.exists('tests_results'): rmtree('tests_results') os.makedirs('tests_results') if not os.path.exists('tests_results_archive') and world.f_cfg.auto_archive: os.makedirs('tests_results_archive') world.result = [] # Initialize the common logger. logging_facility.logger_initialize(world.f_cfg.loglevel) if not world.f_cfg.no_server_management: for each in world.f_cfg.software_under_test: sut = importlib.import_module("softwaresupport.%s.functions" % each) # True passed to stop_srv is to hide output in console. sut.stop_srv(True) if hasattr(sut, 'db_setup'): sut.db_setup() <EMAIL>scenario def initialize(scenario): # try to automagically detect DHCP version based on fixture presence # or marker presence try: dhcp_version = scenario._request.getfixturevalue('dhcp_version') except: if scenario.get_closest_marker('v4'): dhcp_version = 'v4' elif scenario.get_closest_marker('v6'): dhcp_version = 'v6' else: dhcp_version = None # Declare all default values declare_all(dhcp_version) _define_software(dhcp_version) world.cfg["iface"] = world.f_cfg.iface # world.cfg["server_type"] = SOFTWARE_UNDER_TEST for now I'll leave it here, # now we use world.cfg["dhcp_under_test"] and world.cfg["dns_under_test"] (in function _define_software) # it is being filled with values in srv_control world.cfg["wait_interval"] = world.f_cfg.packet_wait_interval world.cfg["cfg_file"] = "server.cfg" world.cfg["cfg_file_2"] = "second_server.cfg" world.cfg["conf"] = "" # Just empty config for now # additional config structure [subnet, client class/simple options, options, pools, host reservation]: world.subcfg = [["", "", "", "", "", "", ""]] world.shared_subcfg = [] world.shared_subnets = [] world.shared_subnets_tmp = [] world.kea_ha = [[], [], [], []] world.hooks = [] world.classification = [] world.reservation_backend = "" test_result_dir = str(scenario.name).replace(".", "_").replace('[', '_').replace(']', '_').replace('/', '_') world.cfg["test_result_dir"] = os.path.join('tests_results', test_result_dir) world.cfg["subnet"] = "" world.cfg["server-id"] = "" world.cfg["csv-format"] = "true" world.cfg["tr_id"] = None world.name = scenario.name world.srvopts = [] world.pref = None world.time = None # append single timestamp to list world.timestamps = [] # response times list world.RTlist = [] # time ranges that response time must fit in world.RTranges = [] world.RTranges.append([0.9, 1.1]) world.c = 0 world.notSolicit = 0 world.saved = [] world.iaid = [] if "dhcp_under_test" in world.cfg: # IPv6: if world.proto == "v6": _v6_initialize() # IPv4: if world.proto == "v4": _v4_initialize() if "dns_under_test" in world.cfg: _dns_initialize() world.set_values() world.cfg["values"]["tr_id"] = world.cfg["tr_id"] # to create separate files for each test we need: # create new directory for that test: if not os.path.exists(world.cfg["test_result_dir"]): os.makedirs(world.cfg["test_result_dir"]) if not os.path.exists(world.cfg["test_result_dir"] + '/dns') and world.dns_enable: os.makedirs(world.cfg["test_result_dir"] + '/dns') if world.f_cfg.tcpdump: cmd = world.f_cfg.tcpdump_path + 'tcpdump' args = [cmd, "-U", "-w", world.cfg["test_result_dir"] + "/capture.pcap", "-s", str(65535), "-i", world.cfg["iface"]] subprocess.Popen(args) # potential probelms with two instances of tcpdump running # TODO make sure it works properly! if world.dhcp_enable and world.dns_enable: if world.cfg["dns_iface"] != world.cfg["iface"]: cmd2 = world.f_cfg.tcpdump_path + 'tcpdump' args2 = [cmd2, "-U", "-w", world.cfg["test_result_dir"] + "/capture_dns.pcap", "-s", str(65535), "-i", world.cfg["dns_iface"]] subprocess.Popen(args2) _clear_remainings() #@after.each_scenario def cleanup(scenario): """ Global cleanup for each scenario. Implemented within tests by "Server is started." """ info = str(scenario.name) + '\n' + str(scenario.failed) if 'outline' not in info: world.result.append(info) # stop dhcp server start_srv('DHCP', 'stopped') if world.f_cfg.tcpdump: time.sleep(1) args = ["killall tcpdump"] subprocess.call(args, shell=True) # TODO: log output in debug mode if not world.f_cfg.no_server_management: for each_remote_server in world.f_cfg.multiple_tested_servers: for each in world.f_cfg.software_under_test: functions = importlib.import_module("softwaresupport.%s.functions" % each) # try: if world.f_cfg.save_leases: # save leases, if there is none leases in your software, just put "pass" in this function. functions.save_leases(destination_address=each_remote_server) if world.f_cfg.save_logs: functions.save_logs(destination_address=each_remote_server) _clear_remainings() def _clear_remainings(): if not world.f_cfg.no_server_management: for each_remote_server in world.f_cfg.multiple_tested_servers: for each in world.f_cfg.software_under_test: functions = importlib.import_module("softwaresupport.%s.functions" % each) # every software have something else to clear. Put in clear_all() whatever you need functions.clear_all(destination_address=each_remote_server) # except: # TODO this should be on multi_server_functions level! # log.info("Remote location " + each_remote_server + " unreachable!") <EMAIL> def say_goodbye(): """ Server stopping after whole work """ if world.f_cfg.history: result = open('result', 'w') for item in world.result: result.write(str(item) + '\n') result.close() if not world.f_cfg.no_server_management: for each_remote_server in world.f_cfg.multiple_tested_servers: for each in world.f_cfg.software_under_test: stop = importlib.import_module("softwaresupport.%s.functions" % each) # True passed to stop_srv is to hide output in console. try: stop.stop_srv(value=True, destination_address=each_remote_server) except: pass if world.f_cfg.auto_archive: name = "" if world.cfg["dhcp_under_test"] != "": name += world.cfg["dhcp_under_test"] if world.cfg["dns_under_test"] != "": if name != "": name += "_" name += world.cfg["dhcp_under_test"] archive_name = world.f_cfg.proto + '_' + name + '_' + time.strftime("%Y-%m-%d-%H:%M") archive_name = archive_file_name(1, 'tests_results_archive/' + archive_name) make_tarfile(archive_name + '.tar.gz', 'tests_results')
searKing/golib
os_/file.go
<reponame>searKing/golib<filename>os_/file.go package os_ import ( "os" "path/filepath" ) func GetAbsBinDir() (dir string, err error) { return filepath.Abs(filepath.Dir(os.Args[0])) } func PathExists(path string) (bool, error) { _, err := os.Stat(path) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } func MakdirAllIfNeeded(path string, perm os.FileMode) (created bool, err error) { dir, _ := filepath.Split(path) has, err := PathExists(dir) if err != nil { return false, err } if has { return false, nil } err = os.MkdirAll(dir, perm) if err != nil { return false, err } return true, nil }
FliesenUI/FliesenUI-samples
HelloWorldAutoTest/JavaProject/gen_src/generated/fliesenui/core/FLUIApplication.java
<reponame>FliesenUI/FliesenUI-samples<filename>HelloWorldAutoTest/JavaProject/gen_src/generated/fliesenui/core/FLUIApplication.java package generated.fliesenui.core; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.image.Image; import javafx.scene.paint.Color; import javafx.stage.Stage; public abstract class FLUIApplication extends Application { private Scene scene; private FLUIWebView webView; private int height; private String title; private int width; private FLUIScreenManager screenManager; private Image icon; private Stage stage; public FLUIApplication(String title, int width, int height, FLUIScreenManager screenManager) { this.title = title; this.width = width; this.height = height; this.screenManager = screenManager; } public void setIcon(Image icon) { this.icon = icon; if (stage != null){ stage.getIcons().add(icon); } } @Override public void start(Stage stage) { this.stage = stage; stage.setTitle(title); if (icon != null){ stage.getIcons().add(icon); } webView = new FLUIWebView(stage, width, height, screenManager); screenManager.setWebView(webView); scene = new Scene(webView, width, height, Color.web("#666970")); stage.setScene(scene); onStart(stage); stage.show(); screenManager.openStartScreen(); } public abstract void onStart(Stage stage); protected FLUIWebView getWebView() { return webView; } public FLUIScreenManager getScreenManager() { return screenManager; } }
549654033/RDHelp
src/src/Share/ShareLib/LinuxPublic/ACE_wrappers/ace/Proactor_Impl.cpp
// Proactor_Impl.cpp #include "ace/Proactor_Impl.h" #if ((defined (ACE_WIN32) && !defined (ACE_HAS_WINCE)) || (defined (ACE_HAS_AIO_CALLS) || defined(ACE_HAS_AIO_EMULATION))) // This only works on Win32 platforms and on Unix platforms supporting // aio calls. ACE_BEGIN_VERSIONED_NAMESPACE_DECL ACE_Proactor_Impl::~ACE_Proactor_Impl (void) { } int ACE_Proactor_Impl::post_wakeup_completions (int how_many) { ACE_Wakeup_Completion wakeup_completion (&this->wakeup_handler_, 0, // act 0, // completion key 0, // priority ACE_SIGRTMIN); for (ssize_t ci = 0; ci < how_many; ci++) { ACE_Asynch_Result_Impl * result_impl = this->create_result_impl (wakeup_completion); if (result_impl == 0 || result_impl->post () < 0) return -1; } return 0; } ACE_END_VERSIONED_NAMESPACE_DECL #endif /* (ACE_WIN32 && ACE_HAS_WINCE) || ACE_HAS_AIO_CALLS */
openml/openml.org
server/src/client/app/src/pages/search/MetaItems.js
import React from "react"; import { FontAwesomeIcon } from "@fortawesome/react-fontawesome"; import { Avatar, Tooltip, Chip } from "@material-ui/core"; export class MetaTag extends React.Component { render() { let icon; let prefix = ""; let suffix = ""; switch (this.props.type) { case "format": icon = "table"; break; case "licence": icon = "closed-captioning"; break; case "visibility": icon = "eye"; break; case "task-type": icon = "flag"; break; case "dataset": icon = "database"; break; case "likes": icon = "heart"; break; case "downloads": icon = "cloud"; suffix = " downloads"; break; case "issues": icon = "exclamation-triangle"; break; case "downvotes": icon = "thumbs-down"; break; case "runs": icon = "star"; suffix = " runs"; break; case "task": icon = "trophy"; prefix = "Task "; break; case "tasks": icon = "trophy"; suffix = " tasks"; break; case "data": icon = "database"; suffix = " datasets"; break; case "flows": icon = "cogs"; suffix = " flows"; break; case "status": icon = (this.props.value === 'verified' ? "check-circle" : (this.props.value === 'deactivated' ? "times" : "wrench")); break; case "id": icon = "id-badge"; break; case "uploaded": let uploadedDate = this.props.date !== undefined ? (<span><FontAwesomeIcon icon={"clock"} />{" "}{this.props.date}{" "}</span>) : ""; let uploadedBy = this.props.uploader !== undefined ? (<span>by <Chip size="small" variant="outlined" color="primary" avatar={<Avatar>{this.props.uploader.charAt(0)}</Avatar>} label={this.props.uploader} /></span>) : ""; return ( <Tooltip title="Date uploaded" placement="top-start"> <span style={{ paddingRight: 15, paddingBottom: 5, display: "inline-block" }}> <FontAwesomeIcon icon={"cloud-upload-alt"} />{" "}uploaded{" "} {uploadedDate} {uploadedBy} </span> </Tooltip>); default: icon = "question"; break; } return ( <Tooltip title={this.props.type} placement="top-start"> <span style={{ paddingRight: 15, paddingBottom: 5, display: "inline-block" }}> <FontAwesomeIcon icon={icon} color={this.props.color} />{" "}{prefix}{this.props.value}{suffix} </span> </Tooltip> ) } } export class VisibilityChip extends React.Component { render() { return (<Chip variant="outlined" color="primary" size={"small"} label={this.props.visibility} style={{ "margin-right": "10px" }} />); } }
cl0udz/Lynx
node_modules/browser-pack-flat/test/simplify/asi.js
// If the `test` import is removed naively, the result will be alert(test), which is incorrect. alert var test = require('./hello'); (test)
LaudateCorpus1/devhub
src/components/Meta.js
import React from 'react'; import PropTypes from 'prop-types'; import { Helmet } from 'react-helmet'; const Meta = ({ nodeData: { options } }) => ( <Helmet> {Object.entries(options).map(([key, value]) => ( <meta key={key} name={key} content={value} /> ))} </Helmet> ); Meta.propTypes = { nodeData: PropTypes.shape({ options: PropTypes.objectOf(PropTypes.string).isRequired, }).isRequired, }; export default Meta;
luhongbin/bidding
litemall-db/src/main/java/org/linlinjava/litemall/db/domain/LitemallPacking.java
package org.linlinjava.litemall.db.domain; import java.math.BigDecimal; import java.time.LocalDateTime; import java.util.ArrayList; import java.util.Arrays; public class LitemallPacking { /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ public static final Boolean IS_DELETED = Deleted.IS_DELETED.value(); /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ public static final Boolean NOT_DELETED = Deleted.NOT_DELETED.value(); /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.id * * @mbg.generated */ private Integer id; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.file_detail_id * * @mbg.generated */ private Integer fileDetailId; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.name * * @mbg.generated */ private String name; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.quantity * * @mbg.generated */ private BigDecimal quantity; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.length * * @mbg.generated */ private BigDecimal length; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.width * * @mbg.generated */ private BigDecimal width; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.height * * @mbg.generated */ private BigDecimal height; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.cube * * @mbg.generated */ private BigDecimal cube; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.add_time * * @mbg.generated */ private LocalDateTime addTime; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.update_time * * @mbg.generated */ private LocalDateTime updateTime; /** * * This field was generated by MyBatis Generator. * This field corresponds to the database column litemall_packing.deleted * * @mbg.generated */ private Boolean deleted; /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.id * * @return the value of litemall_packing.id * * @mbg.generated */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.id * * @param id the value for litemall_packing.id * * @mbg.generated */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.file_detail_id * * @return the value of litemall_packing.file_detail_id * * @mbg.generated */ public Integer getFileDetailId() { return fileDetailId; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.file_detail_id * * @param fileDetailId the value for litemall_packing.file_detail_id * * @mbg.generated */ public void setFileDetailId(Integer fileDetailId) { this.fileDetailId = fileDetailId; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.name * * @return the value of litemall_packing.name * * @mbg.generated */ public String getName() { return name; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.name * * @param name the value for litemall_packing.name * * @mbg.generated */ public void setName(String name) { this.name = name; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.quantity * * @return the value of litemall_packing.quantity * * @mbg.generated */ public BigDecimal getQuantity() { return quantity; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.quantity * * @param quantity the value for litemall_packing.quantity * * @mbg.generated */ public void setQuantity(BigDecimal quantity) { this.quantity = quantity; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.length * * @return the value of litemall_packing.length * * @mbg.generated */ public BigDecimal getLength() { return length; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.length * * @param length the value for litemall_packing.length * * @mbg.generated */ public void setLength(BigDecimal length) { this.length = length; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.width * * @return the value of litemall_packing.width * * @mbg.generated */ public BigDecimal getWidth() { return width; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.width * * @param width the value for litemall_packing.width * * @mbg.generated */ public void setWidth(BigDecimal width) { this.width = width; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.height * * @return the value of litemall_packing.height * * @mbg.generated */ public BigDecimal getHeight() { return height; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.height * * @param height the value for litemall_packing.height * * @mbg.generated */ public void setHeight(BigDecimal height) { this.height = height; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.cube * * @return the value of litemall_packing.cube * * @mbg.generated */ public BigDecimal getCube() { return cube; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.cube * * @param cube the value for litemall_packing.cube * * @mbg.generated */ public void setCube(BigDecimal cube) { this.cube = cube; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.add_time * * @return the value of litemall_packing.add_time * * @mbg.generated */ public LocalDateTime getAddTime() { return addTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.add_time * * @param addTime the value for litemall_packing.add_time * * @mbg.generated */ public void setAddTime(LocalDateTime addTime) { this.addTime = addTime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.update_time * * @return the value of litemall_packing.update_time * * @mbg.generated */ public LocalDateTime getUpdateTime() { return updateTime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.update_time * * @param updateTime the value for litemall_packing.update_time * * @mbg.generated */ public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public void andLogicalDeleted(boolean deleted) { setDeleted(deleted ? Deleted.IS_DELETED.value() : Deleted.NOT_DELETED.value()); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column litemall_packing.deleted * * @return the value of litemall_packing.deleted * * @mbg.generated */ public Boolean getDeleted() { return deleted; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column litemall_packing.deleted * * @param deleted the value for litemall_packing.deleted * * @mbg.generated */ public void setDeleted(Boolean deleted) { this.deleted = deleted; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", IS_DELETED=").append(IS_DELETED); sb.append(", NOT_DELETED=").append(NOT_DELETED); sb.append(", id=").append(id); sb.append(", fileDetailId=").append(fileDetailId); sb.append(", name=").append(name); sb.append(", quantity=").append(quantity); sb.append(", length=").append(length); sb.append(", width=").append(width); sb.append(", height=").append(height); sb.append(", cube=").append(cube); sb.append(", addTime=").append(addTime); sb.append(", updateTime=").append(updateTime); sb.append(", deleted=").append(deleted); sb.append("]"); return sb.toString(); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ @Override public boolean equals(Object that) { if (this == that) { return true; } if (that == null) { return false; } if (getClass() != that.getClass()) { return false; } LitemallPacking other = (LitemallPacking) that; return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId())) && (this.getFileDetailId() == null ? other.getFileDetailId() == null : this.getFileDetailId().equals(other.getFileDetailId())) && (this.getName() == null ? other.getName() == null : this.getName().equals(other.getName())) && (this.getQuantity() == null ? other.getQuantity() == null : this.getQuantity().equals(other.getQuantity())) && (this.getLength() == null ? other.getLength() == null : this.getLength().equals(other.getLength())) && (this.getWidth() == null ? other.getWidth() == null : this.getWidth().equals(other.getWidth())) && (this.getHeight() == null ? other.getHeight() == null : this.getHeight().equals(other.getHeight())) && (this.getCube() == null ? other.getCube() == null : this.getCube().equals(other.getCube())) && (this.getAddTime() == null ? other.getAddTime() == null : this.getAddTime().equals(other.getAddTime())) && (this.getUpdateTime() == null ? other.getUpdateTime() == null : this.getUpdateTime().equals(other.getUpdateTime())) && (this.getDeleted() == null ? other.getDeleted() == null : this.getDeleted().equals(other.getDeleted())); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((getId() == null) ? 0 : getId().hashCode()); result = prime * result + ((getFileDetailId() == null) ? 0 : getFileDetailId().hashCode()); result = prime * result + ((getName() == null) ? 0 : getName().hashCode()); result = prime * result + ((getQuantity() == null) ? 0 : getQuantity().hashCode()); result = prime * result + ((getLength() == null) ? 0 : getLength().hashCode()); result = prime * result + ((getWidth() == null) ? 0 : getWidth().hashCode()); result = prime * result + ((getHeight() == null) ? 0 : getHeight().hashCode()); result = prime * result + ((getCube() == null) ? 0 : getCube().hashCode()); result = prime * result + ((getAddTime() == null) ? 0 : getAddTime().hashCode()); result = prime * result + ((getUpdateTime() == null) ? 0 : getUpdateTime().hashCode()); result = prime * result + ((getDeleted() == null) ? 0 : getDeleted().hashCode()); return result; } /** * This enum was generated by MyBatis Generator. * This enum corresponds to the database table litemall_packing * * @mbg.generated */ public enum Deleted { NOT_DELETED(new Boolean("0"), "未删除"), IS_DELETED(new Boolean("1"), "已删除"); /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private final Boolean value; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private final String name; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ Deleted(Boolean value, String name) { this.value = value; this.name = name; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public Boolean getValue() { return this.value; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public Boolean value() { return this.value; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String getName() { return this.name; } } /** * This enum was generated by MyBatis Generator. * This enum corresponds to the database table litemall_packing * * @mbg.generated */ public enum Column { id("id", "id", "INTEGER", false), fileDetailId("file_detail_id", "fileDetailId", "INTEGER", false), name("name", "name", "VARCHAR", true), quantity("quantity", "quantity", "DECIMAL", false), length("length", "length", "DECIMAL", true), width("width", "width", "DECIMAL", false), height("height", "height", "DECIMAL", false), cube("cube", "cube", "DECIMAL", true), addTime("add_time", "addTime", "TIMESTAMP", false), updateTime("update_time", "updateTime", "TIMESTAMP", false), deleted("deleted", "deleted", "BIT", false); /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private static final String BEGINNING_DELIMITER = "`"; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private static final String ENDING_DELIMITER = "`"; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private final String column; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private final boolean isColumnNameDelimited; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private final String javaProperty; /** * This field was generated by MyBatis Generator. * This field corresponds to the database table litemall_packing * * @mbg.generated */ private final String jdbcType; /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String value() { return this.column; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String getValue() { return this.column; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String getJavaProperty() { return this.javaProperty; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String getJdbcType() { return this.jdbcType; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ Column(String column, String javaProperty, String jdbcType, boolean isColumnNameDelimited) { this.column = column; this.javaProperty = javaProperty; this.jdbcType = jdbcType; this.isColumnNameDelimited = isColumnNameDelimited; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String desc() { return this.getEscapedColumnName() + " DESC"; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String asc() { return this.getEscapedColumnName() + " ASC"; } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public static Column[] excludes(Column ... excludes) { ArrayList<Column> columns = new ArrayList<>(Arrays.asList(Column.values())); if (excludes != null && excludes.length > 0) { columns.removeAll(new ArrayList<>(Arrays.asList(excludes))); } return columns.toArray(new Column[]{}); } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String getEscapedColumnName() { if (this.isColumnNameDelimited) { return new StringBuilder().append(BEGINNING_DELIMITER).append(this.column).append(ENDING_DELIMITER).toString(); } else { return this.column; } } /** * This method was generated by MyBatis Generator. * This method corresponds to the database table litemall_packing * * @mbg.generated */ public String getAliasedEscapedColumnName() { return this.getEscapedColumnName(); } } }
KiritoCyanPine/ipfs-gomobile-shipyard-modified
vendor/github.com/ipfs/go-unixfsnode/utils/utils.go
package utils import dagpb "github.com/ipld/go-codec-dagpb" // Lookup finds a name key in a list of dag pb links func Lookup(links dagpb.PBLinks, key string) dagpb.Link { li := links.Iterator() for !li.Done() { _, next := li.Next() name := "" if next.FieldName().Exists() { name = next.FieldName().Must().String() } if key == name { return next.FieldHash() } } return nil }
MasterLogick/osu-laser-cpp
osu/desktop/logic/db/OsuDatabase.h
// // Created by Masterlogick on 2/13/20. // #ifndef OSU_LASER_C_OSUDATABASE_H #define OSU_LASER_C_OSUDATABASE_H #include <cstdint> #include <string> #include "Database.h" namespace osu { class OsuDatabase : Database { typedef std::pair<int, double> IDPair; struct TimingPoint { double BPM; double offset; bool inherited; }; typedef int64_t DateTime; private: int version; int folderCount; bool accountUnlocked; DateTime unlockTime; std::string playerName; public: void load(const char *name) override; }; } #endif //OSU_LASER_C_OSUDATABASE_H
frederickpek/tp
src/main/java/seedu/track2gather/model/person/attributes/NextOfKinName.java
package seedu.track2gather.model.person.attributes; import java.util.Optional; public class NextOfKinName extends Attribute<Optional<Name>> { /** * Constructs an {@code Attribute}. * * @param value A valid attribute value. */ public NextOfKinName(Optional<Name> value) { super(value); } public NextOfKinName(Name value) { super(Optional.ofNullable(value)); } public NextOfKinName() { super(Optional.empty()); } @Override public boolean equals(Object other) { return other == this // short circuit if same object || (other instanceof NextOfKinName // instanceof handles nulls && value.equals(((NextOfKinName) other).value)); // state check } @Override public int hashCode() { return value.hashCode(); } }
exebixel/oneparams
oneparams/one.py
<reponame>exebixel/oneparams #!/usr/bin/python import click import sys import pandas as pd from oneparams.reset import pw_reset from oneparams.api.login import login from oneparams.excel.card import cards from oneparams.excel.colaborador import colaborador from oneparams.excel.comissao import Comissao from oneparams.excel.servicos import servico from oneparams.excel.cliente import clientes import oneparams.config as config _global_options = [ click.argument('worksheet', required=True, type=click.Path(exists=True)), click.option('-l', '--login', 'login', required=True, type=str, help="Email address to login"), click.option('-p', '--password', 'password', required=False, type=str, default='<PASSWORD>', help="Access password (default = <PASSWORD>)"), click.option('-e', '--empresa', 'empresa', required=True, type=str, help="Company name used to parametrization"), click.option('-eid', '--empresa-id', 'empresa_id', required=False, type=int, default=None, help="Company id (if have some companies with same name)"), click.option('-f', '--filial', 'filial', required=False, type=str, help="Branch name used to parametrization"), click.option('-W', '--no-warning', 'warning', required=False, is_flag=True, default=False, help="Suppress warnings") ] _reset_options = [ click.option('-R', '--reset', 'reset', required=False, is_flag=True, default=False, help="Delete or inactivate all services") ] _error_options = [ click.option('-E', '--no-error', 'error', required=False, is_flag=True, default=False, help="Resolve erros (this can delete data)") ] _skip_options = [ click.option('-S', '--skip', 'skip', required=False, is_flag=True, default=False, help='Skip items already registered') ] def add_option(options): def _add_options(func): for option in reversed(options): func = option(func) return func return _add_options def cli_login(kwargs): one = login() one.login(nome_empresa=kwargs['empresa'], nome_filial=kwargs['filial'], email=kwargs['login'], senha=kwargs['password'], empresa_id=kwargs['empresa_id']) def cli_file(worksheet): try: return pd.ExcelFile(worksheet) except FileNotFoundError as exp: sys.exit(exp) except ValueError as exp: sys.exit(exp) def cli_config(error=False, warning=False, skip=False): config.RESOLVE_ERROS = error config.NO_WARNING = warning config.SKIP = skip @click.group() @click.version_option(config.VERSION) def cli(): pass @cli.command(help="Manipulating Services") @add_option(_global_options) @add_option(_reset_options) def serv(**kwargs): cli_login(kwargs) book = cli_file(kwargs['worksheet']) cli_config(warning=kwargs['warning']) servico(book, reset=kwargs['reset']) @cli.command(help="Manipulating Collaborators") @add_option(_global_options) def cols(**kwargs): cli_login(kwargs) book = cli_file(kwargs['worksheet']) cli_config(warning=kwargs['warning']) colaborador(book) @cli.command(help="Manipulating Cards") @add_option(_global_options) @add_option(_reset_options) def card(**kwargs): cli_login(kwargs) book = cli_file(kwargs['worksheet']) cli_config(warning=kwargs['warning']) cards(book, reset=kwargs['reset']) @cli.command(help="Professional Committee Manipulation") @add_option(_global_options) @add_option(_reset_options) def comm(**kwargs): cli_login(kwargs) book = cli_file(kwargs['worksheet']) cli_config(warning=kwargs['warning']) Comissao(book, reset=kwargs['reset']) @cli.command(help="Manipulating Clients") @add_option(_global_options) @add_option(_reset_options) @add_option(_error_options) @add_option(_skip_options) def clis(**kwargs): cli_login(kwargs) book = cli_file(kwargs['worksheet']) cli_config(error=kwargs['error'], warning=kwargs['warning'], skip=kwargs['skip']) clientes(book, reset=kwargs['reset']) @cli.command(help="Password Reset") @click.argument('email', required=True, type=str) @click.option('-k', '--key', 'acess_key', envvar='ONE_RESET', required=True, type=str) def reset(email, acess_key): pw_reset(email, acess_key) if __name__ == "__main__": cli()
YuriyLisovskiy/xalwart.base
src/unicode/_def_.h
<filename>src/unicode/_def_.h<gh_stars>0 /** * unicode/_def_.h * * Copyright (c) 2021 <NAME> * * Definitions of 'unicode' module. */ #pragma once // C++ libraries. #include <vector> #include "../_def_.h" // xw::unicode #define __UNICODE_BEGIN__ __MAIN_NAMESPACE_BEGIN__ namespace unicode { #define __UNICODE_END__ } __MAIN_NAMESPACE_END__ // xw::unicode::utf8 #define __UNICODE_UTF8_BEGIN__ __UNICODE_BEGIN__ namespace utf8 { #define __UNICODE_UTF8_END__ } __UNICODE_END__ __UNICODE_BEGIN__ // Characters below BYTE_SELF are represented as themselves in a single byte. static inline constexpr const uint16_t UNICODE_ERROR = 0xfffd; static inline constexpr const uint32_t BYTE_SELF = 0x80; static inline constexpr const int32_t MAX_WCHAR_T = 0x10ffff; static inline constexpr const int32_t UPPER_LOWER = MAX_WCHAR_T + 1; static inline constexpr const int32_t MAX_ASCII = 0x7f; static inline constexpr const uint32_t MAX_LATIN_1 = 0x00FF; static inline constexpr const int32_t REPLACEMENT_CHAR = 0xfffd; enum class Case { Upper = 0, Lower, Title, Max }; using Delta = wchar_t[(int)Case::Max]; // Represents a range of Unicode code points for simple (one // code point to one code point) case conversion. // The range runs from `lo` to `hi` inclusive, with a fixed `stride` of 1. Deltas // are the number to add to the code point to reach the code point for a // different case for that character. They may be negative. If zero, it // means the character is in the corresponding case. There is a special // case representing sequences of alternating corresponding Upper and Lower // pairs. It appears with a fixed Delta of // {UPPER_LOWER, UPPER_LOWER, UPPER_LOWER} // The constant UPPER_LOWER has an otherwise impossible delta value. // // The original implementation is in Golang 1.15.8: unicode/letter.go struct CaseRange { uint32_t lo; uint32_t hi; Delta delta; }; // Represents of a range of 16-bit Unicode code points. // The range runs from `lo` to `hi` inclusive and has the specified `stride`. // // The original implementation is in Golang 1.15.8: unicode/letter.go struct Range16 { uint16_t lo; uint16_t hi; uint16_t stride; }; // Represents of a range of Unicode code points and is used when one or // more of the values will not fit in 16 bits. The range runs from `lo` to `hi` // inclusive and has the specified `stride`. `lo` and `hi` must always be >= 1<<16. // // The original implementation is in Golang 1.15.8: unicode/letter.go struct Range32 { uint32_t lo; uint32_t hi; uint32_t stride; }; // Defines a set of Unicode code points by listing the ranges of // code points within the set. The ranges are listed in two vectors // to save space: a slice of 16-bit ranges and a slice of 32-bit ranges. // The two vectors must be in sorted order and non-overlapping. // Also, R32 should contain only values >= 0x10000 (1<<16). // // The original implementation is in Golang 1.15.8: unicode/letter.go struct RangeTable { std::vector<Range16> r16; std::vector<Range32> r32; int latin_offset; }; __UNICODE_END__
tonioshikanlu/tubman-hack
sources/e/a/a/a/y0/j/y/h.java
<reponame>tonioshikanlu/tubman-hack package e.a.a.a.y0.j.y; import e.a.a.a.y0.l.i; import e.a.a.a.y0.l.m; import e.x.c.k; public final class h extends a { /* renamed from: b reason: collision with root package name */ public final i<i> f9456b; public static final class a extends k implements e.x.b.a<i> { /* renamed from: h reason: collision with root package name */ public final /* synthetic */ e.x.b.a f9457h; /* JADX INFO: super call moved to the top of the method (can break code semantics) */ public a(e.x.b.a aVar) { super(0); this.f9457h = aVar; } public Object e() { i iVar = (i) this.f9457h.e(); return iVar instanceof a ? ((a) iVar).h() : iVar; } } public h(m mVar, e.x.b.a<? extends i> aVar) { e.x.c.i.e(mVar, "storageManager"); e.x.c.i.e(aVar, "getScope"); this.f9456b = mVar.a(new a(aVar)); } public i i() { return (i) this.f9456b.e(); } }
starlingx-staging/stx-ha
service-mgmt/sm-1.0.0/src/sm_service_group_go_standby.c
<reponame>starlingx-staging/stx-ha<filename>service-mgmt/sm-1.0.0/src/sm_service_group_go_standby.c // // Copyright (c) 2014 Wind River Systems, Inc. // // SPDX-License-Identifier: Apache-2.0 // #include "sm_service_group_go_standby.h" #include <stdio.h> #include "sm_types.h" #include "sm_debug.h" #include "sm_service_group_member_table.h" #include "sm_service_api.h" // **************************************************************************** // Service Group Go-Standby - Service // ================================== static void sm_service_group_go_standby_service( void* user_data[], SmServiceGroupMemberT* service_group_member ) { SmServiceGroupT* service_group = (SmServiceGroupT*) user_data[0]; SmErrorT error; DPRINTFD( "Go-Standby on %s of %s", service_group_member->service_name, service_group->name ); error = sm_service_api_go_standby( service_group_member->service_name ); if( SM_OKAY != error ) { DPRINTFE( "Failed to send go-standby to service (%s) of " "service group (%s), error=%s.", service_group_member->service_name, service_group->name, sm_error_str( error ) ); return; } } // **************************************************************************** // **************************************************************************** // Service Group Go-Standby // ======================== SmErrorT sm_service_group_go_standby( SmServiceGroupT* service_group ) { void* user_data[] = { service_group }; sm_service_group_member_table_foreach_member( service_group->name, user_data, sm_service_group_go_standby_service ); return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Service Group Go-Standby - Complete // =================================== static void sm_service_group_go_standby_service_complete( void* user_data[], SmServiceGroupMemberT* service_group_member ) { bool* complete_overall = (bool*) user_data[0]; if(( SM_SERVICE_STATE_ENABLED_STANDBY == service_group_member->service_state )|| ( SM_SERVICE_STATE_ENABLING_THROTTLE == service_group_member->service_state )|| ( SM_SERVICE_STATE_ENABLING == service_group_member->service_state )|| ( SM_SERVICE_STATE_DISABLING == service_group_member->service_state )|| ( SM_SERVICE_STATE_DISABLED == service_group_member->service_state )) { DPRINTFD( "Go-Standby of service (%s) for service group (%s) complete, " "state=%s.", service_group_member->service_name, service_group_member->name, sm_service_state_str( service_group_member->service_state ) ); } else { *complete_overall = false; DPRINTFD( "Go-Standby of service (%s) for service group (%s) not yet " "complete, state=%s.", service_group_member->service_name, service_group_member->name, sm_service_state_str( service_group_member->service_state ) ); } } // **************************************************************************** // **************************************************************************** // Service Group Go-Standby - Complete // =================================== SmErrorT sm_service_group_go_standby_complete( SmServiceGroupT* service_group, bool* complete ) { bool go_standby_complete = true; void* user_data[] = { &go_standby_complete }; *complete = false; sm_service_group_member_table_foreach_member( service_group->name, user_data, sm_service_group_go_standby_service_complete ); *complete = go_standby_complete; if( go_standby_complete ) { DPRINTFI( "All services go-standby for service group (%s) " "are complete.", service_group->name ); } else { DPRINTFD( "Some service go-standby for service group (%s) " "are not yet complete.", service_group->name ); } return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Service Group Go-Standby - Initialize // ===================================== SmErrorT sm_service_group_go_standby_initialize( void ) { return( SM_OKAY ); } // **************************************************************************** // **************************************************************************** // Service Group Go-Standby - Finalize // =================================== SmErrorT sm_service_group_go_standby_finalize( void ) { return( SM_OKAY ); } // ****************************************************************************
bumbeishvili/teamapps
teamapps-ui-dsl/src/main/java/org/teamapps/dto/generate/TeamAppsDtoModelValidator.java
/*- * ========================LICENSE_START================================= * TeamApps * --- * Copyright (C) 2014 - 2019 TeamApps.org * --- * 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. * =========================LICENSE_END================================== */ package org.teamapps.dto.generate; import org.teamapps.dto.TeamAppsDtoParser; import java.util.List; import java.util.Map; import java.util.stream.Collectors; public class TeamAppsDtoModelValidator { private final TeamAppsDtoModel model; public TeamAppsDtoModelValidator(TeamAppsDtoModel model) { this.model = model; } public void validate() { List<TeamAppsDtoParser.ClassDeclarationContext> classDeclarations = model.getClassDeclarations(); validateNoDuplicateClassDeclarations(classDeclarations); for (TeamAppsDtoParser.ClassDeclarationContext classDeclaration : classDeclarations) { validateRequiredPropertiesHaveNoDefaultValue(classDeclaration); } List<TeamAppsDtoParser.EnumDeclarationContext> enumDeclarations = model.getEnumDeclarations(); validateNoDuplicateEnumDeclarations(enumDeclarations); } private void validateNoDuplicateClassDeclarations(List<TeamAppsDtoParser.ClassDeclarationContext> classDeclarations) { Map<String, Long> cardinalities = classDeclarations.stream() .collect(Collectors.groupingBy(classDeclarationContext -> classDeclarationContext.Identifier().getText(), Collectors.counting())); validateNoMultipleEntries(cardinalities); } private void validateRequiredPropertiesHaveNoDefaultValue(TeamAppsDtoParser.ClassDeclarationContext classDeclaration) { for (TeamAppsDtoParser.PropertyDeclarationContext pd : classDeclaration.propertyDeclaration()) { if (pd.requiredModifier() != null && pd.defaultValueAssignment() != null) { throw new IllegalArgumentException("A required property declaration may not have a default value! Erroneous declaration: " + ((TeamAppsDtoParser.ClassDeclarationContext) pd .getParent()).Identifier().getText() + "." + pd.Identifier().getText()); } } } private void validateNoDuplicateEnumDeclarations(List<TeamAppsDtoParser.EnumDeclarationContext> enumDeclarations) { Map<String, Long> cardinalities = enumDeclarations.stream() .collect(Collectors.groupingBy(classDeclarationContext -> classDeclarationContext.Identifier().getText(), Collectors.counting())); validateNoMultipleEntries(cardinalities); } private void validateNoMultipleEntries(Map<String, Long> cardinalities) { String errorMessage = cardinalities.entrySet().stream() .filter(e -> e.getValue() > 1) .map(e -> e.getKey() + " is declared " + e.getValue() + " times.") .collect(Collectors.joining(";\n")); if (errorMessage.length() > 0) { throw new IllegalArgumentException(errorMessage); } } }
two-code/grpc-go-clay
server/opts.go
package server import ( "net/http" "time" "github.com/utrack/clay/v3/server/middlewares/mwhttp" "github.com/utrack/clay/v3/transport" "github.com/go-chi/chi" grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware" "google.golang.org/grpc" ) // Option is an optional setting applied to the Server. type Option func(*serverOpts) type serverOpts struct { HTTPMux transport.Router GRPCUnaryInterceptor grpc.UnaryServerInterceptor HTTPMiddlewares []func(http.Handler) http.Handler HTTPShutdownWaitTimeout time.Duration } func defaultServerOpts() *serverOpts { return &serverOpts{ HTTPMux: chi.NewMux(), } } // WithHTTPMiddlewares sets up HTTP middlewares to work with. func WithHTTPMiddlewares(mws ...mwhttp.Middleware) Option { mwGeneric := make([]func(http.Handler) http.Handler, 0, len(mws)) for _, mw := range mws { mwGeneric = append(mwGeneric, mw) } return func(o *serverOpts) { o.HTTPMiddlewares = mwGeneric } } func WithHTTPShutdownWaitTimeout(timeout time.Duration) Option { return func(o *serverOpts) { o.HTTPShutdownWaitTimeout = timeout } } // WithGRPCUnaryMiddlewares sets up unary middlewares for gRPC server. func WithGRPCUnaryMiddlewares(mws ...grpc.UnaryServerInterceptor) Option { mw := grpc_middleware.ChainUnaryServer(mws...) return func(o *serverOpts) { o.GRPCUnaryInterceptor = mw } } // WithHTTPMux sets existing HTTP muxer to use instead of creating new one. func WithHTTPMux(mux *chi.Mux) Option { return func(o *serverOpts) { o.HTTPMux = mux } } func WithHTTPRouterMux(mux transport.Router) Option { return func(o *serverOpts) { o.HTTPMux = mux } }
jelic98/instafram
src/org/ljelic/instafram/view/adapter/tab/TabItem.java
package org.ljelic.instafram.view.adapter.tab; import org.ljelic.instafram.model.AbstractModel; import org.ljelic.instafram.view.adapter.action.BarItem; import org.ljelic.instafram.view.component.ScrollPanel; public class TabItem extends BarItem implements Comparable { private final AbstractModel model; private final ScrollPanel panel; public TabItem(AbstractModel model, ScrollPanel panel) { super(model.getName(), model.getIcon()); this.model = model; this.panel = panel; } public AbstractModel getModel() { return model; } public ScrollPanel getPanel() { return panel; } @Override public int compareTo(Object obj) { return equals(obj) ? 0 : -1; } @Override public boolean equals(Object obj) { if(obj == null || !(obj instanceof TabItem)) { return false; } TabItem item = (TabItem) obj; return getModel().equals(item.getModel()); } }
genisysram/libyami
vaapi/vaapisurfaceallocator.cpp
<filename>vaapi/vaapisurfaceallocator.cpp<gh_stars>10-100 /* * Copyright (C) 2015 Intel Corporation. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "common/log.h" #include "vaapi/vaapisurfaceallocator.h" #include "vaapi/VaapiUtils.h" #include <vector> namespace YamiMediaCodec{ VaapiSurfaceAllocator::VaapiSurfaceAllocator(VADisplay display, uint32_t extraSize) :m_display(display), m_extraSize(extraSize) { } YamiStatus VaapiSurfaceAllocator::doAlloc(SurfaceAllocParams* params) { if (!params) return YAMI_INVALID_PARAM; uint32_t size = params->size; uint32_t width = params->width; uint32_t height = params->height; if (!width || !height || !size) return YAMI_INVALID_PARAM; uint32_t rtFormat = getRtFormat(params->fourcc); if (!rtFormat) { ERROR("unsupported format %x", params->fourcc); return YAMI_UNSUPPORTED; } size += m_extraSize; std::vector<VASurfaceID> v(size); VASurfaceAttrib attrib; attrib.flags = VA_SURFACE_ATTRIB_SETTABLE; attrib.type = VASurfaceAttribPixelFormat; attrib.value.type = VAGenericValueTypeInteger; attrib.value.value.i = params->fourcc; VAStatus status = vaCreateSurfaces(m_display, rtFormat, width, height, &v[0], size, &attrib, 1); if (!checkVaapiStatus(status, "vaCreateSurfaces")) return YAMI_OUT_MEMORY; params->surfaces = new intptr_t[size]; for (uint32_t i = 0; i < size; i++) { params->surfaces[i] = (intptr_t)v[i]; } params->size = size; return YAMI_SUCCESS; } YamiStatus VaapiSurfaceAllocator::doFree(SurfaceAllocParams* params) { if (!params || !params->size || !params->surfaces) return YAMI_INVALID_PARAM; uint32_t size = params->size; std::vector<VASurfaceID> v(size); for (uint32_t i = 0; i < size; i++) { v[i] = (VASurfaceID)params->surfaces[i]; } checkVaapiStatus(vaDestroySurfaces(m_display, &v[0], size), "vaDestroySurfaces"); delete[] params->surfaces; return YAMI_SUCCESS; } void VaapiSurfaceAllocator::doUnref() { delete this; } } //YamiMediaCodec
ibiscum/Crafting-Test-Driven-Software-with-Python
Chapter05/test_randomness.py
<filename>Chapter05/test_randomness.py import pytest def test_something(random_number_generator): a = random_number_generator() b = 10 assert a + b >= 10
RideGreg/LeetCode
Python/element-appearing-more-than-25-in-sorted-array.py
<reponame>RideGreg/LeetCode # Time: O(logn) # Space: O(1) # 1287 biweekly contest 15 12/14/2019 # # Given an integer array SORTED in non-decreasing order, there is exactly one integer in the array # that occurs more than 25% of the time. # # Return that integer. import bisect import collections class Solution(object): def findSpecialInteger(self, arr): # UES THIS: binary search """ :type arr: List[int] :rtype: int """ for x in [arr[len(arr)//4], arr[len(arr)//2], arr[len(arr)*3//4]]: if (bisect.bisect_right(arr, x) - bisect.bisect_left(arr, x)) * 4 > len(arr): return x return -1 # O(n). Pro: no need to check all items def findSpecialInteger_awice(self, A): count = collections.Counter(A) N = len(A) for x in count: if count[x] * 4 > N: return x # O(n) def findSpecialInteger_ming(self, arr): c = collections.Counter(arr) return max(c, key=c.get) print(Solution().findSpecialInteger([1,2,2,6,6,6,6,7,10])) # 6
ScalablyTyped/SlinkyTyped
w/winrt-uwp/src/main/scala/typingsSlinky/winrtUwp/Windows/Management/Deployment/Preview.scala
<gh_stars>10-100 package typingsSlinky.winrtUwp.Windows.Management.Deployment import org.scalablytyped.runtime.StObject import scala.scalajs.js import scala.scalajs.js.`|` import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess} object Preview { @js.native trait ClassicAppManager extends StObject @js.native trait InstalledClassicAppInfo extends StObject { var displayName: js.Any = js.native /* unmapped type */ var displayVersion: js.Any = js.native } object InstalledClassicAppInfo { @scala.inline def apply(displayName: js.Any, displayVersion: js.Any): InstalledClassicAppInfo = { val __obj = js.Dynamic.literal(displayName = displayName.asInstanceOf[js.Any], displayVersion = displayVersion.asInstanceOf[js.Any]) __obj.asInstanceOf[InstalledClassicAppInfo] } @scala.inline implicit class InstalledClassicAppInfoMutableBuilder[Self <: InstalledClassicAppInfo] (val x: Self) extends AnyVal { @scala.inline def setDisplayName(value: js.Any): Self = StObject.set(x, "displayName", value.asInstanceOf[js.Any]) @scala.inline def setDisplayVersion(value: js.Any): Self = StObject.set(x, "displayVersion", value.asInstanceOf[js.Any]) } } }
deszhouandong/shop1
src/src/router/modules/search.js
export default [ { path: '/search', name: 'search', meta: { index: 17 }, component: () => import('@/views/search/index.vue') } ]
SpontaneousCMS/simultaneous
lib/simultaneous/task.rb
module Simultaneous module Task def self.task_name ENV[Simultaneous::ENV_TASK_NAME] end def self.pid $$ end def self.included(klass) Simultaneous.client = Simultaneous::SyncClient.new Simultaneous.set_pid(self.task_name, pid) if task_name at_exit { begin Simultaneous.task_complete(self.task_name) rescue Errno::ECONNREFUSED rescue Errno::ENOENT end # Simultaneous.client.close } rescue Errno::ECONNREFUSED rescue Errno::ENOENT # server isn't running but we don't want this to stop our script end def simultaneous_event(event, message) Simultaneous.send_event(event, message) rescue Errno::ECONNREFUSED rescue Errno::ENOENT # server isn't running but we don't want this to stop our script end end end
Geomatys/constellation
modules/cstl-admin/grunt/src/js/admin/admin-processing.js
<gh_stars>10-100 /* * Constellation - An open source and standard compliant SDI * * http://www.constellation-sdi.org * * Copyright 2014 Geomatys * * 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. */ angular.module('cstl-admin-processing', ['cstl-restapi', 'cstl-services']) .controller('TaskController', function($scope, $timeout, TaskService, StompService) { $scope.tasks = TaskService.listTasks(); var topic = StompService.subscribe('/topic/taskevents', function(data) { var event = JSON.parse(data.body); var task = $scope.tasks[event.id]; if (task) { task.percent = event.percent; if (task.percent > 99) { delete $scope.tasks[event.id]; } $scope.$digest(); } else { // New task $scope.tasks[event.id] = { id: event.id, status: event.status, message: event.message, percent: event.percent }; $scope.$digest(); } }); $scope.$on('$destroy', function() { topic.unsubscribe(); }); });
georgejkaye/ballin-game
src/networking/ClientInformation.java
<gh_stars>0 package networking; import java.util.UUID; /** * This contains all the information about a particular client. * @author aaquibnaved * */ public class ClientInformation { private String id; private String name; private String sessionId; private boolean ready; private resources.Character.Class characterClass; private int playerNumber; public ClientInformation() { } /** * Initialises using only a name. ID is generated and converted to a String. * @param name Name of the Client. */ public ClientInformation(String name) { this.id = UUID.randomUUID().toString(); this.name = name; this.ready = false; } /** * Initialises using a preset ID. * @param id The ID of the client * @param name The Name of the client */ public ClientInformation(String id, String name) { this.id = id; this.name = name; this.ready = false; } /** * Initialises using the ID, the name and type of character class which the Client has chosen to me. * @param id The ID of the client * @param name The name of the client * @param characterClass The character class of the client */ public ClientInformation(String id, String name, resources.Character.Class characterClass) { this.id = id; this.name = name; this.ready = false; this.characterClass = characterClass; } /** * Get the ID of the client * @return The ID of the client */ public String getId() { return id; } /** * Set the ID of the client * @param id The ID of the client */ public void setId(String id) { this.id = id; } /** * Get the name of the client * @return The name of the client */ public String getName() { return name; } /** * Is the client ready for the game to start? * @return true if the client is ready, false otherwise */ public boolean isReady() { return ready; } /** * Set whether the client is ready to start or not. * @param b whether the client is ready or not */ public void setReady(boolean b) { this.ready = b; } /** * Get the session ID which the client has currently joined * This returns null when the client is not part of a session. * @return The Session ID */ public String getSessionId() { return sessionId; } /** * Stores the session ID which the client belongs to. * @param sessionId The session ID */ public void setSessionId(String sessionId) { this.sessionId = sessionId; } /** * Get the character class which this client has chosen. * @return */ public resources.Character.Class getCharacterClass() { return characterClass; } /** * Set the character class of the client. * @param characterClass */ public void setCharacterClass(resources.Character.Class characterClass) { this.characterClass = characterClass; } /** * Get the number assigned to the player (this is used for the player colour) * @return The player number */ public int getPlayerNumber() { return playerNumber; } /** * Set the player number (this is used for the player colour) * @param playerNumber The player number */ public void setPlayerNumber(int playerNumber) { this.playerNumber = playerNumber; } }
Joanguitar/docker-nextepc
virtual-UE-eNB/srsLTE-5d82f19988bc148d7f4cec7a0f29184375a64b40/lib/src/radio/radio_multi.cc
#include "srslte/radio/radio_multi.h" namespace srslte { bool radio_multi::init_multi(uint32_t nof_rx_antennas, char* args, char* devname) { if (srslte_rf_open_devname(&rf_device, devname, args, nof_rx_antennas)) { fprintf(stderr, "Error opening RF device\n"); return false; } tx_adv_negative = false; agc_enabled = false; burst_preamble_samples = 0; burst_preamble_time_rounded = 0; cur_tx_srate = 0; is_start_of_burst = true; // Suppress radio stdout srslte_rf_suppress_stdout(&rf_device); continuous_tx = true; tx_adv_auto = true; // Set default preamble length each known device // We distinguish by device family, maybe we should calibrate per device if (strstr(srslte_rf_name(&rf_device), "uhd")) { burst_preamble_sec = uhd_default_burst_preamble_sec; } else if (strstr(srslte_rf_name(&rf_device), "bladerf")) { burst_preamble_sec = blade_default_burst_preamble_sec; } else { printf("\nWarning burst preamble is not calibrated for device %s. Set a value manually\n\n", srslte_rf_name(&rf_device)); } if (args) { strncpy(saved_args, args, 127); } if (devname) { strncpy(saved_devname, devname, 127); } is_initialized = true; return true; } bool radio_multi::rx_now(cf_t *buffer[SRSLTE_MAX_PORTS], uint32_t nof_samples, srslte_timestamp_t* rxd_time) { void *ptr[SRSLTE_MAX_PORTS]; for (int i=0;i<SRSLTE_MAX_PORTS;i++) { ptr[i] = buffer[i]; } if (!radio_is_streaming) { srslte_rf_start_rx_stream(&rf_device, false); radio_is_streaming = true; } if (srslte_rf_recv_with_time_multi(&rf_device, ptr, nof_samples, true, rxd_time?&rxd_time->full_secs:NULL, rxd_time?&rxd_time->frac_secs:NULL) > 0) { return true; } else { return false; } } }
Seviran/Advanced-Webdev
Section 23/College 262/script.js
<reponame>Seviran/Advanced-Webdev var minYear = d3.min(birthData, function(d) { return d.year; }); var maxYear = d3.max(birthData, function(d) { return d.year; }); var width = 600; var height = 600; var barPadding = 10; var numBars = 12; var barWidth = width / numBars - barPadding; var maxBirths = d3.max(birthData, function(d) { return d.births; }); var yScale = d3 .scaleLinear() .domain([0, maxBirths]) .range([height, 0]); d3 .select('input') .property('min', minYear) .property('max', maxYear) .property('value', minYear); d3 .select('svg') .attr('width', width) .attr('height', height) .selectAll('rect') .data( birthData.filter(function(d) { return d.year === minYear; }) ) .enter() .append('rect') .attr('width', barWidth) .attr('height', function(d) { return height - yScale(d.births); }) .attr('y', function(d) { return yScale(d.births); }) .attr('x', function(d, i) { return (barWidth + barPadding) * i; }) .attr('fill', 'purple'); d3 .select('svg') .append('text') .classed('title', true) .text('Birth Data of the Year ' + minYear) .attr('x', width / 2) .attr('y', 30) .style('text-anchor', 'middle') .style('font-size', '2em'); d3.select('input').on('input', function() { var year = +d3.event.target.value; d3 .selectAll('rect') .data( birthData.filter(function(d) { return d.year === year; }) ) .transition() .duration(2000) .ease(d3.easeLinear) .delay((d, i) => i * 250) .on('start', function(d, i) { if (i === 0) { d3 .select('.title') .text('Updating Data to the Year of ' + year); } }) .on('end', function(d, i, nodes) { if (i === nodes.length - 1) { d3.select('.title').text('Birth Data of the Year ' + year); } }) .on('interrupt', function() { console.log('Interrupted! No longer updating data to the year of ' + year); }) .attr('height', function(d) { return height - yScale(d.births); }) .attr('y', function(d) { return yScale(d.births); }); });
easyopsapis/easyops-api-python
database_delivery_sdk/api/dbtask/liquibase_task_callback_pb2.py
<reponame>easyopsapis/easyops-api-python # -*- coding: utf-8 -*- # Generated by the protocol buffer compiler. DO NOT EDIT! # source: liquibase_task_callback.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from database_delivery_sdk.model.easy_command import task_detail_pb2 as database__delivery__sdk_dot_model_dot_easy__command_dot_task__detail__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='liquibase_task_callback.proto', package='dbtask', syntax='proto3', serialized_options=None, serialized_pb=_b('\n\x1dliquibase_task_callback.proto\x12\x06\x64\x62task\x1a:database_delivery_sdk/model/easy_command/task_detail.proto\"I\n\x1cLiquibaseTaskCallbackRequest\x12)\n\x07\x63ommand\x18\x01 \x01(\x0b\x32\x18.easy_command.TaskDetail\"/\n\x1dLiquibaseTaskCallbackResponse\x12\x0e\n\x06status\x18\x01 \x01(\t\"\x8d\x01\n$LiquibaseTaskCallbackResponseWrapper\x12\x0c\n\x04\x63ode\x18\x01 \x01(\x05\x12\x13\n\x0b\x63odeExplain\x18\x02 \x01(\t\x12\r\n\x05\x65rror\x18\x03 \x01(\t\x12\x33\n\x04\x64\x61ta\x18\x04 \x01(\x0b\x32%.dbtask.LiquibaseTaskCallbackResponseb\x06proto3') , dependencies=[database__delivery__sdk_dot_model_dot_easy__command_dot_task__detail__pb2.DESCRIPTOR,]) _LIQUIBASETASKCALLBACKREQUEST = _descriptor.Descriptor( name='LiquibaseTaskCallbackRequest', full_name='dbtask.LiquibaseTaskCallbackRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='command', full_name='dbtask.LiquibaseTaskCallbackRequest.command', index=0, number=1, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=101, serialized_end=174, ) _LIQUIBASETASKCALLBACKRESPONSE = _descriptor.Descriptor( name='LiquibaseTaskCallbackResponse', full_name='dbtask.LiquibaseTaskCallbackResponse', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='status', full_name='dbtask.LiquibaseTaskCallbackResponse.status', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=176, serialized_end=223, ) _LIQUIBASETASKCALLBACKRESPONSEWRAPPER = _descriptor.Descriptor( name='LiquibaseTaskCallbackResponseWrapper', full_name='dbtask.LiquibaseTaskCallbackResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='dbtask.LiquibaseTaskCallbackResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='dbtask.LiquibaseTaskCallbackResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='dbtask.LiquibaseTaskCallbackResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b("").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='dbtask.LiquibaseTaskCallbackResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=226, serialized_end=367, ) _LIQUIBASETASKCALLBACKREQUEST.fields_by_name['command'].message_type = database__delivery__sdk_dot_model_dot_easy__command_dot_task__detail__pb2._TASKDETAIL _LIQUIBASETASKCALLBACKRESPONSEWRAPPER.fields_by_name['data'].message_type = _LIQUIBASETASKCALLBACKRESPONSE DESCRIPTOR.message_types_by_name['LiquibaseTaskCallbackRequest'] = _LIQUIBASETASKCALLBACKREQUEST DESCRIPTOR.message_types_by_name['LiquibaseTaskCallbackResponse'] = _LIQUIBASETASKCALLBACKRESPONSE DESCRIPTOR.message_types_by_name['LiquibaseTaskCallbackResponseWrapper'] = _LIQUIBASETASKCALLBACKRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) LiquibaseTaskCallbackRequest = _reflection.GeneratedProtocolMessageType('LiquibaseTaskCallbackRequest', (_message.Message,), { 'DESCRIPTOR' : _LIQUIBASETASKCALLBACKREQUEST, '__module__' : 'liquibase_task_callback_pb2' # @@protoc_insertion_point(class_scope:dbtask.LiquibaseTaskCallbackRequest) }) _sym_db.RegisterMessage(LiquibaseTaskCallbackRequest) LiquibaseTaskCallbackResponse = _reflection.GeneratedProtocolMessageType('LiquibaseTaskCallbackResponse', (_message.Message,), { 'DESCRIPTOR' : _LIQUIBASETASKCALLBACKRESPONSE, '__module__' : 'liquibase_task_callback_pb2' # @@protoc_insertion_point(class_scope:dbtask.LiquibaseTaskCallbackResponse) }) _sym_db.RegisterMessage(LiquibaseTaskCallbackResponse) LiquibaseTaskCallbackResponseWrapper = _reflection.GeneratedProtocolMessageType('LiquibaseTaskCallbackResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _LIQUIBASETASKCALLBACKRESPONSEWRAPPER, '__module__' : 'liquibase_task_callback_pb2' # @@protoc_insertion_point(class_scope:dbtask.LiquibaseTaskCallbackResponseWrapper) }) _sym_db.RegisterMessage(LiquibaseTaskCallbackResponseWrapper) # @@protoc_insertion_point(module_scope)
wreulicke/findbugs-slf4j
bug-pattern/src/main/java/jp/skypencil/findbugs/slf4j/CodepointIterator.java
<reponame>wreulicke/findbugs-slf4j package jp.skypencil.findbugs.slf4j; import java.util.Iterator; final class CodepointIterator implements Iterator<Integer> { private CharSequence sequence; private int index; CodepointIterator(CharSequence sequence) { this.sequence = sequence; } @Override public boolean hasNext() { return index < sequence.length(); } @Override public Integer next() { final int result; if (Character.isHighSurrogate(sequence.charAt(index))) { result = (sequence.charAt(index) << 16) + sequence.charAt(index + 1); index += 2; } else { result = sequence.charAt(index); index += 1; } return Integer.valueOf(result); } @Override @Deprecated public void remove() { throw new UnsupportedOperationException(); } }
WrBug/GravityBox
app/src/main/java/com/wrbug/gravitybox/nougat/quicksettings/QsDetailAdapterProxy.java
<filename>app/src/main/java/com/wrbug/gravitybox/nougat/quicksettings/QsDetailAdapterProxy.java /* * Copyright (C) 2016 <NAME> for GravityBox Project (C3C076@xda) * 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.wrbug.gravitybox.nougat.quicksettings; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import android.content.Context; import android.content.Intent; import android.view.View; import android.view.ViewGroup; import de.robv.android.xposed.XposedHelpers; /** * Generic invocation handler for handling tile's DetailAdapter interface proxy calls * Registered callback handles method calls defined on the interface */ public class QsDetailAdapterProxy implements InvocationHandler { public static final String IFACE_DETAIL_ADAPTER = BaseTile.CLASS_BASE_TILE+".DetailAdapter"; public interface Callback { int getTitle(); Boolean getToggleState(); View createDetailView(Context context, View convertView, ViewGroup parent) throws Throwable; Intent getSettingsIntent(); void setToggleState(boolean state); } private Callback mCallback; private QsDetailAdapterProxy() { /* must be created via createProxy */ }; private QsDetailAdapterProxy(Callback cb) { mCallback = cb; } public static Object createProxy(ClassLoader cl, Callback cb) { if (cb == null) throw new IllegalArgumentException("Callback cannot be null"); return Proxy.newProxyInstance(cl, new Class<?>[] { XposedHelpers.findClass(IFACE_DETAIL_ADAPTER, cl) }, new QsDetailAdapterProxy(cb)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("getTitle")) { return mCallback.getTitle(); } else if (method.getName().equals("getToggleState")) { return mCallback.getToggleState(); } else if (method.getName().equals("getSettingsIntent")) { return mCallback.getSettingsIntent(); } else if (method.getName().equals("setToggleState")) { mCallback.setToggleState((boolean)args[0]); return null; } else if (method.getName().equals("getMetricsCategory")) { return 111; } else if (method.getName().equals("createDetailView")) { return mCallback.createDetailView((Context)args[0], (View)args[1], (ViewGroup)args[2]); } else { return null; } } }
wxf163/bareos
src/filed/authenticate.c
<reponame>wxf163/bareos /* BAREOS® - Backup Archiving REcovery Open Sourced Copyright (C) 2000-2010 Free Software Foundation Europe e.V. Copyright (C) 2011-2012 Planets Communications B.V. Copyright (C) 2013-2016 Bareos GmbH & Co. KG This program is Free Software; you can redistribute it and/or modify it under the terms of version three of the GNU Affero General Public License as published by the Free Software Foundation and included in the file LICENSE. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ /* * <NAME>, October 2000 */ /** * @file * Authenticate Director who is attempting to connect. */ #include "bareos.h" #include "filed.h" const int dbglvl = 50; /* Version at end of Hello * prior to 10Mar08 no version * 1 10Mar08 * 2 13Mar09 - Added the ability to restore from multiple storages * 3 03Sep10 - Added the restore object command for vss plugin 4.0 * 4 25Nov10 - Added bandwidth command 5.1 * 5 24Nov11 - Added new restore object command format (pluginname) 6.0 * * 51 21Mar13 - Added reverse datachannel initialization * 52 13Jul13 - Added plugin options * 53 02Apr15 - Added setdebug timestamp * 54 29Oct15 - Added getSecureEraseCmd */ static char OK_hello_compat[] = "2000 OK Hello 5\n"; static char OK_hello[] = "2000 OK Hello 54\n"; static char Dir_sorry[] = "2999 Authentication failed.\n"; /** * To prevent DOS attacks, * wait a bit in case of an * authentication failure of a (remotely) initiated connection. */ static inline void delay() { static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; /* * Single thread all failures to avoid DOS */ P(mutex); bmicrosleep(6, 0); V(mutex); } static inline void authenticate_failed(JCR *jcr, POOL_MEM &message) { Dmsg0(dbglvl, message.c_str()); Jmsg0(jcr, M_FATAL, 0, message.c_str()); delay(); } /** * Inititiate the communications with the Director. * He has made a connection to our server. * * Basic tasks done here: * We read Director's initial message and authorize him. */ bool authenticate_director(JCR *jcr) { BSOCK *dir = jcr->dir_bsock; POOL_MEM errormsg(PM_MESSAGE); POOL_MEM dirname(PM_MESSAGE); DIRRES *director = NULL; if (dir->msglen < 25 || dir->msglen > 500) { char addr[64]; char *who = bnet_get_peer(dir, addr, sizeof(addr)) ? dir->who() : addr; errormsg.bsprintf(_("Bad Hello command from Director at %s. Len=%d.\n"), who, dir->msglen); authenticate_failed(jcr, errormsg); return false; } if (sscanf(dir->msg, "Hello Director %s calling", dirname.check_size(dir->msglen)) != 1) { char addr[64]; char *who = bnet_get_peer(dir, addr, sizeof(addr)) ? dir->who() : addr; dir->msg[100] = 0; errormsg.bsprintf(_("Bad Hello command from Director at %s: %s\n"), who, dir->msg); authenticate_failed(jcr, errormsg); return false; } unbash_spaces(dirname.c_str()); director = (DIRRES *)GetResWithName(R_DIRECTOR, dirname.c_str()); if (!director) { char addr[64]; char *who = bnet_get_peer(dir, addr, sizeof(addr)) ? dir->who() : addr; errormsg.bsprintf(_("Connection from unknown Director %s at %s rejected.\n"), dirname.c_str(), who); authenticate_failed(jcr, errormsg); return false; } if (!director->conn_from_dir_to_fd) { errormsg.bsprintf(_("Connection from Director %s rejected.\n"), dirname.c_str()); authenticate_failed(jcr, errormsg); return false; } if (!dir->authenticate_inbound_connection(jcr, "Director", dirname.c_str(), director->password, director->tls)) { dir->fsend("%s", Dir_sorry); errormsg.bsprintf(_("Unable to authenticate Director %s.\n"), dirname.c_str()); authenticate_failed(jcr, errormsg); return false; } jcr->director = director; return dir->fsend("%s", (me->compatible) ? OK_hello_compat : OK_hello); } /** * Authenticate with a remote director. */ bool authenticate_with_director(JCR *jcr, DIRRES *dir_res) { BSOCK *dir = jcr->dir_bsock; return dir->authenticate_outbound_connection(jcr, "Director", dir_res->name(), dir_res->password, dir_res->tls); } /** * Authenticate a remote storage daemon. */ bool authenticate_storagedaemon(JCR *jcr) { bool result = false; BSOCK *sd = jcr->store_bsock; s_password password; password.encoding = p_encoding_md5; password.value = jcr->sd_auth_key; result = sd->authenticate_inbound_connection(jcr, "Storage daemon", "", password, me->tls); /* * Destroy session key */ memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key)); if (!result) { delay(); } return result; } /** * Authenticate with a remote storage daemon. */ bool authenticate_with_storagedaemon(JCR *jcr) { bool result = false; BSOCK *sd = jcr->store_bsock; s_password password; password.encoding = p_encoding_md5; password.value = jcr->sd_auth_key; result = sd->authenticate_outbound_connection(jcr, "Storage daemon", "", password, me->tls); /* * Destroy session key */ memset(jcr->sd_auth_key, 0, strlen(jcr->sd_auth_key)); return result; }
jivesoftware/amza
amza-api/src/main/java/com/jivesoftware/os/amza/api/wal/WALValue.java
<gh_stars>1-10 /* * Copyright 2013 <NAME>, Inc * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.jivesoftware.os.amza.api.wal; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.jivesoftware.os.amza.api.stream.RowType; import java.util.Arrays; public class WALValue { private final RowType rowType; private final byte[] value; private final long timestamp; private final boolean tombstoned; private final long version; @JsonCreator public WALValue( @JsonProperty("rowType") RowType rowType, @JsonProperty("value") byte[] value, @JsonProperty("timestamp") long timestamp, @JsonProperty("tombstoned") boolean tombstoned, @JsonProperty("version") long version) { this.rowType = rowType; this.timestamp = timestamp; this.value = value; this.tombstoned = tombstoned; this.version = version; } public RowType getRowType() { return rowType; } public byte[] getValue() { return value; } public long getTimestampId() { return timestamp; } public boolean getTombstoned() { return tombstoned; } public long getVersion() { return version; } @Override public String toString() { return "WALValue{" + "rowType=" + rowType + ", timestamp=" + timestamp + ", tombstoned=" + tombstoned + ", version=" + version + ", value=" + (value != null ? Arrays.toString(value) : "null") + '}'; } @Override public int hashCode() { throw new UnsupportedOperationException("NOPE"); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WALValue other = (WALValue) obj; if (this.timestamp != other.timestamp) { return false; } if (this.tombstoned != other.tombstoned) { return false; } if (this.version != other.version) { return false; } if (this.rowType != other.rowType) { return false; } if (!Arrays.equals(this.value, other.value)) { return false; } return true; } }
eutro/jwasm
jwasm-tree/src/main/java/io/github/eutro/jwasm/tree/MemoriesNode.java
package io.github.eutro.jwasm.tree; import io.github.eutro.jwasm.Limits; import io.github.eutro.jwasm.MemoriesVisitor; import io.github.eutro.jwasm.ModuleVisitor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * A node that represents the * <a href="https://webassembly.github.io/spec/core/binary/modules.html#memory-section">memory section</a> * of a module. * * @see ModuleVisitor#visitMems() * @see MemoryNode */ public class MemoriesNode extends MemoriesVisitor implements Iterable<MemoryNode> { /** * The vector of {@link MemoryNode}s, or {@code null} if there aren't any. */ public @Nullable List<MemoryNode> memories; /** * Make the given {@link MemoriesVisitor} visit all the memories of this node. * * @param mmv The visitor to visit. */ public void accept(MemoriesVisitor mmv) { if (memories != null) { for (MemoryNode memory : memories) { memory.accept(mmv); } } mmv.visitEnd(); } @Override public void visitMemory(int min, Integer max) { if (memories == null) memories = new ArrayList<>(); memories.add(new MemoryNode(new Limits(min, max))); } @NotNull @Override public Iterator<MemoryNode> iterator() { return memories == null ? Collections.emptyIterator() : memories.iterator(); } }
svn2github/Escript
escriptcore/src/Pointers.h
<reponame>svn2github/Escript /***************************************************************************** * * Copyright (c) 2003-2018 by The University of Queensland * http://www.uq.edu.au * * Primary Business: Queensland, Australia * Licensed under the Apache License, version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 * * Development until 2012 by Earth Systems Science Computational Center (ESSCC) * Development 2012-2013 by School of Earth Sciences * Development from 2014 by Centre for Geoscience Computing (GeoComp) * *****************************************************************************/ #ifndef POINTERS_H_2008 #define POINTERS_H_2008 /** \file Pointers.h \brief Typedefs and macros for reference counted storage. */ // The idea is that we should be able to easily switch between shared_ptr // and intrusive_ptr if required // Where to find the base class which supplies refcounting #define REFCOUNT_BASE_FILE <boost/enable_shared_from_this.hpp> // The name of the class to extend #define REFCOUNT_BASE_CLASS(x) boost::enable_shared_from_this<x> #define POINTER_WRAPPER_CLASS(x) boost::shared_ptr<x> #define REFCOUNTNS boost #include REFCOUNT_BASE_FILE #endif
lechium/iPhoneOS_12.1.1_Headers
System/Library/PrivateFrameworks/HealthUI.framework/HKDataMetadataReportAccessSection.h
/* * This header is generated by classdump-dyld 1.0 * on Saturday, June 1, 2019 at 6:50:58 PM Mountain Standard Time * Operating System: Version 12.1.1 (Build 16C5050a) * Image Source: /System/Library/PrivateFrameworks/HealthUI.framework/HealthUI * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>. */ #import <HealthUI/HKDataMetadataSection.h> @class UIViewController; @interface HKDataMetadataReportAccessSection : HKDataMetadataSection { UIViewController* _accessViewController; } @property (nonatomic,readonly) UIViewController * accessViewController; //@synthesize accessViewController=_accessViewController - In the implementation block -(unsigned long long)numberOfRowsInSection; -(id)cellForIndex:(unsigned long long)arg1 tableView:(id)arg2 ; -(void)selectCellForIndex:(unsigned long long)arg1 navigationController:(id)arg2 animated:(BOOL)arg3 ; -(id)initWithSample:(id)arg1 healthStore:(id)arg2 delegate:(id)arg3 ; -(UIViewController *)accessViewController; @end
alphaho/TypeFlow
src/main/scala/com/github/notyy/typeflow/editor/GenJavaOutputEndpoint.scala
package com.github.notyy.typeflow.editor import com.github.notyy.typeflow.domain.OutputEndpoint class GenJavaOutputEndpoint(val genFormalParams: GenFormalParams) { def execute(packageName: PackageName, outputEndpoint: OutputEndpoint, codeTemplate: CodeTemplate): JavaCode = { val code = codeTemplate.value.replaceAllLiterally("$PackageName$", packageName.value). replaceAllLiterally("$DefinitionName$", outputEndpoint.name). replaceAllLiterally("$ReturnType$", replaceEmptyReturnTypeWithVoid(outputEndpoint.outputs.head.outputType.name)). replaceAllLiterally("$Params$", genFormalParams.execute(outputEndpoint.inputs)) JavaCode(QualifiedName(s"${packageName.value}.${outputEndpoint.name}"), code) } def replaceEmptyReturnTypeWithVoid(returnType: String): String = { if (returnType == "Unit") "void" else returnType } }
JayLDoherty/VOOGASalad
src/testers/TestMultipleLevels.java
<reponame>JayLDoherty/VOOGASalad<gh_stars>0 package testers; import data.Game; import engine.game.gameloop.GameLoop; import javafx.application.Application; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.paint.Color; import javafx.stage.Stage; import player.score.Overlay; /** * Note to self: Use Case 3 * * @author <NAME> * */ public class TestMultipleLevels extends Application { public static void main(String[] args) { launch(args); } public void start(Stage stage) throws Exception { // The Game Player must give me all parameters to the GameLoop // constructor, since GameLoop is instantiated in it Game game = new Game(); Scene scene = new Scene(new Group(), 250, 250, Color.BLUE); // GameLoop gameLoop = new GameLoop(scene, game); // gameLoop.startTimeline(); } }
DouglasRMiles/QuProlog
src/trace.cc
<filename>src/trace.cc // trace.cc - The Qu-Prolog Abstract Machine Tracer // // ##Copyright## // // Copyright 2000-2016 <NAME> (<EMAIL>) // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.00 // // 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. // // ##Copyright## // // email: <EMAIL> // // $Id: trace.cc,v 1.10 2006/03/30 22:50:31 qp Exp $ #include "debug.h" #ifdef QP_DEBUG #include <sys/types.h> #ifndef WIN32 #include <unistd.h> #endif #include <stdarg.h> #include "atom_table.h" #include "trace_qp.h" #include "thread_qp.h" #include "pseudo_instr_arrays.h" void trace_thread_info(const ThreadInfo& thread_info, const CodeLoc pc) { if (thread_info.IDSet()) { cerr << thread_info.ID(); } else { cerr << " "; } if (thread_info.SymbolSet()) { cerr << thread_info.Symbol().c_str(); } else { cerr << " "; } cerr << hex << pc << dec; } void Trace::TraceInOut(const word32 mode, const word32 num, const word32 pos) { if (mode & (1 << (num - pos))) { cerr << "(out)"; } else { cerr << "(in)"; } } void Trace::Trace0(const char *s) { cerr << s << endl; } void Trace::Trace1(const char *s, const int32 x) { cerr << s << "(" << x << ")" << endl; } void Trace::Trace2(const char *s, const int32 x, const int32 y) { cerr << s << "(" << x << ", " << y << ")" << endl; } void Trace::Trace3(const char *s, const int32 x, const int32 y, const int32 z) { cerr << s << "(" << x << ", " << y << ", " << z << ")" << endl; } void Trace::Trace4(const char *s, const int32 x, const int32 y, const int32 z, const int32 w) { cerr << s << "(" << x << ", " << y << ", " << z << ", " << w << ")" << endl; } void Trace::Trace5(const char *s, const int32 x, const int32 y, const int32 z, const int32 w, const int32 u) { cerr << s << "(" << x << ", " << y << ", " << z << ", " << w << ", " << u << ")" << endl; } void Trace::TraceConst0(AtomTable& atoms, Heap& heap, const char *s, Object* c) { cerr << s << "(" << hex << reinterpret_cast<wordptr>(c) << dec << ") "; heap.displayTerm(cerr, atoms, c, 0); } void Trace::TraceConst1(AtomTable& atoms, Heap& heap, const char *s, Object* c, const int32 x) { cerr << s << "(" << hex << reinterpret_cast<wordptr>(c) << ", " << x << dec << ") "; heap.displayTerm(cerr, atoms, c, 0); } void Trace::TraceConst2(AtomTable& atoms, Heap& heap, const char *s, Object* c, const int32 x, const int32 y) { cerr << s << "(" << hex << reinterpret_cast<wordptr>(c) << ", " << x << ", " << y << dec << ") "; heap.displayTerm(cerr, atoms, c, 0); } void Trace::TraceInt0(const char *s, const int32 n) { cerr << s << "(" << n << ") "; } void Trace::TraceInt1(const char *s, const int32 n, const int32 x) { cerr << s << "(" << n << "' " << x << ") "; } void Trace::TraceString1(const char *s, const char *t) { cerr << s << "(" << t << ") "; } void Trace::TraceString2(const char *s, const char *t, const int32 x) { cerr << s << "(" << t << "' " << x << ") "; } void Trace::TraceString3(const char *s, const char *t, const int32 x, const int32 y) { cerr << s << "(" << t << "' " << x << "' " << y << ") "; } void Trace::TraceXReg(Thread& th, AtomTable& atoms, const word32 reg) { if (trace_level & TRACE_REGS) { cerr << "\tX[" << reg << "]: " << endl; th.heap.displayTerm(cerr, atoms, th.X[reg], 2); } } void Trace::TraceYReg(Thread& th, AtomTable& atoms, const word32 reg) { if (trace_level & TRACE_REGS) { cerr << "\tY[" << reg << "]: " << endl; th.heap.displayTerm(cerr, atoms, th.envStack.yReg(th.currentEnvironment, reg), 2); } } void Trace::TracePseudoRegs(Thread& th, AtomTable& atoms, const word32 mode, const word32 num, ...) { va_list regs; if (num > 0) { va_start(regs, num); cerr << ", "; for (word32 i = 1; i <= num; i++) { const word32 reg = va_arg(regs, word32); cerr << reg << ' '; TraceInOut(mode, num, i); if (i < num) { cerr << ", "; } } va_end(regs); } cerr << ')' << endl; if (num > 0) { va_start(regs, num); for (word32 i = 1; i <= num; i++) { const word32 reg = va_arg(regs, word32); cerr << "\tX[" << reg << "]: " << endl; th.heap.displayTerm(cerr, atoms, th.PSIGetReg(reg), 2); } va_end(regs); } } void Trace::TracePseudo0(Thread& th, AtomTable& atoms, const word32 n) { cerr << "pseudo_instr0(" << n << " = " << pseudo_instr0_array[n].name; TracePseudoRegs(th, atoms, pseudo_instr0_array[n].mode, 0); } void Trace::TracePseudo1(Thread& th, AtomTable& atoms, const word32 n, const word32 reg1) { cerr << "pseudo_instr1(" << n << " = " << pseudo_instr1_array[n].name; TracePseudoRegs(th, atoms, pseudo_instr1_array[n].mode, 1, reg1); } void Trace::TracePseudo2(Thread& th, AtomTable& atoms, const word32 n, const word32 reg1, const word32 reg2) { cerr << "pseudo_instr2(" << n << " = " << pseudo_instr2_array[n].name; TracePseudoRegs(th, atoms, pseudo_instr2_array[n].mode, 2, reg1, reg2); } void Trace::TracePseudo3(Thread& th, AtomTable& atoms, const word32 n, const word32 reg1, const word32 reg2, const word32 reg3) { cerr << "pseudo_instr3(" << n << " = " << pseudo_instr3_array[n].name; TracePseudoRegs(th, atoms, pseudo_instr3_array[n].mode, 3, reg1, reg2, reg3); } void Trace::TracePseudo4(Thread& th, AtomTable& atoms, const word32 n, const word32 reg1, const word32 reg2, const word32 reg3, const word32 reg4) { cerr << "pseudo_instr4(" << n << " = " << pseudo_instr4_array[n].name; TracePseudoRegs(th, atoms, pseudo_instr4_array[n].mode, 4, reg1, reg2, reg3, reg4); } void Trace::TracePseudo5(Thread& th, AtomTable& atoms, const word32 n, const word32 reg1, const word32 reg2, const word32 reg3, const word32 reg4, const word32 reg5) { cerr << "pseudo_instr5(" << n << " = " << pseudo_instr5_array[n].name; TracePseudoRegs(th, atoms, pseudo_instr5_array[n].mode, 5, reg1, reg2, reg3, reg4, reg5); } void Trace::TraceStart(Thread& th) { if (trace_level & TRACE_ENV) { #if 0 if (th.envStack.getTop() == th.envStack.firstEnv()) { trace_init_env = true; trace_current_environment = th.envStack.getTop(); trace_top_of_env = th.envStack.getTop(); } else { trace_init_env = false; trace_current_environment = th.currentEnvironment; trace_env = *(th.envStack.fetchEnv(th.currentEnvironment)); trace_top_of_env = th.envStack.getTop(); } #endif // 0 } if (trace_level & TRACE_CHOICE) { #if 0 if (th.currentChoicePoint == th.choiceStack.firstChoice()) { trace_init_choice = true; trace_current_choice_point = th.currentChoicePoint; } else { trace_init_choice = false; trace_current_choice_point = th.currentChoicePoint; trace_choice = *(th.choiceStack.fetchChoice(th.currentChoicePoint)); } #endif // 0 } if (trace_level & TRACE_CUT) { trace_cut_point = th.cutPoint; } } // // Instruction decoder and printer // void Trace::TraceInstr(Thread& th, AtomTable& atoms, Code& code, PredTab& predicates, CodeLoc pc) { if (trace_level & TRACE_INSTR) { trace_thread_info(th.TInfo(), pc); switch (getInstruction(pc)) { case PUT_X_VARIABLE: // put_x_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_x_variable", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_Y_VARIABLE: // put_y_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_y_variable", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_X_VALUE: // put_x_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_x_value", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_Y_VALUE: // put_y_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_y_value", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_CONSTANT: // put_constant c, i { Object* c = getConstant(pc); const word32 i = getRegister(pc); TraceConst1(atoms, th.heap, "put_constant", c, i); TraceXReg(th, atoms, i); } break; case PUT_INTEGER: { int32 c = getInteger(pc); const word32 i = getRegister(pc); TraceInt1("put_integer", c, i); TraceXReg(th, atoms, i); } break; case PUT_LIST: // put_list i { const word32 i = getRegister(pc); Trace1("put_list", i); TraceXReg(th, atoms, i); } break; case PUT_STRUCTURE: // put_structure n, i { const word32 n = getNumber(pc); const word32 i = getRegister(pc); Trace2("put_structure", n, i); TraceXReg(th, atoms, i); } break; case PUT_X_OBJECT_VARIABLE: // put_x_object_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_x_object_variable", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_Y_OBJECT_VARIABLE: // put_y_object_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_y_object_variable", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_X_OBJECT_VALUE: // put_x_object_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_x_object_value", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_Y_OBJECT_VALUE: // put_y_object_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_y_object_value", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_QUANTIFIER: // put_quantifier i { const word32 i = getRegister(pc); Trace1("put_quantifier", i); TraceXReg(th, atoms, i); } break; case CHECK_BINDER: // check_binder i { const word32 i = getRegister(pc); Trace1("check_binder", i); TraceXReg(th, atoms, i); } break; case PUT_SUBSTITUTION: // put_substitution n, i { const word32 n = getNumber(pc); const word32 i = getRegister(pc); Trace2("put_substitution", n, i); TraceXReg(th, atoms, i); } break; case PUT_X_TERM_SUBSTITUTION: // put_x_term_substitution i j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_x_term_substitution", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_Y_TERM_SUBSTITUTION: // put_y_term_substitution i j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("put_y_term_substitution", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case PUT_INITIAL_EMPTY_SUBSTITUTION: // put_initial_empty_substitution i { const word32 i = getRegister(pc); Trace1("put_initial_empty_substitution", i); TraceXReg(th, atoms, i); } break; case GET_X_VARIABLE: // get_x_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_x_variable", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_Y_VARIABLE: // get_y_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_y_variable", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_X_VALUE: // get_x_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_x_value", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_Y_VALUE: // get_y_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_y_value", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_CONSTANT: // get_constant c, i { Object* c = getConstant(pc); const word32 i = getRegister(pc); TraceConst1(atoms, th.heap, "get_constant", c, i); TraceXReg(th, atoms, i); } break; case GET_INTEGER: { int32 c = getInteger(pc); const word32 i = getRegister(pc); TraceInt1("get_integer", c, i); TraceXReg(th, atoms, i); } break; case GET_LIST: // get_list i { const word32 i = getRegister(pc); Trace1("get_list", i); TraceXReg(th, atoms, i); } break; case GET_STRUCTURE: // get_structure c, n, i { Object* c = getConstant(pc); const word32 n = getNumber(pc); const word32 i = getRegister(pc); TraceConst2(atoms, th.heap, "get_structure", c, n, i); TraceXReg(th, atoms, i); } break; case GET_STRUCTURE_FRAME: // get_structure_frame n, i { const word32 n = getNumber(pc); const word32 i = getRegister(pc); Trace2("get_structure_frame", n, i); TraceXReg(th, atoms, i); } break; case GET_X_OBJECT_VARIABLE: // get_x_object_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_x_object_variable", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_Y_OBJECT_VARIABLE: // get_y_object_variable i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_y_object_variable", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_X_OBJECT_VALUE: // get_x_object_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_x_object_value", i, j); TraceXReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case GET_Y_OBJECT_VALUE: // get_y_object_value i, j { const word32 i = getRegister(pc); const word32 j = getRegister(pc); Trace2("get_y_object_value", i, j); TraceYReg(th, atoms, i); TraceXReg(th, atoms, j); } break; case UNIFY_X_VARIABLE: // unify_x_variable i { const word32 i = getRegister(pc); Trace1("unify_x_variable", i); TraceXReg(th, atoms, i); } break; case UNIFY_Y_VARIABLE: // unify_y_variable i { const word32 i = getRegister(pc); Trace1("unify_y_variable", i); TraceYReg(th, atoms, i); } break; case UNIFY_X_REF: // unify_x_ref i { const word32 i = getRegister(pc); Trace1("unify_x_ref", i); TraceXReg(th, atoms, i); } break; case UNIFY_Y_REF: // unify_y_ref i { const word32 i = getRegister(pc); Trace1("unify_y_ref", i); TraceYReg(th, atoms, i); } break; case UNIFY_X_VALUE: // unify_x_value i { const word32 i = getRegister(pc); Trace1("unify_x_value", i); TraceXReg(th, atoms, i); } break; case UNIFY_Y_VALUE: // unify_y_value i { const word32 i = getRegister(pc); Trace1("unify_y_value", i); TraceYReg(th, atoms, i); } break; case UNIFY_VOID: // unify_void n { const word32 n = getNumber(pc); Trace1("unify_void", n); } break; case SET_X_VARIABLE: // set_x_variable i { const word32 i = getRegister(pc); Trace1("set_x_variable", i); TraceXReg(th, atoms, i); } break; case SET_Y_VARIABLE: // set_y_variable i { const word32 i = getRegister(pc); Trace1("set_y_variable", i); TraceYReg(th, atoms, i); } break; case SET_X_VALUE: // set_x_value i { const word32 i = getRegister(pc); Trace1("set_x_value", i); TraceXReg(th, atoms, i); } break; case SET_Y_VALUE: // set_y_value i { const word32 i = getRegister(pc); Trace1("set_y_value", i); TraceYReg(th, atoms, i); } break; case SET_X_OBJECT_VARIABLE: // set_x_object_variable i { const word32 i = getRegister(pc); Trace1("set_x_object_variable", i); TraceXReg(th, atoms, i); } break; case SET_Y_OBJECT_VARIABLE: // set_y_object_variable i { const word32 i = getRegister(pc); Trace1("set_y_object_variable", i); TraceYReg(th, atoms, i); } break; case SET_X_OBJECT_VALUE: // set_x_object_value i { const word32 i = getRegister(pc); Trace1("set_x_object_value", i); TraceXReg(th, atoms, i); } break; case SET_Y_OBJECT_VALUE: // set_y_object_value i { const word32 i = getRegister(pc); Trace1("set_y_object_value", i); TraceYReg(th, atoms, i); } break; case SET_CONSTANT: // set_constant c { Object* c = getConstant(pc); TraceConst0(atoms, th.heap, "set_constant", c); } break; case SET_INTEGER: { int32 c = getInteger(pc); TraceInt0("set_integer", c); } break; case SET_VOID: // set_void n { const word32 n = getNumber(pc); Trace1("set_void", n); } break; case SET_OBJECT_VOID: // set_object_void n { const word32 n = getNumber(pc); Trace1("set_object_void", n); } break; case ALLOCATE: // allocate n { const word32 n = getNumber(pc); Trace1("allocate", n); } break; case DEALLOCATE: // deallocate Trace0("deallocate"); break; case CALL_PREDICATE: // call_predicate predicate, arity, n { const char *s = getPredAtom(pc)->getName(); const word32 arity = getNumber(pc); const word32 n = getNumber(pc); TraceString3("call_predicate", s, arity, n); } break; case CALL_ADDRESS: // call_address address, n { const CodeLoc address = getCodeLoc(pc); const word32 n = getNumber(pc); CodeLoc loc = address - Code::SIZE_OF_HEADER; Atom* predicate = reinterpret_cast<Atom*>(getAddress(loc)); const char *s = predicate->getName(); TraceString2("call_address", s, n); } break; case CALL_ESCAPE: // call_escape address, n { const CodeLoc address = getCodeLoc(pc); const word32 n = getNumber(pc); Atom* predicate = predicates.getPredName((wordptr)address, &atoms); const char *s = predicate->getName(); TraceString2("call_escape", s, n); } break; case EXECUTE_PREDICATE: // execute_predicate predicate, arity { Atom* predicate = getPredAtom(pc); const word32 arity = getNumber(pc); const char *s = predicate->getName(); TraceString2("execute_predicate", s, arity); } break; case EXECUTE_ADDRESS: // execute_address address { const CodeLoc address = getCodeLoc(pc); CodeLoc loc = address - Code::SIZE_OF_HEADER; Atom* predicate = reinterpret_cast<Atom*>(getAddress(loc)); const char *s = predicate->getName(); TraceString1("execute_address", s); } break; case EXECUTE_ESCAPE: // execute_escape address { const CodeLoc address = getCodeLoc(pc); Atom* predicate = predicates.getPredName((wordptr)address, &atoms); const char *s = predicate->getName(); TraceString1("execute_escape", s); } break; case NOOP: // noop Trace0("noop"); break; case JUMP: // jump address { const CodeLoc address = getCodeLoc(pc); Trace1("jump", (wordptr)address); } break; case PROCEED: // proceed Trace0("proceed"); break; case FAIL: // fail Trace0("fail"); break; case HALT: // halt Trace0("halt"); break; case EXIT: // exit Trace0("exit"); break; case TRY_ME_ELSE: // try_me_else arity, label { const word32 arity = getNumber(pc); const word32 label = getOffset(pc); Trace2("try_me_else", arity, label); } break; case RETRY_ME_ELSE: // retry_me_else label { const word32 label = getOffset(pc); Trace1("retry_me_else", label); } break; case TRUST_ME_ELSE_FAIL: // trust_me_else_fail Trace0("trust_me_else_fail"); break; case TRY: // try arity, label { const word32 arity = getNumber(pc); const word32 label = getOffset(pc); Trace2("try", arity, label); } break; case RETRY: // retry label { const word32 label = getOffset(pc); Trace1("retry", label); } break; case TRUST: // trust label { const word32 label = getOffset(pc); Trace1("trust", label); } break; case NECK_CUT: // neck_cut Trace0("neck_cut"); break; case GET_X_LEVEL: // get_x_level i { const word32 i = getRegister(pc); Trace1("get_x_level", i); } break; case GET_Y_LEVEL: // get_y_level i { const word32 i = getRegister(pc); Trace1("get_y_level", i); } break; case CUT: // cut i { const word32 i = getRegister(pc); Trace1("cut", i); } break; case SWITCH_ON_TERM: // switch_on_term i, { // VARIABLE_LABEL, // OB_VARIABLE_LABEL, // LIST_LABEL, // STRUCTURE_LABEL, // QUANTIFIER_LABEL, // CONSTANT_LABEL const word32 i = getRegister(pc); cerr << "switch_on_term(" << i; for (word32 j = 0; j < 6; j++) { cerr << ", " << getOffset(pc); } cerr << ")" << endl; TraceXReg(th, atoms, i); } break; case SWITCH_ON_CONSTANT: // switch_on_constant i, n { const word32 i = getRegister(pc); const word32 n = getTableSize(pc); Trace2("switch_on_constant", i, n); TraceXReg(th, atoms, i); } break; case SWITCH_ON_STRUCTURE: // switch_on_structure i, n { const word32 i = getRegister(pc); const word32 n = getTableSize(pc); Trace2("switch_on_structure", i, n); TraceXReg(th, atoms, i); } break; case SWITCH_ON_QUANTIFIER: // switch_on_quantifier i, n { const word32 i = getRegister(pc); const word32 n = getTableSize(pc); Trace2("switch_on_quantifier", i, n); TraceXReg(th, atoms, i); } break; case PSEUDO_INSTR0: { const word32 n = getNumber(pc); TracePseudo0(th, atoms, n); } break; case PSEUDO_INSTR1: { const word32 n = getNumber(pc); const word32 i = getRegister(pc); TracePseudo1(th, atoms, n, i); } break; case PSEUDO_INSTR2: { const word32 n = getNumber(pc); const word32 i = getRegister(pc); const word32 j = getRegister(pc); TracePseudo2(th, atoms, n, i, j); } break; case PSEUDO_INSTR3: { const word32 n = getNumber(pc); const word32 i = getRegister(pc); const word32 j = getRegister(pc); const word32 k = getRegister(pc); TracePseudo3(th, atoms, n, i, j, k); } break; case PSEUDO_INSTR4: { const word32 n = getNumber(pc); const word32 i = getRegister(pc); const word32 j = getRegister(pc); const word32 k = getRegister(pc); const word32 m = getRegister(pc); TracePseudo4(th, atoms, n, i, j, k, m); } break; case PSEUDO_INSTR5: { const word32 n = getNumber(pc); const word32 i = getRegister(pc); const word32 j = getRegister(pc); const word32 k = getRegister(pc); const word32 m = getRegister(pc); const word32 o = getRegister(pc); TracePseudo5(th, atoms, n, i, j, k, m, o); } break; case UNIFY_CONSTANT: { Object* c = getConstant(pc); TraceConst0(atoms, th.heap, "unify_constant", c); } break; case UNIFY_INTEGER: { int32 c = getInteger(pc); TraceInt0("unify_integer", c); } break; case DB_JUMP: { (void)getNumber(pc); (void)getAddress(pc); const CodeLoc jump = getCodeLoc(pc); Trace1("db jump", (wordptr)jump); } break; case DB_EXECUTE_PREDICATE: // execute_predicate predicate, arity { Atom* predicate = getPredAtom(pc); const word32 arity = getNumber(pc); const char *s = predicate->getName(); TraceString2("db_execute_predicate", s, arity); } break; case DB_EXECUTE_ADDRESS: // execute_address address { const CodeLoc address = getCodeLoc(pc); CodeLoc loc = address - Code::SIZE_OF_HEADER; Atom* predicate = reinterpret_cast<Atom*>(getAddress(loc)); const char *s = predicate->getName(); TraceString1("db_execute_address", s); } break; case DB_PROCEED: { Trace0("db_proceed"); } break; default: { CodeLoc oldpc = pc - Code::SIZE_OF_INSTRUCTION; cerr << "*** UNKNOWN INSTRUCTION = " << getInstruction(oldpc) << endl; } break; } cerr.flush(); } } void Trace::TraceBacktrack(Thread& th, const CodeLoc pc) { if (trace_level & TRACE_INSTR) { trace_thread_info(th.TInfo(), pc); cerr << "backtrack" << endl; } } void Trace::TraceEnd(Thread& th) { if ((trace_level & TRACE_ENV) && (trace_current_environment != th.currentEnvironment || trace_top_of_env != th.envStack.getTop() || (!trace_init_env && !(trace_env == th.envStack.fetchEnv(th.currentEnvironment))))) { #if 0 cerr.form("%6ld envStack[%ld] (Top = %ld)\n", th.TInfo().ID(), th.currentEnvironment, th.envStack.getTop); th.envStack.display(cerr, th.currentEnvironment, 1); cerr.flush(); #endif // 0 } if ((trace_level & TRACE_CHOICE) && (trace_current_choice_point != th.currentChoicePoint || (!trace_init_choice && !(trace_choice == th.choiceStack.fetchChoice(th.currentChoicePoint))))) { #if 0 cerr.form("%6ld choiceStack[%ld]\n", th.TInfo().ID(), th.currentChoicePoint); th.choiceStack.display(cerr, th.currentChoicePoint, 1); cerr.flush(); #endif // 0 } if ((trace_level & TRACE_CUT) && trace_cut_point != th.cutPoint) { cerr << th.TInfo().ID() << " cutPoint=" << th.cutPoint << endl; cerr.flush(); } } Trace::Trace(const word32 level) : trace_level(level), trace_init_env(false), trace_init_choice(false) { } #endif // QP_DEBUG
HaydeeLinkous/b
pseudonymization/common/metadata.go
/* * Copyright 2020, Cossack Labs Limited * * 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 common import ( "time" "github.com/golang/protobuf/proto" ) // TokenMetadata is additional bookeeping information kept by TokenStorage along with the token value. type TokenMetadata struct { Created time.Time Accessed time.Time Disabled bool } // NewTokenMetadata creates metadata for a newly created token entry, func NewTokenMetadata() TokenMetadata { now := time.Now().UTC() return TokenMetadata{Created: now, Accessed: now, Disabled: false} } // AccessedBefore checks that the token has been accessed before the specified time instance with given granularity. func (t *TokenMetadata) AccessedBefore(instant time.Time, granularity time.Duration) bool { return t.Accessed.Before(instant.Add(-granularity)) } // Equal returns true if this metadata is equal to the other one. func (t TokenMetadata) Equal(other TokenMetadata) bool { return t.Created.Equal(other.Created) && t.Accessed.Equal(other.Accessed) && t.Disabled == other.Disabled } // EmbedMetadata composes data with additional metadata into a single byte slice. func EmbedMetadata(data []byte, metadata TokenMetadata) []byte { value := MetadataContainer{ Data: data, Created: metadata.Created.Unix(), Accessed: metadata.Accessed.Unix(), Disabled: metadata.Disabled, } bytes, _ := proto.Marshal(&value) return bytes } // ExtractMetadata extracts data and metadata back from a composite byte slice. func ExtractMetadata(data []byte) ([]byte, TokenMetadata, error) { var value MetadataContainer err := proto.Unmarshal(data, &value) if err != nil { return nil, TokenMetadata{}, err } metadata := TokenMetadata{ Created: time.Unix(value.Created, 0), Accessed: time.Unix(value.Accessed, 0), Disabled: value.Disabled, } return value.Data, metadata, nil }
DiegoOrtegoP/Software
catkin_ws/src/f4-devel/visual_odometry/tests/odometry_training_pairs_2csv_node.py
#!/usr/bin/env python import rospy import rospkg, os from duckietown_msgs.msg import Vsample, ThetaDotSample import csv class OdometryTrainingPairsNode(object): def __init__(self): self.node_name = rospy.get_name() #Init the files self.rpkg = rospkg.RosPack() self.v_sample_filename = self.setupParameter("~v_sample_filename", self.rpkg.get_path('visual_odometry') + '/tests/v_sample.csv') try: os.remove(self.v_sample_filename) except OSError: pass self.rpkg = rospkg.RosPack() self.theta_dot_sample_filename = self.setupParameter("~theta_dot_sample_filename", self.rpkg.get_path('visual_odometry') + '/tests/theta_dot_sample.csv') try: os.remove(self.theta_dot_sample_filename) except OSError: pass ## state vars ## publishers and subscribers self.sub_v_sample = rospy.Subscriber("odometry_training_pairs_node/v_sample", Vsample, self.vSampleCB) self.sub_theta_dot_sample = rospy.Subscriber("odometry_training_pairs_node/theta_dot_sample", ThetaDotSample, self.thetaDotSampleCB) rospy.loginfo('[%s] Initialized' % self.node_name) def setupParameter(self, param_name, default_value): value = rospy.get_param(param_name, default_value) rospy.set_param(param_name, value) # Write to parameter server for transparancy rospy.loginfo("[%s] %s = %s " % (self.node_name, param_name, value)) return value def vSampleCB(self, v_sample_msg): row = [v_sample_msg.d_L, \ v_sample_msg.d_R, \ v_sample_msg.dt, \ v_sample_msg.theta_angle_pose_delta, \ v_sample_msg.x_axis_pose_delta, \ v_sample_msg.y_axis_pose_delta] with open(self.v_sample_filename, 'a+') as csvfile: writer = csv.writer(csvfile, delimiter=' ', quoting=csv.QUOTE_MINIMAL) writer.writerow(row) def thetaDotSampleCB(self, theta_dot_sample_msg): row = [theta_dot_sample_msg.d_L, \ theta_dot_sample_msg.d_R, \ theta_dot_sample_msg.dt, \ theta_dot_sample_msg.theta_angle_pose_delta] with open(self.theta_dot_sample_filename, 'a+') as csvfile: writer = csv.writer(csvfile, delimiter=' ', quoting=csv.QUOTE_MINIMAL) print row writer.writerow(row) def onShutdown(self): rospy.loginfo("[%s] Shutdown."%self.node_name) if __name__ == '__main__': rospy.init_node('odometry_training_pairs_2csv',anonymous=False) training_pairs_node_2csv = OdometryTrainingPairsNode() rospy.on_shutdown(training_pairs_node_2csv.onShutdown) rospy.spin()
JustinDunnWahoo/netsuite
lib/netsuite/records/inventory_item.rb
<gh_stars>0 module NetSuite module Records class InventoryItem include Support::Fields include Support::RecordRefs include Support::Records include Support::Actions include Namespaces::ListAcct # NOTE NetSuite doesn't have a InventoryItemSearch object. So we use # the ItemSearch instead. In order to actually get Inventory Items only # you will still have to specify the type: # # basic: [ # { # field: 'type', # operator: 'anyOf', # type: 'SearchEnumMultiSelectField', # value: ['_inventoryItem'] # } # ] # actions :get, :get_list, :add, :delete, :search, :update, :upsert, :update_list fields :auto_lead_time, :auto_preferred_stock_level, :auto_reorder_point, :available_to_partners, :average_cost, :backward_consumption_days, :contingent_revenue_handling, :conversion_rate, :copy_description, :cost, :cost_estimate, :cost_estimate_type, :cost_estimate_units, :costing_method, :costing_method_display, :cost_units, :country_of_manufacture, :created_date, :currency, :date_converted_to_inv, :default_return_cost, :defer_rev_rec, :demand_modifier, :demand_time_fence, :direct_revenue_posting, :display_name, :dont_show_price, :enable_catch_weight, :enforce_min_qty_internally, :exclude_from_sitemap, :featured_description, :fixed_lot_size, :forward_consumption_days, :fraud_risk, :future_horizon, :handling_cost, :handling_cost_units, :hazmat_hazard_class, :hazmat_id, :hazmat_item_units, :hazmat_item_units_qty, :hazmat_packing_group, :hazmat_shipping_name, :include_children, :invt_classification, :invt_count_interval, :is_donation_item, :is_drop_ship_item, :is_gco_compliant, :is_hazmat_item, :is_inactive, :is_online, :is_special_order_item, :is_store_pickup_allowed, :is_taxable, :item_carrier, :item_id, :last_invt_count_date, :last_modified_date, :last_purchase_price, :lead_time, :lower_warning_limit, :manufacturer, :manufacturer_addr1, :manufacturer_city, :manufacturer_state, :manufacturer_tariff, :manufacturer_tax_id, :manufacturer_zip, :match_bill_to_receipt, :matrix_item_name_template, :matrix_type, :max_donation_amount, :maximum_quantity, :meta_tag_html, :minimum_quantity, :minimum_quantity_units, :mpn, :mult_manufacture_addr, :nex_tag_category, :next_invt_count_date, :no_price_message, :offer_support, :on_hand_value_mli, :on_special, :original_item_subtype, :original_item_type, :out_of_stock_behavior, :out_of_stock_message, :overall_quantity_pricing_type, :page_title, :periodic_lot_size_days, :periodic_lot_size_type, :preference_criterion, :preferred_stock_level, :preferred_stock_level_days, :preferred_stock_level_units, :prices_include_tax, :producer, :purchase_description, :purchase_order_amount, :purchase_order_quantity, :purchase_order_quantity_diff, :quantity_available, :quantity_available_units, :quantity_back_ordered, :quantity_committed, :quantity_committed_units, :quantity_on_hand, :quantity_on_hand_units, :quantity_on_order, :quantity_on_order_units, :quantity_reorder_units, :rate, :receipt_amount, :receipt_quantity, :receipt_quantity_diff, :related_items_description, :reorder_multiple, :reorder_point, :reorder_point_units, :reschedule_in_days, :reschedule_out_days, :round_up_as_component, :safety_stock_level, :safety_stock_level_days, :safety_stock_level_units, :sales_description, :schedule_b_code, :schedule_b_number, :schedule_b_quantity, :search_keywords, :seasonal_demand, :ship_individually, :shipping_cost, :shipping_cost_units, :shopping_dot_com_category, :shopzilla_category_id, :show_default_donation_amount, :sitemap_priority, :specials_description, :stock_description, :store_description, :store_detailed_description, :store_display_name, :supply_time_fence, :total_value, :track_landed_cost, :transfer_price, :upc_code, :upper_warning_limit, :url_component, :use_bins, :use_marginal_rates, :vendor_name, :vsoe_deferral, :vsoe_delivered, :vsoe_permit_discount, :vsoe_price, :vsoe_sop_group, :weight, :weight_unit, :weight_units # https://system.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2020_2/schema/search/itemsearchrowbasic.html?mode=package search_only_fields :acc_book_rev_rec_forecast_rule, :accounting_book, :accounting_book_amortization, :accounting_book_create_plans_on, :accounting_book_rev_rec_rule, :accounting_book_rev_rec_schedule, :allowed_shipping_method, :atp_lead_time, :atp_method, :base_price, :bin_number, :bin_on_hand_avail, :bin_on_hand_count, :bom_quantity, :build_entire_assembly, :build_time, :buy_it_now_price, :category, :category_preferred, :component_yield, :correlated_item, :correlated_item_correlation, :correlated_item_count, :correlated_item_lift, :correlated_item_purchase_rate, :cost_accounting_status, :created, :create_job, :cust_return_variance_account, :date_viewed, :days_before_expiration, :default_shipping_method, :deferred_expense_account, :departmentnohierarchy, :display_ine_bay_store, :e_bay_item_description, :e_bay_item_subtitle, :e_bay_item_title, :ebay_relisting_option, :effective_bom_control, :effective_date, :effective_revision, :end_auctions_when_out_of_stock, :feed_description, :feed_name, :froogle_product_feed, :fx_cost, :generate_accruals, :gift_cert_auth_code, :gift_cert_email, :gift_cert_expiration_date, :gift_cert_from, :gift_cert_message, :gift_cert_original_amount, :gift_cert_recipient, :hierarchy_node, :hierarchy_version, :hits, :image_url, :interco_expense_account, :inventory_location, :is_available, :is_fulfillable, :is_lot_item, :is_serial_item, :is_special_work_order_item, :is_vsoe_bundle, :is_wip, :item_url, :last_quantity_available_change, :liability_account, :listing_duration, :location_allow_store_pickup, :location_atp_lead_time, :location_average_cost, :location_bin_quantity_available, :location_build_time, :location_cost, :location_cost_accounting_status, :location_default_return_cost, :location_demand_source, :location_demand_time_fence, :location_fixed_lot_size, :location_inventory_cost_template, :location_invt_classification, :location_invt_count_interval, :location_last_invt_count_date, :location_lead_time, :location_next_invt_count_date, :location_periodic_lot_size_days, :location_periodic_lot_size_type, :location_preferred_stock_level, :location_qty_avail_for_store_pickup, :location_quantity_available, :location_quantity_back_ordered, :location_quantity_committed, :location_quantity_in_transit, :location_quantity_on_hand, :location_quantity_on_order, :location_re_order_point, :location_reschedule_in_days, :location_reschedule_out_days, :location_safety_stock_level, :location_store_pickup_buffer_stock, :location_supply_lot_sizing_method, :location_supply_time_fence, :location_supply_type, :location_total_value, :loc_backward_consumption_days, :loc_forward_consumption_days, :manufacturing_charge_item, :member_item, :member_quantity, :modified, :moss_applies, :nextag_product_feed, :num_active_listings, :number_allowed_downloads, :num_currently_listed, :obsolete_date, :obsolete_revision, :online_customer_price, :online_price, :other_prices, :other_vendor, :overhead_type, :preferred_bin, :primary_category, :prod_price_variance_acct, :prod_qty_variance_acct, :reserve_price, :same_as_primary_book_amortization, :same_as_primary_book_rev_rec, :scrap_acct, :sell_on_ebay, :serial_number, :serial_number_location, :shipping_carrier, :shipping_rate, :shopping_product_feed, :shopzilla_product_feed, :starting_price, :subsidiary, :sub_type, :thumb_nail_url, :type, :unbuild_variance_account, :use_component_yield, :vendor_code, :vendor_cost, :vendor_cost_entered, :vendor_price_currency, :vendor_schedule, :vend_return_variance_account, :web_site, :wip_acct, :wip_variance_acct, :yahoo_product_feed record_refs :alternate_demand_source_item, :asset_account, :bill_exch_rate_variance_acct, :billing_schedule, :bill_price_variance_acct, :bill_qty_variance_acct, :klass, :cogs_account, :consumption_unit, :cost_category, :create_revenue_plans_on, :custom_form, :default_item_ship_method, :deferred_revenue_account, :demand_source, :department, :distribution_category, :distribution_network, :dropship_expense_account, :expense_account, :gain_loss_account, :income_account, :interco_cogs_account, :interco_def_rev_account, :interco_income_account, :issue_product, :item_revenue_category, :location, :parent, :planning_item_category, :preferred_location, :pricing_group, :purchase_price_variance_acct, :purchase_tax_code, :purchase_unit, :quantity_pricing_schedule, :revenue_allocation_group, :revenue_recognition_rule, :rev_rec_forecast_rule, :rev_reclass_f_x_account, :rev_rec_schedule, :sales_tax_code, :sale_unit, :secondary_base_unit, :secondary_consumption_unit, :secondary_purchase_unit, :secondary_sale_unit, :secondary_stock_unit, :secondary_units_type, :ship_package, :soft_descriptor, :stock_unit, :store_display_image, :store_display_thumbnail, :store_item_template, :supply_lot_sizing_method, :supply_replenishment_method, :supply_type, :tax_schedule, :units_type, :vendor field :bin_number_list, BinNumberList field :custom_field_list, CustomFieldList field :item_ship_method_list, RecordRefList field :item_vendor_list, ItemVendorList field :locations_list, LocationsList field :matrix_option_list, MatrixOptionList field :pricing_matrix, PricingMatrix field :subsidiary_list, RecordRefList # TODO: :accounting_book_detail_list, ItemAccountingBookDetailList # TODO: :hierarchy_versions_list, InventoryItemHierarchyVersionsList # TODO: :item_options_list, ItemOptionsList # TODO: :presentation_item_list, PresentationItemList # TODO: :product_feed_list, ProductFeedList # TODO: :site_category_list, SiteCategoryList field :translations_list, TranslationList attr_reader :internal_id attr_accessor :external_id def initialize(attributes = {}) @internal_id = attributes.delete(:internal_id) || attributes.delete(:@internal_id) @external_id = attributes.delete(:external_id) || attributes.delete(:@external_id) initialize_from_attributes_hash(attributes) end def self.search_class_name "Item" end end end end
hakandrmz/CampNotes
rentacar/src/main/java/com/turkcell/rentacar/api/controller/CarMaintenancesController.java
package com.turkcell.rentacar.api.controller; import java.util.List; import javax.validation.Valid; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.turkcell.rentacar.business.abstracts.CarMaintenanceService; import com.turkcell.rentacar.business.dtos.carmaintenance.CarMaintenanceByIdDto; import com.turkcell.rentacar.business.dtos.carmaintenance.CarMaintenanceListDto; import com.turkcell.rentacar.business.requests.carmaintenance.CreateCarMaintenanceRequest; import com.turkcell.rentacar.business.requests.carmaintenance.UpdateCarMaintenanceRequest; import com.turkcell.rentacar.core.utilities.results.DataResult; import com.turkcell.rentacar.core.utilities.results.Result; @RestController @RequestMapping("/api/carMaintenances") public class CarMaintenancesController { private CarMaintenanceService carMaintenanceService; public CarMaintenancesController(CarMaintenanceService carMaintenanceService) { this.carMaintenanceService = carMaintenanceService; } @GetMapping("/getall") public DataResult<List<CarMaintenanceListDto>> getAll() { return this.carMaintenanceService.getAll(); } @PostMapping("/add") public Result add(@RequestBody @Valid CreateCarMaintenanceRequest createcarMaintenanceRequest) { return this.carMaintenanceService.add(createcarMaintenanceRequest); } @GetMapping("/getbyid") public DataResult<CarMaintenanceByIdDto> getById(@RequestParam(required = true) int carMaintenanceId) { return this.carMaintenanceService.getById(carMaintenanceId); } @PutMapping("/update") public Result update(@RequestBody @Valid UpdateCarMaintenanceRequest updateCarMaintenanceRequest) { return this.carMaintenanceService.update(updateCarMaintenanceRequest); } @DeleteMapping("/deletebyid") public Result deleteById(@RequestParam int carMaintenanceId) { return this.carMaintenanceService.deleteById(carMaintenanceId); } @GetMapping("/getbycarid") public DataResult<List<CarMaintenanceListDto>> getByCarId(@RequestParam(required = true) int carId) { return this.carMaintenanceService.getByCarId(carId); } }
ekholabs/elsie-dee
src/main/java/nl/ekholabs/nlp/client/StreamServicesFeignClient.java
package nl.ekholabs.nlp.client; import nl.ekholabs.nlp.client.configuration.JsonSupportConfig; import nl.ekholabs.nlp.model.ExtractSubtitlesRequest; import nl.ekholabs.nlp.model.Streams; import nl.ekholabs.nlp.model.VideoUrl; import org.springframework.cloud.netflix.feign.FeignClient; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import static org.springframework.http.MediaType.APPLICATION_JSON_UTF8_VALUE; @FeignClient(serviceId = "stream-services", configuration = JsonSupportConfig.class) public interface StreamServicesFeignClient { @PostMapping(path = "/ffmpeg/streamDetails", consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) Streams streamDetails(@RequestBody final VideoUrl videoUrl); @PostMapping(path = "/ffmpeg/extractSubtitles", consumes = APPLICATION_JSON_UTF8_VALUE, produces = APPLICATION_JSON_UTF8_VALUE) String extractSubtitles(@RequestBody final ExtractSubtitlesRequest subtitlesRequest); }
Mozilla-GitHub-Standards/f9c78643f5862cda82001d4471255ac29ef0c6b2c6171e2c1cbecab3d2fef4dd
auto_nag/scripts/workflow/p2_no_activity.py
<reponame>Mozilla-GitHub-Standards/f9c78643f5862cda82001d4471255ac29ef0c6b2c6171e2c1cbecab3d2fef4dd # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this file, # You can obtain one at http://mozilla.org/MPL/2.0/. from dateutil.relativedelta import relativedelta from libmozdata import utils as lmdutils from auto_nag.bzcleaner import BzCleaner from auto_nag.escalation import Escalation from auto_nag.nag_me import Nag from auto_nag import utils class P2NoActivity(BzCleaner, Nag): def __init__(self): super(P2NoActivity, self).__init__() self.nmonths = utils.get_config(self.name(), 'months_lookup', 3) self.escalation = Escalation( self.people, data=utils.get_config(self.name(), 'escalation'), blacklist=utils.get_config('workflow', 'supervisor_blacklist', []), ) def description(self): return 'Get P2 bugs and no activity for {} months'.format(self.nmonths) def name(self): return 'workflow-p2-no-activity' def template(self): return 'workflow_p2_no_activity.html' def nag_template(self): return self.template() def subject(self): return 'P2 bugs without activity for {} months'.format(self.nmonths) def get_extra_for_template(self): return {'nmonths': self.nmonths} def get_extra_for_nag_template(self): return self.get_extra_for_template() def ignore_meta(self): return True def has_last_comment_time(self): return True def has_product_component(self): return True def columns(self): return ['component', 'id', 'summary', 'last_comment'] def set_people_to_nag(self, bug, buginfo): priority = 'default' if not self.filter_bug(priority): return None owner = bug['triage_owner'] self.add_triage_owner(owner, utils.get_config('workflow', 'components')) if not self.add(owner, buginfo, priority=priority): self.add_no_manager(buginfo['id']) return bug def get_bz_params(self, date): date = lmdutils.get_date_ymd(date) start_date = date - relativedelta(months=self.nmonths) days = (date - start_date).days fields = ['triage_owner'] comps = utils.get_config('workflow', 'components') params = { 'include_fields': fields, 'component': comps, 'resolution': '---', 'f1': 'priority', 'o1': 'equals', 'v1': 'P2', 'f2': 'days_elapsed', 'o2': 'greaterthaneq', 'v2': days, } return params if __name__ == '__main__': P2NoActivity().run()
xyzst/gvisor
pkg/sentry/kernel/timekeeper_state.go
// Copyright 2018 The gVisor 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 kernel import ( "gvisor.dev/gvisor/pkg/sentry/time" ) // beforeSave is invoked by stateify. func (t *Timekeeper) beforeSave() { if t.stop != nil { panic("pauseUpdates must be called before Save") } // N.B. we want the *offset* monotonic time. var err error if t.saveMonotonic, err = t.GetTime(time.Monotonic); err != nil { panic("unable to get current monotonic time: " + err.Error()) } if t.saveRealtime, err = t.GetTime(time.Realtime); err != nil { panic("unable to get current realtime: " + err.Error()) } } // afterLoad is invoked by stateify. func (t *Timekeeper) afterLoad() { t.restored = make(chan struct{}) }
sleepy-monax/projet-jeu-video
src/game/inventory/Craft.h
#pragma once #include "utils/Vector.h" #include "game/components/Inventory.h" #include "game/inventory/Craft.h" namespace game { struct Craft { Stack result; utils::Vector<Stack> ingredients; bool can_be_made(Inventory inv) const { for (size_t i = 0; i < ingredients.count(); i++) { if (inv.count(ingredients[i].item()) < ingredients[i].quantity()) { return false; } } return true; } void do_it(Inventory &inv) const { if (can_be_made(inv)) { for (size_t i = 0; i < ingredients.count(); i++) { inv.remove(ingredients[i]); } inv.add(result); } } }; } // namespace game
mjfwalsh/lemmini
Game/Music.java
package Game; import java.io.File; import java.io.FileFilter; /* * Copyright 2009 <NAME> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Play background music. Abstraction layer for ModMusic and MidiMusic. * * @author <NAME> */ public class Music { /** music type */ private static enum Type { /** no type */ NONE, /** midi music */ MIDI, /** MOD music */ MOD } /** music type */ private static Type type; /** currently playing? */ private static boolean playing; /** MOD music object */ private static ModMusic modMusic; /** Midi music object */ private static MidiMusic midiMusic; /** music gain */ private static double gain = 1.0; /** array of file names */ private static String musicFiles[]; /** * Initialization. */ public static void init() { type = Type.NONE; modMusic = new ModMusic(); // read available musicfiles for random mode File dir = new File(Core.resourcePath+"music"); File files[] = dir.listFiles(new MusicFileFilter()); musicFiles = new String[files.length]; for (int i=0; i<files.length; i++) musicFiles[i] = files[i].getName(); } /** * Load music file. * @param fName file name * @throws ResourceException * @throws LemmException */ public static void load(final String fName) throws ResourceException, LemmException { if (fName.toLowerCase().indexOf(".mid") != -1) { // MIDI midiMusic = new MidiMusic(fName); if (type == Type.MOD) modMusic.close(); type = Type.MIDI; } else if (fName.toLowerCase().indexOf(".mod") != -1) { // MOD modMusic.load(fName); if (type == Type.MIDI) midiMusic.close(); type = Type.MOD; } playing = false; } /** * Get file name of a random track. * @return file name of a random track */ public static String getRandomTrack() { double r = Math.random()*musicFiles.length; return musicFiles[(int)r]; } /** * Play music. */ public static void play() { switch (type) { case MIDI: midiMusic.play(); playing = true; break; case MOD: modMusic.play(); playing = true; break; } } /** * Stop music. */ public static void stop() { switch (type) { case MIDI: midiMusic.stop(); playing = false; break; case MOD: modMusic.stop(); playing = false; break; } } /** * Close music. */ public static void close() { switch (type) { case MIDI: midiMusic.close(); playing = false; break; case MOD: modMusic.close(); playing = false; break; } } /** * Check if music is currently playing * @return true if music is currently playing, else false */ public static boolean isPlaying() { return playing; } /** * Get current music gain (1.0=100%) * @return current music gain (1.0=100%) */ public static double getGain() { return gain; } /** * Set music gain * @param gn gain (1.0=100%) */ public static void setGain(final double gn) { if (gn > 1.0) gain = 1.0; else if (gn < 0) gain = 0; else gain = gn; switch (type) { case MIDI: midiMusic.setGain(gain); break; case MOD: modMusic.setGain(gain); break; } Core.programProps.set("musicGain", gain); } /** * Get current music type. * @return music type */ public static Type getType() { return type; } } /** * File filter for music files. * @author <NAME> */ class MusicFileFilter implements FileFilter { /* (non-Javadoc) * @see java.io.FileFilter#accept(java.io.File) */ @Override public boolean accept(final File f) { if (!f.isFile()) return false; if (f.getName().toLowerCase().indexOf(".mid") != -1) return true; if (f.getName().toLowerCase().indexOf(".mod") != -1) return true; return false; } }
uk-gov-mirror/hmcts.fpl-ccd-configuration
service/src/functionalTest/java/uk/gov/hmcts/reform/fpl/model/User.java
<reponame>uk-gov-mirror/hmcts.fpl-ccd-configuration package uk.gov.hmcts.reform.fpl.model; import lombok.Data; @Data public class User { String name; String password; }
ifnode/ifnode
examples/models_custom_schema/protected/extensions/custom-schema-without-constructor.js
var SCHEMA = require('./../../../../core/PLUGIN_TYPES').SCHEMA; module.exports[SCHEMA] = function(app, CustomSchemaWithoutConstructor) { CustomSchemaWithoutConstructor.schema = 'custom-schema-without-constructor'; CustomSchemaWithoutConstructor.prototype.compile = function compile() { return this; }; return CustomSchemaWithoutConstructor; };
oimchat/oim-fx
client/oim-client-base/src/main/java/com/onlyxiahui/im/message/server/ResultBodyMessage.java
package com.onlyxiahui.im.message.server; import com.only.common.result.Info; import com.onlyxiahui.im.message.AbstractMessage; import com.onlyxiahui.im.message.Head; /** * @author Only * @date 2016-05-19 04:12:15 */ public class ResultBodyMessage extends AbstractMessage { private Head head; private Info info = new Info(); private Object body; @Override public Head getHead() { return head; } @Override public void setHead(Head head) { this.head = head; } public Object getBody() { return body; } public void setBody(Object body) { this.body = body; } public void setInfo(Info info) { this.info = info; } public Info getInfo() { return info; } public void setSuccess(boolean success) { info.setSuccess(success); } public void addError(String code, String text) { info.addError(code, text); } public void addWarning(String code, String text) { info.addWarning(code, text); } }
pnkosev/nutri-meter
src/main/java/pn/nutrimeter/data/models/User.java
package pn.nutrimeter.data.models; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import org.springframework.security.core.userdetails.UserDetails; import pn.nutrimeter.data.models.base.BaseEntity; import pn.nutrimeter.data.models.enums.ActivityLevel; import pn.nutrimeter.data.models.enums.AgeCategory; import pn.nutrimeter.data.models.enums.Sex; import javax.persistence.*; import java.time.LocalDate; import java.time.Period; import java.util.List; import java.util.Set; @Getter @Setter @NoArgsConstructor @Entity @Table(name = "users") @NamedStoredProcedureQuery( name = "usp_update_user", procedureName = "usp_update_user", parameters = { @StoredProcedureParameter(mode = ParameterMode.IN, name = "user_id", type = String.class), @StoredProcedureParameter(mode = ParameterMode.IN, name = "life_stage_group_id", type = String.class) }) public class User extends BaseEntity implements UserDetails { @Column(name = "username", nullable = false, unique = true, length = 15) private String username; @Column(name = "email", nullable = false, unique = true, updatable = false) private String email; @Column(name = "password", nullable = false) private String password; @Column(name = "sex", nullable = false) @Enumerated(EnumType.STRING) private Sex sex; @Column(name = "weight", nullable = false, precision = 5, scale = 2) private Double weight; @Column(name = "target_weight") private Double targetWeight; @Column(name = "kilos_per_week") private Double kilosPerWeek; @Column(name = "kcal_from_target") private Double kcalFromTarget; @Column(name = "height", nullable = false, precision = 5, scale = 2) private Double height; @Column(name = "birthday", nullable = false) private LocalDate birthday; @Column(name = "years_old", nullable = false, precision = 3, scale = 1) private Double yearsOld; @Column(name = "age_category") @Enumerated(EnumType.STRING) private AgeCategory ageCategory; @Column(name = "activity_level", nullable = false) @Enumerated(EnumType.STRING) private ActivityLevel activityLevel; @Column(name = "kcal_from_bmr") private Double bmr; @Column(name = "bmi") private Double bmi; @Column(name = "body_fat") private Double bodyFat; @Column(name = "kcal_from_activity_level") private Double kcalFromActivityLevel; @Column(name = "total_kcal_target") private Double totalKcalTarget; @Column(name = "proteins_target_in_percentage") private Double proteinTargetInPercentage; @Column(name = "protein_target_in_kcal") private Double proteinTargetInKcal; @Column(name = "carbs_target_in_percentage") private Double carbohydrateTargetInPercentage; @Column(name = "carbohydrate_target_in_kcal") private Double carbohydrateTargetInKcal; // concerns the target as % @Column(name = "lipid_target_in_percentage") private Double lipidTargetInPercentage; @Column(name = "lipid_target_in_kcal") private Double lipidTargetInKcal; // concerns the target as % @ManyToOne @JoinColumn(name = "life_group_stage_id", referencedColumnName = "id") private LifeStageGroup lifeStageGroup; @ManyToOne @JoinColumn(name = "macro_target_id", referencedColumnName = "id") private MacroTarget macroTarget; @ManyToOne @JoinColumn(name = "micro_target_id", referencedColumnName = "id") private MicroTarget microTarget; @OneToMany(mappedBy = "user") private List<Food> customFoods; @OneToMany(mappedBy = "user") private List<Exercise> customExercises; @OneToMany(mappedBy = "user") private List<DailyStory> dailyStories; @ManyToMany(fetch = FetchType.EAGER) @JoinTable( name = "users_roles", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "role_id", referencedColumnName = "id") ) private Set<Role> authorities; @ManyToMany @JoinTable( name = "users_foods", joinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id"), inverseJoinColumns = @JoinColumn(name = "food_id", referencedColumnName = "id") ) private List<Food> favoriteFoods; @Override public boolean isAccountNonExpired() { return true; } @Override public boolean isAccountNonLocked() { return true; } @Override public boolean isCredentialsNonExpired() { return true; } @Override public boolean isEnabled() { return true; } }
Apokalypser/go-ebay
integration_test.go
<reponame>Apokalypser/go-ebay package ebay import ( "flag" "testing" "github.com/stretchr/testify/suite" ) var devID, appID, certID, ruName, authToken string func init() { flag.StringVar(&devID, "devid", "", "EBay sandbox DevID") flag.StringVar(&devID, "appid", "", "EBay sandbox AppID") flag.StringVar(&devID, "certid", "", "EBay sandbox CertID") flag.StringVar(&devID, "runame", "", "EBay sandbox RuName") flag.StringVar(&devID, "authtoken", "", "EBay sandbox AuthToken") } type EbayIntegrationTestSuite struct { suite.Suite ebayConf EbayConf } func (s *EbayIntegrationTestSuite) SetupSuite() { s.ebayConf = EbayConf{ DevId: devID, AppId: appID, CertId: certID, RuName: ruName, AuthToken: authToken, SiteId: 0, }.Sandbox() } func TestEbayIntegrationTestSuite(t *testing.T) { suite.Run(t, new(EbayIntegrationTestSuite)) }
wdonne/pincette-common
src/main/java/net/pincette/cls/ExceptionHandler.java
<reponame>wdonne/pincette-common package net.pincette.cls; public class ExceptionHandler { short endPC; short handlerPC; short startPC; String type; public short getEndProgramCounter() { return endPC; } public short getHandlerProgramCounter() { return handlerPC; } public String getName() { return type; } public short getStartProgramHandler() { return startPC; } public String getType() { return Util.getType(type); } }
mealdy/google-api-objectivec-client-for-rest
Source/GeneratedServices/Customsearch/GTLRCustomsearchObjects.h
<gh_stars>0 // NOTE: This file was generated by the ServiceGenerator. // ---------------------------------------------------------------------------- // API: // CustomSearch API (customsearch/v1) // Description: // Lets you search over a website or collection of websites // Documentation: // https://developers.google.com/custom-search/v1/using_rest #if GTLR_BUILT_AS_FRAMEWORK #import "GTLR/GTLRObject.h" #else #import "GTLRObject.h" #endif #if GTLR_RUNTIME_VERSION != 3000 #error This file was generated by a different version of ServiceGenerator which is incompatible with this GTLR library source. #endif @class GTLRCustomsearch_Context; @class GTLRCustomsearch_Context_Facets_Item; @class GTLRCustomsearch_Promotion; @class GTLRCustomsearch_Promotion_BodyLines_Item; @class GTLRCustomsearch_Promotion_Image; @class GTLRCustomsearch_Query; @class GTLRCustomsearch_Result; @class GTLRCustomsearch_Result_Image; @class GTLRCustomsearch_Result_Labels_Item; @class GTLRCustomsearch_Result_Pagemap; @class GTLRCustomsearch_Result_Pagemap_Pagemap_Item; @class GTLRCustomsearch_Search_Queries; @class GTLRCustomsearch_Search_SearchInformation; @class GTLRCustomsearch_Search_Spelling; @class GTLRCustomsearch_Search_Url; NS_ASSUME_NONNULL_BEGIN /** * GTLRCustomsearch_Context */ @interface GTLRCustomsearch_Context : GTLRObject @property(nonatomic, strong, nullable) NSArray<NSArray<GTLRCustomsearch_Context_Facets_Item *> *> *facets; @property(nonatomic, copy, nullable) NSString *title; @end /** * GTLRCustomsearch_Context_Facets_Item */ @interface GTLRCustomsearch_Context_Facets_Item : GTLRObject @property(nonatomic, copy, nullable) NSString *anchor; @property(nonatomic, copy, nullable) NSString *label; @property(nonatomic, copy, nullable) NSString *labelWithOp; @end /** * GTLRCustomsearch_Promotion */ @interface GTLRCustomsearch_Promotion : GTLRObject @property(nonatomic, strong, nullable) NSArray<GTLRCustomsearch_Promotion_BodyLines_Item *> *bodyLines; @property(nonatomic, copy, nullable) NSString *displayLink; @property(nonatomic, copy, nullable) NSString *htmlTitle; @property(nonatomic, strong, nullable) GTLRCustomsearch_Promotion_Image *image; @property(nonatomic, copy, nullable) NSString *link; @property(nonatomic, copy, nullable) NSString *title; @end /** * GTLRCustomsearch_Promotion_BodyLines_Item */ @interface GTLRCustomsearch_Promotion_BodyLines_Item : GTLRObject @property(nonatomic, copy, nullable) NSString *htmlTitle; @property(nonatomic, copy, nullable) NSString *link; @property(nonatomic, copy, nullable) NSString *title; @property(nonatomic, copy, nullable) NSString *url; @end /** * GTLRCustomsearch_Promotion_Image */ @interface GTLRCustomsearch_Promotion_Image : GTLRObject /** * height * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *height; @property(nonatomic, copy, nullable) NSString *source; /** * width * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *width; @end /** * GTLRCustomsearch_Query */ @interface GTLRCustomsearch_Query : GTLRObject /** * count * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *count; @property(nonatomic, copy, nullable) NSString *cr; @property(nonatomic, copy, nullable) NSString *cref; @property(nonatomic, copy, nullable) NSString *cx; @property(nonatomic, copy, nullable) NSString *dateRestrict; @property(nonatomic, copy, nullable) NSString *disableCnTwTranslation; @property(nonatomic, copy, nullable) NSString *exactTerms; @property(nonatomic, copy, nullable) NSString *excludeTerms; @property(nonatomic, copy, nullable) NSString *fileType; @property(nonatomic, copy, nullable) NSString *filter; @property(nonatomic, copy, nullable) NSString *gl; @property(nonatomic, copy, nullable) NSString *googleHost; @property(nonatomic, copy, nullable) NSString *highRange; @property(nonatomic, copy, nullable) NSString *hl; @property(nonatomic, copy, nullable) NSString *hq; @property(nonatomic, copy, nullable) NSString *imgColorType; @property(nonatomic, copy, nullable) NSString *imgDominantColor; @property(nonatomic, copy, nullable) NSString *imgSize; @property(nonatomic, copy, nullable) NSString *imgType; @property(nonatomic, copy, nullable) NSString *inputEncoding; @property(nonatomic, copy, nullable) NSString *language; @property(nonatomic, copy, nullable) NSString *linkSite; @property(nonatomic, copy, nullable) NSString *lowRange; @property(nonatomic, copy, nullable) NSString *orTerms; @property(nonatomic, copy, nullable) NSString *outputEncoding; @property(nonatomic, copy, nullable) NSString *relatedSite; @property(nonatomic, copy, nullable) NSString *rights; @property(nonatomic, copy, nullable) NSString *safe; @property(nonatomic, copy, nullable) NSString *searchTerms; @property(nonatomic, copy, nullable) NSString *searchType; @property(nonatomic, copy, nullable) NSString *siteSearch; @property(nonatomic, copy, nullable) NSString *siteSearchFilter; @property(nonatomic, copy, nullable) NSString *sort; /** * startIndex * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *startIndex; /** * startPage * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *startPage; @property(nonatomic, copy, nullable) NSString *title; /** * totalResults * * Uses NSNumber of longLongValue. */ @property(nonatomic, strong, nullable) NSNumber *totalResults; @end /** * GTLRCustomsearch_Result */ @interface GTLRCustomsearch_Result : GTLRObject @property(nonatomic, copy, nullable) NSString *cacheId; @property(nonatomic, copy, nullable) NSString *displayLink; @property(nonatomic, copy, nullable) NSString *fileFormat; @property(nonatomic, copy, nullable) NSString *formattedUrl; @property(nonatomic, copy, nullable) NSString *htmlFormattedUrl; @property(nonatomic, copy, nullable) NSString *htmlSnippet; @property(nonatomic, copy, nullable) NSString *htmlTitle; @property(nonatomic, strong, nullable) GTLRCustomsearch_Result_Image *image; @property(nonatomic, copy, nullable) NSString *kind; @property(nonatomic, strong, nullable) NSArray<GTLRCustomsearch_Result_Labels_Item *> *labels; @property(nonatomic, copy, nullable) NSString *link; @property(nonatomic, copy, nullable) NSString *mime; @property(nonatomic, strong, nullable) GTLRCustomsearch_Result_Pagemap *pagemap; @property(nonatomic, copy, nullable) NSString *snippet; @property(nonatomic, copy, nullable) NSString *title; @end /** * GTLRCustomsearch_Result_Image */ @interface GTLRCustomsearch_Result_Image : GTLRObject /** * byteSize * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *byteSize; @property(nonatomic, copy, nullable) NSString *contextLink; /** * height * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *height; /** * thumbnailHeight * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *thumbnailHeight; @property(nonatomic, copy, nullable) NSString *thumbnailLink; /** * thumbnailWidth * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *thumbnailWidth; /** * width * * Uses NSNumber of intValue. */ @property(nonatomic, strong, nullable) NSNumber *width; @end /** * GTLRCustomsearch_Result_Labels_Item */ @interface GTLRCustomsearch_Result_Labels_Item : GTLRObject @property(nonatomic, copy, nullable) NSString *displayName; @property(nonatomic, copy, nullable) NSString *labelWithOp; @property(nonatomic, copy, nullable) NSString *name; @end /** * GTLRCustomsearch_Result_Pagemap * * @note This class is documented as having more properties of NSArrays of * GTLRCustomsearch_Result_Pagemap_Pagemap_Item. Use @c * -additionalJSONKeys and @c -additionalPropertyForName: to get the list * of properties and then fetch them; or @c -additionalProperties to * fetch them all at once. */ @interface GTLRCustomsearch_Result_Pagemap : GTLRObject @end /** * GTLRCustomsearch_Result_Pagemap_Pagemap_Item * * @note This class is documented as having more properties of any valid JSON * type. Use @c -additionalJSONKeys and @c -additionalPropertyForName: to * get the list of properties and then fetch them; or @c * -additionalProperties to fetch them all at once. */ @interface GTLRCustomsearch_Result_Pagemap_Pagemap_Item : GTLRObject @end /** * GTLRCustomsearch_Search * * @note This class supports NSFastEnumeration and indexed subscripting over * its "items" property. */ @interface GTLRCustomsearch_Search : GTLRCollectionObject @property(nonatomic, strong, nullable) GTLRCustomsearch_Context *context; /** * items * * @note This property is used to support NSFastEnumeration and indexed * subscripting on this class. */ @property(nonatomic, strong, nullable) NSArray<GTLRCustomsearch_Result *> *items; @property(nonatomic, copy, nullable) NSString *kind; @property(nonatomic, strong, nullable) NSArray<GTLRCustomsearch_Promotion *> *promotions; @property(nonatomic, strong, nullable) GTLRCustomsearch_Search_Queries *queries; @property(nonatomic, strong, nullable) GTLRCustomsearch_Search_SearchInformation *searchInformation; @property(nonatomic, strong, nullable) GTLRCustomsearch_Search_Spelling *spelling; @property(nonatomic, strong, nullable) GTLRCustomsearch_Search_Url *url; @end /** * GTLRCustomsearch_Search_Queries * * @note This class is documented as having more properties of NSArrays of * GTLRCustomsearch_Query. Use @c -additionalJSONKeys and @c * -additionalPropertyForName: to get the list of properties and then * fetch them; or @c -additionalProperties to fetch them all at once. */ @interface GTLRCustomsearch_Search_Queries : GTLRObject @end /** * GTLRCustomsearch_Search_SearchInformation */ @interface GTLRCustomsearch_Search_SearchInformation : GTLRObject @property(nonatomic, copy, nullable) NSString *formattedSearchTime; @property(nonatomic, copy, nullable) NSString *formattedTotalResults; /** * searchTime * * Uses NSNumber of doubleValue. */ @property(nonatomic, strong, nullable) NSNumber *searchTime; /** * totalResults * * Uses NSNumber of longLongValue. */ @property(nonatomic, strong, nullable) NSNumber *totalResults; @end /** * GTLRCustomsearch_Search_Spelling */ @interface GTLRCustomsearch_Search_Spelling : GTLRObject @property(nonatomic, copy, nullable) NSString *correctedQuery; @property(nonatomic, copy, nullable) NSString *htmlCorrectedQuery; @end /** * GTLRCustomsearch_Search_Url */ @interface GTLRCustomsearch_Search_Url : GTLRObject /** * templateProperty * * Remapped to 'templateProperty' to avoid language reserved word 'template'. */ @property(nonatomic, copy, nullable) NSString *templateProperty; @property(nonatomic, copy, nullable) NSString *type; @end NS_ASSUME_NONNULL_END
goranbjelanovic/jet
mysql/lock_statement.go
<reponame>goranbjelanovic/jet package mysql import "github.com/goranbjelanovic/jet/v2/internal/jet" // LockStatement is interface for MySQL LOCK tables type LockStatement interface { Statement READ() Statement WRITE() Statement } // LOCK creates LockStatement from list of tables func LOCK(tables ...jet.SerializerTable) LockStatement { newLock := &lockStatementImpl{ Lock: jet.ClauseStatementBegin{Name: "LOCK TABLES", Tables: tables}, Read: jet.ClauseOptional{Name: "READ"}, Write: jet.ClauseOptional{Name: "WRITE"}, } newLock.SerializerStatement = jet.NewStatementImpl(Dialect, jet.LockStatementType, newLock, &newLock.Lock, &newLock.Read, &newLock.Write) return newLock } type lockStatementImpl struct { jet.SerializerStatement Lock jet.ClauseStatementBegin Read jet.ClauseOptional Write jet.ClauseOptional } func (l *lockStatementImpl) READ() Statement { l.Read.Show = true return l } func (l *lockStatementImpl) WRITE() Statement { l.Write.Show = true return l } // UNLOCK_TABLES explicitly releases any table locks held by the current session func UNLOCK_TABLES() Statement { newUnlock := &unlockStatementImpl{ Unlock: jet.ClauseStatementBegin{Name: "UNLOCK TABLES"}, } newUnlock.SerializerStatement = jet.NewStatementImpl(Dialect, jet.UnLockStatementType, newUnlock, &newUnlock.Unlock) return newUnlock } type unlockStatementImpl struct { jet.SerializerStatement Unlock jet.ClauseStatementBegin }