repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
GuillermoSaldana/GESPRO_Gestion_de_tareas
|
Updateposter/app/src/main/java/com/davidmiguel/gobees/apiary/ApiaryPresenter.java
|
/*
* GoBees
* Copyright (c) 2016 - 2017 <NAME>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/gpl-3.0.txt>.
*/
package com.davidmiguel.gobees.apiary;
import android.app.Activity;
import android.support.annotation.NonNull;
import com.davidmiguel.gobees.addeditapiary.AddEditApiaryActivity;
import com.davidmiguel.gobees.data.model.Apiary;
import com.davidmiguel.gobees.data.model.Hive;
import com.davidmiguel.gobees.data.source.GoBeesDataSource;
import com.davidmiguel.gobees.data.source.repository.GoBeesRepository;
import java.util.Date;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Listens to user actions from the UI ApiaryHivesFragment, retrieves the data and updates the
* UI as required.
*/
class ApiaryPresenter implements ApiaryContract.Presenter {
private GoBeesRepository goBeesRepository;
private ApiaryContract.ApiaryHivesView apiaryHivesView;
private ApiaryContract.ApiaryInfoView apiaryInfoView;
/**
* Force update the first time.
*/
private boolean firstLoad = true;
private long apiaryId;
private Apiary apiary;
private AtomicInteger ready;
ApiaryPresenter(GoBeesRepository goBeesRepository,
ApiaryContract.ApiaryHivesView apiaryHivesView,
ApiaryContract.ApiaryInfoView apiaryInfoView, long apiaryId) {
this.goBeesRepository = goBeesRepository;
this.apiaryHivesView = apiaryHivesView;
this.apiaryHivesView.setPresenter(this);
this.apiaryInfoView = apiaryInfoView;
apiaryInfoView.setPresenter(this);
this.apiaryId = apiaryId;
this.ready = new AtomicInteger(0);
}
@Override
public void result(int requestCode, int resultCode) {
// If a hive was successfully added, show snackbar
if (AddEditApiaryActivity.REQUEST_ADD_APIARY == requestCode
&& Activity.RESULT_OK == resultCode) {
apiaryHivesView.showSuccessfullySavedMessage();
}
}
@Override
public void loadData(boolean forceUpdate) {
// Force update the first time
boolean update = forceUpdate || firstLoad;
firstLoad = false;
// Refresh data if needed
if (update) {
goBeesRepository.refreshHives(apiaryId);
}
// Get apiary
goBeesRepository.getApiary(apiaryId, new GoBeesDataSource.GetApiaryCallback() {
@Override
public void onApiaryLoaded(Apiary apiary) {
// Save apiary
ApiaryPresenter.this.apiary = apiary;
// The view may not be able to handle UI updates anymore
if (!apiaryHivesView.isActive() && !apiaryInfoView.isActive()) {
return;
}
// Hide progress indicator
apiaryHivesView.setLoadingIndicator(false);
apiaryInfoView.setLoadingIndicator(false);
// Set apiary name as title
apiaryHivesView.showTitle(apiary.getName());
// Process hives
if (apiary.getHives() == null || apiary.getHives().isEmpty()) {
// Show a message indicating there are no hives
apiaryHivesView.showNoHives();
} else {
// Show the list of hives
apiaryHivesView.showHives(apiary.getHives());
}
// Show apiary info
apiaryInfoView.showInfo(apiary, getApiaryLastRevision());
}
@Override
public void onDataNotAvailable() {
// The view may not be able to handle UI updates anymore
if (!apiaryHivesView.isActive() && !apiaryInfoView.isActive()) {
return;
}
// Hide progress indicator
apiaryHivesView.setLoadingIndicator(false);
apiaryInfoView.setLoadingIndicator(false);
// Show error
apiaryHivesView.showLoadingHivesError();
}
});
}
@Override
public void addEditHive(long hiveId) {
apiaryHivesView.showAddEditHive(apiaryId, hiveId);
}
@Override
public void openHiveDetail(@NonNull Hive requestedHive) {
apiaryHivesView.showHiveDetail(apiaryId, requestedHive.getId());
}
@Override
public void deleteHive(@NonNull Hive hive) {
// Show progress indicator
apiaryHivesView.setLoadingIndicator(true);
// Delete hive
goBeesRepository.deleteHive(hive.getId(), new GoBeesDataSource.TaskCallback() {
@Override
public void onSuccess() {
// The view may not be able to handle UI updates anymore
if (!apiaryHivesView.isActive()) {
return;
}
// Refresh recordings
loadData(true);
// Show success message
apiaryHivesView.showSuccessfullyDeletedMessage();
}
@Override
public void onFailure() {
// The view may not be able to handle UI updates anymore
if (!apiaryHivesView.isActive()) {
return;
}
// Hide progress indicator
apiaryHivesView.setLoadingIndicator(false);
// Show error
apiaryHivesView.showDeletedErrorMessage();
}
});
}
@Override
public void onOpenMapClicked() {
apiaryInfoView.openMap(apiary);
}
@Override
public void start() {
int num = ready.incrementAndGet();
if(num >= 2) {
loadData(false);
}
}
/**
* Gets apiary last revision.
*
* @return last revision date.
*/
private Date getApiaryLastRevision() {
return goBeesRepository.getApiaryLastRevision(apiaryId);
}
}
|
liumapp/compiling-jvm
|
openjdk/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/KeyManagerTrustManager.java
|
<filename>openjdk/jdk/test/sun/security/ssl/javax/net/ssl/NewAPIs/KeyManagerTrustManager.java
/*
* Copyright (c) 2001, 2004, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 4387949 4302197 4396290 4395286
* @summary A compile test to make sure some of the new functionality
* is there. It doesn't actually call anything, just compiles it.
*
* 4387949: Need to add Sockets and key arrays to the
* X509KeyManager.choose*Alias() methods
* chooseServerAlias method is reverted back to accept a single
* keytype as a parameter, please see RFE: 4501014
* 4302197: There's no mechanism to select one key out of many in a keystore.
* 4396290: Need a way to pass algorithm specific parameters to TM's and KM's
* 4395286: The property for setting the default
* KeyManagerFactory/TrustManagerFactory algorithms needs real name
* @author <NAME>
*/
import java.net.*;
import java.security.*;
import java.security.cert.*;
import java.security.spec.*;
import javax.net.ssl.*;
public class KeyManagerTrustManager implements X509KeyManager {
public String[] getServerAliases(String keyType, Principal[] issuers) {
return null;
}
public String[] getClientAliases(String keyType, Principal[] issuers) {
return null;
}
public String chooseServerAlias(String keyType, Principal[] issuers,
Socket socket) {
return null;
}
public String chooseClientAlias(String [] keyType, Principal[] issuers,
Socket socket) {
return null;
}
public PrivateKey getPrivateKey(String alias) {
return null;
}
public X509Certificate[] getCertificateChain(String alias) {
return null;
}
public void doit(KeyManagerFactory kmf, TrustManagerFactory tmf,
ManagerFactoryParameters mfp) throws Exception {
kmf.init(mfp);
tmf.init(mfp);
}
public static void main(String args[]) throws Exception {
String kmfAlg = null;
String tmfAlg = null;
Security.setProperty("ssl.KeyManagerFactory.algorithm", "hello");
Security.setProperty("ssl.TrustManagerFactory.algorithm", "goodbye");
kmfAlg = KeyManagerFactory.getDefaultAlgorithm();
tmfAlg = TrustManagerFactory.getDefaultAlgorithm();
if (!kmfAlg.equals("hello")) {
throw new Exception("ssl.KeyManagerFactory.algorithm not set");
}
if (!tmfAlg.equals("goodbye")) {
throw new Exception("ssl.TrustManagerFactory.algorithm not set");
}
}
}
|
kingrom/jstarcraft-ai
|
jstarcraft-ai-jsat/src/main/java/com/jstarcraft/ai/jsat/testing/StatisticTest.java
|
package com.jstarcraft.ai.jsat.testing;
/**
*
* @author <NAME>
*/
public interface StatisticTest {
public enum H1 {
LESS_THAN {
@Override
public String toString() {
return "<";
}
},
GREATER_THAN {
@Override
public String toString() {
return ">";
}
},
NOT_EQUAL {
@Override
public String toString() {
return "\u2260";
}
}
};
/**
*
* @return an array of the valid alternate hypothesis for this test
*/
public H1[] validAlternate();
public void setAltHypothesis(H1 h1);
/**
*
* @return a descriptive name for the statistical test
*/
public String testName();
public double pValue();
}
|
kubohiroya/sqs-util
|
src/main/java/net/sqs2/lang/JVMUtil.java
|
<reponame>kubohiroya/sqs-util
package net.sqs2.lang;
public class JVMUtil {
/**
* JVM constant for any Windows 9x JVM
*/
public final static int WINDOWS_9x = 1;
/**
* JVM constant for any Windows NT JVM
*/
public final static int WINDOWS_NT = 2;
/**
* JVM constant for any other platform
*/
public final static int OTHER = -1;
private static int jvmTypeCode;
static {
String osName = System.getProperty("os.name");
if (osName.startsWith("Mac OS")) {
jvmTypeCode = OTHER;
} else if (osName.startsWith("Windows")) {
if (osName.indexOf("9") != -1) {
jvmTypeCode = WINDOWS_9x;
} else {
jvmTypeCode = WINDOWS_NT;
}
} else {
jvmTypeCode = OTHER;
}
}
public static int getJVMTypeCode() {
return jvmTypeCode;
}
}
|
cincheo/backend4dlite
|
dlite-applications/dlite-university-case-study/src/main/java/univcs/domain/MajorYearInstance.java
|
<reponame>cincheo/backend4dlite
package univcs.domain;
import org.cincheo.dlite.Entity;
import java.util.List;
@Entity
public class MajorYearInstance {
private Major major;
private List<CourseYearInstance> requiredCourses;
private List<CourseYearInstance> electiveCourses;
private Year year;
}
|
zljxh/EDU
|
src/main/java/com/zl/edu/dao/entity/CourseEvaluate.java
|
package com.zl.edu.dao.entity;
import java.util.Date;
public class CourseEvaluate {
private Long id;
private Long courseid;
private Long stuid;
private String desp;
private Date createtime;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getCourseid() {
return courseid;
}
public void setCourseid(Long courseid) {
this.courseid = courseid;
}
public Long getStuid() {
return stuid;
}
public void setStuid(Long stuid) {
this.stuid = stuid;
}
public String getDesp() {
return desp;
}
public void setDesp(String desp) {
this.desp = desp == null ? null : desp.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
}
|
TriggerMail/luci-go
|
common/gcloud/iam/client.go
|
<filename>common/gcloud/iam/client.go
// Copyright 2016 The LUCI 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 iam
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"time"
"golang.org/x/net/context/ctxhttp"
"golang.org/x/oauth2"
"google.golang.org/api/googleapi"
"github.com/TriggerMail/luci-go/common/logging"
)
const (
// OAuthScope is an OAuth scope required by IAM API.
OAuthScope = "https://www.googleapis.com/auth/iam"
// Token type for generated OAauth2 tokens
tokenType = "Bearer"
)
var (
// DefaultIamBaseURL resembles IAM's core API endpoint.
DefaultIamBaseURL = &url.URL{
Scheme: "https",
Host: "iam.googleapis.com",
}
// DefaultAccountCredentialsBaseURL resembles IAM's account credentials API endpoint.
DefaultAccountCredentialsBaseURL = &url.URL{
Scheme: "https",
Host: "iamcredentials.googleapis.com",
}
)
// ClaimSet contains information about the JWT signature including the
// permissions being requested (scopes), the target of the token, the issuer,
// the time the token was issued, and the lifetime of the token.
//
// See RFC 7515.
type ClaimSet struct {
Iss string `json:"iss"` // email address of the client_id of the application making the access token request
Scope string `json:"scope,omitempty"` // space-delimited list of the permissions the application requests
Aud string `json:"aud"` // descriptor of the intended target of the assertion (Optional).
Exp int64 `json:"exp"` // the expiration time of the assertion (seconds since Unix epoch)
Iat int64 `json:"iat"` // the time the assertion was issued (seconds since Unix epoch)
Typ string `json:"typ,omitempty"` // token type (Optional).
// Email for which the application is requesting delegated access (Optional).
Sub string `json:"sub,omitempty"`
}
// Client knows how to perform IAM API v1 calls.
type Client struct {
Client *http.Client // client to use to make calls
BasePath string // replaceable in tests, DefaultIamBaseURL / DefaultAccountCredentials by default.
}
// SignBlob signs a blob using a service account's system-managed key.
//
// The caller must have "roles/iam.serviceAccountActor" role in the service
// account's IAM policy and caller's OAuth token must have one of the scopes:
// * https://www.googleapis.com/auth/iam
// * https://www.googleapis.com/auth/cloud-platform
//
// Returns ID of the signing key and the signature on success.
//
// On API-level errors (e.g. insufficient permissions) returns *googleapi.Error.
func (cl *Client) SignBlob(c context.Context, serviceAccount string, blob []byte) (keyName string, signature []byte, err error) {
var request struct {
BytesToSign []byte `json:"bytesToSign"`
}
request.BytesToSign = blob
var response struct {
KeyID string `json:"keyId"`
Signature []byte `json:"signature"`
}
if err = cl.iamAPIRequest(c, "projects/-/serviceAccounts/"+serviceAccount, "signBlob", &request, &response); err != nil {
return "", nil, err
}
return response.KeyID, response.Signature, nil
}
// SignJWT signs a claim set using a service account's system-managed key.
//
// It injects the key ID into the JWT header before singing. As a result, JWTs
// produced by SignJWT are slightly faster to verify, because we know what
// public key to use exactly and don't need to enumerate all active keys.
//
// It also checks the expiration time and refuses to sign claim sets with
// 'exp' set to more than 1h from now. Otherwise it is similar to SignBlob.
//
// The caller must have "roles/iam.serviceAccountActor" role in the service
// account's IAM policy and caller's OAuth token must have one of the scopes:
// * https://www.googleapis.com/auth/iam
// * https://www.googleapis.com/auth/cloud-platform
//
// Returns ID of the signing key and the signed JWT on success.
//
// On API-level errors (e.g. insufficient permissions) returns *googleapi.Error.
func (cl *Client) SignJWT(c context.Context, serviceAccount string, cs *ClaimSet) (keyName, signedJwt string, err error) {
blob, err := json.Marshal(cs)
if err != nil {
return "", "", err
}
var request struct {
Payload string `json:"payload"`
}
request.Payload = string(blob) // yep, this is JSON inside JSON
var response struct {
KeyID string `json:"keyId"`
SignedJwt string `json:"signedJwt"`
}
if err = cl.iamAPIRequest(c, "projects/-/serviceAccounts/"+serviceAccount, "signJwt", &request, &response); err != nil {
return "", "", err
}
return response.KeyID, response.SignedJwt, nil
}
// GetIAMPolicy fetches an IAM policy of a resource.
//
// On non-success HTTP status codes returns googleapi.Error.
func (cl *Client) GetIAMPolicy(c context.Context, resource string) (*Policy, error) {
response := &Policy{}
if err := cl.iamAPIRequest(c, resource, "getIamPolicy", nil, response); err != nil {
return nil, err
}
return response, nil
}
// SetIAMPolicy replaces an IAM policy of a resource.
//
// Returns a new policy (with Etag field updated).
func (cl *Client) SetIAMPolicy(c context.Context, resource string, p Policy) (*Policy, error) {
var request struct {
Policy *Policy `json:"policy"`
}
request.Policy = &p
response := &Policy{}
if err := cl.iamAPIRequest(c, resource, "setIamPolicy", &request, response); err != nil {
return nil, err
}
return response, nil
}
// ModifyIAMPolicy reads IAM policy, calls callback to modify it, and then
// puts it back (if callback really changed it).
//
// Cast error to *googleapi.Error and compare http status to http.StatusConflict
// to detect update race conditions. It is usually safe to retry in case of
// a conflict.
func (cl *Client) ModifyIAMPolicy(c context.Context, resource string, cb func(*Policy) error) error {
policy, err := cl.GetIAMPolicy(c, resource)
if err != nil {
return err
}
// Make a copy to be mutated in the callback. Need to keep the original to
// be able to detect changes.
clone := policy.Clone()
if err := cb(&clone); err != nil {
return err
}
if clone.Equals(*policy) {
return nil
}
_, err = cl.SetIAMPolicy(c, resource, clone)
return err
}
// GenerateAccessToken creates a service account OAuth token using IAM's
// :generateAccessToken API.
//
// On non-success HTTP status codes returns googleapi.Error.
func (cl *Client) GenerateAccessToken(c context.Context, serviceAccount string, scopes []string, delegates []string, lifetime time.Duration) (*oauth2.Token, error) {
var body struct {
Delegates []string `json:"delegates"`
Scope []string `json:"scope"`
Lifetime string `json:"lifetime,omitempty"`
}
body.Scope = scopes
body.Delegates = delegates
// Default lifetime is 3600 seconds according to API documentation.
// Requesting longer lifetime will cause an API error which is
// forwarded to the caller.
if lifetime > 0 {
body.Lifetime = lifetime.String()
}
var resp struct {
AccessToken string `json:"accessToken"`
ExpireTime string `json:"expireTime"`
}
if err := cl.credentialsAPIRequest(c, fmt.Sprintf("projects/-/serviceAccounts/%s", url.QueryEscape(serviceAccount)), "generateAccessToken", &body, &resp); err != nil {
return nil, err
}
expires, err := time.Parse(time.RFC3339, resp.ExpireTime)
if err != nil {
err = fmt.Errorf("Unable to parse 'expireTime': %s", resp.ExpireTime)
logging.WithError(err).Errorf(c, "Bad token endpoint response, unable to parse expireTime")
return nil, err
}
return &oauth2.Token{
AccessToken: resp.AccessToken,
TokenType: tokenType,
Expiry: expires.UTC(),
}, nil
}
// iamAPIRequest performs HTTP POST to the core IAM API endpoint.
func (cl *Client) iamAPIRequest(c context.Context, resource, action string, body, resp interface{}) error {
if cl.BasePath != "" {
// We are in "testing"
base, err := url.Parse(cl.BasePath)
if err != nil {
return err
}
return cl.genericAPIRequest(c, base, resource, action, body, resp)
}
return cl.genericAPIRequest(c, DefaultIamBaseURL, resource, action, body, resp)
}
// credentialsAPIRequest performs HTTP POST to the IAM credentials API endpoint.
func (cl *Client) credentialsAPIRequest(c context.Context, resource, action string, body, resp interface{}) error {
if cl.BasePath != "" {
// We are in "testing"
base, err := url.Parse(cl.BasePath)
if err != nil {
return err
}
return cl.genericAPIRequest(c, base, resource, action, body, resp)
}
return cl.genericAPIRequest(c, DefaultAccountCredentialsBaseURL, resource, action, body, resp)
}
// genericAPIRequest performs HTTP POST to an IAM API endpoint.
func (cl *Client) genericAPIRequest(c context.Context, base *url.URL, resource, action string, body, resp interface{}) error {
query, err := url.Parse(fmt.Sprintf("v1/%s:%s?alt=json", resource, action))
if err != nil {
return err
}
endpoint := base.ResolveReference(query)
// Serialize the body.
var reader io.Reader
if body != nil {
blob, err := json.Marshal(body)
if err != nil {
return err
}
reader = bytes.NewReader(blob)
}
// Issue the request
req, err := http.NewRequest("POST", endpoint.String(), reader)
if err != nil {
return err
}
if reader != nil {
req.Header.Set("Content-Type", "application/json")
}
// Send and handle errors. This is roughly how google-api-go-client calls
// methods. CheckResponse returns *googleapi.Error.
logging.Debugf(c, "POST %s", endpoint)
res, err := ctxhttp.Do(c, cl.Client, req)
if err != nil {
return err
}
defer googleapi.CloseBody(res)
if err := googleapi.CheckResponse(res); err != nil {
logging.WithError(err).Errorf(c, "POST %s failed", endpoint)
return err
}
return json.NewDecoder(res.Body).Decode(resp)
}
|
s6530085/Algorithm4th
|
src/me/sunmin/algs4/Ch1_02_10.java
|
<gh_stars>0
package me.sunmin.algs4;
import edu.princeton.cs.algs4.Counter;
import edu.princeton.cs.algs4.StdDraw;
public class Ch1_02_10 {
private class VisualCounter {
private int count;
private int op;
public VisualCounter(int N, int max) {
StdDraw.setXscale(0, N);
StdDraw.setYscale(-Math.abs(max), Math.abs(max));
}
void increment() {
count++;
op++;
StdDraw.point(op, count);
}
void decrement() {
count--;
op++;
StdDraw.point(op, count);
}
int tally() {
return count;
}
public String toString() {
return "count is " + count;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Counter c = new Counter("");
}
}
|
madmax2612/rajyug_solutions
|
src/components/Sidebar/Sidebar.js
|
<reponame>madmax2612/rajyug_solutions<gh_stars>0
/*eslint-disable*/
import React from "react";
import classNames from "classnames";
import PropTypes from "prop-types";
import { NavLink } from "react-router-dom";
// @material-ui/core components
import { makeStyles } from "@material-ui/core/styles";
import Drawer from "@material-ui/core/Drawer";
import Hidden from "@material-ui/core/Hidden";
import { List, Collapse, Typography, Container } from "@material-ui/core";
import ListItem from "@material-ui/core/ListItem";
import ListItemText from "@material-ui/core/ListItemText";
import Icon from "@material-ui/core/Icon";
// core components
import AdminNavbarLinks from "components/Navbars/AdminNavbarLinks.js";
import RTLNavbarLinks from "components/Navbars/RTLNavbarLinks.js";
import styles from "assets/jss/material-dashboard-react/components/sidebarStyle.js";
import DashboardIcon from '@material-ui/icons/Dashboard';
import PersonIcon from '@material-ui/icons/Person';
import Home from "@material-ui/icons/Home";
import Stars from "@material-ui/icons/Stars";
import Redeem from '@material-ui/icons/Redeem';
import ListAltIcon from '@material-ui/icons/ListAlt';
import '../../stylee.css';
import ArrowRightIcon from '@material-ui/icons/ArrowRight';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import ExpansionPanel from '@material-ui/core/ExpansionPanel';
// import ExpansionPanelDetails from '@material-ui/core/ExpansionPanelDetails';
import ExpansionPanelSummary from '@material-ui/core/ExpansionPanelSummary';
import TocIcon from '@material-ui/icons/Toc';
import UserSeg from "views/UserSegment/Ublock";
import { Link } from 'react-router-dom';
import '../../stylee.css';
const useStyles = makeStyles(styles);
export default function Sidebar(props) {
const classes = useStyles();
const [expanded1, setExpanded1] = React.useState(false);
const [expanded2, setExpanded2] = React.useState(false);
const [expanded3, setExpanded3] = React.useState(false);
const [expanded4, setExpanded4] = React.useState(false);
const [expanded5, setExpanded5] = React.useState(false);
const [expanded7, setExpanded7] = React.useState(false);
const [expanded11, setExpande11] = React.useState(false);
// const [expanded7, setExpanded7] = React.useState(false);
const [expanded6_1, setExpanded6_1] = React.useState(false);
const [expanded6_2, setExpanded6_2] = React.useState(false);
const handleChange1 = (panel) => (event, isExpanded) => {
setExpanded1(isExpanded ? panel : false);
};
const handleChange2 = (panel) => (event, isExpanded) => {
setExpanded2(isExpanded ? panel : false);
};
const handleChange3 = (panel) => (event, isExpanded) => {
setExpanded3(isExpanded ? panel : false);
};
const handleChange4 = (panel) => (event, isExpanded) => {
setExpanded4(isExpanded ? panel : false);
};
const handleChange5 = (panel) => (event, isExpanded) => {
setExpanded5(isExpanded ? panel : false);
};
const handleChange6 = (panel) => (event, isExpanded) => {
setExpanded6(isExpanded ? panel : false);
};
const handleChange6_1 = (panel) => (event, isExpanded) => {
setExpanded6_1(isExpanded ? panel : false);
};
const handleChange6_2 = (panel) => (event, isExpanded) => {
setExpanded6_2(isExpanded ? panel : false);
};
const handleChange7 = (panel) => (event, isExpanded) => {
setExpanded7(isExpanded ? panel : false);
};
const handleChange11 = (panel) => (event, isExpanded) => {
setExpanded11(isExpanded ? panel : false);
};
// verifies if routeName is the one active (in browser input)
function activeRoute(routeName) {
return window.location.href.indexOf(routeName) > -1 ? true : false;
}
const { color, logo, image, logoText, routes, routes1, routes2, routes3, routes4, routes5, routes6, routes7 } = props;
var Dashboard = (
<List className={classes.list}>
{routes.map((prop, key) => {
var activePro = " ";
var listItemClasses;
if (prop.path === "/upgrade-to-pro") {
activePro = classes.activePro + " ";
listItemClasses = classNames({
[" " + classes[color]]: true
});
} else {
listItemClasses = classNames({
[" " + classes[color]]: activeRoute(prop.layout + prop.path)
});
}
const whiteFontClasses = classNames({
[" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
});
const display = prop.name === "Dashboard" ? { display:"none" } : {display: "block"}
return (
<NavLink
to={prop.layout + prop.path}
className={activePro + classes.item}
activeClassName="active"
key={key}
>
{typeof prop.icon && prop.name!==''?
<ListItem style={display} button className={classes.itemLink + listItemClasses}>
{typeof prop.icon === "string" ? (
<Icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
>
{prop.icon}
</Icon>
) : (
<prop.icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
/>
)}
<ListItemText
primary={props.rtlActive ? prop.rtlName : prop.name}
className={classNames(classes.itemText, whiteFontClasses, {
[classes.itemTextRTL]: props.rtlActive
})}
disableTypography={true}
/>
</ListItem>
:null}
</NavLink>
);
})}
</List>
);
var Users = (
<List className={classes.list}>
{routes1.map((prop, key) => {
var activePro = " ";
var listItemClasses;
if (prop.path === "/upgrade-to-pro") {
activePro = classes.activePro + " ";
listItemClasses = classNames({
[" " + classes[color]]: true
});
} else {
listItemClasses = classNames({
[" " + classes[color]]: activeRoute(prop.layout + prop.path)
});
}
const whiteFontClasses = classNames({
[" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
});
const display = prop.name === "Users" ? { display:"none" } : {display: "block"}
return (
<NavLink
to={prop.layout + prop.path}
className={activePro + classes.item}
activeClassName="active"
key={key}
>
{typeof prop.icon && prop.name!==''?
<ListItem style={display} button className={classes.itemLink + listItemClasses}>
{typeof prop.icon === "string" ? (
<Icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
>
{prop.icon}
</Icon>
) : (
<prop.icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
/>
)}
<ListItemText
primary={props.rtlActive ? prop.rtlName : prop.name}
className={classNames(classes.itemText, whiteFontClasses, {
[classes.itemTextRTL]: props.rtlActive
})}
disableTypography={true}
/>
</ListItem>
:null}
</NavLink>
);
})}
</List>
);
var SiteAdmin = (
<List className={classes.list}>
{routes2.map((prop, key) => {
var activePro = " ";
var listItemClasses;
if (prop.path === "/upgrade-to-pro") {
activePro = classes.activePro + " ";
listItemClasses = classNames({
[" " + classes[color]]: true
});
} else {
listItemClasses = classNames({
[" " + classes[color]]: activeRoute(prop.layout + prop.path)
});
}
const whiteFontClasses = classNames({
[" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
});
const display = prop.name === "Site Admin" ? { display:"none" } : {display: "block"}
return (
<NavLink
to={prop.layout + prop.path}
className={activePro + classes.item}
activeClassName="active"
key={key}
>
{typeof prop.icon && prop.name!==''?
<ListItem style={display}button className={classes.itemLink + listItemClasses}>
{typeof prop.icon === "string" ? (
<Icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
>
{prop.icon}
</Icon>
) : (
<prop.icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
/>
)}
<ListItemText
primary={props.rtlActive ? prop.rtlName : prop.name}
className={classNames(classes.itemText, whiteFontClasses, {
[classes.itemTextRTL]: props.rtlActive
})}
disableTypography={true}
/>
</ListItem>
:null}
</NavLink>
);
})}
</List>
);
// var Tier = (
// <List className={classes.list}>
// {routes3.map((prop, key) => {
// var activePro = " ";
// var listItemClasses;
// if (prop.path === "/upgrade-to-pro") {
// activePro = classes.activePro + " ";
// listItemClasses = classNames({
// [" " + classes[color]]: true
// });
// } else {
// listItemClasses = classNames({
// [" " + classes[color]]: activeRoute(prop.layout + prop.path)
// });
// }
// const whiteFontClasses = classNames({
// [" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
// });
// const display = prop.name === "Tier" ? { display:"none" } : {display: "block"}
// return (
// <NavLink
// to={prop.layout + prop.path}
// className={activePro + classes.item}
// activeClassName="active"
// key={key}
// >
// <ListItem style={ display}button className={classes.itemLink + listItemClasses}>
// {typeof prop.icon === "string" ? (
// <Icon
// className={classNames(classes.itemIcon, whiteFontClasses, {
// [classes.itemIconRTL]: props.rtlActive
// })}
// >
// {prop.icon}
// </Icon>
// ) : (
// <prop.icon
// className={classNames(classes.itemIcon, whiteFontClasses, {
// [classes.itemIconRTL]: props.rtlActive
// })}
// />
// )}
// <ListItemText
// primary={props.rtlActive ? prop.rtlName : prop.name}
// className={classNames(classes.itemText, whiteFontClasses, {
// [classes.itemTextRTL]: props.rtlActive
// })}
// disableTypography={true}
// />
// </ListItem>
// </NavLink>
// );
// })}
// </List>
// );
var Advertisement =(
<List className={classes.list}>
{routes7.map((prop, key) => {
console.log(prop);
var activePro = " ";
var listItemClasses;
if (prop.path === "/upgrade-to-pro") {
activePro = classes.activePro + " ";
listItemClasses = classNames({
[" " + classes[color]]: true
});
} else {
listItemClasses = classNames({
[" " + classes[color]]: activeRoute(prop.layout + prop.path)
});
}
const whiteFontClasses = classNames({
[" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
});
const display = prop.name === "Advertisement" ? { display:"none" } : {display: "block"}
return (
<NavLink
to={prop.layout + prop.path}
className={activePro + classes.item}
activeClass
Name="active"
key={key}
>
{typeof prop.icon && prop.name!==''?
<ListItem style={display} button className={classes.itemLink + listItemClasses}>
{typeof prop.icon === "string" ? (
<Icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
>
{prop.icon}
</Icon>
) : (
<prop.icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
/>
)}
<ListItemText
primary={props.rtlActive ? prop.rtlName : prop.name}
className={classNames(classes.itemText, whiteFontClasses, {
[classes.itemTextRTL]: props.rtlActive
})}
disableTypography={true}
/>
</ListItem>:null}
</NavLink>
);
})}
</List>
)
var Rewards = (
<List className={classes.list}>
{routes4.map((prop, key) => {
var activePro = " ";
var listItemClasses;
if (prop.path === "/upgrade-to-pro") {
activePro = classes.activePro + " ";
listItemClasses = classNames({
[" " + classes[color]]: true
});
} else {
listItemClasses = classNames({
[" " + classes[color]]: activeRoute(prop.layout + prop.path)
});
}
const whiteFontClasses = classNames({
[" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
});
const display = prop.name === "Rewards" ? { display:"none" } : {display: "block"}
return (
<NavLink
to={prop.layout + prop.path}
className={activePro + classes.item}
activeClassName="active"
key={key}
>
{ typeof prop.icon && prop.name!==''?
<ListItem style={display} button className={classes.itemLink + listItemClasses}>
{typeof prop.icon === "string" ? (
<Icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
>
{prop.icon}
</Icon>
) : (
<prop.icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
/>
)}
<ListItemText
primary={props.rtlActive ? prop.rtlName : prop.name}
className={classNames(classes.itemText, whiteFontClasses, {
[classes.itemTextRTL]: props.rtlActive
})}
disableTypography={true}
/>
</ListItem>:null}
</NavLink>
);
})}
</List>
);
var Useg = (
<List className={classes.list}>
{routes5.map((prop, key) => {
var activePro = " ";
var listItemClasses;
if (prop.path === "/upgrade-to-pro") {
activePro = classes.activePro + " ";
listItemClasses = classNames({
[" " + classes[color]]: true
});
} else {
listItemClasses = classNames({
[" " + classes[color]]: activeRoute(prop.layout + prop.path)
});
}
const whiteFontClasses = classNames({
[" " + classes.whiteFont]: activeRoute(prop.layout + prop.path)
});
return (
<NavLink
to={prop.layout + prop.path}
className={activePro + classes.item}
activeClassName="active"
key={key}
>
{typeof prop.icon!=='' && prop.name!==''?
<ListItem button className={classes.itemLink + listItemClasses}>
{typeof prop.icon === "string" ? (
<Icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
>
{prop.icon}
</Icon>
) : (
<prop.icon
className={classNames(classes.itemIcon, whiteFontClasses, {
[classes.itemIconRTL]: props.rtlActive
})}
/>
)}
<ListItemText
primary={props.rtlActive ? prop.rtlName : prop.name}
className={classNames(classes.itemText, whiteFontClasses, {
[classes.itemTextRTL]: props.rtlActive
})}
disableTypography={true}
/>
</ListItem>
:null}
</NavLink>
);
})}
</List>
);
var brand = (
<div className={classes.logo}>
<a
className={classNames(classes.logoLink, {
[classes.logoLinkRTL]: props.rtlActive
})}
target="_blank"
>
<div className={classes.logoImage}>
<img src={"https://rajyugsolutions.com/wp-content/uploads/2020/04/soil_new.png"} alt="logo" className={classes.img} />
</div>
</a>
</div>
);
return (
<div>
<Hidden mdUp implementation="css">
<Drawer
variant="temporary"
anchor={props.rtlActive ? "left" : "right"}
open={props.open}
classes={{
paper: classNames(classes.drawerPaper, {
[classes.drawerPaperRTL]: props.rtlActive
})
}}
onClose={props.handleDrawerToggle}
ModalProps={{
keepMounted: true // Better open performance on mobile.
}}
>
{brand}
<div className={classes.sidebarWrapper}>
{props.rtlActive ? <RTLNavbarLinks /> : <AdminNavbarLinks />}
<ExpansionPanel className={classes.list1}
expanded1={expanded1 === 'panel1'} onChange={handleChange1('panel1')} >
<ExpansionPanelSummary
>
<Home style={{ color: 'white', marginRight: 15 }} />
<Link to="admin/dashboard"> <Typography style={{ color: 'white' }} >Dashboard</Typography></Link>
</ExpansionPanelSummary>
{Dashboard}
</ExpansionPanel>
{/* <ExpansionPanel className={classes.list1}
expanded7={expanded7 === 'panel1'} onChange={handleChange7('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<DashboardIcon style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/ucreate"> <Typography style={{ color: 'white' }} >User Segment</Typography></Link>
</ExpansionPanelSummary>
{Useg}
</ExpansionPanel> */}
<ExpansionPanel className={classes.list1}
expanded2={expanded2 === 'panel1'} onChange={handleChange2('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<PersonIcon style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/useruserview"> <Typography style={{ color: 'white' }} >Users</Typography> </Link>
</ExpansionPanelSummary>
{Users}
</ExpansionPanel>
<ExpansionPanel className={classes.list1}
expanded3={expanded3 === 'panel1'} onChange={handleChange3('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<PersonIcon style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/sadmin"> <Typography style={{ color: 'white' }} > Site Admin</Typography></Link>
</ExpansionPanelSummary>
{SiteAdmin}
</ExpansionPanel>
{/* <ExpansionPanel className={classes.list1}
expanded4={expanded4 === 'panel1'} onChange={handleChange4('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Stars style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/tier1"> <Typography style={{ color: 'white' }} >Tier</Typography></Link>
</ExpansionPanelSummary>
{Tier}
</ExpansionPanel> */}
<ExpansionPanel className={classes.list1}
expanded5={expanded5 === 'panel1'} onChange={handleChange5('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Redeem style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/advt"> <Typography style={{ color: 'white' }} >Advertisement</Typography></Link>
</ExpansionPanelSummary>
{Advertisement}
</ExpansionPanel>
<ExpansionPanel className={classes.list1}
expanded5={expanded5 === 'panel1'} onChange={handleChange5('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Redeem style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/rewards"> <Typography style={{ color: 'white' }} >Rewards</Typography></Link>
</ExpansionPanelSummary>
{Rewards}
</ExpansionPanel>
</div>
{image !== undefined ? (
<div
className={classes.background}
style={{ backgroundImage: "url(" + image + ")" }}
/>
) : null}
</Drawer>
</Hidden>
{/* ///////////////////// Sidebar For Web Start //////////////////////////////////// */}
<Hidden smDown implementation="css">
<Drawer
anchor={props.rtlActive ? "right" : "left"}
variant="permanent"
open
classes={{
paper: classNames(classes.drawerPaper, {
[classes.drawerPaperRTL]: props.rtlActive
})
}}
>
{brand}
<div className={classes.sidebarWrapper}>
<div className="makeStyles-item-16">
<ExpansionPanel className={classes.list1}
expanded1={expanded1 === 'panel1'} onChange={handleChange1('panel1')} >
<ExpansionPanelSummary
>
<Home style={{ color: 'white', marginRight: 15 }} />
<div >
<Link to="admin/dashboard"> <Typography style={{ color: 'white'}} >Dashboard</Typography></Link>
</div>
</ExpansionPanelSummary>
{Dashboard}
</ExpansionPanel>
</div>
{/* <ExpansionPanel className={classes.list1}
expanded7={expanded7 === 'panel1'} onChange={handleChange7('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<DashboardIcon style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/view"> <Typography style={{ color: 'white' }} >User Segment</Typography></Link>
</ExpansionPanelSummary>
{Useg}
</ExpansionPanel> */}
<ExpansionPanel className={classes.list1}
expanded2={expanded2 === 'panel1'} onChange={handleChange2('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<PersonIcon style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/useruserview"> <Typography style={{ color: 'white' }} >Users</Typography> </Link>
</ExpansionPanelSummary>
{Users}
</ExpansionPanel>
<ExpansionPanel className={classes.list1}
expanded3={expanded3 === 'panel1'} onChange={handleChange3('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<PersonIcon style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/sadmin"> <Typography style={{ color: 'white' }} >Site Admin</Typography></Link>
</ExpansionPanelSummary>
{SiteAdmin}
</ExpansionPanel>
<ExpansionPanel className={classes.list1}
expanded5={expanded5 === 'panel1'} onChange={handleChange5('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Redeem style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/advt"> <Typography style={{ color: 'white' }} >Advertisement</Typography></Link>
</ExpansionPanelSummary>
{Advertisement}
</ExpansionPanel>
{/* <ExpansionPanel className={classes.list1}
expanded4={expanded4 === 'panel1'} onChange={handleChange4('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Stars style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/tier1"> <Typography style={{ color: 'white' }} >Tier</Typography></Link>
</ExpansionPanelSummary>
{Tier}
</ExpansionPanel> */}
<ExpansionPanel className={classes.list1}
expanded5={expanded5 === 'panel1'} onChange={handleChange5('panel1')} >
<ExpansionPanelSummary
expandIcon={<ExpandMoreIcon style={{ color: 'white' }} />}
// aria-controls="panel1bh-content"
id="panel1bh-header"
>
<Redeem style={{ color: 'white', marginRight: 15 }} />
<Link to="/admin/rewards"> <Typography style={{ color: 'white' }} >Rewards</Typography></Link>
</ExpansionPanelSummary>
{Rewards}
</ExpansionPanel>
</div> {/* ////////// */}
{image !== undefined ? (
<div
className={classes.background}
style={{ backgroundImage: "url(" + image + ")" }}
/>
) : null}
</Drawer>
</Hidden>
</div>
);
}
Sidebar.propTypes = {
rtlActive: PropTypes.bool,
handleDrawerToggle: PropTypes.func,
bgColor: PropTypes.oneOf(["purple", "blue", "green", "orange", "red"]),
logo: PropTypes.string,
image: PropTypes.string,
logoText: PropTypes.string,
routes: PropTypes.arrayOf(PropTypes.object),
routes1: PropTypes.arrayOf(PropTypes.object),
routes2: PropTypes.arrayOf(PropTypes.object),
routes3: PropTypes.arrayOf(PropTypes.object),
routes4: PropTypes.arrayOf(PropTypes.object),
open: PropTypes.bool
};
|
baodingfengyun/turbo-rpc
|
turbo-rpc/src/main/java/rpc/turbo/invoke/JavassistInvoker.java
|
<reponame>baodingfengyun/turbo-rpc<filename>turbo-rpc/src/main/java/rpc/turbo/invoke/JavassistInvoker.java
package rpc.turbo.invoke;
import javassist.*;
import rpc.turbo.param.EmptyMethodParam;
import rpc.turbo.param.MethodParam;
import rpc.turbo.param.MethodParamClassFactory;
import rpc.turbo.util.SingleClassLoader;
import rpc.turbo.util.TypeUtils;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.UUID;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import static rpc.turbo.util.SourceCodeUtils.*;
/**
* high performance invoker
*
* @param <T> the method return type
* @author <EMAIL>
*/
public class JavassistInvoker<T> implements Invoker<T> {
private static final String NOT_SUPPORT_PARAMETER_NAME_MSG = "must turn on \"Store information about method parameters (usable via reflection)\", see https://www.concretepage.com/java/jdk-8/java-8-reflection-access-to-parameter-names-of-method-and-constructor-with-maven-gradle-and-eclipse-using-parameters-compiler-argument";
final int serviceId;
private final Object service;
final Class<?> clazz;
final Method method;
private final Class<?>[] parameterTypes;
private final String[] parameterNames;
private final int parameterCount;
final Class<? extends MethodParam> methodParamClass;
private final Invoker<T> realInvoker;
private final boolean supportHttpForm;
/**
* @param serviceId
* @param service the service implemention
* @param clazz the service interface
* @param method
* @throws InvokeException
*/
public JavassistInvoker(int serviceId, Object service, Class<?> clazz, Method method) {
this.serviceId = serviceId;
this.service = service;
this.clazz = clazz;
this.method = method;
this.parameterTypes = method.getParameterTypes();
this.parameterCount = parameterTypes.length;
if (service == null) {
throw new InvokeException("service cannot be null");
}
if (!clazz.equals(method.getDeclaringClass())) {
throw new InvokeException(clazz + " have no method: " + method);
}
if (!Modifier.isPublic(clazz.getModifiers())) {
throw new InvokeException("the method must be public");
}
try {
methodParamClass = MethodParamClassFactory.createClass(method);
} catch (Exception e) {
throw new InvokeException(e);
}
try {
this.realInvoker = generateRealInvoker();
} catch (Exception e) {
throw new InvokeException(e);
}
boolean _supportHttpForm = true;
for (int i = 0; i < parameterCount; i++) {
Class<?> paramType = parameterTypes[i];
if (!TypeUtils.supportCast(paramType)) {
_supportHttpForm = false;
break;
}
}
supportHttpForm = _supportHttpForm;
parameterNames = new String[parameterCount];
Parameter[] parameters = method.getParameters();
for (int i = 0; i < parameterCount; i++) {
Parameter parameter = parameters[i];
if (!parameter.isNamePresent()) {
throw new RuntimeException(NOT_SUPPORT_PARAMETER_NAME_MSG);
}
parameterNames[i] = parameter.getName();
}
}
/**
* @throws InvokeException
*/
@Override
public T invoke(Object... params) {
if (params == null) {
if (parameterCount != 0) {
throw new InvokeException(method.getName() + " params count error, params is null");
}
} else if (parameterCount != params.length) {
throw new InvokeException(method.getName() + " params count error, " + Arrays.toString(params));
}
return realInvoker.invoke(params);
}
@Override
public T invoke() {
return realInvoker.invoke();
}
public T invoke(MethodParam methodParam) {
if (methodParam == null || methodParam instanceof EmptyMethodParam) {
return realInvoker.invoke();
}
if (!methodParamClass.isInstance(methodParam)) {
throw new IllegalArgumentException("methodParam not instanceof " + methodParamClass.getName());
}
return realInvoker.invoke(methodParam);
}
@Override
public T invoke(Object params0) {
return realInvoker.invoke(params0);
}
@Override
public T invoke(Object param0, Object param1) {
return realInvoker.invoke(param0, param1);
}
@Override
public T invoke(Object param0, Object param1, Object param2) {
return realInvoker.invoke(param0, param1, param2);
}
@Override
public T invoke(Object param0, Object param1, Object param2, Object param3) {
return realInvoker.invoke(param0, param1, param2, param3);
}
@Override
public T invoke(Object param0, Object param1, Object param2, Object param3, Object param4) {
return realInvoker.invoke(param0, param1, param2, param3, param4);
}
@Override
public T invoke(Object param0, Object param1, Object param2, Object param3, Object param4, Object param5) {
return realInvoker.invoke(param0, param1, param2, param3, param4, param5);
}
@Override
public int getServiceId() {
return serviceId;
}
@Override
public Method getMethod() {
return method;
}
@Override
public Class<?>[] getParameterTypes() {
return parameterTypes;
}
@Override
public String[] getParameterNames() {
return parameterNames;
}
@Override
public Class<? extends MethodParam> getMethodParamClass() {
return methodParamClass;
}
@Override
public boolean supportHttpForm() {
return supportHttpForm;
}
private Invoker<T> generateRealInvoker() throws Exception {
final String invokerClassName = "rpc.turbo.invoke.generate.Invoker_"//
+ serviceId + "_" //
+ UUID.randomUUID().toString().replace("-", "");
// 创建类
ClassPool pool = ClassPool.getDefault();
CtClass invokerCtClass = pool.makeClass(invokerClassName);
invokerCtClass.setInterfaces(new CtClass[]{pool.getCtClass(Invoker.class.getName())});
// 添加私有成员service
CtField serviceField = new CtField(pool.get(service.getClass().getName()), "service", invokerCtClass);
serviceField.setModifiers(Modifier.PRIVATE | Modifier.FINAL);
invokerCtClass.addField(serviceField);
// 添加有参的构造函数
CtConstructor constructor = new CtConstructor(new CtClass[]{pool.get(service.getClass().getName())},
invokerCtClass);
constructor.setBody("{$0.service = $1;}");
invokerCtClass.addConstructor(constructor);
{// 添加MethodParam方法
StringBuilder methodBuilder = new StringBuilder();
StringBuilder resultBuilder = new StringBuilder();
methodBuilder.append("public Object invoke(rpc.turbo.param.MethodParam methodParam) {\r\n");
if (parameterTypes.length > 0) {
// 强制类型转换
methodBuilder.append(methodParamClass.getName());
methodBuilder.append(" params = (");
methodBuilder.append(methodParamClass.getName());
methodBuilder.append(")methodParam;");
}
methodBuilder.append(" return ");
resultBuilder.append("service.");
resultBuilder.append(method.getName());
resultBuilder.append("(");
for (int i = 0; i < parameterTypes.length; i++) {
resultBuilder.append("params.$param");
resultBuilder.append(i);
resultBuilder.append("()");
if (i != parameterTypes.length - 1) {
methodBuilder.append(", ");
}
}
resultBuilder.append(")");
String resultStr = box(method.getReturnType(), resultBuilder.toString());
methodBuilder.append(resultStr);
methodBuilder.append(";\r\n}");
CtMethod m = CtNewMethod.make(methodBuilder.toString(), invokerCtClass);
invokerCtClass.addMethod(m);
}
{// 添加通用方法
StringBuilder methodBuilder = new StringBuilder();
StringBuilder resultBuilder = new StringBuilder();
methodBuilder.append("public Object invoke(Object[] params) {\r\n");
methodBuilder.append(" return ");
resultBuilder.append("service.");
resultBuilder.append(method.getName());
resultBuilder.append("(");
for (int i = 0; i < parameterTypes.length; i++) {
Class<?> paramType = parameterTypes[i];
resultBuilder.append("((");
resultBuilder.append(forceCast(paramType));
resultBuilder.append(")params[");
resultBuilder.append(i);
resultBuilder.append("])");
resultBuilder.append(unbox(paramType));
}
resultBuilder.append(")");
String resultStr = box(method.getReturnType(), resultBuilder.toString());
methodBuilder.append(resultStr);
methodBuilder.append(";\r\n}");
CtMethod m = CtNewMethod.make(methodBuilder.toString(), invokerCtClass);
invokerCtClass.addMethod(m);
}
if (parameterCount <= 6) {// just for benchmark
StringBuilder methodBuilder = new StringBuilder();
StringBuilder resultBuilder = new StringBuilder();
methodBuilder.append("public Object invoke(");
String params = IntStream//
.range(0, parameterCount)//
.mapToObj(i -> "Object param" + i)//
.collect(Collectors.joining(","));
methodBuilder.append(params);
methodBuilder.append(") {\r\n");
methodBuilder.append(" return ");
resultBuilder.append("service.");
resultBuilder.append(method.getName());
resultBuilder.append("(");
for (int i = 0; i < parameterCount; i++) {
Class<?> paramType = parameterTypes[i];
resultBuilder.append("((");
resultBuilder.append(forceCast(paramType));
resultBuilder.append(")param");
resultBuilder.append(i);
resultBuilder.append(")");
resultBuilder.append(unbox(paramType));
if (i != parameterCount - 1) {
resultBuilder.append(",");
}
}
resultBuilder.append(")");
String resultStr = box(method.getReturnType(), resultBuilder.toString());
methodBuilder.append(resultStr);
methodBuilder.append(";\r\n}");
CtMethod m = CtNewMethod.make(methodBuilder.toString(), invokerCtClass);
invokerCtClass.addMethod(m);
}
byte[] bytes = invokerCtClass.toBytecode();
Class<?> invokerClass = SingleClassLoader.loadClass(service.getClass().getClassLoader(), bytes);
// 通过反射创建有参的实例
@SuppressWarnings("unchecked")
Invoker<T> invoker = (Invoker<T>) invokerClass.getConstructor(service.getClass()).newInstance(service);
return invoker;
}
@Override
public int hashCode() {
return serviceId;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
JavassistInvoker<?> other = (JavassistInvoker<?>) obj;
if (serviceId != other.serviceId)
return false;
return true;
}
}
|
ffonseca1985/jorney-react-redux-konvajs
|
src/pages/administrator/role/newRole.js
|
import React from 'react';
import {
Row,
Col,
Card,
CardHeader,
CardBody,
Button,
Form,
FormGroup,
Label,
Container,
Input
} from 'reactstrap';
class NewRole extends React.Component {
render() {
return (
<Container>
<Row>
<Col xl={8} lg={12} md={12}>
<Card>
<CardHeader>New Role</CardHeader>
<CardBody>
<Form>
<FormGroup>
<Col sm={{ size: 10 }}>
<Label>Name Role</Label>
<Input name="role" type="text" />
</Col>
</FormGroup>
<FormGroup>
<Col sm={{ size: 10 }}>
<Label>Description</Label>
<Input name="description" type="text" />
</Col>
</FormGroup>
<FormGroup check row>
<Col sm={{ size: 10 }}>
<Button>Create</Button>
</Col>
</FormGroup>
</Form>
</CardBody>
</Card>
</Col>
</Row>
</Container>
)
}
}
export default NewRole;
|
MahendraSondagar/STMicroelectronics
|
SensorTile/STM32CubeFunctionPack_SENSING1_V4.0.2/Projects/STM32L476RG-Nucleo/Applications/SENSING1/Src/har_ign_wsdm.c
|
<reponame>MahendraSondagar/STMicroelectronics
/**
******************************************************************************
* @file har_ign_wsdm.c
* @author AST Embedded Analytics Research Platform
* @date Tue Oct 15 11:25:12 2019
* @brief AI Tool Automatic Code Generator for Embedded NN computing
******************************************************************************
* @attention
*
* Copyright (c) 2018 STMicroelectronics.
* All rights reserved.
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include "har_ign_wsdm.h"
#include "ai_platform_interface.h"
#include "ai_math_helpers.h"
#include "core_common.h"
#include "layers.h"
#undef AI_TOOLS_VERSION_MAJOR
#undef AI_TOOLS_VERSION_MINOR
#undef AI_TOOLS_VERSION_MICRO
#define AI_TOOLS_VERSION_MAJOR 4
#define AI_TOOLS_VERSION_MINOR 1
#define AI_TOOLS_VERSION_MICRO 0
#undef AI_TOOLS_API_VERSION_MAJOR
#undef AI_TOOLS_API_VERSION_MINOR
#undef AI_TOOLS_API_VERSION_MICRO
#define AI_TOOLS_API_VERSION_MAJOR 1
#define AI_TOOLS_API_VERSION_MINOR 3
#define AI_TOOLS_API_VERSION_MICRO 0
#undef AI_NET_OBJ_INSTANCE
#define AI_NET_OBJ_INSTANCE g_har_ign_wsdm
#undef AI_HAR_IGN_WSDM_MODEL_SIGNATURE
#define AI_HAR_IGN_WSDM_MODEL_SIGNATURE "156fec2c9716d991c6dcbe5ac8b0053f"
#ifndef AI_TOOLS_REVISION_ID
#define AI_TOOLS_REVISION_ID "(rev-4.1.0)"
#endif
#undef AI_TOOLS_DATE_TIME
#define AI_TOOLS_DATE_TIME "Tue Oct 15 11:25:12 2019"
#undef AI_TOOLS_COMPILE_TIME
#define AI_TOOLS_COMPILE_TIME __DATE__ " " __TIME__
#undef AI_HAR_IGN_WSDM_N_BATCHES
#define AI_HAR_IGN_WSDM_N_BATCHES (1)
/** Forward network declaration section *************************************/
AI_STATIC ai_network AI_NET_OBJ_INSTANCE;
/** Forward network array declarations **************************************/
AI_STATIC ai_array conv2d_1_scratch0_array; /* Array #0 */
AI_STATIC ai_array dense_2_bias_array; /* Array #1 */
AI_STATIC ai_array dense_2_weights_array; /* Array #2 */
AI_STATIC ai_array dense_1_bias_array; /* Array #3 */
AI_STATIC ai_array dense_1_weights_array; /* Array #4 */
AI_STATIC ai_array conv2d_1_bias_array; /* Array #5 */
AI_STATIC ai_array conv2d_1_weights_array; /* Array #6 */
AI_STATIC ai_array input_0_output_array; /* Array #7 */
AI_STATIC ai_array conv2d_1_output_array; /* Array #8 */
AI_STATIC ai_array dense_1_output_array; /* Array #9 */
AI_STATIC ai_array dense_2_output_array; /* Array #10 */
AI_STATIC ai_array dense_2_nl_output_array; /* Array #11 */
/** Forward network tensor declarations *************************************/
AI_STATIC ai_tensor conv2d_1_scratch0; /* Tensor #0 */
AI_STATIC ai_tensor dense_2_bias; /* Tensor #1 */
AI_STATIC ai_tensor dense_2_weights; /* Tensor #2 */
AI_STATIC ai_tensor dense_1_bias; /* Tensor #3 */
AI_STATIC ai_tensor dense_1_weights; /* Tensor #4 */
AI_STATIC ai_tensor conv2d_1_bias; /* Tensor #5 */
AI_STATIC ai_tensor conv2d_1_weights; /* Tensor #6 */
AI_STATIC ai_tensor input_0_output; /* Tensor #7 */
AI_STATIC ai_tensor conv2d_1_output; /* Tensor #8 */
AI_STATIC ai_tensor conv2d_1_output0; /* Tensor #9 */
AI_STATIC ai_tensor dense_1_output; /* Tensor #10 */
AI_STATIC ai_tensor dense_2_output; /* Tensor #11 */
AI_STATIC ai_tensor dense_2_nl_output; /* Tensor #12 */
/** Forward network tensor chain declarations *******************************/
AI_STATIC_CONST ai_tensor_chain conv2d_1_chain; /* Chain #0 */
AI_STATIC_CONST ai_tensor_chain dense_1_chain; /* Chain #1 */
AI_STATIC_CONST ai_tensor_chain dense_2_chain; /* Chain #2 */
AI_STATIC_CONST ai_tensor_chain dense_2_nl_chain; /* Chain #3 */
/** Subgraph network operator tensor chain declarations *********************/
/** Subgraph network operator declarations *********************************/
/** Forward network layer declarations **************************************/
AI_STATIC ai_layer_conv2d_nl_pool conv2d_1_layer; /* Layer #0 */
AI_STATIC ai_layer_dense dense_1_layer; /* Layer #1 */
AI_STATIC ai_layer_dense dense_2_layer; /* Layer #2 */
AI_STATIC ai_layer_nl dense_2_nl_layer; /* Layer #3 */
/** Array declarations section **********************************************/
AI_ARRAY_OBJ_DECLARE(
conv2d_1_scratch0_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 216,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_2_bias_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 4,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_2_weights_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 48,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_1_bias_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 12,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_1_weights_array, AI_ARRAY_FORMAT_LUT8_FLOAT,
NULL, NULL, 2592,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
conv2d_1_bias_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 24,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
conv2d_1_weights_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 384,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
input_0_output_array, AI_ARRAY_FORMAT_FLOAT|AI_FMT_FLAG_IS_IO,
NULL, NULL, 72,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
conv2d_1_output_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 216,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_1_output_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 12,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_2_output_array, AI_ARRAY_FORMAT_FLOAT,
NULL, NULL, 4,
AI_STATIC)
AI_ARRAY_OBJ_DECLARE(
dense_2_nl_output_array, AI_ARRAY_FORMAT_FLOAT|AI_FMT_FLAG_IS_IO,
NULL, NULL, 4,
AI_STATIC)
/** Tensor declarations section *********************************************/
AI_TENSOR_OBJ_DECLARE(
conv2d_1_scratch0, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 24, 3, 3), AI_STRIDE_INIT(4, 4, 4, 96, 288),
1, &conv2d_1_scratch0_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_2_bias, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 4, 1, 1), AI_STRIDE_INIT(4, 4, 4, 16, 16),
1, &dense_2_bias_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_2_weights, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 12, 4, 1, 1), AI_STRIDE_INIT(4, 4, 48, 192, 192),
1, &dense_2_weights_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_1_bias, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 12, 1, 1), AI_STRIDE_INIT(4, 4, 4, 48, 48),
1, &dense_1_bias_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_1_weights, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 216, 12, 1, 1), AI_STRIDE_INIT(4, 1, 216, 2592, 2592),
1, &dense_1_weights_array, NULL)
AI_TENSOR_OBJ_DECLARE(
conv2d_1_bias, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 24, 1, 1), AI_STRIDE_INIT(4, 4, 4, 96, 96),
1, &conv2d_1_bias_array, NULL)
AI_TENSOR_OBJ_DECLARE(
conv2d_1_weights, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 1, 16, 24), AI_STRIDE_INIT(4, 4, 4, 4, 64),
1, &conv2d_1_weights_array, NULL)
AI_TENSOR_OBJ_DECLARE(
input_0_output, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 1, 3, 24), AI_STRIDE_INIT(4, 4, 4, 4, 12),
1, &input_0_output_array, NULL)
AI_TENSOR_OBJ_DECLARE(
conv2d_1_output, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 24, 3, 3), AI_STRIDE_INIT(4, 4, 4, 96, 288),
1, &conv2d_1_output_array, NULL)
AI_TENSOR_OBJ_DECLARE(
conv2d_1_output0, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 216, 1, 1), AI_STRIDE_INIT(4, 4, 4, 864, 864),
1, &conv2d_1_output_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_1_output, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 12, 1, 1), AI_STRIDE_INIT(4, 4, 4, 48, 48),
1, &dense_1_output_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_2_output, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 4, 1, 1), AI_STRIDE_INIT(4, 4, 4, 16, 16),
1, &dense_2_output_array, NULL)
AI_TENSOR_OBJ_DECLARE(
dense_2_nl_output, AI_STATIC,
0x0, 0x0, AI_SHAPE_INIT(4, 1, 4, 1, 1), AI_STRIDE_INIT(4, 4, 4, 16, 16),
1, &dense_2_nl_output_array, NULL)
/** Layer declarations section **********************************************/
AI_TENSOR_CHAIN_OBJ_DECLARE(
conv2d_1_chain, AI_STATIC_CONST, 4,
AI_TENSOR_LIST_ENTRY(&input_0_output),
AI_TENSOR_LIST_ENTRY(&conv2d_1_output),
AI_TENSOR_LIST_ENTRY(&conv2d_1_weights, &conv2d_1_bias, NULL),
AI_TENSOR_LIST_ENTRY(&conv2d_1_scratch0)
)
AI_LAYER_OBJ_DECLARE(
conv2d_1_layer, 0,
OPTIMIZED_CONV2D_TYPE,
conv2d_nl_pool, forward_conv2d_nl_pool,
&AI_NET_OBJ_INSTANCE, &dense_1_layer, AI_STATIC,
.tensors = &conv2d_1_chain,
.groups = 1,
.nl_func = nl_func_relu_array_f32,
.filter_stride = AI_SHAPE_2D_INIT(1, 1),
.dilation = AI_SHAPE_2D_INIT(1, 1),
.filter_pad = AI_SHAPE_INIT(4, 0, 0, 0, 0),
.pool_size = AI_SHAPE_2D_INIT(1, 3),
.pool_stride = AI_SHAPE_2D_INIT(1, 3),
.pool_pad = AI_SHAPE_INIT(4, 0, 0, 0, 0),
.pool_func = pool_func_mp_array_f32,
)
AI_TENSOR_CHAIN_OBJ_DECLARE(
dense_1_chain, AI_STATIC_CONST, 4,
AI_TENSOR_LIST_ENTRY(&conv2d_1_output0),
AI_TENSOR_LIST_ENTRY(&dense_1_output),
AI_TENSOR_LIST_ENTRY(&dense_1_weights, &dense_1_bias),
AI_TENSOR_LIST_EMPTY
)
AI_LAYER_OBJ_DECLARE(
dense_1_layer, 3,
DENSE_TYPE,
dense, forward_dense,
&AI_NET_OBJ_INSTANCE, &dense_2_layer, AI_STATIC,
.tensors = &dense_1_chain,
)
AI_TENSOR_CHAIN_OBJ_DECLARE(
dense_2_chain, AI_STATIC_CONST, 4,
AI_TENSOR_LIST_ENTRY(&dense_1_output),
AI_TENSOR_LIST_ENTRY(&dense_2_output),
AI_TENSOR_LIST_ENTRY(&dense_2_weights, &dense_2_bias),
AI_TENSOR_LIST_EMPTY
)
AI_LAYER_OBJ_DECLARE(
dense_2_layer, 5,
DENSE_TYPE,
dense, forward_dense,
&AI_NET_OBJ_INSTANCE, &dense_2_nl_layer, AI_STATIC,
.tensors = &dense_2_chain,
)
AI_TENSOR_CHAIN_OBJ_DECLARE(
dense_2_nl_chain, AI_STATIC_CONST, 4,
AI_TENSOR_LIST_ENTRY(&dense_2_output),
AI_TENSOR_LIST_ENTRY(&dense_2_nl_output),
AI_TENSOR_LIST_EMPTY,
AI_TENSOR_LIST_EMPTY
)
AI_LAYER_OBJ_DECLARE(
dense_2_nl_layer, 5,
NL_TYPE,
nl, forward_sm,
&AI_NET_OBJ_INSTANCE, &dense_2_nl_layer, AI_STATIC,
.tensors = &dense_2_nl_chain,
)
AI_NETWORK_OBJ_DECLARE(
AI_NET_OBJ_INSTANCE, AI_STATIC,
AI_BUFFER_OBJ_INIT(AI_BUFFER_FORMAT_U8,
1, 1, 5504, 1,
NULL),
AI_BUFFER_OBJ_INIT(AI_BUFFER_FORMAT_U8,
1, 1, 1728, 1,
NULL),
AI_TENSOR_LIST_IO_ENTRY(AI_FLAG_NONE, AI_HAR_IGN_WSDM_IN_NUM, &input_0_output),
AI_TENSOR_LIST_IO_ENTRY(AI_FLAG_NONE, AI_HAR_IGN_WSDM_OUT_NUM, &dense_2_nl_output),
&conv2d_1_layer, 0, NULL)
AI_DECLARE_STATIC
ai_bool har_ign_wsdm_configure_activations(
ai_network* net_ctx, const ai_buffer* activation_buffer)
{
AI_ASSERT(net_ctx && activation_buffer && activation_buffer->data)
ai_ptr activations = AI_PTR(AI_PTR_ALIGN(activation_buffer->data, 4));
AI_ASSERT(activations)
AI_UNUSED(net_ctx)
{
/* Updating activations (byte) offsets */
conv2d_1_scratch0_array.data = AI_PTR(activations + 0);
conv2d_1_scratch0_array.data_start = AI_PTR(activations + 0);
input_0_output_array.data = AI_PTR(NULL);
input_0_output_array.data_start = AI_PTR(NULL);
conv2d_1_output_array.data = AI_PTR(activations + 864);
conv2d_1_output_array.data_start = AI_PTR(activations + 864);
dense_1_output_array.data = AI_PTR(activations + 0);
dense_1_output_array.data_start = AI_PTR(activations + 0);
dense_2_output_array.data = AI_PTR(activations + 48);
dense_2_output_array.data_start = AI_PTR(activations + 48);
dense_2_nl_output_array.data = AI_PTR(NULL);
dense_2_nl_output_array.data_start = AI_PTR(NULL);
}
return true;
}
AI_DECLARE_STATIC
ai_bool har_ign_wsdm_configure_weights(
ai_network* net_ctx, const ai_buffer* weights_buffer)
{
AI_ASSERT(net_ctx && weights_buffer && weights_buffer->data)
ai_ptr weights = AI_PTR(weights_buffer->data);
AI_ASSERT(weights)
AI_UNUSED(net_ctx)
{
/* Updating weights (byte) offsets */
dense_2_bias_array.format |= AI_FMT_FLAG_CONST;
dense_2_bias_array.data = AI_PTR(weights + 5488);
dense_2_bias_array.data_start = AI_PTR(weights + 5488);
dense_2_weights_array.format |= AI_FMT_FLAG_CONST;
dense_2_weights_array.data = AI_PTR(weights + 5296);
dense_2_weights_array.data_start = AI_PTR(weights + 5296);
dense_1_bias_array.format |= AI_FMT_FLAG_CONST;
dense_1_bias_array.data = AI_PTR(weights + 5248);
dense_1_bias_array.data_start = AI_PTR(weights + 5248);
dense_1_weights_array.format |= AI_FMT_FLAG_CONST;
dense_1_weights_array.data = AI_PTR(weights + 2656);
dense_1_weights_array.data_start = AI_PTR(weights + 1632);
conv2d_1_bias_array.format |= AI_FMT_FLAG_CONST;
conv2d_1_bias_array.data = AI_PTR(weights + 1536);
conv2d_1_bias_array.data_start = AI_PTR(weights + 1536);
conv2d_1_weights_array.format |= AI_FMT_FLAG_CONST;
conv2d_1_weights_array.data = AI_PTR(weights + 0);
conv2d_1_weights_array.data_start = AI_PTR(weights + 0);
}
return true;
}
/** PUBLIC APIs SECTION *****************************************************/
AI_API_ENTRY
ai_bool ai_har_ign_wsdm_get_info(
ai_handle network, ai_network_report* report)
{
ai_network* net_ctx = AI_NETWORK_ACQUIRE_CTX(network);
if ( report && net_ctx )
{
ai_network_report r = {
.model_name = AI_HAR_IGN_WSDM_MODEL_NAME,
.model_signature = AI_HAR_IGN_WSDM_MODEL_SIGNATURE,
.model_datetime = AI_TOOLS_DATE_TIME,
.compile_datetime = AI_TOOLS_COMPILE_TIME,
.runtime_revision = ai_platform_runtime_get_revision(),
.runtime_version = ai_platform_runtime_get_version(),
.tool_revision = AI_TOOLS_REVISION_ID,
.tool_version = {AI_TOOLS_VERSION_MAJOR, AI_TOOLS_VERSION_MINOR,
AI_TOOLS_VERSION_MICRO, 0x0},
.tool_api_version = {AI_TOOLS_API_VERSION_MAJOR, AI_TOOLS_API_VERSION_MINOR,
AI_TOOLS_API_VERSION_MICRO, 0x0},
.api_version = ai_platform_api_get_version(),
.interface_api_version = ai_platform_interface_api_get_version(),
.n_macc = 14388,
.n_inputs = 0,
.inputs = NULL,
.n_outputs = 0,
.outputs = NULL,
.activations = AI_STRUCT_INIT,
.params = AI_STRUCT_INIT,
.n_nodes = 0,
.signature = 0x0,
};
if ( !ai_platform_api_get_network_report(network, &r) ) return false;
*report = r;
return true;
}
return false;
}
AI_API_ENTRY
ai_error ai_har_ign_wsdm_get_error(ai_handle network)
{
return ai_platform_network_get_error(network);
}
AI_API_ENTRY
ai_error ai_har_ign_wsdm_create(
ai_handle* network, const ai_buffer* network_config)
{
return ai_platform_network_create(
network, network_config,
&AI_NET_OBJ_INSTANCE,
AI_TOOLS_API_VERSION_MAJOR, AI_TOOLS_API_VERSION_MINOR, AI_TOOLS_API_VERSION_MICRO);
}
AI_API_ENTRY
ai_handle ai_har_ign_wsdm_destroy(ai_handle network)
{
return ai_platform_network_destroy(network);
}
AI_API_ENTRY
ai_bool ai_har_ign_wsdm_init(
ai_handle network, const ai_network_params* params)
{
ai_network* net_ctx = ai_platform_network_init(network, params);
if ( !net_ctx ) return false;
ai_bool ok = true;
ok &= har_ign_wsdm_configure_weights(net_ctx, ¶ms->params);
ok &= har_ign_wsdm_configure_activations(net_ctx, ¶ms->activations);
return ok;
}
AI_API_ENTRY
ai_i32 ai_har_ign_wsdm_run(
ai_handle network, const ai_buffer* input, ai_buffer* output)
{
return ai_platform_network_process(network, input, output);
}
AI_API_ENTRY
ai_i32 ai_har_ign_wsdm_forward(ai_handle network, const ai_buffer* input)
{
return ai_platform_network_process(network, input, NULL);
}
#undef AI_HAR_IGN_WSDM_MODEL_SIGNATURE
#undef AI_NET_OBJ_INSTANCE
#undef AI_TOOLS_VERSION_MAJOR
#undef AI_TOOLS_VERSION_MINOR
#undef AI_TOOLS_VERSION_MICRO
#undef AI_TOOLS_API_VERSION_MAJOR
#undef AI_TOOLS_API_VERSION_MINOR
#undef AI_TOOLS_API_VERSION_MICRO
#undef AI_TOOLS_DATE_TIME
#undef AI_TOOLS_COMPILE_TIME
|
MercurieVV/stryker4s
|
core/src/test/scala/stryker4s/testutil/MockitoSuite.scala
|
package stryker4s.testutil
import org.mockito.scalatest.MockitoSugar
import org.scalatest.Suite
trait MockitoSuite extends MockitoSugar {
// Will cause a compile error if MockitoSuite is used outside of a ScalaTest Suite
this: Suite =>
}
|
go-sif/sif
|
datasource/odbc/odbc_datasource_partition_iterator.go
|
package odbc
import (
"database/sql"
"sync"
"github.com/go-sif/sif"
"github.com/go-sif/sif/datasource"
)
type odbcPartitionIterator struct {
rows *sql.Rows
hasNext bool
source *DataSource
lock sync.Mutex
endListeners []func()
}
// OnEnd registers a listener which fires when this iterator runs out of Partitions
func (opi *odbcPartitionIterator) OnEnd(onEnd func()) {
opi.lock.Lock()
defer opi.lock.Unlock()
opi.endListeners = append(opi.endListeners, onEnd)
}
// HasNextPartition returns true iff this PartitionIterator can produce another Partition
func (opi *odbcPartitionIterator) HasNextPartition() bool {
opi.lock.Lock()
defer opi.lock.Unlock()
return opi.hasNext
}
// NextPartition returns the next Partition if one is available, or an error
func (opi *odbcPartitionIterator) NextPartition() (sif.Partition, func(), error) {
opi.lock.Lock()
defer opi.lock.Unlock()
colNames := opi.source.schema.ColumnNames()
colTypes := opi.source.schema.ColumnTypes()
part := datasource.CreateBuildablePartition(opi.source.conf.PartitionSize, opi.source.schema)
scannedValues, err := generateRowTargetSlice(colNames, colTypes)
if err != nil {
return nil, nil, err
}
// parse lines
tempRow := datasource.CreateTempRow()
for {
// If the partition is full, we're done
if part.GetNumRows() == part.GetMaxRows() {
return part, nil, nil
}
// Otherwise, grab another row from the cursor
if !opi.rows.Next() {
if nextErr := opi.rows.Err(); nextErr != nil {
return nil, nil, nextErr
}
opi.hasNext = false
for _, l := range opi.endListeners {
l()
}
opi.endListeners = []func(){}
// TODO have the other side discard empty partitions
return part, nil, nil
}
// create a new partition row to place values into
targetRow, err := part.AppendEmptyRowData(tempRow)
if err != nil {
return nil, nil, err
}
err = opi.rows.Scan(scannedValues...)
if err != nil {
return nil, nil, err
}
err = loadScanIntoPartitionRow(colNames, colTypes, scannedValues, targetRow)
if err != nil {
return nil, nil, err
}
}
}
|
ckamtsikis/cmssw
|
FWCore/Framework/interface/stream/AbilityChecker.h
|
<filename>FWCore/Framework/interface/stream/AbilityChecker.h
#ifndef FWCore_Framework_AbilityChecker_h
#define FWCore_Framework_AbilityChecker_h
// -*- C++ -*-
//
// Package: FWCore/Framework
// Class : AbilityChecker
//
/**\class edm::stream::AbilityChecker AbilityChecker.h "FWCore/Framework/interface/stream/AbilityChecker.h"
Description: [one line class summary]
Usage:
<usage>
*/
//
// Original Author: <NAME>
// Created: Sat, 03 Aug 2013 15:38:02 GMT
//
// system include files
// user include files
#include "FWCore/Framework/interface/moduleAbilities.h"
// forward declarations
namespace edm {
namespace stream {
namespace impl {
struct LastCheck {};
template <typename T, typename... U>
struct HasAbility;
template <typename G, typename... U>
struct HasAbility<GlobalCache<G>, U...> : public HasAbility<U...> {
static constexpr bool kGlobalCache = true;
};
template <typename R, typename... U>
struct HasAbility<InputProcessBlockCache<R>, U...> : public HasAbility<U...> {
static constexpr bool kInputProcessBlockCache = true;
};
template <typename R, typename... U>
struct HasAbility<RunCache<R>, U...> : public HasAbility<U...> {
static constexpr bool kRunCache = true;
};
template <typename R, typename... U>
struct HasAbility<LuminosityBlockCache<R>, U...> : public HasAbility<U...> {
static constexpr bool kLuminosityBlockCache = true;
};
template <typename R, typename... U>
struct HasAbility<RunSummaryCache<R>, U...> : public HasAbility<U...> {
static constexpr bool kRunSummaryCache = true;
};
template <typename R, typename... U>
struct HasAbility<LuminosityBlockSummaryCache<R>, U...> : public HasAbility<U...> {
static constexpr bool kLuminosityBlockSummaryCache = true;
};
template <typename... U>
struct HasAbility<edm::WatchProcessBlock, U...> : public HasAbility<U...> {
static constexpr bool kWatchProcessBlock = true;
};
template <typename... U>
struct HasAbility<edm::BeginProcessBlockProducer, U...> : public HasAbility<U...> {
static constexpr bool kBeginProcessBlockProducer = true;
};
template <typename... U>
struct HasAbility<edm::EndProcessBlockProducer, U...> : public HasAbility<U...> {
static constexpr bool kEndProcessBlockProducer = true;
};
template <typename... U>
struct HasAbility<edm::BeginRunProducer, U...> : public HasAbility<U...> {
static constexpr bool kBeginRunProducer = true;
};
template <typename... U>
struct HasAbility<edm::EndRunProducer, U...> : public HasAbility<U...> {
static constexpr bool kEndRunProducer = true;
};
template <typename... U>
struct HasAbility<edm::BeginLuminosityBlockProducer, U...> : public HasAbility<U...> {
static constexpr bool kBeginLuminosityBlockProducer = true;
};
template <typename... U>
struct HasAbility<edm::EndLuminosityBlockProducer, U...> : public HasAbility<U...> {
static constexpr bool kEndLuminosityBlockProducer = true;
};
template <typename... U>
struct HasAbility<edm::ExternalWork, U...> : public HasAbility<U...> {
static constexpr bool kExternalWork = true;
};
template <typename... U>
struct HasAbility<edm::Accumulator, U...> : public HasAbility<U...> {
static constexpr bool kAccumulator = true;
};
template <>
struct HasAbility<LastCheck> {
static constexpr bool kGlobalCache = false;
static constexpr bool kInputProcessBlockCache = false;
static constexpr bool kRunCache = false;
static constexpr bool kLuminosityBlockCache = false;
static constexpr bool kRunSummaryCache = false;
static constexpr bool kLuminosityBlockSummaryCache = false;
static constexpr bool kWatchProcessBlock = false;
static constexpr bool kBeginProcessBlockProducer = false;
static constexpr bool kEndProcessBlockProducer = false;
static constexpr bool kBeginRunProducer = false;
static constexpr bool kEndRunProducer = false;
static constexpr bool kBeginLuminosityBlockProducer = false;
static constexpr bool kEndLuminosityBlockProducer = false;
static constexpr bool kExternalWork = false;
static constexpr bool kAccumulator = false;
};
} // namespace impl
template <typename... T>
struct AbilityChecker : public impl::HasAbility<T..., impl::LastCheck> {};
} // namespace stream
} // namespace edm
#endif
|
bencz/smalltalk-jit
|
vm/Bootstrap.h
|
#ifndef BOOTSTRAP_H
#define BOOTSTRAP_H
_Bool bootstrap(char *kernelDir);
#endif
|
Joneswn/Baloti
|
djlang/models.py
|
import re
from django.db import models
from django.core import serializers
from django.core.cache import cache
from django.conf import settings
from django.utils.translation import get_language
from django.utils.html import escape
from django.utils.safestring import mark_safe
from electeez_sites.models import Site
# Create your models here.
class Language(models.Model):
iso = models.CharField(max_length=3)
name = models.CharField(max_length=255)
active = models.BooleanField(default=True, blank=True)
site = models.ForeignKey(
Site,
on_delete=models.CASCADE
)
class Text(models.Model):
language = models.ForeignKey(
Language,
on_delete=models.CASCADE
)
key = models.CharField(
max_length=1024,
)
val = models.TextField(blank=True, null=True)
nval = models.TextField(blank=True, null=True)
def save(self, *args, **kwargs):
super().save(*args, **kwargs)
serialized = serializers.serialize('json', [self])
cache.set(f'{self.language.site}-{self.language.iso}-{self.key}', serialized)
def process(self, n=0, allow_unsecure=False, **placeholders):
# If pluralize return nval
# If not nval use val
# If not val use key
val = self.val or self.key
if self.val and n > 1:
val = self.nval or self.val
if not allow_unsecure:
val = escape(val)
# Replace strings by placeholders
matches = re.findall(r'(%\((?P<ph>[^%( )]*?)\)s)', val)
for match in matches:
if match[1] in placeholders:
val = val.replace(match[0], str(placeholders[match[1]]))
return mark_safe(val)
|
Teraguchi0804/WebARSimpleTemplate
|
development/src/assets/js/_devjs/src/utils/url/Url.js
|
/**
* fileOverview: urlから値取得、取得した値を操作する系
* Project:
* File: Url
* Date:
* Author:
*/
export default class Url {
constructor() {
}
/**
* クエリ抜き出し
* @returns {*}
*/
getParam() {
var url = location.href;
var param = url.split('?')[1];
if (param==undefined) return undefined;
var paramItems = param.split('&');
var list = {};
for( var i = 0; i<paramItems.length; i++ ){
paramItem = paramItems[i].split('=');
list[paramItem[0]] = paramItem[1];
}
return list;
}
/**
* ハッシュ取得 : location.hashの#を削除したやつを取得
* @returns {string}
*/
hash() {
return location.hash.replace("#", "");
}
/**
* getHash
* @returns {string}
*/
getHash () {
return location.hash
}
/**
* setHash
* @param text
*/
setHash (text) {
location.hash = text;
}
/**
* checkCookie : 指定したstringがクッキーにセットされていたらtrue
* @param str
* @returns {*}
*/
checkCookie(str) {
var flag = null;
if ($.cookie(str) == undefined || $.cookie(str) == '') flag = false;
else flag = true;
return flag;
}
/**
* setCookie
* @param str
*/
setCookie(str) {
var date = new Date();
// date.setTime( date.getTime() + ( 30 * 1000 )); //30秒
date.setTime( date.getTime() + ( 15 * 60 * 1000 )); //15分
$.cookie(str, true, { expires: date, path: '/' });
}
/**
* protcol
* @returns {string}
*/
protocol() {
return location.protocol;
}
/**
* host
* @returns {string}
*/
host() {
return location.hostname;
}
/**
* port
* @returns {string}
*/
port() {
return location.port;
}
/**
* path
* @returns {string}
*/
path() {
return location.pathname;
}
}
|
Speedwag00n/RadeonProRenderMayaPlugin
|
FireRender.Maya.Src/FireRenderDot.cpp
|
<reponame>Speedwag00n/RadeonProRenderMayaPlugin<filename>FireRender.Maya.Src/FireRenderDot.cpp
/**********************************************************************
Copyright 2020 Advanced Micro Devices, 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.
********************************************************************/
#include "FireRenderDot.h"
#include <maya/MFnEnumAttribute.h>
namespace
{
namespace Attribute
{
MObject uv;
MObject uvScale;
MObject output;
MObject mapChannel;
}
}
void* FireMaya::Dot::creator()
{
return new FireMaya::Dot;
}
MStatus FireMaya::Dot::initialize()
{
MFnNumericAttribute nAttr;
MFnEnumAttribute eAttr;
Attribute::uv = nAttr.create("uvCoord", "uv", MFnNumericData::k2Float);
MAKE_INPUT(nAttr);
nAttr.setSoftMin(0.1);
nAttr.setSoftMax(100.0);
Attribute::uvScale = nAttr.create("uvScale", "uvs", MFnNumericData::kFloat, 1);
MAKE_INPUT(nAttr);
Attribute::output = nAttr.createColor("out", "o");
MAKE_OUTPUT(nAttr);
Attribute::mapChannel = eAttr.create("mapChannel", "mc", 0);
eAttr.addField("0", kTexture_Channel0);
eAttr.addField("1", kTexture_Channel1);
MAKE_INPUT_CONST(eAttr);
CHECK_MSTATUS(addAttribute(Attribute::uv));
CHECK_MSTATUS(addAttribute(Attribute::uvScale));
CHECK_MSTATUS(addAttribute(Attribute::output));
CHECK_MSTATUS(addAttribute(Attribute::mapChannel));
CHECK_MSTATUS(attributeAffects(Attribute::uv, Attribute::output));
CHECK_MSTATUS(attributeAffects(Attribute::uvScale, Attribute::output));
CHECK_MSTATUS(attributeAffects(Attribute::mapChannel, Attribute::output));
return MS::kSuccess;
}
frw::Value FireMaya::Dot::GetValue(const Scope& scope) const
{
MFnDependencyNode shaderNode(thisMObject());
frw::ValueNode valueNode(scope.MaterialSystem(), frw::ValueTypeDotMap);
Type mapChannel = kTexture_Channel0;
MPlug mapChannelPlug = shaderNode.findPlug(Attribute::mapChannel, false);
if (!mapChannelPlug.isNull())
{
int n = 0;
if (MStatus::kSuccess == mapChannelPlug.getValue(n))
{
mapChannel = static_cast<Type>(n);
}
}
valueNode.SetValue(RPR_MATERIAL_INPUT_UV, scope.GetConnectedValue(shaderNode.findPlug(Attribute::uv, false)) | scope.MaterialSystem().ValueLookupUV(mapChannel));
auto uvScale = scope.GetValue(shaderNode.findPlug(Attribute::uvScale, false));
if (uvScale != 1.)
valueNode.SetValue(RPR_MATERIAL_INPUT_UV_SCALE, uvScale);
return valueNode;
}
|
tsueygoto/NexIoTStudio
|
nodes/dashboard/static/js/model/datasource.js
|
<reponame>tsueygoto/NexIoTStudio<filename>nodes/dashboard/static/js/model/datasource.js
var App = App || {};
App.Model = App.Model || {};
App.Model.Datasource = ( function() {
var Datasource = function( id , config ) {
if( config ) { this.unserialize( config ); }
this.id = id;
this.chartCount = 0;
this.charts = {};
this.end = null;
this.historyRequests = {};
this.buttonRequests = {};
this.clickRequests = {};
this.dataBrokers = {};
};
Datasource.prototype.unserialize = function( data ) {
this.name = data.name;
this.tstampField = data.tstampField;
this.dataField = data.dataField;
this.dataComponents = data.dataComponents;
if( this.tstampField !== "tstamp" ) { this.tstampField = this.tstampField.split("."); }
if( this.dataField !== "data" ) { this.dataField = this.dataField.split("."); }
};
Datasource.prototype.getNestedValue = function( obj , keyArr ) {
try
{
return keyArr.reduce( function( reduceObj , i ) {
return reduceObj[i];
} , obj );
}
catch( e )
{
return undefined;
}
};
Datasource.prototype.addChart = function( chart ) {
if( this.charts.hasOwnProperty( chart.id ) )
{
console.error( "Datasource already has chart: " + chart.id );
return;
}
this.charts[ chart.id ] = chart;
this.chartCount++;
};
Datasource.prototype.removeChart = function( id ) {
if( this.charts.hasOwnProperty( id ) )
{
delete this.charts[ id ];
delete this.historyRequests[ id ];
this.chartCount--;
}
};
Datasource.prototype.updateConfig = function( config )
{
this.unserialize( config );
for( var id in this.charts )
{
if (this.charts.hasOwnProperty(id)) {
this.charts[ id ].datasourceConfigChanged( this );
}
}
};
Datasource.prototype.isEmpty = function() {
return this.chartCount === 0;
};
Datasource.prototype.isReady = function() {
return this.dataComponents !== undefined;
};
Datasource.prototype.convertData = function( data ) {
if( $.isArray( data ) )
{
for( var i = 0; i < data.length; i++ )
{ data[i] = this.convertDataPoint( data[i] ); }
return data;
}
else { return this.convertDataPoint( data ); }
};
Datasource.prototype.convertDataPoint = function( data ) {
var converted = {
tstamp : this.tstampField == "tstamp" ? data.tstamp : this.getNestedValue( data , this.tstampField ),
data : this.dataField == "data" ? data.data : this.getNestedValue( data , this.dataField )
};
return converted;
};
Datasource.prototype.pushData = function( data ) {
data = this.convertData( data );
for( var id in this.charts )
{
if (this.charts.hasOwnProperty(id)) {
this.charts[id].pushData( this , data );
}
}
};
Datasource.prototype.pushHistoryData = function( chartID , data ) {
if( !this.charts.hasOwnProperty( chartID ) || !this.historyRequests.hasOwnProperty( chartID ) ) { return; }
if( this.tstampField !== "tstamp" || this.dataField !== "data" )
{
data = this.convertData( data );
}
this.charts[ chartID ].pushData( this , data , this.historyRequests[ chartID ] );
delete this.historyRequests[ chartID ];
};
Datasource.prototype.requestHistoryData = function( chart , start , end , callback ) {
console.log("request data 1");
console.log(this.charts.hasOwnProperty( chart.id ));
console.log(this.historyRequests.hasOwnProperty( chart.id ));
if( !this.charts.hasOwnProperty( chart.id ) || this.historyRequests.hasOwnProperty( chart.id ) ) { return; }
if( typeof callback != "function" ) { return; }
console.log("request data 2");
this.historyRequests[ chart.id ] = callback;
App.Net.requestHistoryData( this.id , chart.id , start , end );
};
Datasource.prototype.buttonRequest = function( chart , start , end , callback ) {
console.log("button request data 1");
console.log(this.charts.hasOwnProperty( chart.id ));
console.log(this.buttonRequests.hasOwnProperty( chart.id ));
if( !this.charts.hasOwnProperty( chart.id ) ) { return; }
if( typeof callback != "function" ) { return; }
console.log("button request data 2");
//this.historyRequests[ chart.id ] = callback;
this.buttonRequests[ chart.id ] = callback;
//App.Net.requestHistoryData( this.id , chart.id , start , end );
App.Net.buttonRequest( this.id , chart.id , start , end );
};
///
///
///
Datasource.prototype.clickRequest = function( chart , data , callback ) {
console.log("click request data 1");
console.log(this.charts.hasOwnProperty( chart.id ));
console.log(this.clickRequests.hasOwnProperty( chart.id ));
if( !this.charts.hasOwnProperty( chart.id ) ) { return; }
if( typeof callback != "function" ) { return; }
console.log("click request data 2");
this.clickRequests[ chart.id ] = callback;
App.Net.clickRequest( this.id , chart.id , data );
};
/**
*
*/
Datasource.prototype.dataBroker = function( chart , data )
{
console.log("data Broker data");
console.log(this.charts.hasOwnProperty( chart.id ));
console.log(this.dataBrokers.hasOwnProperty( chart.id ));
if( !this.charts.hasOwnProperty( chart.id ) ) { return; }
//if( typeof callback != "function" ) return;
//console.log("click request data 2");
//this.clickRequests[ chart.id ] = callback;
App.Net.dataBroker( this.id , chart.id , data );
};
Datasource.getDatasources = function(usedDss)
{
var dfd = $.Deferred();
console.info(">>> usedDss : ", usedDss);
if ((usedDss != null) && (usedDss.length == 0))
{
if( !Datasource.datasources ) { Datasource.datasources = {}; }
dfd.resolve();
}
else
{
var param = null;
if (usedDss != null)
{
param = {"usedDss[]" : usedDss} ;
}
console.info(">>>>> param : ", param);
$.getJSON( "api/datasources", param ).done( function( datasources ) {
//console.info("--------- location : ", location.pathname.replace( $( "base" ).attr( "href" ) , "" ));
//var item = location.pathname.replace( $( "base" ).attr( "href" ) , "" ).split("/");
//alert(item);
//if(item.length > 0) {
// console.log(item[1]);
// var dashboard = App.Model.Dashboard.getDashboard( item[1] );
// console.info("dashboard : ", dashboard)
//}
//console.log( "getDatasources start .............................." );
if( !Datasource.datasources ) { Datasource.datasources = {}; }
//console.info("%%%%%%%%%%%%%%%%%% datasources : ", datasources);
// sort by name
//var nameArr = [];
//for( var id in datasources ) {
// nameArr.push({name:datasources[id].name, id:id });
//}
//nameArr = nameArr.sort(function (a, b) {
// return a.name > b.name ? 1 : -1;
//});
//console.info("sort name array: ", nameArr);
//for(var index=0; index<nameArr.length; index++) {
// var id = nameArr[index].id;
// if( Datasource.datasources.hasOwnProperty( id ) )
// Datasource.datasources[ id ].updateConfig( datasources[id] );
// else
// Datasource.datasources[ id ] = new Datasource( id , datasources[id] );
//}
for( var id in datasources ) {
if (datasources.hasOwnProperty(id)) {
//console.info("datasources id : ", id, " name : ", datasources[id].name);
if( Datasource.datasources.hasOwnProperty( id ) ) {
Datasource.datasources[ id ].updateConfig( datasources[id] );
}
else {
Datasource.datasources[ id ] = new Datasource( id , datasources[id] );
}
}
}
console.info( "getDatasources end ................................." );
console.info("Datasource.datasources : ",Datasource.datasources);
dfd.resolve();
} ).fail(function(){ dtd.reject(); });
}
return dfd.promise();
};
Datasource.getDatasource = function( id )
{
if (Datasource.datasources == null) { return null; }
return Datasource.datasources.hasOwnProperty( id ) ? Datasource.datasources[id] : null;
};
Datasource.datasources = null;
return Datasource;
} )();
|
0xpr03/VocableTrainer-Android
|
app/src/main/java/vocabletrainer/heinecke/aron/vocabletrainer/lib/Adapter/ListRecyclerAdapter.java
|
package vocabletrainer.heinecke.aron.vocabletrainer.lib.Adapter;
import android.content.Context;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.ListAdapter;
import androidx.recyclerview.widget.DiffUtil;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import vocabletrainer.heinecke.aron.vocabletrainer.R;
import vocabletrainer.heinecke.aron.vocabletrainer.lib.Storage.VList;
/**
* Recycler adapter for VList recycler with optional multi selection
* @author <NAME>
*/
public class ListRecyclerAdapter extends ListAdapter<VList,ListRecyclerAdapter.VListViewHolder> {
@SuppressWarnings("unused")
private static final String TAG = "ListRecyclerAdapter";
private static final DiffUtil.ItemCallback<VList> DIFF_CALLBACK =
new DiffUtil.ItemCallback<VList>() {
@Override
public boolean areItemsTheSame(VList oldItem, VList newItem) {
return oldItem.getId() == newItem.getId();
}
@Override
public boolean areContentsTheSame(VList oldItem, VList newItem) {
return oldItem.getName().equals(newItem.getName())
&& oldItem.getNameA().equals(newItem.getNameA())
&& oldItem.getNameB().equals(newItem.getNameB());
}
};
/**
* Item click listener used for recycler
*/
public interface ItemClickListener {
void onItemClick(View view, int position);
}
/**
* Item long click listener used for recycler
*/
public interface ItemLongClickListener {
void onItemLongClick(View view, int postion);
}
private List<VList> data;
private final boolean multiselect;
private DateFormat dateFormat;
private ItemLongClickListener itemLongClickListener;
private ItemClickListener itemClickListener;
public void setItemLongClickListener(ItemLongClickListener itemLongClickListener) {
this.itemLongClickListener = itemLongClickListener;
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
/**
* New VList recycler adapter
* @param data initial data
* @param multiSelect enable checkbox mode
* @param context context for date formatting etc
*/
public ListRecyclerAdapter(@NonNull List<VList> data, final boolean multiSelect, Context context){
super(DIFF_CALLBACK);
this.data = data;
this.multiselect = multiSelect;
this.dateFormat = android.text.format.DateFormat.getDateFormat(context);
}
/**
* Set all elements as select
* @param select
*/
public void selectAll(final boolean select){
for(VList entry : data){
entry.setSelected(select);
}
notifyDataSetChanged();
}
/**
* Submit data with sorting
* @param newData
* @param comparator
*/
public void submitList(List<VList> newData, @Nullable Comparator<VList> comparator) {
if(comparator != null)
Collections.sort(newData,comparator);
this.submitList(newData);
}
@Override
public void submitList(List<VList> newData) {
// don't rely on this being checked by super.submitList
// essential for selection persistence on viewport change (re-trigger of LiveData)
if(newData == data){
return;
}
this.data = newData;
super.submitList(newData);
}
/**
* Remove entry<br>
* Does not actually delete the item from the Database
* @param entry
*/
public void removeEntry(VList entry){
int pos = data.indexOf(entry);
data.remove(entry);
this.notifyItemRemoved(pos);
}
/**
* Restore entry in list
* @param entry
* @param position
*/
public void restoreEntry(VList entry, int position){
data.add(position,entry);
notifyItemInserted(position);
}
@NonNull
@Override
public VListViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_recycler_item,parent,false);
return new VListViewHolder(view,itemLongClickListener,itemClickListener);
}
@Override
public void onBindViewHolder(@NonNull VListViewHolder holder, int position) {
final VList entry = data.get(position);
holder.checkBox.setVisibility(multiselect ? View.VISIBLE : View.GONE);
holder.checkBox.setChecked(entry.isSelected());
holder.colB.setText(entry.getNameB());
holder.colA.setText(entry.getNameA());
holder.name.setText(entry.getName());
holder.created.setText(dateFormat.format(entry.getCreated()));
if(multiselect) {
holder.viewForeground.setOnClickListener(v -> {
entry.setSelected(!entry.isSelected());
this.notifyItemChanged(position);
});
}
}
/**
* Update sorting, forcing a redraw
* @param comparator
*/
public void updateSorting(@NonNull Comparator<VList> comparator){
Collections.sort(data,comparator);
// required, submitList wouldn't trigger when same list is used
this.notifyDataSetChanged();
}
/**
* Get item at position
* @param pos
* @return
*/
public VList getItemAt(int pos) {
return data.get(pos);
}
@Override
public int getItemCount() {
return data == null ? 0 : data.size();
}
/**
* VList view holder with click & long click capabilities
*/
public class VListViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnLongClickListener {
private CheckBox checkBox;
private TextView colA,colB,name,created;
private ItemClickListener itemClickListener;
private ItemLongClickListener itemLongClickListener;
final RelativeLayout viewBackground;
final ConstraintLayout viewForeground;
private VListViewHolder(View itemView,ItemLongClickListener itemLongClickListener, ItemClickListener itemClickListener) {
super(itemView);
checkBox = itemView.findViewById(R.id.chkListEntrySelect);
colA = itemView.findViewById(R.id.tListEntryColA);
colB = itemView.findViewById(R.id.tListEntryColB);
name = itemView.findViewById(R.id.tListEntryName);
created = itemView.findViewById(R.id.tListEntryCreated);
viewBackground = itemView.findViewById(R.id.view_background);
viewForeground = itemView.findViewById(R.id.view_foreground);
this.itemClickListener = itemClickListener;
this.itemLongClickListener = itemLongClickListener;
if(!multiselect){
viewForeground.setOnClickListener(this);
viewForeground.setOnLongClickListener(itemLongClickListener != null ? this : null);
}
}
@Override
public void onClick(View v) {
if(itemClickListener != null)
itemClickListener.onItemClick(v,getAdapterPosition());
}
@Override
public boolean onLongClick(View v) {
if(itemLongClickListener != null)
itemLongClickListener.onItemLongClick(v,getAdapterPosition());
return true;
}
}
}
|
zeknox/gofalcon
|
falcon/models/registration_i_o_m_event.go
|
<filename>falcon/models/registration_i_o_m_event.go
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// RegistrationIOMEvent registration i o m event
//
// swagger:model registration.IOMEvent
type RegistrationIOMEvent struct {
// account id
// Required: true
AccountID *string `json:"account_id"`
// account name
// Required: true
AccountName *string `json:"account_name"`
// azure tenant id
// Required: true
AzureTenantID *string `json:"azure_tenant_id"`
// cid
// Required: true
Cid *string `json:"cid"`
// cloud provider
// Required: true
CloudProvider *string `json:"cloud_provider"`
// finding
// Required: true
Finding *string `json:"finding"`
// policy id
// Required: true
PolicyID *string `json:"policy_id"`
// policy statement
// Required: true
PolicyStatement *string `json:"policy_statement"`
// region
// Required: true
Region *string `json:"region"`
// report date time
// Required: true
ReportDateTime *string `json:"report_date_time"`
// resource attributes
// Required: true
ResourceAttributes *string `json:"resource_attributes"`
// resource create time
// Required: true
ResourceCreateTime *string `json:"resource_create_time"`
// resource id
// Required: true
ResourceID *string `json:"resource_id"`
// resource id type
// Required: true
ResourceIDType *string `json:"resource_id_type"`
// resource url
// Required: true
ResourceURL *string `json:"resource_url"`
// service
// Required: true
Service *string `json:"service"`
// severity
// Required: true
Severity *string `json:"severity"`
// status
// Required: true
Status *string `json:"status"`
// tags
// Required: true
Tags *string `json:"tags"`
}
// Validate validates this registration i o m event
func (m *RegistrationIOMEvent) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateAccountID(formats); err != nil {
res = append(res, err)
}
if err := m.validateAccountName(formats); err != nil {
res = append(res, err)
}
if err := m.validateAzureTenantID(formats); err != nil {
res = append(res, err)
}
if err := m.validateCid(formats); err != nil {
res = append(res, err)
}
if err := m.validateCloudProvider(formats); err != nil {
res = append(res, err)
}
if err := m.validateFinding(formats); err != nil {
res = append(res, err)
}
if err := m.validatePolicyID(formats); err != nil {
res = append(res, err)
}
if err := m.validatePolicyStatement(formats); err != nil {
res = append(res, err)
}
if err := m.validateRegion(formats); err != nil {
res = append(res, err)
}
if err := m.validateReportDateTime(formats); err != nil {
res = append(res, err)
}
if err := m.validateResourceAttributes(formats); err != nil {
res = append(res, err)
}
if err := m.validateResourceCreateTime(formats); err != nil {
res = append(res, err)
}
if err := m.validateResourceID(formats); err != nil {
res = append(res, err)
}
if err := m.validateResourceIDType(formats); err != nil {
res = append(res, err)
}
if err := m.validateResourceURL(formats); err != nil {
res = append(res, err)
}
if err := m.validateService(formats); err != nil {
res = append(res, err)
}
if err := m.validateSeverity(formats); err != nil {
res = append(res, err)
}
if err := m.validateStatus(formats); err != nil {
res = append(res, err)
}
if err := m.validateTags(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *RegistrationIOMEvent) validateAccountID(formats strfmt.Registry) error {
if err := validate.Required("account_id", "body", m.AccountID); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateAccountName(formats strfmt.Registry) error {
if err := validate.Required("account_name", "body", m.AccountName); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateAzureTenantID(formats strfmt.Registry) error {
if err := validate.Required("azure_tenant_id", "body", m.AzureTenantID); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateCid(formats strfmt.Registry) error {
if err := validate.Required("cid", "body", m.Cid); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateCloudProvider(formats strfmt.Registry) error {
if err := validate.Required("cloud_provider", "body", m.CloudProvider); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateFinding(formats strfmt.Registry) error {
if err := validate.Required("finding", "body", m.Finding); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validatePolicyID(formats strfmt.Registry) error {
if err := validate.Required("policy_id", "body", m.PolicyID); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validatePolicyStatement(formats strfmt.Registry) error {
if err := validate.Required("policy_statement", "body", m.PolicyStatement); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateRegion(formats strfmt.Registry) error {
if err := validate.Required("region", "body", m.Region); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateReportDateTime(formats strfmt.Registry) error {
if err := validate.Required("report_date_time", "body", m.ReportDateTime); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateResourceAttributes(formats strfmt.Registry) error {
if err := validate.Required("resource_attributes", "body", m.ResourceAttributes); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateResourceCreateTime(formats strfmt.Registry) error {
if err := validate.Required("resource_create_time", "body", m.ResourceCreateTime); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateResourceID(formats strfmt.Registry) error {
if err := validate.Required("resource_id", "body", m.ResourceID); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateResourceIDType(formats strfmt.Registry) error {
if err := validate.Required("resource_id_type", "body", m.ResourceIDType); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateResourceURL(formats strfmt.Registry) error {
if err := validate.Required("resource_url", "body", m.ResourceURL); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateService(formats strfmt.Registry) error {
if err := validate.Required("service", "body", m.Service); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateSeverity(formats strfmt.Registry) error {
if err := validate.Required("severity", "body", m.Severity); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateStatus(formats strfmt.Registry) error {
if err := validate.Required("status", "body", m.Status); err != nil {
return err
}
return nil
}
func (m *RegistrationIOMEvent) validateTags(formats strfmt.Registry) error {
if err := validate.Required("tags", "body", m.Tags); err != nil {
return err
}
return nil
}
// ContextValidate validates this registration i o m event based on context it is used
func (m *RegistrationIOMEvent) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *RegistrationIOMEvent) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *RegistrationIOMEvent) UnmarshalBinary(b []byte) error {
var res RegistrationIOMEvent
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}
|
bvdsanden/ludus
|
backend/src/main/java/org/ludus/backend/automaton/MPGA.java
|
package org.ludus.backend.automaton;
import org.ludus.backend.games.ratio.solvers.policy.RatioGamePolicyIteration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* Max-plus game automaton.
* We assume that the nodes for player 1 have a negative index value.
*
* @author <NAME>
*/
public class MPGA<T> extends MaxPlusAutomaton<T> implements RatioGamePolicyIteration<MPAState<T>, MPATransition, Double> {
private final Set<MPAState<T>> player0states;
private final Set<MPAState<T>> player1states;
private final Map<MPAState<T>, Integer> idMap;
private Integer currentId;
public MPGA() {
super();
player0states = new HashSet<>();
player1states = new HashSet<>();
idMap = new HashMap<>();
currentId = 0;
}
@Override
public void addState(MPAState<T> MPAState) {
super.addState(MPAState);
if (MPAState.getIndex() < 0) {
player1states.add(MPAState);
} else {
player0states.add(MPAState);
}
idMap.put(MPAState, currentId);
currentId++;
}
@Override
public Set<MPAState<T>> getV0() {
return player0states;
}
@Override
public Set<MPAState<T>> getV1() {
return player1states;
}
@Override
public Double getMaxAbsValue() {
Double max = Double.NEGATIVE_INFINITY;
for (MPATransition t : getEdges()) {
max = Double.max(max, getWeight1(t));
max = Double.max(max, getWeight2(t));
}
return max;
}
@Override
public Integer getId(MPAState<T> vertex) {
return idMap.get(vertex);
}
}
|
asalkeld/rp
|
hack/db/db.go
|
package main
import (
"context"
"fmt"
"os"
uuid "github.com/satori/go.uuid"
"github.com/sirupsen/logrus"
"github.com/ugorji/go/codec"
"github.com/jim-minter/rp/pkg/api"
"github.com/jim-minter/rp/pkg/database"
"github.com/jim-minter/rp/pkg/env"
)
func run(ctx context.Context, log *logrus.Entry) error {
for _, key := range []string{
"RESOURCEGROUP",
} {
if _, found := os.LookupEnv(key); !found {
return fmt.Errorf("environment variable %q unset", key)
}
}
if len(os.Args) != 2 {
return fmt.Errorf("usage: %s resourceid", os.Args[0])
}
env, err := env.NewEnv(ctx, log, os.Getenv("AZURE_SUBSCRIPTION_ID"), os.Getenv("RESOURCEGROUP"))
if err != nil {
return err
}
db, err := database.NewOpenShiftClusters(ctx, env, uuid.NewV4(), "OpenShiftClusters", "OpenShiftClusterDocuments")
if err != nil {
return err
}
doc, err := db.Get(os.Args[1])
if err != nil {
return err
}
h := &codec.JsonHandle{
BasicHandle: codec.BasicHandle{
DecodeOptions: codec.DecodeOptions{
ErrorIfNoField: true,
},
},
Indent: 2,
}
err = api.AddExtensions(&h.BasicHandle)
if err != nil {
return err
}
return codec.NewEncoder(os.Stdout, h).Encode(doc)
}
func main() {
logrus.SetReportCaller(true)
logrus.SetFormatter(&logrus.TextFormatter{
FullTimestamp: true,
DisableLevelTruncation: true,
})
log := logrus.NewEntry(logrus.StandardLogger())
if err := run(context.Background(), log); err != nil {
panic(err)
}
}
|
byypipo/Mgcp-Client
|
src/main/java/com/mgcp/eventpackages/parameters/Announcement.java
|
package com.mgcp.eventpackages.parameters;
public class Announcement extends BaseEventParameter {
public Announcement(String value) {
super("an", value);
}
@Override
public String getCommentRFC2897() {
return "An announcement to be played. Consists of one or more audio segments";
}
}
|
BuildJet/ebl-api
|
ebl/tests/fragmentarium/test_fragment_schema.py
|
from ebl.fragmentarium.application.fragment_schema import FragmentSchema
from ebl.fragmentarium.application.museum_number_schema import MuseumNumberSchema
from ebl.fragmentarium.domain.joins import Join, Joins
from ebl.fragmentarium.domain.museum_number import MuseumNumber
from ebl.tests.factories.fragment import LemmatizedFragmentFactory
def test_serialization_and_deserialization():
fragment = LemmatizedFragmentFactory.build(
joins=Joins(((Join(MuseumNumber("X", "1")),),))
)
schema = FragmentSchema()
data = schema.dump(fragment)
assert schema.load(data) == fragment
def test_default_joins():
fragment = LemmatizedFragmentFactory.build(joins=Joins())
data = FragmentSchema(exclude=["joins"]).dump(fragment)
assert FragmentSchema().load(data) == fragment
def test_number_serialization():
fragment = LemmatizedFragmentFactory.build()
data = FragmentSchema().dump(fragment)
assert data["museumNumber"] == MuseumNumberSchema().dump(fragment.number)
def test_number_deserialization():
number = MuseumNumber.of("Z.1.b")
fragment = FragmentSchema().load(
{
**FragmentSchema().dump(LemmatizedFragmentFactory.build()),
"museumNumber": MuseumNumberSchema().dump(number),
}
)
assert fragment.number == number
|
vagabond1-1983/webUIPractice
|
src/main/java/com/test/java/webui/api/highLevelSkills/testFlowControl/ImplicitlyWaitDemo.java
|
package com.test.java.webui.api.highLevelSkills.testFlowControl;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;
import java.util.concurrent.TimeUnit;
/**
* Created by beigui on 2016/3/22.
* 隐式等待:用来同步测试。当使用了隐式等待执行测试的时候,如果WebDriver没有在DOM中找到元素,将继续等待
* 超出设定时间后则抛出找不到元素的异常。
* 换句话说,当查找元素或元素并没有立即出现的时候,隐式等待将等待一段时间再查找DOM.默认时间为0。
* 一旦设置了隐式等待,则它存在于整个WebDriver对象实例的生命周期中,
* 但是,隐式等待会让一个正常响应的应用的测试变慢,它将会在寻找每个元素的时候都进行等待,
* 这样就增加了整个测试执行的时间。
*/
public class ImplicitlyWaitDemo {
@Test
public void implicitWaitTest() throws InterruptedException {
WebDriver driver = new FirefoxDriver();
driver.get("http://demo.tutorialzine.com/2009/09/simple-ajax-website-jquery/demo.html");
//等待10秒
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement page4Button = driver.findElement(By.linkText("Page 4"));
page4Button.click();
WebElement message = driver.findElement(By.id("pageContent"));
//等待ajax的内容出现
//为什么这边用的线程等待,而不用隐式等待?
// Thread.sleep(4000)意思是等待4秒钟,如果没有这句加上pageContent本身就存在,
// 所以它的内容就是最初没有点击时候的文本,不是我们所期望的。可见这样的方法本不是很
// 好。所以尽量去使用显示的等待,提供了更多的方法来精确的控制同步。
// Thread.sleep(4000);
Assert.assertTrue(message.getText().contains("Nunc nibh tortor"));
driver.close();
}
}
|
sajas-nm/medapp-test
|
node_modules/@tinymce/tinymce-react/lib/es2015/main/ts/Utils.js
|
/**
* Copyright (c) 2017-present, Ephox, Inc.
*
* This source code is licensed under the Apache 2 license found in the
* LICENSE file in the root directory of this source tree.
*
*/
import { eventPropTypes } from './components/EditorPropTypes';
export var isFunction = function (x) { return typeof x === 'function'; };
var isEventProp = function (name) { return name in eventPropTypes; };
var eventAttrToEventName = function (attrName) { return attrName.substr(2); };
export var configHandlers2 = function (handlerLookup, on, off, adapter, prevProps, props, boundHandlers) {
var prevEventKeys = Object.keys(prevProps).filter(isEventProp);
var currEventKeys = Object.keys(props).filter(isEventProp);
var removedKeys = prevEventKeys.filter(function (key) { return props[key] === undefined; });
var addedKeys = currEventKeys.filter(function (key) { return prevProps[key] === undefined; });
removedKeys.forEach(function (key) {
// remove event handler
var eventName = eventAttrToEventName(key);
var wrappedHandler = boundHandlers[eventName];
off(eventName, wrappedHandler);
delete boundHandlers[eventName];
});
addedKeys.forEach(function (key) {
var wrappedHandler = adapter(handlerLookup, key);
var eventName = eventAttrToEventName(key);
boundHandlers[eventName] = wrappedHandler;
on(eventName, wrappedHandler);
});
};
export var configHandlers = function (editor, prevProps, props, boundHandlers, lookup) {
return configHandlers2(lookup, editor.on.bind(editor), editor.off.bind(editor), function (handlerLookup, key) { return function (e) { var _a; return (_a = handlerLookup(key)) === null || _a === void 0 ? void 0 : _a(e, editor); }; }, prevProps, props, boundHandlers);
};
var unique = 0;
export var uuid = function (prefix) {
var time = Date.now();
var random = Math.floor(Math.random() * 1000000000);
unique++;
return prefix + '_' + random + unique + String(time);
};
export var isTextareaOrInput = function (element) {
return element !== null && (element.tagName.toLowerCase() === 'textarea' || element.tagName.toLowerCase() === 'input');
};
var normalizePluginArray = function (plugins) {
if (typeof plugins === 'undefined' || plugins === '') {
return [];
}
return Array.isArray(plugins) ? plugins : plugins.split(' ');
};
// eslint-disable-next-line max-len
export var mergePlugins = function (initPlugins, inputPlugins) { return normalizePluginArray(initPlugins).concat(normalizePluginArray(inputPlugins)); };
export var isBeforeInputEventAvailable = function () { return window.InputEvent && typeof InputEvent.prototype.getTargetRanges === 'function'; };
|
larsk21/lean4
|
stage0/stdlib/Lean/Elab/Tactic/Conv/Rewrite.c
|
<filename>stage0/stdlib/Lean/Elab/Tactic/Conv/Rewrite.c
// Lean compiler output
// Module: Lean.Elab.Tactic.Conv.Rewrite
// Imports: Init Lean.Meta.Tactic.Rewrite Lean.Elab.Tactic.Rewrite Lean.Elab.Tactic.Conv.Basic
#include <lean/lean.h>
#if defined(__clang__)
#pragma clang diagnostic ignored "-Wunused-parameter"
#pragma clang diagnostic ignored "-Wunused-label"
#elif defined(__GNUC__) && !defined(__CLANG__)
#pragma GCC diagnostic ignored "-Wunused-parameter"
#pragma GCC diagnostic ignored "-Wunused-label"
#pragma GCC diagnostic ignored "-Wunused-but-set-variable"
#endif
#ifdef __cplusplus
extern "C" {
#endif
lean_object* l_Lean_Elab_Tactic_withRWRulesSeq(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* lean_name_mk_string(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__2___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__12;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__7;
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__1___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Elab_Tactic_withMainContext___rarg(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__2;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__13;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__1;
lean_object* l_Lean_KeyedDeclsAttribute_addBuiltin___rarg(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__4;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__1;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__8;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__17;
LEAN_EXPORT lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite(lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__9;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__15;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__3;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__14;
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__2(lean_object*, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__18;
lean_object* l_Lean_addBuiltinDeclarationRanges(lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__10;
lean_object* l_Lean_Elab_Tactic_getMainGoal(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__1(lean_object*, lean_object*, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Meta_rewrite(lean_object*, lean_object*, lean_object*, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__3;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__6;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__5;
lean_object* l_Lean_Elab_Tactic_Conv_getLhs(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
extern lean_object* l_Lean_Elab_Tactic_tacticElabAttribute;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__4;
lean_object* l_Lean_Elab_Tactic_elabRewriteConfig(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l___private_Lean_Elab_SyntheticMVars_0__Lean_Elab_Term_withSynthesizeImp___rarg(lean_object*, uint8_t, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Elab_Tactic_elabTerm(lean_object*, lean_object*, uint8_t, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16;
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__6;
lean_object* l_Lean_Elab_Tactic_Conv_updateLhs(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Elab_Tactic_replaceMainGoal(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___boxed(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite(lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*, lean_object*);
lean_object* l_Lean_Syntax_getArg(lean_object*, lean_object*);
LEAN_EXPORT lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange(lean_object*);
static lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__11;
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__1(lean_object* x_1, lean_object* x_2, uint8_t x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13) {
_start:
{
uint8_t x_14; lean_object* x_15;
x_14 = 1;
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
x_15 = l_Lean_Elab_Tactic_elabTerm(x_1, x_2, x_14, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13);
if (lean_obj_tag(x_15) == 0)
{
lean_object* x_16; lean_object* x_17; lean_object* x_18;
x_16 = lean_ctor_get(x_15, 0);
lean_inc(x_16);
x_17 = lean_ctor_get(x_15, 1);
lean_inc(x_17);
lean_dec(x_15);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
x_18 = l_Lean_Elab_Tactic_getMainGoal(x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_17);
if (lean_obj_tag(x_18) == 0)
{
lean_object* x_19; lean_object* x_20; lean_object* x_21;
x_19 = lean_ctor_get(x_18, 0);
lean_inc(x_19);
x_20 = lean_ctor_get(x_18, 1);
lean_inc(x_20);
lean_dec(x_18);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
x_21 = l_Lean_Elab_Tactic_Conv_getLhs(x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_20);
if (lean_obj_tag(x_21) == 0)
{
lean_object* x_22; lean_object* x_23; lean_object* x_24; lean_object* x_25;
x_22 = lean_ctor_get(x_21, 0);
lean_inc(x_22);
x_23 = lean_ctor_get(x_21, 1);
lean_inc(x_23);
lean_dec(x_21);
x_24 = lean_box(0);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
x_25 = l_Lean_Meta_rewrite(x_19, x_22, x_16, x_3, x_24, x_4, x_9, x_10, x_11, x_12, x_23);
if (lean_obj_tag(x_25) == 0)
{
lean_object* x_26; lean_object* x_27; lean_object* x_28; lean_object* x_29; lean_object* x_30;
x_26 = lean_ctor_get(x_25, 0);
lean_inc(x_26);
x_27 = lean_ctor_get(x_25, 1);
lean_inc(x_27);
lean_dec(x_25);
x_28 = lean_ctor_get(x_26, 0);
lean_inc(x_28);
x_29 = lean_ctor_get(x_26, 1);
lean_inc(x_29);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
x_30 = l_Lean_Elab_Tactic_Conv_updateLhs(x_28, x_29, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_27);
if (lean_obj_tag(x_30) == 0)
{
lean_object* x_31; lean_object* x_32;
x_31 = lean_ctor_get(x_30, 1);
lean_inc(x_31);
lean_dec(x_30);
lean_inc(x_12);
lean_inc(x_11);
lean_inc(x_10);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
x_32 = l_Lean_Elab_Tactic_getMainGoal(x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_31);
if (lean_obj_tag(x_32) == 0)
{
lean_object* x_33; lean_object* x_34; lean_object* x_35; lean_object* x_36; lean_object* x_37;
x_33 = lean_ctor_get(x_32, 0);
lean_inc(x_33);
x_34 = lean_ctor_get(x_32, 1);
lean_inc(x_34);
lean_dec(x_32);
x_35 = lean_ctor_get(x_26, 2);
lean_inc(x_35);
lean_dec(x_26);
x_36 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_36, 0, x_33);
lean_ctor_set(x_36, 1, x_35);
x_37 = l_Lean_Elab_Tactic_replaceMainGoal(x_36, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_34);
return x_37;
}
else
{
uint8_t x_38;
lean_dec(x_26);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
x_38 = !lean_is_exclusive(x_32);
if (x_38 == 0)
{
return x_32;
}
else
{
lean_object* x_39; lean_object* x_40; lean_object* x_41;
x_39 = lean_ctor_get(x_32, 0);
x_40 = lean_ctor_get(x_32, 1);
lean_inc(x_40);
lean_inc(x_39);
lean_dec(x_32);
x_41 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_41, 0, x_39);
lean_ctor_set(x_41, 1, x_40);
return x_41;
}
}
}
else
{
uint8_t x_42;
lean_dec(x_26);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
x_42 = !lean_is_exclusive(x_30);
if (x_42 == 0)
{
return x_30;
}
else
{
lean_object* x_43; lean_object* x_44; lean_object* x_45;
x_43 = lean_ctor_get(x_30, 0);
x_44 = lean_ctor_get(x_30, 1);
lean_inc(x_44);
lean_inc(x_43);
lean_dec(x_30);
x_45 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_45, 0, x_43);
lean_ctor_set(x_45, 1, x_44);
return x_45;
}
}
}
else
{
uint8_t x_46;
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
x_46 = !lean_is_exclusive(x_25);
if (x_46 == 0)
{
return x_25;
}
else
{
lean_object* x_47; lean_object* x_48; lean_object* x_49;
x_47 = lean_ctor_get(x_25, 0);
x_48 = lean_ctor_get(x_25, 1);
lean_inc(x_48);
lean_inc(x_47);
lean_dec(x_25);
x_49 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_49, 0, x_47);
lean_ctor_set(x_49, 1, x_48);
return x_49;
}
}
}
else
{
uint8_t x_50;
lean_dec(x_19);
lean_dec(x_16);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_50 = !lean_is_exclusive(x_21);
if (x_50 == 0)
{
return x_21;
}
else
{
lean_object* x_51; lean_object* x_52; lean_object* x_53;
x_51 = lean_ctor_get(x_21, 0);
x_52 = lean_ctor_get(x_21, 1);
lean_inc(x_52);
lean_inc(x_51);
lean_dec(x_21);
x_53 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_53, 0, x_51);
lean_ctor_set(x_53, 1, x_52);
return x_53;
}
}
}
else
{
uint8_t x_54;
lean_dec(x_16);
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_54 = !lean_is_exclusive(x_18);
if (x_54 == 0)
{
return x_18;
}
else
{
lean_object* x_55; lean_object* x_56; lean_object* x_57;
x_55 = lean_ctor_get(x_18, 0);
x_56 = lean_ctor_get(x_18, 1);
lean_inc(x_56);
lean_inc(x_55);
lean_dec(x_18);
x_57 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_57, 0, x_55);
lean_ctor_set(x_57, 1, x_56);
return x_57;
}
}
}
else
{
uint8_t x_58;
lean_dec(x_12);
lean_dec(x_11);
lean_dec(x_10);
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
x_58 = !lean_is_exclusive(x_15);
if (x_58 == 0)
{
return x_15;
}
else
{
lean_object* x_59; lean_object* x_60; lean_object* x_61;
x_59 = lean_ctor_get(x_15, 0);
x_60 = lean_ctor_get(x_15, 1);
lean_inc(x_60);
lean_inc(x_59);
lean_dec(x_15);
x_61 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_61, 0, x_59);
lean_ctor_set(x_61, 1, x_60);
return x_61;
}
}
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__2(lean_object* x_1, uint8_t x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12) {
_start:
{
lean_object* x_13; lean_object* x_14; lean_object* x_15; lean_object* x_16; uint8_t x_17; uint8_t x_18; lean_object* x_19;
x_13 = lean_box(0);
x_14 = lean_box(x_2);
x_15 = lean_alloc_closure((void*)(l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__1___boxed), 13, 4);
lean_closure_set(x_15, 0, x_3);
lean_closure_set(x_15, 1, x_13);
lean_closure_set(x_15, 2, x_14);
lean_closure_set(x_15, 3, x_1);
x_16 = lean_alloc_closure((void*)(l_Lean_Elab_Tactic_withMainContext___rarg), 10, 3);
lean_closure_set(x_16, 0, x_15);
lean_closure_set(x_16, 1, x_4);
lean_closure_set(x_16, 2, x_5);
x_17 = 0;
x_18 = 1;
x_19 = l___private_Lean_Elab_SyntheticMVars_0__Lean_Elab_Term_withSynthesizeImp___rarg(x_16, x_17, x_18, x_6, x_7, x_8, x_9, x_10, x_11, x_12);
return x_19;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11; lean_object* x_12; lean_object* x_13;
x_11 = lean_unsigned_to_nat(1u);
x_12 = l_Lean_Syntax_getArg(x_1, x_11);
lean_inc(x_9);
lean_inc(x_8);
lean_inc(x_7);
lean_inc(x_6);
lean_inc(x_5);
lean_inc(x_4);
x_13 = l_Lean_Elab_Tactic_elabRewriteConfig(x_12, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
lean_dec(x_12);
if (lean_obj_tag(x_13) == 0)
{
lean_object* x_14; lean_object* x_15; lean_object* x_16; lean_object* x_17; lean_object* x_18; lean_object* x_19; lean_object* x_20; lean_object* x_21;
x_14 = lean_ctor_get(x_13, 0);
lean_inc(x_14);
x_15 = lean_ctor_get(x_13, 1);
lean_inc(x_15);
lean_dec(x_13);
x_16 = lean_unsigned_to_nat(0u);
x_17 = l_Lean_Syntax_getArg(x_1, x_16);
x_18 = lean_unsigned_to_nat(2u);
x_19 = l_Lean_Syntax_getArg(x_1, x_18);
x_20 = lean_alloc_closure((void*)(l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__2___boxed), 12, 1);
lean_closure_set(x_20, 0, x_14);
x_21 = l_Lean_Elab_Tactic_withRWRulesSeq(x_17, x_19, x_20, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_15);
lean_dec(x_19);
return x_21;
}
else
{
uint8_t x_22;
lean_dec(x_9);
lean_dec(x_8);
lean_dec(x_7);
lean_dec(x_6);
lean_dec(x_5);
lean_dec(x_4);
lean_dec(x_3);
lean_dec(x_2);
x_22 = !lean_is_exclusive(x_13);
if (x_22 == 0)
{
return x_13;
}
else
{
lean_object* x_23; lean_object* x_24; lean_object* x_25;
x_23 = lean_ctor_get(x_13, 0);
x_24 = lean_ctor_get(x_13, 1);
lean_inc(x_24);
lean_inc(x_23);
lean_dec(x_13);
x_25 = lean_alloc_ctor(1, 2, 0);
lean_ctor_set(x_25, 0, x_23);
lean_ctor_set(x_25, 1, x_24);
return x_25;
}
}
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__1___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12, lean_object* x_13) {
_start:
{
uint8_t x_14; lean_object* x_15;
x_14 = lean_unbox(x_3);
lean_dec(x_3);
x_15 = l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__1(x_1, x_2, x_14, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12, x_13);
return x_15;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__2___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10, lean_object* x_11, lean_object* x_12) {
_start:
{
uint8_t x_13; lean_object* x_14;
x_13 = lean_unbox(x_2);
lean_dec(x_2);
x_14 = l_Lean_Elab_Tactic_Conv_evalRewrite___lambda__2(x_1, x_13, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10, x_11, x_12);
return x_14;
}
}
LEAN_EXPORT lean_object* l_Lean_Elab_Tactic_Conv_evalRewrite___boxed(lean_object* x_1, lean_object* x_2, lean_object* x_3, lean_object* x_4, lean_object* x_5, lean_object* x_6, lean_object* x_7, lean_object* x_8, lean_object* x_9, lean_object* x_10) {
_start:
{
lean_object* x_11;
x_11 = l_Lean_Elab_Tactic_Conv_evalRewrite(x_1, x_2, x_3, x_4, x_5, x_6, x_7, x_8, x_9, x_10);
lean_dec(x_1);
return x_11;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__1() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("Lean", 4);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_box(0);
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__1;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__3() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("Parser", 6);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__4() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__3;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("Tactic", 6);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__6() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__4;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("Conv", 4);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__8() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__6;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__9() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("rewrite", 7);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__10() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__8;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__9;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__11() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("Elab", 4);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__12() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__11;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__13() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__12;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__14() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__13;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__15() {
_start:
{
lean_object* x_1;
x_1 = lean_mk_string_from_bytes("evalRewrite", 11);
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__14;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__15;
x_3 = lean_name_mk_string(x_1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__17() {
_start:
{
lean_object* x_1;
x_1 = l_Lean_Elab_Tactic_tacticElabAttribute;
return x_1;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__18() {
_start:
{
lean_object* x_1;
x_1 = lean_alloc_closure((void*)(l_Lean_Elab_Tactic_Conv_evalRewrite___boxed), 10, 0);
return x_1;
}
}
LEAN_EXPORT lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5; lean_object* x_6;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__17;
x_3 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__10;
x_4 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16;
x_5 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__18;
x_6 = l_Lean_KeyedDeclsAttribute_addBuiltin___rarg(x_2, x_3, x_4, x_5, x_1);
return x_6;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__1() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_unsigned_to_nat(13u);
x_2 = lean_unsigned_to_nat(49u);
x_3 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_3, 0, x_1);
lean_ctor_set(x_3, 1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__2() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_unsigned_to_nat(20u);
x_2 = lean_unsigned_to_nat(52u);
x_3 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_3, 0, x_1);
lean_ctor_set(x_3, 1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__3() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__1;
x_2 = lean_unsigned_to_nat(49u);
x_3 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__2;
x_4 = lean_unsigned_to_nat(52u);
x_5 = lean_alloc_ctor(0, 4, 0);
lean_ctor_set(x_5, 0, x_1);
lean_ctor_set(x_5, 1, x_2);
lean_ctor_set(x_5, 2, x_3);
lean_ctor_set(x_5, 3, x_4);
return x_5;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__4() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_unsigned_to_nat(13u);
x_2 = lean_unsigned_to_nat(53u);
x_3 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_3, 0, x_1);
lean_ctor_set(x_3, 1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__5() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = lean_unsigned_to_nat(13u);
x_2 = lean_unsigned_to_nat(64u);
x_3 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_3, 0, x_1);
lean_ctor_set(x_3, 1, x_2);
return x_3;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__6() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3; lean_object* x_4; lean_object* x_5;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__4;
x_2 = lean_unsigned_to_nat(53u);
x_3 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__5;
x_4 = lean_unsigned_to_nat(64u);
x_5 = lean_alloc_ctor(0, 4, 0);
lean_ctor_set(x_5, 0, x_1);
lean_ctor_set(x_5, 1, x_2);
lean_ctor_set(x_5, 2, x_3);
lean_ctor_set(x_5, 3, x_4);
return x_5;
}
}
static lean_object* _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__7() {
_start:
{
lean_object* x_1; lean_object* x_2; lean_object* x_3;
x_1 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__3;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__6;
x_3 = lean_alloc_ctor(0, 2, 0);
lean_ctor_set(x_3, 0, x_1);
lean_ctor_set(x_3, 1, x_2);
return x_3;
}
}
LEAN_EXPORT lean_object* l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange(lean_object* x_1) {
_start:
{
lean_object* x_2; lean_object* x_3; lean_object* x_4;
x_2 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16;
x_3 = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__7;
x_4 = l_Lean_addBuiltinDeclarationRanges(x_2, x_3, x_1);
return x_4;
}
}
lean_object* initialize_Init(uint8_t builtin, lean_object*);
lean_object* initialize_Lean_Meta_Tactic_Rewrite(uint8_t builtin, lean_object*);
lean_object* initialize_Lean_Elab_Tactic_Rewrite(uint8_t builtin, lean_object*);
lean_object* initialize_Lean_Elab_Tactic_Conv_Basic(uint8_t builtin, lean_object*);
static bool _G_initialized = false;
LEAN_EXPORT lean_object* initialize_Lean_Elab_Tactic_Conv_Rewrite(uint8_t builtin, lean_object* w) {
lean_object * res;
if (_G_initialized) return lean_io_result_mk_ok(lean_box(0));
_G_initialized = true;
res = initialize_Init(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Meta_Tactic_Rewrite(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_Tactic_Rewrite(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
res = initialize_Lean_Elab_Tactic_Conv_Basic(builtin, lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__1 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__1();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__1);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__2);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__3 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__3();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__3);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__4 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__4();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__4);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__5);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__6 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__6();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__6);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__7);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__8 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__8();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__8);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__9 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__9();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__9);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__10 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__10();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__10);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__11 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__11();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__11);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__12 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__12();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__12);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__13 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__13();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__13);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__14 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__14();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__14);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__15 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__15();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__15);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__16);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__17 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__17();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__17);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__18 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__18();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite___closed__18);
res = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__1 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__1();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__1);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__2 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__2();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__2);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__3 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__3();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__3);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__4 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__4();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__4);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__5 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__5();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__5);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__6 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__6();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__6);
l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__7 = _init_l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__7();
lean_mark_persistent(l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange___closed__7);
res = l___regBuiltin_Lean_Elab_Tactic_Conv_evalRewrite_declRange(lean_io_mk_world());
if (lean_io_result_is_error(res)) return res;
lean_dec_ref(res);
return lean_io_result_mk_ok(lean_box(0));
}
#ifdef __cplusplus
}
#endif
|
simonklb/ck8s-cluster
|
api/aws/flavors_test.go
|
package aws
import (
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/elastisys/ck8s/api"
)
func TestFlavors(t *testing.T) {
clusterType := api.ServiceCluster
clusterName := "foo"
latestImage := supportedImages["us-west-1"][len(supportedImages["us-west-1"])-1]
type testCase struct {
want, got api.Cluster
}
testCases := []testCase{{
want: &Cluster{
config: AWSConfig{
BaseConfig: api.BaseConfig{
ClusterType: clusterType,
CloudProviderType: api.AWS,
EnvironmentName: clusterName,
DNSPrefix: clusterName,
S3BucketNameHarbor: clusterName + "-harbor",
S3BucketNameVelero: clusterName + "-velero",
S3BucketNameElasticsearch: clusterName + "-es-backup",
S3BucketNameInfluxDB: clusterName + "-influxdb",
S3BucketNameFluentd: clusterName + "-sc-logs",
},
S3Region: "us-west-1",
},
secret: AWSSecret{
BaseSecret: api.BaseSecret{
S3AccessKey: "changeme",
S3SecretKey: "changeme",
},
AWSAccessKeyID: "changeme",
AWSSecretAccessKey: "changeme",
DNSAccessKeyID: "changeme",
DNSSecretAccessKey: "changeme",
},
tfvars: AWSTFVars{
Region: "",
PublicIngressCIDRWhitelist: []string{},
APIServerWhitelist: []string{},
NodeportWhitelist: []string{},
},
},
got: Default(clusterType, clusterName),
}, {
want: &Cluster{
config: AWSConfig{
BaseConfig: api.BaseConfig{
ClusterType: clusterType,
CloudProviderType: api.AWS,
EnvironmentName: clusterName,
DNSPrefix: clusterName,
S3BucketNameHarbor: clusterName + "-harbor",
S3BucketNameVelero: clusterName + "-velero",
S3BucketNameElasticsearch: clusterName + "-es-backup",
S3BucketNameInfluxDB: clusterName + "-influxdb",
S3BucketNameFluentd: clusterName + "-sc-logs",
},
S3Region: "us-west-1",
},
secret: AWSSecret{
BaseSecret: api.BaseSecret{
S3AccessKey: "changeme",
S3SecretKey: "changeme",
},
AWSAccessKeyID: "changeme",
AWSSecretAccessKey: "changeme",
DNSAccessKeyID: "changeme",
DNSSecretAccessKey: "changeme",
},
tfvars: AWSTFVars{
Region: "us-west-1",
PublicIngressCIDRWhitelist: []string{},
APIServerWhitelist: []string{},
NodeportWhitelist: []string{},
MachinesSC: map[string]*api.Machine{
"master-0": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"worker-0": {
NodeType: api.Worker,
Size: "t3.xlarge",
Image: latestImage,
},
"worker-1": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
},
MachinesWC: map[string]*api.Machine{
"master-0": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"worker-0": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
"worker-1": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
},
},
},
got: Development(clusterType, clusterName),
}, {
want: &Cluster{
config: AWSConfig{
BaseConfig: api.BaseConfig{
ClusterType: clusterType,
CloudProviderType: api.AWS,
EnvironmentName: clusterName,
DNSPrefix: clusterName,
S3BucketNameHarbor: clusterName + "-harbor",
S3BucketNameVelero: clusterName + "-velero",
S3BucketNameElasticsearch: clusterName + "-es-backup",
S3BucketNameInfluxDB: clusterName + "-influxdb",
S3BucketNameFluentd: clusterName + "-sc-logs",
},
S3Region: "us-west-1",
},
secret: AWSSecret{
BaseSecret: api.BaseSecret{
S3AccessKey: "changeme",
S3SecretKey: "changeme",
},
AWSAccessKeyID: "changeme",
AWSSecretAccessKey: "changeme",
DNSAccessKeyID: "changeme",
DNSSecretAccessKey: "changeme",
},
tfvars: AWSTFVars{
Region: "us-west-1",
PublicIngressCIDRWhitelist: []string{},
APIServerWhitelist: []string{},
NodeportWhitelist: []string{},
MachinesSC: map[string]*api.Machine{
"master-0": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"master-1": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"master-2": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"worker-0": {
NodeType: api.Worker,
Size: "t3.xlarge",
Image: latestImage,
},
"worker-1": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
"worker-2": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
"worker-3": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
},
MachinesWC: map[string]*api.Machine{
"master-0": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"master-1": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"master-2": {
NodeType: api.Master,
Size: "t3.small",
Image: latestImage,
},
"worker-0": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
"worker-1": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
"worker-2": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
"worker-ck8s-0": {
NodeType: api.Worker,
Size: "t3.large",
Image: latestImage,
},
},
},
},
got: Production(clusterType, clusterName),
}}
for _, tc := range testCases {
if diff := cmp.Diff(
tc.want,
tc.got,
cmp.AllowUnexported(Cluster{}),
cmpopts.IgnoreFields(api.Image{}, "KubeletVersion"),
); diff != "" {
t.Errorf("flavor mismatch (-want +got):\n%s", diff)
}
}
}
|
belgianGeek/open-planner
|
src/js/settings.js
|
<filename>src/js/settings.js
const settings = () => {
// Show settings on btn click
$('.settingsLink').click(() => {
$('.settings__container').toggleClass('hidden flex');
$('.wrapper').addClass('blur');
});
$('.settings__container').click(function(e) {
if (e.target === this) {
let updatedSettings = {};
$(this).toggleClass('hidden flex');
$('.wrapper').removeClass('blur');
if (globalSettings.instance_name !== $('.settings__child__instanceNameContainer__label__input').val()) {
updatedSettings.instance_name = globalSettings.instance_name = $('.settings__child__instanceNameContainer__label__input').val().replace(/\'\'/g, "'");
}
if (globalSettings.instance_description !== $('.settings__child__descriptionContainer__label__textarea').val()) {
updatedSettings.instance_description = globalSettings.instance_description = $('.settings__child__descriptionContainer__label__textarea').val().replace(/\'\'/g, "'");
}
if (globalSettings.sendmail !== $('.toggleMail__Input').prop('checked')) {
updatedSettings.sendmail = globalSettings.sendmail = $('.toggleMail__Input').prop('checked');
}
if (globalSettings.sendcc !== $('.toggleMailCc__Input').prop('checked')) {
updatedSettings.sendcc = globalSettings.sendcc = $('.toggleMailCc__Input').prop('checked');
}
if (globalSettings.sendattachments !== $('.toggleAttachments__Input').prop('checked')) {
updatedSettings.sendattachments = globalSettings.sendattachments = $('.toggleAttachments__Input').prop('checked');
}
if (globalSettings.sender !== $('.settings__child__senderContainer__senderLabel__input').val()) {
updatedSettings.sender = globalSettings.sender = $('.settings__child__senderContainer__senderLabel__input').val();
}
if (globalSettings.smtp_host !== $('.settings__child__mailContainer__smtpHostLabel__input').val()) {
updatedSettings.smtp_host = globalSettings.smtp_host = $('.settings__child__mailContainer__smtpHostLabel__input').val();
}
if (globalSettings.smtp_user !== $('.settings__child__mailContainer__smtpUserLabel__input').val()) {
updatedSettings.smtp_user = globalSettings.smtp_user = $('.settings__child__mailContainer__smtpUserLabel__input').val();
}
if ($('.settings__child__mailContainer__smtpPasswdLabel__input').val() !== '') {
updatedSettings.smtp_passwd = $('.settings__child__mailContainer__smtpPasswdLabel__input').val();
}
if (globalSettings.allowpasswordupdate !== $('.toggleUserPasswordUpdate__Input').prop('checked')) {
updatedSettings.allowpasswordupdate = globalSettings.allowpasswordupdate = $('.toggleUserPasswordUpdate__Input').prop('checked');
}
if (globalSettings.allowsearchpageaccess !== $('.toggleSearchPageUserAccess__Input').prop('checked')) {
updatedSettings.allowsearchpageaccess = globalSettings.allowsearchpageaccess = $('.toggleSearchPageUserAccess__Input').prop('checked');
}
if (globalSettings.displaymyrequestsmenu !== $('.toggleMyRequests__Input').prop('checked')) {
updatedSettings.displaymyrequestsmenu = globalSettings.displaymyrequestsmenu = $('.toggleMyRequests__Input').prop('checked');
}
if (globalSettings.sendrequestdeletionmail !== $('.toggleRequestDeletionMail__Input').prop('checked')) {
updatedSettings.sendrequestdeletionmail = globalSettings.sendrequestdeletionmail = $('.toggleRequestDeletionMail__Input').prop('checked');
}
if (Object.keys(updatedSettings).length > 0) {
socket.emit('settings', updatedSettings);
}
}
});
}
settings();
|
ThisIsNotRocketScience/Syntonovo_PAN
|
Raspberry/ArpSettings.h
|
#pragma once
#ifndef ARPSETTINGS_H
#define ARPSETTINGS_H
#ifndef __max
#define __max(x,y) (((x)>(y))?(x):(y))
#endif
#ifndef __min
#define __min(x,y) (((x)<(y))?(x):(y))
#endif
#ifdef WIN32
#define PACKED
#else
#define PACKED __attribute__((packed))
#endif
typedef enum ClockSource_t : char
{
Clock1,
Clock2,
Clock3,
__ClockSource_Count
} PACKED ClockSource_t;
typedef enum ArpeggioMode_t : char
{
Arp_Up,
Arp_Down,
Arp_UpDown,
Arp_DownUp,
Arp_InOrder,
Arp_ReverseOrder,
Arp_Random,
__ArpeggioMode_Count
} PACKED ArpeggioMode_t;
typedef enum ArpeggioOctaves_t : char
{
Oct_None,
Oct_One,
Oct_Two,
Oct_Three,
Oct_Four,
__ArpeggioOctaves_Count
} PACKED ArpeggioOctaves_t;
typedef enum ArpeggioOctaveInterleaving_t : char
{
Interleave_Pattern,
Interleave_Note,
__ArpeggioOctavesInterleaving_Count
} PACKED ArpeggioOctaveInterleaving_t;
#define MAXBOTTOM 32
#define MAXTOP 8
class SpeedMode_t
{
public:
SpeedMode_t()
{
Top = 4;
Bottom = 4;
}
void Delta(int delta)
{
int B = Bottom;
int T = Top;
B += delta>0?1:-1;
if (B > MAXBOTTOM) {
if (T < MAXTOP)
{
T++;
B = 1;
}
else
{
B = MAXBOTTOM;
}
}
else
{
if (B < 1)
{
if (T > 1)
{
T--;
B = MAXBOTTOM;
}
else
{
B = 1;
}
}
}
Bottom = B;
Top = T;
}
uint8_t Top;
uint8_t Bottom;
void DeltaBottom(int delta)
{
int B = Bottom + delta;
if (B < 1) { B = 1; }
else
{
if (B > MAXBOTTOM) B = MAXBOTTOM;
}
Bottom = B;
}
void DeltaTop(int delta)
{
int T = Top + delta;
if (T < 1) { T = 1; }
else
{
if (T > MAXTOP) T = MAXTOP;
}
Top = T;
}
} PACKED;
typedef enum VelocityMode_t : char
{
VelMode_MaxVelocity,
VelMode_LastVelocity,
VelMode_NoteVelocity,
__VelocityMode_Count
} PACKED VelocityMode_t;
typedef enum TimeSource_t : char
{
TimeSource_Internal,
TimeSource_USB,
TimeSource_DIN,
__TimeSource_Count
} PACKED TimeSource_t;
class ClockChannelSettings_t
{
public:
ClockChannelSettings_t()
{
Source = TimeSource_Internal;
Division.Bottom = 4;
Division.Top = 4;
}
TimeSource_t Source;
SpeedMode_t Division;
} PACKED;
class ClockSettings_t
{
public:
ClockSettings_t()
{
BPM = 120;
Running = false;
}
ClockChannelSettings_t Channel[3];
TimeSource_t ResetSource;
int BPM;
bool Running;
} PACKED;
class ArpSettings_t
{
public:
ArpSettings_t()
{
Mode = ArpeggioMode_t::Arp_UpDown;
Transpose = 0;
Speed.Top = 4;
Speed.Bottom = 4;
Octaves = Oct_None;
//Octaves = Oct_One;
VelocityMode = VelMode_NoteVelocity;
ResetTimeOnFirstKey = true;
KillNotesAfterLastNoteOff = true;
Interleave = Interleave_Pattern;
Rhythm = 255;
TimingSource = TimeSource_Internal;
}
TimeSource_t TimingSource;
uint8_t Rhythm;
ArpeggioMode_t Mode;
SpeedMode_t Speed;
VelocityMode_t VelocityMode;
ArpeggioOctaveInterleaving_t Interleave;
ArpeggioOctaves_t Octaves;
int Transpose;
bool ResetTimeOnFirstKey;
bool KillNotesAfterLastNoteOff;
bool Hold;
} PACKED;
#endif
|
ycyangchun/TemplateAppProject
|
app/src/main/java/com/zhcw/lib/BASE64/DesUtil.java
|
<filename>app/src/main/java/com/zhcw/lib/BASE64/DesUtil.java<gh_stars>0
package com.zhcw.lib.BASE64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class DesUtil {
public static final String password = "<PASSWORD>";
public static String encryptDES(String encryptString, String encryptKey) {
String enStr = encryptString;
try {
SecretKeySpec key = new SecretKeySpec(encryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
String encodeForUrl = (new BASE64Encoder()).encode(encryptedData);
//转成针对url的base64编码
encodeForUrl = encodeForUrl.replaceAll("\\=", "!");
encodeForUrl = encodeForUrl.replaceAll("\\+", "*");
encodeForUrl = encodeForUrl.replaceAll("\\/", "-");
//去除换行
encodeForUrl = encodeForUrl.replaceAll("\\n", "");
encodeForUrl = encodeForUrl.replaceAll("\\r", "");
//转换*号为 -x-
//防止有违反协议的字符
enStr = encodeSpecialLetter(encodeForUrl);
} catch (Exception e) {
} finally {
return enStr;
}
}
public static String decryptDES(String decryptString, String decryptKey) {
String deStr = decryptString;
try {
decryptString = decodeSpecialLetter(decryptString);
decryptString = decryptString.replaceAll("\\!", "=");
decryptString = decryptString.replaceAll("\\*", "+");
decryptString = decryptString.replaceAll("\\-", "/");
BASE64Decoder decoder = new BASE64Decoder();
byte[] byteMi = decoder.decodeBuffer(decryptString);
SecretKeySpec key = new SecretKeySpec(decryptKey.getBytes(), "DES");
Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decryptedData = cipher.doFinal(byteMi);
deStr = new String(decryptedData, "UTF-8");
} catch (Exception e) {
} finally {
return deStr;
}
}
/**
* 转换*号为 -x-,
* 为了防止有违反协议的字符,-x 转换为-xx
*
* @param str
* @return
*/
private static String encodeSpecialLetter(String str) {
str = str.replaceAll("\\-x", "-xx");
str = str.replaceAll("\\*", "-x-");
return str;
}
/**
* 转换 -x-号为*,-xx转换为-x
*
* @param str
* @return
*/
private static String decodeSpecialLetter(String str) {
str = str.replaceAll("\\-x-", "*");
str = str.replaceAll("\\-xx", "-x");
return str;
}
}
|
rewriting/tom
|
utils/eclipse-plugin/plugin/src/fr/loria/eclipse/jtom/editor/util/TomColorManager.java
|
<reponame>rewriting/tom
/*
TOM - To One Matching Compiler
Copyright (C) 2004 Inria
Nancy, France.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
<NAME> e-mail: <EMAIL>
<NAME> e-mail: <EMAIL>
*/
package fr.loria.eclipse.jtom.editor.util;
import java.util.*;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.RGB;
import org.eclipse.swt.widgets.Display;
import org.eclipse.jdt.ui.text.IColorManager;
import org.eclipse.jface.resource.StringConverter;
/**
* Manager for colors used in the Tom editor
*/
public class TomColorManager implements IColorManager{
public static final RGB RED_COLOR= new RGB(255, 0, 0);
public static final RGB GREEN_COLOR= new RGB(0, 255, 0);
public static final RGB BLUE_COLOR= new RGB(0, 0, 255);
public static final RGB REDGREEN_COLOR= new RGB(255, 255, 0);
public static final RGB GREENBLUE_COLOR= new RGB(0, 255, 255);
public static final RGB REDBLUE_COLOR= new RGB(255, 0, 255);
public static final RGB WHITE_COLOR= new RGB(255, 255, 255);
public static final RGB BLACK_COLOR= new RGB(0, 0, 0);
public static final RGB OTHER_COLOR= new RGB(128, 128, 128);
public static final RGB MULTI_LINE_COMMENT_COLOR= new RGB(128, 0, 0);
public static final RGB SINGLE_LINE_COMMENT_COLOR= new RGB(128, 128, 0);
public static final RGB KEYWORD_COLOR= new RGB(0, 0, 128);
public static final RGB TYPE_COLOR= new RGB(0, 0, 128);
public static final RGB STRING_COLOR= new RGB(128, 0, 0);
public static final RGB DEFAULT_COLOR= new RGB(128, 128, 0);
public static final RGB TOM_COLOR= new RGB(0, 128, 128);
public static final RGB JAVADOC_KEYWORD_COLOR= new RGB(0, 128, 0);
public static final RGB JAVADOC_TAG_COLOR= new RGB(128, 128, 128);
public static final RGB JAVADOC_LINK_COLOR= new RGB(128, 128, 128);
public static final RGB JAVADOC_DEFAULT_COLOR= new RGB(0, 128, 128);
protected Map<RGB, Color> fColorTable= new HashMap<RGB, Color>(20);
/**
* Release all of the color resources held onto by the receiver.
*/
public void dispose() {
Iterator<Color> e= fColorTable.values().iterator();
while (e.hasNext())
((Color) e.next()).dispose();
}
/**
* Return the Color that is stored in the Color table as rgb.
*/
public Color getColor(RGB rgb) {
Color color= (Color) fColorTable.get(rgb);
if (color == null) {
color= new Color(Display.getCurrent(), rgb);
fColorTable.put(rgb, color);
}
return color;
}
public Color getColor(String color) {
return getColor(StringConverter.asRGB(color));
}
} //class TomColorProvider
|
brycewang-microsoft/iot-sdks-e2e-fx
|
test-runner/conftest.py
|
<reponame>brycewang-microsoft/iot-sdks-e2e-fx
# http://localhost:8099, Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
import pytest
import sys
import logging
from adapters import adapter_config
from dump_object import dump_object
import runtime_capabilities
import scenarios
from distutils.version import LooseVersion
from horton_logging import set_logger
from horton_settings import settings, ObjectWithAdapter
from fixtures import ( # noqa: F401
eventhub,
registry,
friend,
leaf_device,
service,
test_device,
test_module,
system_control,
longhaul_control_device,
telemetry_payload,
device_provisioning,
)
from hooks import ( # noqa: F401
pytest_runtest_logstart,
pytest_runtest_logfinish,
pytest_runtest_teardown,
pytest_pyfunc_call,
pytest_runtestloop,
)
# default to logging.INFO
logging.basicConfig(level=logging.INFO)
# AMQP is chatty at INFO level. Dial this down to WARNING.
logging.getLogger("uamqp").setLevel(level=logging.WARNING)
logging.getLogger("paho").setLevel(level=logging.DEBUG)
logging.getLogger("adapters.direct_azure_rest.amqp_service_client").setLevel(
level=logging.WARNING
) # info level can leak credentials into the log
logging.getLogger("azure.iot.device").setLevel(level=logging.INFO)
logging.getLogger("azure.eventhub").setLevel(level=logging.DEBUG)
logging.getLogger("asyncio").setLevel(logging.DEBUG)
class Unbuffered(object):
def __init__(self, stream):
self.stream = stream
def write(self, data):
self.stream.write(data)
self.stream.flush()
def writelines(self, datas):
self.stream.writelines(datas)
self.stream.flush()
def __getattr__(self, attr):
return getattr(self.stream, attr)
sys.stdout = Unbuffered(sys.stdout)
sys.stderr = Unbuffered(sys.stderr)
def pytest_addoption(parser):
parser.addoption(
"--scenario",
help="scenario to run",
required=True,
type=str,
choices=scenarios.scenarios.keys(),
)
parser.addoption(
"--local",
action="store_true",
default=False,
help="run tests against local module (probably in debugger)",
)
parser.addoption(
"--transport",
action="store",
default="mqtt",
help="transport to use for test",
choices=["mqtt", "mqttws", "amqp", "amqpws"],
)
parser.addoption(
"--python_inproc",
action="store_true",
default=False,
help="run tests for the pythonv2 wrapper in-proc",
)
parser.addoption(
"--debug-container",
action="store_true",
default=False,
help="adjust run for container debugging (disable timeouts)",
)
parser.addoption(
"--async",
action="store_true",
default=False,
help="run async tests (currently pythonv2 only)",
)
skip_for_c_connection_string = set(
["invokesModuleMethodCalls", "invokesDeviceMethodCalls"]
)
skip_for_python_inproc = set(["invokesModuleMethodCalls", "invokesDeviceMethodCalls"])
def _get_marker(item, marker):
if LooseVersion(pytest.__version__) < LooseVersion("3.6"):
return item.get_marker(marker)
else:
return item.get_closest_marker(marker)
def remove_tests_not_in_marker_list(items, markers):
"""
remove all items that don't have one of the specified markers set
"""
remaining = []
for item in items:
keep = False
for marker in markers:
if _get_marker(item, marker):
keep = True
if keep:
remaining.append(item)
items[:] = remaining
def skip_tests_by_marker(items, skiplist, reason):
skip_me = pytest.mark.skip(reason=reason)
for markname in skiplist:
print("skipping {} because {}:".format(markname, reason))
for item in items:
if markname in item.keywords:
item.add_marker(skip_me)
print(" " + str(item))
__tracebackhide__ = True
def set_transport(transport):
print("Using " + transport)
settings.friend_module.transport = "mqtt"
settings.horton.transport = transport
settings.test_module.transport = transport
settings.leaf_device.transport = transport
settings.test_device.transport = transport
def set_local_system_control():
if settings.system_control.adapter_address:
settings.system_control.adapter_address = "http://localhost:{}".format(
settings.system_control.container_port
)
def set_local():
print("Running against local module")
if settings.test_module.connection_type == "environment":
settings.test_module.connection_type = "connection_string_with_edge_gateway"
# any objects that were previously using the test module host port now use
# the test module container port.
for obj in (settings.test_module, settings.test_device, settings.leaf_device):
if obj.host_port == settings.test_module.host_port:
obj.adapter_address = "http://localhost:{}".format(
settings.test_module.container_port
)
set_local_system_control()
def set_python_inproc():
print("Using pythonv2 wrapper in-proc")
settings.test_module.adapter_address = "python_inproc"
settings.test_device.adapter_address = "python_inproc"
settings.leaf_device.adapter_address = "python_inproc"
if settings.test_module.connection_type == "environment":
settings.test_module.connection_type = "connection_string_with_edge_gateway"
set_local_system_control()
def set_sas_renewal():
return
if settings.test_module.device_id:
settings.test_module.wrapper_api.set_flags_sync({"sas_renewal_interval": 60})
if settings.test_device.device_id:
settings.test_device.wrapper_api.set_flags_sync({"sas_renewal_interval": 60})
def set_async():
if settings.test_module.device_id:
settings.test_module.wrapper_api.set_flags_sync({"test_async": True})
else:
raise Exception("--async specified, but test module does not support async")
def add_service_settings():
class ServiceSettings:
pass
settings.eventhub = ObjectWithAdapter("eventhub", "eventhub")
settings.eventhub.connection_string = settings.iothub.connection_string
settings.eventhub.adapter_address = "direct_rest"
settings.registry = ObjectWithAdapter("registry", "iothub_registry")
settings.registry.connection_string = settings.iothub.connection_string
settings.registry.adapter_address = settings.test_module.adapter_address
settings.service = ObjectWithAdapter("service", "iothub_service")
settings.service.connection_string = settings.iothub.connection_string
settings.service.adapter_address = settings.test_module.adapter_address
def adjust_surfaces_for_missing_implementations():
if (
settings.test_module.language
not in runtime_capabilities.language_has_service_client
):
settings.registry.adapter_address = "direct_rest"
settings.service.adapter_address = "direct_rest"
if (
settings.test_module.language
not in runtime_capabilities.language_has_leaf_device_client
):
settings.leaf_device.adapter_address = settings.friend_module.adapter_address
settings.leaf_device.container_port = settings.friend_module.container_port
settings.leaf_device.host_port = settings.friend_module.host_port
settings.leaf_device.language = settings.friend_module.language
# adapter has changed. recollect capabilities.
runtime_capabilities.collect_capabilities(settings.leaf_device)
if (
settings.test_module.language
not in runtime_capabilities.language_has_full_device_client
):
settings.test_device.adapter_address = None
def only_include_scenario_tests(items, scenario_name):
markers = scenarios.scenarios[scenario_name]
remove_tests_not_in_marker_list(items, markers)
def pytest_collection_modifyitems(config, items):
print("")
if not settings.test_module.connection_string:
raise Exception(
"settings are missing credentials. Please run `horton get_credentials` and try again"
)
set_transport(config.getoption("--transport"))
if config.getoption("--local"):
set_local()
if config.getoption("--python_inproc"):
set_python_inproc()
set_logger()
runtime_capabilities.collect_all_capabilities()
if config.getoption("--async"):
set_async()
add_service_settings()
adjust_surfaces_for_missing_implementations()
only_include_scenario_tests(items, config.getoption("--scenario"))
if "stress" in config.getoption("--scenario"):
set_sas_renewal()
if getattr(config, "_origargs", None):
adapter_config.logger("HORTON: starting run: {}".format(config._origargs))
elif getattr(config, "invocation_params", None):
adapter_config.logger(
"HORTON: starting run: {}".format(config.invocation_params.args)
)
if config.getoption("--debug-container"):
print("Debugging the container. Removing all timeouts")
adapter_config.default_api_timeout = 3600
config._env_timeout = 0
dump_object(settings)
|
fahadnasrullah109/KalturaClient-Android
|
KalturaClient/src/main/java/com/kaltura/client/types/ReoccurringVendorCredit.java
|
<filename>KalturaClient/src/main/java/com/kaltura/client/types/ReoccurringVendorCredit.java
// ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platfroms allow them to do with
// text.
//
// Copyright (C) 2006-2018 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.types;
import android.os.Parcel;
import com.google.gson.JsonObject;
import com.kaltura.client.Params;
import com.kaltura.client.enums.VendorCreditRecurrenceFrequency;
import com.kaltura.client.utils.GsonParser;
import com.kaltura.client.utils.request.MultiRequestBuilder;
/**
* This class was generated using exec.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
@SuppressWarnings("serial")
@MultiRequestBuilder.Tokenizer(ReoccurringVendorCredit.Tokenizer.class)
public class ReoccurringVendorCredit extends TimeRangeVendorCredit {
public interface Tokenizer extends TimeRangeVendorCredit.Tokenizer {
String frequency();
}
private VendorCreditRecurrenceFrequency frequency;
// frequency:
public VendorCreditRecurrenceFrequency getFrequency(){
return this.frequency;
}
public void setFrequency(VendorCreditRecurrenceFrequency frequency){
this.frequency = frequency;
}
public void frequency(String multirequestToken){
setToken("frequency", multirequestToken);
}
public ReoccurringVendorCredit() {
super();
}
public ReoccurringVendorCredit(JsonObject jsonObject) throws APIException {
super(jsonObject);
if(jsonObject == null) return;
// set members values:
frequency = VendorCreditRecurrenceFrequency.get(GsonParser.parseString(jsonObject.get("frequency")));
}
public Params toParams() {
Params kparams = super.toParams();
kparams.add("objectType", "KalturaReoccurringVendorCredit");
kparams.add("frequency", this.frequency);
return kparams;
}
public static final Creator<ReoccurringVendorCredit> CREATOR = new Creator<ReoccurringVendorCredit>() {
@Override
public ReoccurringVendorCredit createFromParcel(Parcel source) {
return new ReoccurringVendorCredit(source);
}
@Override
public ReoccurringVendorCredit[] newArray(int size) {
return new ReoccurringVendorCredit[size];
}
};
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(this.frequency == null ? -1 : this.frequency.ordinal());
}
public ReoccurringVendorCredit(Parcel in) {
super(in);
int tmpFrequency = in.readInt();
this.frequency = tmpFrequency == -1 ? null : VendorCreditRecurrenceFrequency.values()[tmpFrequency];
}
}
|
kuhjunge/NeoDatabaseDesigner
|
NeoDBDesigner/src/main/java/de/mach/tools/neodesigner/inex/nexport/pdf/PdfConf.java
|
<reponame>kuhjunge/NeoDatabaseDesigner<filename>NeoDBDesigner/src/main/java/de/mach/tools/neodesigner/inex/nexport/pdf/PdfConf.java
/* Copyright (C) 2018 <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. */
package de.mach.tools.neodesigner.inex.nexport.pdf;
/** Interface über welches der Path Manager seine Informationen beziehen kann.
*
* @author cd */
public interface PdfConf {
/** Pfad zur MikTex Installation.
*
* @return der Pfad */
String getMikTexPath();
/** Pfad zum PDF.
*
* @return der Pfad */
String getPdfFile();
/** gibt den PDF Title zurück.
*
* @return Title als String */
String getPdfTitle();
/** Pfad des Config Ordners.
*
* @return der Pfad */
String getConfigPath();
/** Setze den Pfad der MikTex Installation.
*
* @param path der Pfad */
void setMikTexPath(String path);
/** Setze die PDF Datei.
*
* @param path der Pfad */
void setPdfFile(String path);
/** Setzt den PDF Title.
*
* @param title der neue Title */
void setPdfTitle(String title);
/** Setzt den PDF Autohr.
*
* @param title der neue Title */
void setPdfAuthor(String title);
/** Speichert die Informationen. */
void save();
String getPdfAuthor();
}
|
jordandavidson/MuckyFoot-UrbanChaos
|
fallen/outro/mf.h
|
<reponame>jordandavidson/MuckyFoot-UrbanChaos<gh_stars>100-1000
//
// Functions that act on the imported meshes
//
#ifndef _MF_
#define _MF_
#include "imp.h"
//
// Loads all the textures for the mesh.
//
void MF_load_textures(IMP_Mesh *im);
//
// Backs up the mesh, so it can be rotated later on.
//
void MF_backup(IMP_Mesh *im);
//
// MAKE SURE YOU'VE ALREADY CALLED MF_backup()
//
void MF_rotate_mesh(
IMP_Mesh *im,
float yaw,
float pitch = 0.0F,
float roll = 0.0F,
float scale = 1.0F,
float pos_x = 0.0F,
float pos_y = 0.0F,
float pos_z = 0.0F);
void MF_rotate_mesh(
IMP_Mesh *im,
float pos_x,
float pos_y,
float pos_z,
float matrix[9]); // Matrix must be normalised or the mesh normals will be fucked up.
//
// Transforms all the points of the mesh into the OS_trans array
//
void MF_transform_points(IMP_Mesh *im);
//
// Inverts the zbuffer-zeds of all the transformed points. Call this
// function after calling MF_transform_points().
//
void MF_invert_zeds(IMP_Mesh *im);
//
// Lights the sverts of the mesh from the given parallel light.
//
void MF_ambient(
IMP_Mesh *im,
float light_dx, // The light vector does not need to
float light_dy, // be normalised...
float light_dz,
SLONG light_r,
SLONG light_g,
SLONG light_b,
SLONG amb_r,
SLONG amb_g,
SLONG amb_b);
//
// Sets the (lu,lv)s of the vertices of the mesh to give a diffuse spotlight.
// It also sets the colour field of the shared vertices for diffuse lighting
// depending on the normal and the bumpmap (du,dv)s in the shared vectices.
//
void MF_diffuse_spotlight(
IMP_Mesh *im,
float light_x,
float light_y,
float light_z,
float light_matrix[9],
float light_lens); // The bigger the lens the smaller the spotlight.
//
// Sets the (lu,lv)s of the shared vertices of the given light to
// create a specular highlight. This treats the light as a spot-light.
// It also sets the 'colour' field which should be used as a gouraud value
// for the specular map.
//
void MF_specular_spotlight(
IMP_Mesh *im,
float light_x,
float light_y,
float light_z,
float light_matrix[9],
float light_lens); // The bigger the lens the smaller the spotlight.
//
// Adds all the faces of the mesh normally...
//
void MF_add_triangles_normal(IMP_Mesh *im, ULONG draw = OS_DRAW_NORMAL);
//
// Adds all the faces of the mesh normally but uses the given gouraud shade
// value for all the points.
//
void MF_add_triangles_normal_colour(IMP_Mesh *im, ULONG draw = OS_DRAW_NORMAL, ULONG colour = 0xffffff);
//
// Creates each face using the (u,v)s from the verts and the colour from the
// sverts. Draws using the given texture page.
//
void MF_add_triangles_light (IMP_Mesh *im, OS_Texture *ot, ULONG draw = OS_DRAW_ADD | OS_DRAW_CLAMP);
void MF_add_triangles_light_bumpmapped(IMP_Mesh *im, OS_Texture *ot, ULONG draw = OS_DRAW_ADD | OS_DRAW_CLAMP);
//
// Adds the faces using a mesh light with MF_specular_spotlight. It takes the (u,v) from
// the sverts. The texture (ot) should be a specular spotlight texture.
//
void MF_add_triangles_specular (IMP_Mesh *im, OS_Texture *ot, ULONG draw = OS_DRAW_ADD | OS_DRAW_CLAMP);
void MF_add_triangles_specular_bumpmapped(IMP_Mesh *im, OS_Texture *ot, ULONG draw = OS_DRAW_ADD | OS_DRAW_CLAMP);
//
// Draws the specular shadowed using the diffuse spotlight.
//
void MF_add_triangles_specular_shadowed(IMP_Mesh *im, OS_Texture *ot_specdot, OS_Texture *ot_diffdot, ULONG draw = OS_DRAW_ADD | OS_DRAW_CLAMP | OS_DRAW_TEX_MUL);
//
// Draws the visible edges of the mesh in wireframe.
//
void MF_add_wireframe(IMP_Mesh *im, OS_Texture *ot, ULONG colour, float width = 0.002F, ULONG draw = OS_DRAW_ADD | OS_DRAW_NOZWRITE);
//
// Bumpmapping with single pass hardware... pass should be 0 or 1.
//
void MF_add_triangles_bumpmapped_pass(IMP_Mesh *im, SLONG pass, ULONG draw = OS_DRAW_NORMAL);
//
// Adds the textures for the mesh. If the material has a bumpmap, then the texture is drawn
// with multiply and decal. Otherwise it is just plotted.
//
void MF_add_triangles_texture_after_bumpmap(IMP_Mesh *im);
#endif
|
eaglezzb/rsdc
|
Sankore-AppToolkit/src/gui/SyntaxHighlighter.cpp
|
<reponame>eaglezzb/rsdc<filename>Sankore-AppToolkit/src/gui/SyntaxHighlighter.cpp
#include <QTextEdit>
#include "SyntaxHighlighter.h"
#include "core/globalDefs.h"
SyntaxHighlighter::SyntaxHighlighter(QObject *parent):QSyntaxHighlighter(parent)
{
QSyntaxHighlighter::setDocument(dynamic_cast<QTextEdit*>(parent)->document());
}
SyntaxHighlighter::~SyntaxHighlighter()
{
}
void SyntaxHighlighter::highlightBlock(const QString &text)
{
// Will be overloaded by the children
Q_UNUSED(text);
}
// -------------------------------------------------------------------------------
JSSyntaxHighlighter::JSSyntaxHighlighter(QObject *parent):SyntaxHighlighter(parent)
{
HighlightingRule rule;
// Keywords
keywordFormat.setForeground(Qt::darkBlue);
keywordFormat.setFontWeight(QFont::Bold);
QStringList keywordPatterns;
keywordPatterns << "\\bbreak\\b"
<< "\\bcase\\b"
<< "\\bcatch\\b"
<< "\\bcontinue\\b"
<< "\\bdebugger\\b"
<< "\\bdefault\\b"
<< "\\bdelete\\b"
<< "\\bdo\\b"
<< "\\belse\\b"
<< "\\bfinally\\b"
<< "\\bfor\\b"
<< "\\bfunction\\b"
<< "\\bif\\b"
<< "\\bin\\b"
<< "\\binstanceof\\b"
<< "\\bnew\\b"
<< "\\breturn\\b"
<< "\\bswitch\\b"
<< "\\bthis\\b"
<< "\\bthrow\\b"
<< "\\btry\\b"
<< "\\btypeof\\b"
<< "\\bvar\\b"
<< "\\bvoid\\b"
<< "\\bwhile\\b"
<< "\\bwith\\b"
;
foreach (const QString &pattern, keywordPatterns) {
rule.pattern = QRegExp(pattern);
rule.format = keywordFormat;
highlightingRules.append(rule);
}
// Class
classFormat.setFontWeight(QFont::Bold);
classFormat.setForeground(Qt::darkMagenta);
rule.pattern = QRegExp("\\bQ[A-Za-z]+\\b");
rule.format = classFormat;
highlightingRules.append(rule);
// Single Line Comment
singleLineCommentFormat.setForeground(Qt::darkGreen);
rule.pattern = QRegExp("//[^\n]*");
rule.format = singleLineCommentFormat;
highlightingRules.append(rule);
// Multi Line Comment
multiLineCommentFormat.setForeground(Qt::darkGreen);
// Quotation
quotationFormat.setForeground(Qt::darkRed);
rule.pattern = QRegExp("\".*\"");
rule.format = quotationFormat;
highlightingRules.append(rule);
// functionFormat.setFontItalic(true);
// functionFormat.setForeground(Qt::blue);
// rule.pattern = QRegExp("\\b[A-Za-z0-9_]+(?=\\()");
// rule.format = functionFormat;
// highlightingRules.append(rule);
commentStartExpression = QRegExp("/\\*");
commentEndExpression = QRegExp("\\*/");
}
JSSyntaxHighlighter::~JSSyntaxHighlighter()
{
}
void JSSyntaxHighlighter::highlightBlock(const QString &text)
{
foreach (const HighlightingRule &rule, highlightingRules)
{
QRegExp expression(rule.pattern);
int index = expression.indexIn(text);
while (index >= 0)
{
int length = expression.matchedLength();
setFormat(index, length, rule.format);
index = expression.indexIn(text, index + length);
}
}
setCurrentBlockState(0);
int startIndex = 0;
if (previousBlockState() != 1)
startIndex = commentStartExpression.indexIn(text);
while (startIndex >= 0)
{
int endIndex = commentEndExpression.indexIn(text, startIndex);
int commentLength;
if(endIndex == -1)
{
setCurrentBlockState(1);
commentLength = text.length() - startIndex;
}
else
{
commentLength = endIndex - startIndex + commentEndExpression.matchedLength();
}
setFormat(startIndex, commentLength, multiLineCommentFormat);
startIndex = commentStartExpression.indexIn(text, startIndex + commentLength);
}
}
// -------------------------------------------------------------------------------
XMLSyntaxHighlighter::XMLSyntaxHighlighter(QObject *parent):SyntaxHighlighter(parent)
{
fmtSyntaxChar.setForeground(Qt::blue);
fmtElementName.setForeground(Qt::darkRed);
fmtComment.setForeground(Qt::darkGreen);
fmtAttributeName.setForeground(Qt::red);
fmtAttributeValue.setForeground(Qt::blue);
fmtError.setForeground(Qt::darkMagenta);
fmtOther.setForeground(Qt::black);
}
XMLSyntaxHighlighter::~XMLSyntaxHighlighter()
{
}
void XMLSyntaxHighlighter::highlightBlock(const QString &text)
{
int i = 0;
int pos = 0;
int brackets = 0;
state = (previousBlockState() == InElement ? ExpectAttributeOrEndOfElement : NoState);
if (previousBlockState() == InComment)
{
// search for the end of the comment
QRegExp expression("[^-]*-([^-][^-]*-)*->");
pos = expression.indexIn(text, i);
if (pos >= 0)
{
// end comment found
const int iLength = expression.matchedLength();
setFormat(0, iLength - 3, fmtComment);
setFormat(iLength - 3, 3, fmtSyntaxChar);
i += iLength; // skip comment
}
else
{
// in comment
setFormat(0, text.length(), fmtComment);
setCurrentBlockState(InComment);
return;
}
}
for (; i < text.length(); i++)
{
switch (text.at(i).toAscii())
{
case '<':
brackets++;
if (brackets == 1)
{
setFormat(i, 1, fmtSyntaxChar);
state = ExpectElementNameOrSlash;
}
else
{
// wrong bracket nesting
setFormat(i, 1, fmtError);
}
break;
case '>':
brackets--;
if (brackets == 0)
{
setFormat(i, 1, fmtSyntaxChar);
}
else
{
// wrong bracket nesting
setFormat( i, 1, fmtError);
}
state = NoState;
break;
case '/':
if (state == ExpectElementNameOrSlash)
{
state = ExpectElementName;
setFormat(i, 1, fmtSyntaxChar);
}
else
{
if (state == ExpectAttributeOrEndOfElement)
{
setFormat(i, 1, fmtSyntaxChar);
}
else
{
processDefaultText(i, text);
}
}
break;
case '=':
if (state == ExpectEqual)
{
state = ExpectAttributeValue;
setFormat(i, 1, fmtOther);
}
else
{
processDefaultText(i, text);
}
break;
case '\'':
case '\"':
if (state == ExpectAttributeValue)
{
// search attribute value
QRegExp expression("\"[^<\"]*\"|'[^<']*'");
pos = expression.indexIn(text, i);
if (pos == i) // attribute value found ?
{
const int iLength = expression.matchedLength();
setFormat(i, 1, fmtOther);
setFormat(i + 1, iLength - 2, fmtAttributeValue);
setFormat(i + iLength - 1, 1, fmtOther);
i += iLength - 1; // skip attribute value
state = ExpectAttributeOrEndOfElement;
}
else
{
processDefaultText(i, text);
}
}
else
{
processDefaultText(i, text);
}
break;
case '!':
if (state == ExpectElementNameOrSlash)
{
// search comment
QRegExp expression("<!--[^-]*-([^-][^-]*-)*->");
pos = expression.indexIn(text, i - 1);
if (pos == i - 1) // comment found ?
{
const int iLength = expression.matchedLength();
setFormat(pos, 4, fmtSyntaxChar);
setFormat(pos + 4, iLength - 7, fmtComment);
setFormat(iLength - 3, 3, fmtSyntaxChar);
i += iLength - 2; // skip comment
state = NoState;
brackets--;
}
else
{
// Try find multiline comment
QRegExp expression("<!--"); // search comment start
pos = expression.indexIn(text, i - 1);
//if (pos == i - 1) // comment found ?
if (pos >= i - 1)
{
setFormat(i, 3, fmtSyntaxChar);
setFormat(i + 3, text.length() - i - 3, fmtComment);
setCurrentBlockState(InComment);
return;
}
else
{
processDefaultText(i, text);
}
}
}
else
{
processDefaultText(i, text);
}
break;
default:
const int iLength = processDefaultText(i, text);
if (iLength > 0)
i += iLength - 1;
break;
}
}
if (state == ExpectAttributeOrEndOfElement)
{
setCurrentBlockState(InElement);
}
}
int XMLSyntaxHighlighter::processDefaultText(int i, const QString& text)
{
// length of matched text
int iLength = 0;
switch(state)
{
case ExpectElementNameOrSlash:
case ExpectElementName:
{
// search element name
QRegExp expression("([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*");
const int pos = expression.indexIn(text, i);
if (pos == i) // found ?
{
iLength = expression.matchedLength();
setFormat(pos, iLength, fmtElementName);
state = ExpectAttributeOrEndOfElement;
}
else
{
setFormat(i, 1, fmtOther);
}
}
break;
case ExpectAttributeOrEndOfElement:
{
// search attribute name
QRegExp expression("([A-Za-z_:]|[^\\x00-\\x7F])([A-Za-z0-9_:.-]|[^\\x00-\\x7F])*");
const int pos = expression.indexIn(text, i);
if (pos == i) // found ?
{
iLength = expression.matchedLength();
setFormat(pos, iLength, fmtAttributeName);
state = ExpectEqual;
}
else
{
setFormat(i, 1, fmtOther);
}
}
break;
default:
setFormat(i, 1, fmtOther);
break;
}
return iLength;
}
void XMLSyntaxHighlighter::setHighlightColor(HighlightType type, QColor color, bool foreground)
{
QTextCharFormat format;
if (foreground)
format.setForeground(color);
else
format.setBackground(color);
setHighlightFormat(type, format);
}
void XMLSyntaxHighlighter::setHighlightFormat(HighlightType type, QTextCharFormat format)
{
switch (type)
{
case SyntaxChar:
fmtSyntaxChar = format;
break;
case ElementName:
fmtElementName = format;
break;
case Comment:
fmtComment = format;
break;
case AttributeName:
fmtAttributeName = format;
break;
case AttributeValue:
fmtAttributeValue = format;
break;
case Error:
fmtError = format;
break;
case Other:
fmtOther = format;
break;
}
rehighlight();
}
|
Gpinchon/TabGraph
|
TabGraph/src/Driver/OpenGL/Shader/Program.cpp
|
<gh_stars>1-10
/*
* @Author: gpinchon
* @Date: 2021-04-13 22:39:37
* @Last Modified by: gpinchon
* @Last Modified time: 2021-04-30 02:02:37
*/
#include "Driver/OpenGL/Shader/Program.hpp"
#include "Driver/OpenGL/Shader/Global.hpp"
#include "Driver/OpenGL/Texture/Texture.hpp"
#include "Driver/OpenGL/Texture/TextureSampler.hpp"
#include "Driver/OpenGL/Texture/Framebuffer.hpp"
#include "Shader/Stage.hpp"
#include <GL/glew.h>
#include <array>
#include <glm/glm.hpp>
#include <string>
static inline bool IsTextureType(GLenum type)
{
switch (type) {
case GL_SAMPLER_1D:
case GL_SAMPLER_2D:
case GL_SAMPLER_3D:
case GL_SAMPLER_CUBE:
case GL_SAMPLER_1D_SHADOW:
case GL_SAMPLER_2D_SHADOW:
case GL_SAMPLER_1D_ARRAY:
case GL_SAMPLER_2D_ARRAY:
case GL_SAMPLER_1D_ARRAY_SHADOW:
case GL_SAMPLER_2D_ARRAY_SHADOW:
case GL_SAMPLER_2D_MULTISAMPLE:
case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_SAMPLER_CUBE_SHADOW:
case GL_SAMPLER_BUFFER:
case GL_SAMPLER_2D_RECT:
case GL_SAMPLER_2D_RECT_SHADOW:
case GL_INT_SAMPLER_1D:
case GL_INT_SAMPLER_2D:
case GL_INT_SAMPLER_3D:
case GL_INT_SAMPLER_CUBE:
case GL_INT_SAMPLER_1D_ARRAY:
case GL_INT_SAMPLER_2D_ARRAY:
case GL_INT_SAMPLER_2D_MULTISAMPLE:
case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_INT_SAMPLER_BUFFER:
case GL_INT_SAMPLER_2D_RECT:
case GL_UNSIGNED_INT_SAMPLER_1D:
case GL_UNSIGNED_INT_SAMPLER_2D:
case GL_UNSIGNED_INT_SAMPLER_3D:
case GL_UNSIGNED_INT_SAMPLER_CUBE:
case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
case GL_UNSIGNED_INT_SAMPLER_BUFFER:
case GL_UNSIGNED_INT_SAMPLER_2D_RECT:
case GL_IMAGE_1D:
case GL_IMAGE_2D:
case GL_IMAGE_3D:
case GL_IMAGE_2D_RECT:
case GL_IMAGE_CUBE:
case GL_IMAGE_BUFFER:
case GL_IMAGE_1D_ARRAY:
case GL_IMAGE_2D_ARRAY:
case GL_IMAGE_2D_MULTISAMPLE:
case GL_IMAGE_2D_MULTISAMPLE_ARRAY:
case GL_INT_IMAGE_1D:
case GL_INT_IMAGE_2D:
case GL_INT_IMAGE_3D:
case GL_INT_IMAGE_2D_RECT:
case GL_INT_IMAGE_CUBE:
case GL_INT_IMAGE_BUFFER:
case GL_INT_IMAGE_1D_ARRAY:
case GL_INT_IMAGE_2D_ARRAY:
case GL_INT_IMAGE_2D_MULTISAMPLE:
case GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
case GL_UNSIGNED_INT_IMAGE_1D:
case GL_UNSIGNED_INT_IMAGE_2D:
case GL_UNSIGNED_INT_IMAGE_3D:
case GL_UNSIGNED_INT_IMAGE_2D_RECT:
case GL_UNSIGNED_INT_IMAGE_CUBE:
case GL_UNSIGNED_INT_IMAGE_BUFFER:
case GL_UNSIGNED_INT_IMAGE_1D_ARRAY:
case GL_UNSIGNED_INT_IMAGE_2D_ARRAY:
case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE:
case GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY:
return true;
default:
return false;
}
}
std::array<GLenum, 6> GLStageLUT = {
GL_GEOMETRY_SHADER, //Geometry
GL_VERTEX_SHADER, //Vertex
GL_FRAGMENT_SHADER, //Fragment
GL_COMPUTE_SHADER, //Compute
GL_TESS_EVALUATION_SHADER, //TessellationEvaluation
GL_TESS_CONTROL_SHADER //TessellationControl
};
namespace Shader {
Program::Impl::~Impl()
{
glDeleteProgram(GetHandle());
}
const Program::Handle& Program::Impl::GetHandle() const
{
return _handle;
}
void Program::Impl::Attach(const Stage& stage)
{
_stages.at((int)stage.GetType()) = stage;
}
Stage& Program::Impl::GetStage(Stage::Type type)
{
return _stages.at((int)type);
}
void Program::Impl::Compile()
{
if (GetCompiled())
return;
_SetHandle(glCreateProgram());
std::array<GLuint, (int)Stage::Type::MaxValue> handles { 0 };
for (const auto& stage : _stages) {
if (stage.GetCode().code.empty() && stage.GetCode().technique.empty())
continue;
std::string fullCode = "#version " + GetGLSLVersion() + '\n';
for (const auto& define : _defines)
fullCode += "#define " + define.first + ' ' + define.second + '\n';
for (const auto& define : stage.GetDefines())
fullCode += "#define " + define.first + ' ' + define.second + '\n';
if (!stage.GetCode().code.empty())
fullCode += stage.GetCode().code + '\n';
fullCode += "void main(void) {\n";
if (!stage.GetCode().technique.empty())
fullCode += stage.GetCode().technique + '\n';
fullCode += "}\n";
auto codeBuff { fullCode.c_str() };
auto handle = handles.at((int)stage.GetType()) = glCreateShader(GLStageLUT.at((int)stage.GetType()));
glShaderSource(handle, 1, &codeBuff, nullptr);
glCompileShader(handle);
GLint result;
GLint loglength;
result = GL_FALSE;
glGetShaderiv(handle, GL_COMPILE_STATUS, &result);
if (result != GL_TRUE) {
glGetShaderiv(handle, GL_INFO_LOG_LENGTH, &loglength);
if (loglength > 1) {
std::vector<char> log(loglength, 0);
glGetShaderInfoLog(handle, loglength, nullptr, log.data());
std::string logString(log.begin(), log.end());
throw std::runtime_error(logString);
} else {
throw std::runtime_error("Unknown Error");
}
}
glAttachShader(GetHandle(), handle);
}
glLinkProgram(GetHandle());
GLint result;
GLint loglength;
result = GL_FALSE;
glGetProgramiv(GetHandle(), GL_LINK_STATUS, &result);
if (result != GL_TRUE) {
glGetProgramiv(GetHandle(), GL_INFO_LOG_LENGTH, &loglength);
if (loglength > 1) {
std::vector<char> log(loglength, 0);
glGetProgramInfoLog(GetHandle(), loglength, nullptr, log.data());
std::string logString(log.begin(), log.end());
throw std::runtime_error(logString);
} else {
throw std::runtime_error("Unknown Error");
}
}
for (const auto& handle : handles) {
if (handle == 0)
continue;
glDetachShader(GetHandle(), handle);
glDeleteShader(handle);
}
GLint numUniforms = 0;
glGetProgramiv(GetHandle(), GL_ACTIVE_UNIFORMS, &numUniforms);
uint16_t textureIndex { 0 };
char name[4096];
while (--numUniforms >= 0) {
GLenum type;
GLint size;
glGetActiveUniform(GetHandle(), static_cast<GLuint>(numUniforms), 4096, nullptr, &size, &type, name);
auto loc { glGetUniformLocation(GetHandle(), name) };
_uniformLocs[name] = loc;
if (IsTextureType(type))
_textureIndice[loc] = ++textureIndex;
}
_SetCompiled(true);
}
void Program::Impl::SetTexture(const std::string& name, const std::shared_ptr<Texture> value)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end()) {
auto index { _textureIndice.find(loc->second) };
if (index != _textureIndice.end()) {
glActiveTexture(GL_TEXTURE0 + index->second);
if (value != nullptr) {
value->Load();
glBindTexture(OpenGL::GetEnum(value->GetType()), value->GetImpl().GetHandle());
glBindSampler(index->second, value->GetTextureSampler()->GetImpl().GetHandle());
} else {
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture1D), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture1DArray), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture2D), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture2DArray), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture2DMultisample), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture2DMultisampleArray), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::Texture3D), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::TextureCubemap), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::TextureRectangle), 0);
glBindTexture(OpenGL::GetEnum(Texture::Type::TextureCubemapArray), 0);
glBindSampler(index->second, 0);
}
glUniform1i(loc->second, index->second);
}
}
}
void Program::Impl::SetUniform(const std::string& name, const float value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const float* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniform1fv(loc->second + index, count, value);
}
void Program::Impl::SetUniform(const std::string& name, const int32_t value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const int32_t* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniform1iv(loc->second + index, count, value);
}
void Program::Impl::SetUniform(const std::string& name, const uint32_t value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const uint32_t* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniform1uiv(loc->second + index, count, value);
}
void Program::Impl::SetUniform(const std::string& name, const glm::vec2& value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const glm::vec2* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniform2fv(loc->second + index, count, (float*)value);
}
void Program::Impl::SetUniform(const std::string& name, const glm::vec3& value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const glm::vec3* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniform3fv(loc->second + index, count, (float*)value);
}
void Program::Impl::SetUniform(const std::string& name, const glm::vec4& value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const glm::vec4* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniform4fv(loc->second + index, count, (float*)value);
}
void Program::Impl::SetUniform(const std::string& name, const glm::mat4& value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const glm::mat4* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniformMatrix4fv(loc->second + index, count, false, (float*)value);
}
void Program::Impl::SetUniform(const std::string& name, const glm::mat3& value)
{
SetUniform(name, &value, 1, 0);
}
void Program::Impl::SetUniform(const std::string& name, const glm::mat3* value, const uint16_t count, const uint16_t index)
{
auto loc { _uniformLocs.find(name) };
if (loc != _uniformLocs.end())
glUniformMatrix3fv(loc->second + index, count, false, (float*)value);
}
void Program::Impl::SetDefine(const std::string& name, const std::string& value)
{
auto& define { _defines.find(name) };
if (define == _defines.end() || define->second != value) {
_defines[name] = value;
glDeleteProgram(GetHandle());
_SetHandle(0);
_SetCompiled(false);
}
}
void Program::Impl::RemoveDefine(const std::string& name)
{
if (_defines.erase(name) > 0) {
glDeleteProgram(GetHandle());
_SetHandle(0);
_SetCompiled(false);
}
}
void Program::Impl::Use()
{
for (const auto& globalDefine : Global::Impl::GetDefines())
SetDefine(globalDefine.first, globalDefine.second);
if (!GetCompiled())
Compile();
glUseProgram(GetHandle());
for (const auto& globalVec2 : Global::Impl::GetVec2())
SetUniform(globalVec2.first, globalVec2.second.data(), globalVec2.second.size(), 0);
for (const auto& globalVec3 : Global::Impl::GetVec3())
SetUniform(globalVec3.first, globalVec3.second.data(), globalVec3.second.size(), 0);
for (const auto& globalVec4 : Global::Impl::GetVec4())
SetUniform(globalVec4.first, globalVec4.second.data(), globalVec4.second.size(), 0);
for (const auto& globalMat4 : Global::Impl::GetMat4())
SetUniform(globalMat4.first, globalMat4.second.data(), globalMat4.second.size(), 0);
for (const auto& globalMat3 : Global::Impl::GetMat3())
SetUniform(globalMat3.first, globalMat3.second.data(), globalMat3.second.size(), 0);
for (const auto& globalFloat : Global::Impl::GetFloats())
SetUniform(globalFloat.first, globalFloat.second.data(), globalFloat.second.size(), 0);
for (const auto& globalInt : Global::Impl::GetInts())
SetUniform(globalInt.first, globalInt.second.data(), globalInt.second.size(), 0);
for (const auto& globalUint : Global::Impl::GetUints())
SetUniform(globalUint.first, globalUint.second.data(), globalUint.second.size(), 0);
for (const auto& globalTexture : Global::Impl::GetTextures())
SetTexture(globalTexture.first, globalTexture.second);
}
void Program::Impl::UseNone()
{
glUseProgram(0);
}
void Program::Impl::_SetHandle(uint32_t value)
{
_handle = value;
}
};
|
hiranp/ExpectIt
|
expectit-core/src/test/java/net/sf/expectit/SshLocalhostNoEchoExample.java
|
<reponame>hiranp/ExpectIt<filename>expectit-core/src/test/java/net/sf/expectit/SshLocalhostNoEchoExample.java
package net.sf.expectit;
/*
* #%L
* ExpectIt
* %%
* Copyright (C) 2014 <NAME> and contributors
* %%
* 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 static net.sf.expectit.matcher.Matchers.contains;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import java.io.IOException;
import java.util.Properties;
/**
* An example of interacting with the local SSH server
*/
public class SshLocalhostNoEchoExample {
public static void main(String[] args) throws JSchException, IOException {
JSch jSch = new JSch();
Session session = jSch.getSession(System.getenv("USER"), "localhost");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
jSch.addIdentity(System.getProperty("user.home") + "/.ssh/id_rsa");
session.setConfig(config);
session.connect();
Channel channel = session.openChannel("shell");
channel.connect();
Expect expect = new ExpectBuilder()
.withOutput(channel.getOutputStream())
.withInputs(channel.getInputStream(), channel.getExtInputStream())
.build();
try {
expect.expect(contains("$"));
expect.sendLine("stty -echo");
expect.expect(contains("$"));
expect.sendLine("pwd");
System.out.println("pwd1:" + expect.expect(contains("\n")).getBefore());
expect.sendLine("exit");
} finally {
expect.close();
channel.disconnect();
session.disconnect();
}
}
}
|
ZachBray/kgw-aeron-poc
|
server/src/main/java/org/kaazing/gateway/server/test/GatewayRule.java
|
<gh_stars>100-1000
/**
* Copyright 2007-2016, Kaazing Corporation. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kaazing.gateway.server.test;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.log4j.PropertyConfigurator;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import org.kaazing.gateway.server.test.config.GatewayConfiguration;
/**
* Declaring an instance of this class as a @Rule causes the gateway to be started in process before each test method and stopped
* after it. The rule can be chained with a K3poRule for use with robot (this causes Robot to be started before the gateway and
* stopped after it).
*/
public class GatewayRule implements TestRule {
private GatewayConfiguration configuration;
private String log4jPropertiesResourceName;
@Override
public Statement apply(Statement base, Description description) {
return new GatewayStatement(base);
}
public void init(GatewayConfiguration configuration) {
this.configuration = configuration;
}
public void init(GatewayConfiguration configuration, String log4jPropertiesResourceName) {
init(configuration);
this.log4jPropertiesResourceName = log4jPropertiesResourceName;
}
private final class GatewayStatement extends Statement {
private final Statement base;
public GatewayStatement(Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
if (log4jPropertiesResourceName != null) {
// Initialize log4j using a properties file available on the class path
Properties log4j = new Properties();
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream(log4jPropertiesResourceName);
if (in == null) {
throw new IOException(String.format("Could not load resource %s", log4jPropertiesResourceName));
}
log4j.load(in);
PropertyConfigurator.configure(log4j);
}
Gateway gateway = new Gateway();
try {
gateway.start(configuration);
base.evaluate();
} finally {
gateway.stop();
}
}
}
}
|
DNAstack/wdl4j
|
src/main/java/com/dnastack/wdl4j/lib/exception/WdlValidationError.java
|
<reponame>DNAstack/wdl4j<filename>src/main/java/com/dnastack/wdl4j/lib/exception/WdlValidationError.java
package com.dnastack.wdl4j.lib.exception;
public class WdlValidationError extends Exception {
public WdlValidationError() {
super();
}
public WdlValidationError(String s) {
super(s);
}
public WdlValidationError(String s, Throwable throwable) {
super(s, throwable);
}
}
|
AlexRogalskiy/DevArtifacts
|
master/jenkins-rest-api-master/jenkins-rest-api-master/JenkinsRest/src/main/java/org/fkunnen/jenkinsrestapi/buildnotification/BuildInfo.java
|
<reponame>AlexRogalskiy/DevArtifacts
package org.fkunnen.jenkinsrestapi.buildnotification;
public class BuildInfo {
private String full_url;
private int number;
private String phase;
private String status;
private String url;
private SCMInfo scm;
public String getFull_url() {
return full_url;
}
public void setFull_url(String full_url) {
this.full_url = full_url;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getPhase() {
return phase;
}
public void setPhase(String phase) {
this.phase = phase;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public SCMInfo getScm() {
return scm;
}
public void setScm(SCMInfo scm) {
this.scm = scm;
}
@Override
public String toString() {
return "BuildInfo{" +
"full_url='" + full_url + '\'' +
", number=" + number +
", phase='" + phase + '\'' +
", status='" + status + '\'' +
", url='" + url + '\'' +
", scm=" + scm +
'}';
}
}
|
ahmeshaf/ctakes
|
ctakes-dictionary-lookup/src/main/java/org/apache/ctakes/dictionary/lookup/filter/MetaDataPostLookupFilterImpl.java
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.ctakes.dictionary.lookup.filter;
import org.apache.ctakes.dictionary.lookup.DictionaryEngine;
import org.apache.ctakes.dictionary.lookup.DictionaryException;
import org.apache.ctakes.dictionary.lookup.MetaDataHit;
/**
*
* @author <NAME>
*/
public class MetaDataPostLookupFilterImpl implements PostLookupFilter
{
private String[] iv_metaFieldNames;
private DictionaryEngine iv_dictEngine;
private boolean iv_excludeMatches = false;
public MetaDataPostLookupFilterImpl(
DictionaryEngine dictEngine,
String[] metaFieldNames,
boolean excludeMatches)
{
iv_dictEngine = dictEngine;
iv_metaFieldNames = metaFieldNames;
iv_excludeMatches = excludeMatches;
}
public boolean contains(MetaDataHit mdh) throws FilterException
{
String mdVal = getMetaDataValue(mdh);
try
{
boolean isContained = iv_dictEngine.binaryLookup(mdVal);
if (iv_excludeMatches)
{
return isContained;
}
return !isContained;
}
catch (DictionaryException ge)
{
throw new FilterException(ge);
}
}
private String getMetaDataValue(MetaDataHit mdh) throws FilterException
{
for (int i = 0; i < iv_metaFieldNames.length; i++)
{
String mdVal = mdh.getMetaFieldValue(iv_metaFieldNames[i]);
if (mdVal != null)
{
return mdVal;
}
}
throw new FilterException(
new Exception("Unable to extract meta data from MetaDataHit object."));
}
}
|
nitrologic/emu
|
mame/src/mame/includes/seta.h
|
/***************************************************************************
-= Seta Hardware =-
***************************************************************************/
#define __uPD71054_TIMER 1
/*----------- defined in video/seta.c -----------*/
extern UINT16 *seta_vram_0, *seta_vctrl_0;
extern UINT16 *seta_vram_2, *seta_vctrl_2;
extern UINT16 *seta_vregs;
extern size_t seta_paletteram_size;
extern UINT16 *seta_workram; // Needed for zombraid Crosshair hack
extern int seta_tiles_offset;
void seta_coin_lockout_w(running_machine *machine, int data);
WRITE16_HANDLER( twineagl_tilebank_w );
WRITE16_HANDLER( seta_vram_0_w );
WRITE16_HANDLER( seta_vram_2_w );
WRITE16_HANDLER( seta_vregs_w );
PALETTE_INIT( blandia );
PALETTE_INIT( gundhara );
PALETTE_INIT( inttoote );
PALETTE_INIT( setaroul );
PALETTE_INIT( jjsquawk );
PALETTE_INIT( usclssic );
PALETTE_INIT( zingzip );
VIDEO_START( seta_no_layers);
VIDEO_START( twineagl_1_layer);
VIDEO_START( seta_1_layer);
VIDEO_START( seta_2_layers);
VIDEO_START( oisipuzl_2_layers );
VIDEO_UPDATE( seta );
VIDEO_UPDATE( seta_no_layers );
VIDEO_UPDATE( usclssic );
VIDEO_UPDATE( inttoote );
/*----------- defined in video/seta2.c -----------*/
extern UINT16 *seta2_vregs;
WRITE16_HANDLER( seta2_vregs_w );
VIDEO_START( seta2 );
VIDEO_START( seta2_offset );
VIDEO_UPDATE( seta2 );
VIDEO_EOF( seta2 );
/*----------- defined in video/ssv.c -----------*/
extern UINT16 *ssv_scroll;
extern int ssv_special;
extern int ssv_tile_code[16];
extern int ssv_sprites_offsx, ssv_sprites_offsy;
extern int ssv_tilemap_offsx, ssv_tilemap_offsy;
extern UINT16 *eaglshot_gfxram, *gdfs_tmapram, *gdfs_tmapscroll;
READ16_HANDLER( ssv_vblank_r );
WRITE16_HANDLER( ssv_scroll_w );
WRITE16_HANDLER( paletteram16_xrgb_swap_word_w );
WRITE16_HANDLER( gdfs_tmapram_w );
void ssv_enable_video(int enable);
VIDEO_START( ssv );
VIDEO_START( eaglshot );
VIDEO_START( gdfs );
VIDEO_UPDATE( ssv );
VIDEO_UPDATE( eaglshot );
VIDEO_UPDATE( gdfs );
|
khall001/testsystem
|
src/am57xx/mputest.c
|
/* SPDX-License-Identifier: MIT */
/*
* Author: <NAME> <<EMAIL>>
* Date: 2016
*/
#include <stdint.h>
#include <stdio.h>
#include <mpu9250.h>
#include <spi.h>
#include <FreeRTOS.h>
#include <task.h>
#include <devs.h>
void mputest_task(void *data) {
struct mpu9250 *mpu = data;
TickType_t lastWakeUpTime = xTaskGetTickCount();
for(;;) {
struct mpu9250_vector vec;
int32_t ret;
ret = mpu9250_getAccel(mpu, &vec, portMAX_DELAY);
CONFIG_ASSERT(ret >= 0);
printf("Accel: x: %f y: %f z: %f\n", vec.x, vec.y, vec.z);
ret = mpu9250_getGyro(mpu, &vec, portMAX_DELAY);
CONFIG_ASSERT(ret >= 0);
printf("Gyro: x: %f y: %f z: %f\n", vec.x, vec.y, vec.z);
vTaskDelayUntil(&lastWakeUpTime, 100 / portTICK_PERIOD_MS);
}
}
MPU9250_ADDDEV(mpu0, 0, 0, SPI_OPT_GPIO_DIS, 500000);
OS_DEFINE_TASK(mpuTask, 1024);
OS_DEFINE_TASK(mpuInitTask, 1024);
void mputest_initTask(void *data) {
BaseType_t ret;
struct spi *spi;
struct mpu9250 *mpu;
struct accel *accel;
struct gyro *gyro;
struct spi_slave *slave[3];
{
struct spi_opt opt = {
.lsb = false,
.cpol = false,
.cpha = false,
.cs = 0,
.csLowInactive = false,
.gpio = SPI_OPT_GPIO_DIS,
.size = 8,
.wdelay = 0,
.cs_hold = 8,
.cs_delay = 500,
.bautrate = 500000,
};
spi = spi_init(SPI1_ID, SPI_3WIRE_CS, NULL);
CONFIG_ASSERT(spi != NULL);
/*slave[0] = spiSlave_init(spi, &opt);
CONFIG_ASSERT(slave[0] != NULL);*/ /* Init by Driver*/
opt.cs_hold = 6;
opt.cs_delay = 8;
opt.cs = 1;
slave[1] = spiSlave_init(spi, &opt);
CONFIG_ASSERT(slave[1] != NULL);
}
printf("MPU9250 init\n");
do {
mpu = mpu9250_init(0, portMAX_DELAY);
} while (mpu == NULL);
printf("MPU9250 inited\n");
accel = accel_init(0);
CONFIG_ASSERT(accel != NULL);
gyro = gyro_init(0);
CONFIG_ASSERT(gyro != NULL);
ret = OS_CREATE_TASK(mputest_task, "MPU Task", 1024, mpu, 1, mpuTask);
CONFIG_ASSERT(ret == pdPASS);
vTaskSuspend(NULL);
}
void mputest_init() {
CONFIG_ASSERT(OS_CREATE_TASK(mputest_initTask, "MPU Init Task", 1024, NULL, 2, mpuInitTask));
}
|
athenagroup/brxm
|
site-toolkit/components/core/src/main/java/org/hippoecm/hst/core/container/ResourceServingValve.java
|
/*
* Copyright 2008-2015 <NAME>.V. (http://www.onehippo.com)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.hippoecm.hst.core.container;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstRequestImpl;
import org.hippoecm.hst.core.component.HstResourceResponseImpl;
import org.hippoecm.hst.core.component.HstResponse;
import org.hippoecm.hst.core.request.HstRequestContext;
/**
* ResourceServingValve
*/
public class ResourceServingValve extends AbstractBaseOrderableValve {
@Override
public void invoke(ValveContext context) throws ContainerException {
HstRequestContext requestContext = context.getRequestContext();
HstContainerURL baseURL = requestContext.getBaseURL();
String resourceWindowRef = baseURL.getResourceWindowReferenceNamespace();
if (resourceWindowRef == null) {
// not a resource request, so skip it..
context.invokeNext();
return;
}
if (context.getServletResponse().isCommitted()) {
log.warn("Stopping resource serving. The response is already committed.");
context.invokeNext();
return;
}
HttpServletRequest servletRequest = context.getServletRequest();
HttpServletResponse servletResponse = context.getServletResponse();
final HstComponentWindow window = context.getRootComponentWindow();
HstRequest request = new HstRequestImpl(servletRequest, requestContext, window, HstRequest.RESOURCE_PHASE);
HstResponse response = new HstResourceResponseImpl(servletResponse, requestContext, window);
HstComponentInvoker invoker = getComponentInvoker();
invoker.invokeBeforeServeResource(context.getRequestContainerConfig(), request, response);
// page error handling...
PageErrors pageErrors = getPageErrors(new HstComponentWindow [] { window }, true);
if (pageErrors != null) {
handleComponentExceptions(pageErrors, context.getRequestContainerConfig(), window, request, response);
}
invoker.invokeServeResource(context.getRequestContainerConfig(), request, response);
// page error handling...
pageErrors = getPageErrors(new HstComponentWindow [] { window }, true);
if (pageErrors != null) {
handleComponentExceptions(pageErrors, context.getRequestContainerConfig(), window, request, response);
}
}
}
|
embl-communications/science-in-school
|
advanced-custom-fields-pro/pro/assets/build/js/_acf-setting-clone.js
|
(function($){
/**
* CloneDisplayFieldSetting
*
* Extra logic for this field setting
*
* @date 18/4/18
* @since 5.6.9
*
* @param void
* @return void
*/
var CloneDisplayFieldSetting = acf.FieldSetting.extend({
type: 'clone',
name: 'display',
render: function(){
// vars
var display = this.field.val();
// set data attribute used by CSS to hide/show
this.$fieldObject.attr('data-display', display);
}
});
acf.registerFieldSetting( CloneDisplayFieldSetting );
/**
* ClonePrefixLabelFieldSetting
*
* Extra logic for this field setting
*
* @date 18/4/18
* @since 5.6.9
*
* @param void
* @return void
*/
var ClonePrefixLabelFieldSetting = acf.FieldSetting.extend({
type: 'clone',
name: 'prefix_label',
render: function(){
// vars
var prefix = '';
// if checked
if( this.field.val() ) {
prefix = this.fieldObject.prop('label') + ' ';
}
// update HTML
this.$('code').html( prefix + '%field_label%' );
}
});
acf.registerFieldSetting( ClonePrefixLabelFieldSetting );
/**
* ClonePrefixNameFieldSetting
*
* Extra logic for this field setting
*
* @date 18/4/18
* @since 5.6.9
*
* @param void
* @return void
*/
var ClonePrefixNameFieldSetting = acf.FieldSetting.extend({
type: 'clone',
name: 'prefix_name',
render: function(){
// vars
var prefix = '';
// if checked
if( this.field.val() ) {
prefix = this.fieldObject.prop('name') + '_';
}
// update HTML
this.$('code').html( prefix + '%field_name%' );
}
});
acf.registerFieldSetting( ClonePrefixNameFieldSetting );
/**
* cloneFieldSelectHelper
*
* Customizes the clone field setting Select2 isntance
*
* @date 18/4/18
* @since 5.6.9
*
* @param void
* @return void
*/
var cloneFieldSelectHelper = new acf.Model({
filters: {
'select2_args': 'select2Args'
},
select2Args: function( options, $select, data, $el, instance ){
// check
if( data.ajaxAction == 'acf/fields/clone/query' ) {
// remain open on select
options.closeOnSelect = false;
// customize ajaxData function
instance.data.ajaxData = this.ajaxData;
}
// return
return options;
},
ajaxData: function( data ){
// find current fields
data.fields = {};
// loop
acf.getFieldObjects().map(function(fieldObject){
// append
data.fields[ fieldObject.prop('key') ] = {
key: fieldObject.prop('key'),
type: fieldObject.prop('type'),
label: fieldObject.prop('label'),
ancestors: fieldObject.getParents().length
};
});
// append title
data.title = $('#title').val();
// return
return data;
}
});
})(jQuery);
|
harper-carroll/kibana
|
src/ui/public/agg_types/__tests__/param_types/_string.js
|
import _ from 'lodash';
import expect from 'expect.js';
import ngMock from 'ngMock';
import AggTypesParamTypesBaseProvider from 'ui/agg_types/param_types/base';
import AggTypesParamTypesStringProvider from 'ui/agg_types/param_types/string';
module.exports = describe('String', function () {
var paramName = 'json_test';
var BaseAggParam;
var StringAggParam;
var aggParam;
var aggConfig;
var output;
function initAggParam(config) {
config = config || {};
var defaults = {
name: paramName,
type: 'string'
};
aggParam = new StringAggParam(_.defaults(config, defaults));
}
beforeEach(ngMock.module('kibana'));
// fetch our deps
beforeEach(ngMock.inject(function (Private) {
BaseAggParam = Private(AggTypesParamTypesBaseProvider);
StringAggParam = Private(AggTypesParamTypesStringProvider);
aggConfig = { params: {} };
output = { params: {} };
}));
describe('constructor', function () {
it('it is an instance of BaseAggParam', function () {
initAggParam();
expect(aggParam).to.be.a(BaseAggParam);
});
});
describe('write', function () {
it('should append param by name', function () {
var paramName = 'testing';
var params = {};
params[paramName] = 'some input';
initAggParam({ name: paramName });
aggConfig.params = params;
aggParam.write(aggConfig, output);
expect(output.params).to.eql(params);
});
it('should not be in output with empty input', function () {
var paramName = 'more_testing';
var params = {};
params[paramName] = '';
initAggParam({ name: paramName });
aggConfig.params = params;
aggParam.write(aggConfig, output);
expect(output.params).to.eql({});
});
});
});
|
Anlon-Burke/vespa
|
config-model/src/test/java/com/yahoo/searchdefinition/processing/BoldingTestCase.java
|
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.searchdefinition.processing;
import com.yahoo.searchdefinition.SchemaBuilder;
import com.yahoo.searchdefinition.AbstractSchemaTestCase;
import com.yahoo.searchdefinition.parser.ParseException;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.fail;
/**
* @author bratseth
*/
public class BoldingTestCase extends AbstractSchemaTestCase {
private final String boldonnonstring =
"search boldnonstring {\n" +
" document boldnonstring {\n" +
" field title type string {\n" +
" indexing: summary | index\n" +
" }\n" +
"\n" +
" field year4 type int {\n" +
" indexing: summary | attribute\n" +
" bolding: on\n" +
" }\n" +
" }\n" +
"}\n";
@Test
public void testBoldOnNonString() throws ParseException {
try {
SchemaBuilder.createFromString(boldonnonstring);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("'bolding: on' for non-text field 'year4' (datatype int (code: 0)) is not allowed",
e.getMessage());
}
}
private final String boldonarray =
"search boldonarray {\n" +
" document boldonarray {\n" +
" field myarray type array<string> {\n" +
" indexing: summary | index\n" +
" bolding: on\n" +
" }\n" +
" }\n" +
"}\n";
@Test
public void testBoldOnArray() throws ParseException {
try {
SchemaBuilder.createFromString(boldonarray);
fail("Expected exception");
} catch (IllegalArgumentException e) {
assertEquals("'bolding: on' for non-text field 'myarray' (datatype Array<string> (code: -1486737430)) is not allowed",
e.getMessage());
}
}
}
|
saewoonam/thorium_daq_uqd
|
zmqLockServer.py
|
<filename>zmqLockServer.py
import zmq
import time
import sys
import psutil
import threading
import logging
import logzero
from logzero import logger
logzero.loglevel(logging.INFO)
port = "5556"
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:%s" % port)
LOCKS = {'default': [False, 0]}
def process_lock(key, message_id):
global LOCKS
if key not in LOCKS:
response = 'unrecognized lock: %s' % key
return response
locked, pid = LOCKS[key]
if locked:
response = 'Already locked by another process %d' % pid
else:
locked = True
# pid = int(pid_message)
LOCKS[key] = [locked, message_id]
print('locked by: %r' % message_id)
response = 'locked by %r' % message_id
return response
def process_unlock(key, message_id=''):
global LOCKS
if key not in LOCKS:
response = 'unrecognized unlock: %s' % key
return response
else:
if LOCKS[key][1] == message_id:
LOCKS[key] = [False, 0]
response = 'unlocked %s' % key
else:
response = 'failed to unlock; mismatched id: %r %r' % \
(LOCKS[key][1], message_id)
return response
def check_pid():
logger.debug('Check_pids')
for key in LOCKS:
if LOCKS[key][0]:
lock_id = LOCKS[key][1]
pid = int(lock_id.decode().split('_')[-1])
logger.debug('check pid: %d' % pid)
if not psutil.pid_exists(pid):
logger.debug('lock_id %s, pid does not exist, removing' % lock_id)
LOCKS[key] = [False, 0]
time.sleep(1)
check_thread = threading.Thread(target=check_pid)
if socket is not None:
check_thread.start()
check_pid()
while True:
# Wait for next request from client
try:
message = socket.recv()
except KeyboardInterrupt:
print("W: interrupt received, stopping…")
break;
# print("Received request: %r" % message)
# time.sleep (10)
message = message.split()
request = message[0].decode().lower()
print(message)
print(request)
if request == 'lock':
if len(message) == 2:
response = process_lock('default', message[1])
elif len(message) == 3:
response = process_lock(message[2], message[1])
elif request == 'unlock':
if len(message) == 1:
response = process_unlock('default')
elif len(message) == 3:
response = process_unlock(message[2], message[1])
elif request == 'create':
if len(message) == 2:
key = message[1]
if key not in LOCKS:
LOCKS[key] = [False, 0]
response = 'Created lock: %r' % key
else:
response = 'Already exists: %r' % key
else:
response = 'Failed to create a lock'
elif request == 'status':
response = '%r' % LOCKS
else:
response = 'failed to understand: %s' % request
socket.send_string(response)
# clean up
socket.close()
context.term()
socket = None
|
verma-kunal/Data-Structures-Algortihms-ToolBox
|
code-practice/CodePrac./src/Arrays/ArrayListEx.java
|
package Arrays;
import java.util.*;
public class ArrayListEx {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
ArrayList<Integer> list = new ArrayList<>(10);
}
}
|
rikvb/camel
|
components/camel-spring-rabbitmq/src/main/java/org/apache/camel/component/springrabbit/ListenerContainerFactory.java
|
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.component.springrabbit;
import org.springframework.amqp.rabbit.listener.AbstractMessageListenerContainer;
/**
* Factory to create {@link AbstractMessageListenerContainer}
*/
public interface ListenerContainerFactory {
/**
* Creates the listener container to use for the consumer.
*
* @param endpoint the endpoint
* @return the created and configured listener container
*/
AbstractMessageListenerContainer createListenerContainer(SpringRabbitMQEndpoint endpoint);
}
|
LucasLCarreira/Python
|
ex034.py
|
# Exercício Python 034
# Pergunte o salário do funcionario
# Salários > 1250, aumento de 10%
# Salários <= 1250, aumento de 15%
s = int(input('Digite o salário do funcionário: '))
if s > 1250:
sr = s * (1 + 0.1)
print('O salário reajustado é R$ {:.2f}'.format(sr))
else:
sr = s * (1 + 0.15)
print('O salário reajustado é R$ {:.2f}'.format(sr))
|
seukjung/sentry-custom
|
tests/sentry/utils/test_dates.py
|
<gh_stars>10-100
from __future__ import absolute_import
import datetime
import pytz
from sentry.utils.dates import (
to_datetime,
to_timestamp,
)
def test_timestamp_conversions():
value = datetime.datetime(2015, 10, 1, 21, 19, 5, 648517, tzinfo=pytz.utc)
assert int(to_timestamp(value)) == int(value.strftime('%s'))
assert to_datetime(to_timestamp(value)) == value
|
Impelon/PyGVisuals
|
pygvisuals/widgets/listbox.py
|
<reponame>Impelon/PyGVisuals
# --- imports
# pygame imports
import pygame
# local imports
from .selection_text_widget import *
from ..designs import getDefaultDesign
from ..util import inherit_docstrings_from_superclass
# constants
VIEWPOINT = 'v'
class Listbox(SelectionTextWidget):
"""
Listbox for displaying lists of multiple objects as strings.
"""
def __init__(self, x, y, width, height, font=getDefaultDesign().font, editable=False, validation_function=(lambda *x: True), selection_overlay=getDefaultDesign().selection_overlay):
"""
Initialisation of an Listbox.
Args:
inherit_doc:: arguments
"""
super(Listbox, self).__init__(x, y, width, height, "", font, editable, validation_function, selection_overlay)
self._list = []
self.viewpoint = self.cursor
def setViewpoint(self, index):
"""
Set the widget's viewpoint-position.
Args:
index: An integer (or known constant) representing the index the viewpoint should be set to.
Returns:
Itsself (the widget) for convenience.
"""
self._viewpoint = self.getActualIndex(index)
self.markDirty()
return self
def moveViewpoint(self, index):
"""
Move the widget's viewpoint-position by the given amount.
Args:
amount: An integer representing the amount the viewpoint should be moved by.
Returns:
Itsself (the widget) for convenience.
"""
return self.setViewpoint(self.viewpoint + int(index))
def getViewpoint(self):
"""
Return the widget's viewpoint-position.
Returns:
An integer representing the index the viewpoint is at.
"""
return self._viewpoint
def setCursor(self, index):
if self._indexToPos(index)[1] < 0:
self.setViewpoint(index)
elif self._indexToPos(index)[1] > self.rect.h:
self.setViewpoint(index - (self.rect.h / self.font.get_linesize()))
return super(Listbox, self).setCursor(index)
def setText(self, text):
"""
Note: Any given text will be ignored; use insert or delete instead.
inherit_doc::
"""
return self
def getText(self):
return "\n".join(map(str, self.list))
def setList(self, list):
"""
Set the widget' list-representation of its content.
Args:
list: A list with the content to set.
Returns:
Itsself (the widget) for convenience.
"""
self._list = list
self.markDirty()
return self
def getList(self):
"""
Return the widget' list-representation of its content.
Returns:
A list representing the content of the widget.
"""
return self._list
def insert(self, index, text):
"""
Note: The argument 'text' can be of any type, not only a string.
inherit_doc::
"""
index = self.getActualIndex(index)
self._list.append(text)
self.markDirty()
def delete(self, start, end):
start, end = self._sort(start, end)
del self._list[start:end]
self.markDirty()
def getActualIndex(self, index, constrain=True):
if index == END:
return len(self._list)
if index == VIEWPOINT:
return self._viewpoint
return super(Listbox, self).getActualIndex(index, constrain)
def _indexToPos(self, index):
return 0, self.font.get_linesize() * (index - self._viewpoint)
def _posToIndex(self, x, y):
return (y / self.font.get_linesize()) + self._viewpoint
def update(self, *args):
"""
Additionally handles keyboard-input.
inherit_doc::
"""
if len(args) > 0 and self.isActive() and self.isFocused():
event = args[0]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
self.moveCursor(-1)
elif event.key == pygame.K_DOWN:
self.moveCursor(1)
elif event.type == pygame.MOUSEBUTTONUP:
if event.button == 4:
self.moveViewpoint(-1)
elif event.button == 5:
self.moveViewpoint(1)
super(Listbox, self).update(*args)
def _getAppearance(self, *args):
"""
Additionally renders the listbox's list and selection.
inherit_doc::
"""
surface = super(Listbox, self)._getAppearance(*args)
linesize = self.font.get_linesize()
for n in range(self._viewpoint, len(self._list)):
surface.blit(self._render(str(self._list[n])), (0, linesize * (n - self._viewpoint)))
if self.isFocused():
s, e = self._sort(CURSOR, SELECTION)
for n in range(s, e + 1):
selection = pygame.Surface((self.bounds.width, linesize), pygame.SRCALPHA, 32)
selection.fill(self.selection_overlay)
surface.blit(selection, (0, linesize * (n - self._viewpoint)))
return surface
list = property(getList, setList, doc="""The widget' list-representation of its content.""")
viewpoint = property(getViewpoint, setViewpoint, doc="""The widget's position of the viewpoint as a index. This is the first currently visible index.""")
# inherit docs from superclass
Listbox = inherit_docstrings_from_superclass(Listbox)
|
jack-flash/MysticalAgriculture
|
src/main/java/com/blakebr0/mysticalagriculture/block/InferiumCropBlock.java
|
package com.blakebr0.mysticalagriculture.block;
import com.blakebr0.mysticalagriculture.api.crop.Crop;
import com.blakebr0.mysticalagriculture.api.farmland.IEssenceFarmland;
import com.blakebr0.mysticalagriculture.config.ModConfigs;
import net.minecraft.core.BlockPos;
import net.minecraft.server.level.ServerLevel;
import net.minecraft.world.item.ItemStack;
import net.minecraft.world.level.block.Block;
import net.minecraft.world.level.block.state.BlockState;
import net.minecraft.world.level.storage.loot.LootContext;
import net.minecraft.world.level.storage.loot.parameters.LootContextParams;
import java.util.ArrayList;
import java.util.List;
public class InferiumCropBlock extends MysticalCropBlock {
public InferiumCropBlock(Crop crop) {
super(crop);
}
@Override
public List<ItemStack> getDrops(BlockState state, LootContext.Builder builder) {
int age = state.getValue(AGE);
int crop = 0;
int seed = 1;
if (age == this.getMaxAge()) {
crop = 1;
var vec = builder.getOptionalParameter(LootContextParams.ORIGIN);
if (vec != null) {
ServerLevel world = builder.getLevel();
BlockPos pos = new BlockPos(vec);
Block below = world.getBlockState(pos.below()).getBlock();
if (below instanceof IEssenceFarmland farmland) {
int tier = farmland.getTier().getValue();
crop = (int) ((0.5D * tier) + 0.5D);
if (tier > 1 && tier % 2 == 0 && Math.random() < 0.5D)
crop++;
}
double chance = this.getCrop().getSecondaryChance(below);
if (ModConfigs.SECONDARY_SEED_DROPS.get() && Math.random() < chance)
seed = 2;
}
}
List<ItemStack> drops = new ArrayList<>();
if (crop > 0)
drops.add(new ItemStack(this.getCropsItem(), crop));
drops.add(new ItemStack(this.getBaseSeedId(), seed));
return drops;
}
}
|
ScalablyTyped/SlinkyTyped
|
s/s3-streams/src/main/scala/typingsSlinky/s3Streams/mod.scala
|
package typingsSlinky.s3Streams
import typingsSlinky.awsSdk.mod.S3
import typingsSlinky.awsSdk.s3Mod.CreateMultipartUploadRequest
import typingsSlinky.awsSdk.s3Mod.GetObjectRequest
import typingsSlinky.node.streamMod.Readable
import typingsSlinky.node.streamMod.Writable
import org.scalablytyped.runtime.StObject
import scala.scalajs.js
import scala.scalajs.js.`|`
import scala.scalajs.js.annotation.{JSGlobalScope, JSGlobal, JSImport, JSName, JSBracketAccess}
object mod {
@JSImport("s3-streams", "ReadStream")
@js.native
class ReadStream protected () extends Readable {
def this(client: S3, options: GetObjectRequest) = this()
def this(client: S3, options: GetObjectRequest, streamOptions: StreamOptions) = this()
}
@JSImport("s3-streams", "WriteStream")
@js.native
class WriteStream protected () extends Writable {
def this(client: S3, options: CreateMultipartUploadRequest) = this()
def this(client: S3, options: CreateMultipartUploadRequest, streamOptions: StreamOptions) = this()
}
@js.native
trait StreamOptions extends StObject {
/**
* Number of bytes to read or write before emitting a chunk to the stream.
* Must be above 5MB for {@link WriteStream}
*
* @default 4MB for {@link ReadStream}
* @default 10MB for {@link WriteStream}
*/
var highWaterMark: js.UndefOr[Double] = js.native
}
object StreamOptions {
@scala.inline
def apply(): StreamOptions = {
val __obj = js.Dynamic.literal()
__obj.asInstanceOf[StreamOptions]
}
@scala.inline
implicit class StreamOptionsMutableBuilder[Self <: StreamOptions] (val x: Self) extends AnyVal {
@scala.inline
def setHighWaterMark(value: Double): Self = StObject.set(x, "highWaterMark", value.asInstanceOf[js.Any])
@scala.inline
def setHighWaterMarkUndefined: Self = StObject.set(x, "highWaterMark", js.undefined)
}
}
}
|
epam/edp-ddm-liquibase-ddm-ext
|
src/test/java/com/epam/digital/data/platform/liquibase/extension/sqlgenerator/core/DdmPartialUpdateGeneratorTest.java
|
/*
* Copyright 2021 EPAM Systems.
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.epam.digital.data.platform.liquibase.extension.sqlgenerator.core;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import com.epam.digital.data.platform.liquibase.extension.DdmMockSnapshotGeneratorFactory;
import com.epam.digital.data.platform.liquibase.extension.change.DdmColumnConfig;
import com.epam.digital.data.platform.liquibase.extension.change.DdmTableConfig;
import com.epam.digital.data.platform.liquibase.extension.statement.core.DdmPartialUpdateStatement;
import liquibase.database.core.MockDatabase;
import liquibase.sql.Sql;
import liquibase.structure.core.Column;
import liquibase.structure.core.DataType;
import liquibase.structure.core.Table;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
class DdmPartialUpdateGeneratorTest {
@Test
@DisplayName("Validate SQL")
public void validateSQL() {
Table snapshotTable = new Table();
snapshotTable.setName("table");
Column snapshotColumn = new Column("column");
snapshotColumn.setNullable(false);
snapshotColumn.setType(new DataType("text"));
snapshotTable.addColumn(snapshotColumn);
DdmPartialUpdateGenerator generator = new DdmPartialUpdateGenerator(new DdmMockSnapshotGeneratorFactory(snapshotTable));
DdmPartialUpdateStatement statement = new DdmPartialUpdateStatement("name");
List<DdmTableConfig> tables = new ArrayList<>();
DdmTableConfig table = new DdmTableConfig("table");
DdmColumnConfig column = new DdmColumnConfig();
column.setName("column");
table.addColumn(column);
tables.add(table);
statement.setTables(tables);
Sql[] sqls = generator.generateSql(statement, new MockDatabase(), null);
assertEquals("insert into ddm_liquibase_metadata(change_type, change_name, attribute_name, attribute_value) values ('partialUpdate', 'name', 'table', 'column');", sqls[0].toSql());
}
}
|
dos1/card10-firmware
|
lib/sdk/Libraries/BTLE/documentation/html/Cordio_Stack_Cordio_Profiles/search/groups_3.js
|
var searchData=
[
['device_20information_20profile',['Device Information Profile',['../group___d_e_v_i_c_e___i_n_f_o_r_m_a_t_i_o_n___p_r_o_f_i_l_e.html',1,'']]],
['device_20information_20service',['Device Information Service',['../group___d_e_v_i_c_e___i_n_f_o_r_m_a_t_i_o_n___s_e_r_v_i_c_e.html',1,'']]],
['dm_20connection_20behavior',['DM Connection Behavior',['../group___d_m___connections.html',1,'']]],
['dm_20synchronization_20behavior',['DM Synchronization Behavior',['../group___d_m___synchronization.html',1,'']]],
['device_20manager_20api',['Device Manager API',['../group___s_t_a_c_k___d_m___a_p_i.html',1,'']]]
];
|
wh00sh/Tanda-DAPP
|
node_modules/mdi-material-ui/DiceD4Outline.js
|
<gh_stars>0
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _createIcon = _interopRequireDefault(require("./util/createIcon"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; }
var _default = (0, _createIcon["default"])('M13.43,15.15H14.29V16.36H13.43V18H11.92V16.36H8.82L8.75,15.41L11.91,10.42H13.43V15.15M10.25,15.15H11.92V12.47L10.25,15.15M22,21H2C1.64,21 1.31,20.81 1.13,20.5C0.95,20.18 0.96,19.79 1.15,19.5L11.15,3C11.5,2.38 12.5,2.38 12.86,3L22.86,19.5C23.04,19.79 23.05,20.18 22.87,20.5C22.69,20.81 22.36,21 22,21M3.78,19H20.23L12,5.43L3.78,19Z');
exports["default"] = _default;
|
GlobalLogicLatam/futbol-android
|
Library/futbol/src/main/java/com/globallogic/futbol/core/strategies/mock/StrategyDbMock.java
|
<reponame>GlobalLogicLatam/futbol-android<gh_stars>0
package com.globallogic.futbol.core.strategies.mock;
import android.os.Handler;
import com.globallogic.futbol.core.interfaces.analyzers.IStrategyDbAnalyzer;
import com.globallogic.futbol.core.operations.Operation;
import com.globallogic.futbol.core.responses.StrategyDbResponse;
import com.globallogic.futbol.core.responses.StrategyHttpResponse;
import com.globallogic.futbol.core.strategies.DbOperationStrategy;
import com.google.gson.JsonSyntaxException;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeoutException;
/**
* It allows mock responses from the DB.
*
* @param <T> The class of the expected response.
*/
public class StrategyDbMock<T> extends DbOperationStrategy<T> {
public static final String DETAIL_MESSAGE = "Hardcode dummy exception";
protected final ArrayList<StrategyDbResponse<T>> responses = new ArrayList<>();
protected final ArrayList<Exception> responsesException = new ArrayList<>();
private final Float mErrorProbability;
private Random random = new Random();
private boolean wasCanceled;
/**
* A StrategyDbMock allows to simulate any response that the database can return.
*
* @param analyzer An analyzer for the responses mocked.
* @param errorProbability Determines the probability that the error occurs. If it is less than or equal to 0 returns a {@link StrategyHttpResponse} (or an exception if there is no added replies). If it is greater or equal to 1 always returns an exception
*/
public StrategyDbMock(Operation anOperation, IStrategyDbAnalyzer<T> analyzer, float errorProbability) {
super(anOperation, analyzer);
this.mErrorProbability = errorProbability;
}
/**
* {@inheritDoc}
*/
@Override
public void doRequestImpl() {
if (!wasCanceled) {
if (random.nextFloat() < mErrorProbability) {
// Ejecuto un error
Exception mockException = getMockException();
if (mockException != null)
parseResponse(mockException, null);
else
onNotResponseAdded();
} else {
// Retorno alguna respuesta dummy
StrategyDbResponse<T> mockResponse = getMockResponse();
if (mockResponse != null)
parseResponse(null, mockResponse);
else
onNotResponseAdded();
}
}
}
@Override
public void cancel() {
wasCanceled = true;
}
/**
* A default response to return when any response was set.
*/
private void onNotResponseAdded() {
parseResponse(new Exception(DETAIL_MESSAGE), null);
}
/**
* Obtains a response mocked. It will be some random response.
*
* @return Some response previously added.
*/
private StrategyDbResponse<T> getMockResponse() {
if (responses.size() > 0) {
return responses.get(random.nextInt(responses.size()));
}
return null;
}
/**
* Obtains a exception mocked. It will be some random exception.
*
* @return Some exception previously added.
*/
private Exception getMockException() {
if (responsesException.size() > 0) {
return responsesException.get(random.nextInt(responsesException.size()));
}
return null;
}
/**
* Adds an expected response.
*
* @param mockResponse The response to add.
* @return The strategy where was added.
* @see StrategyDbResponse
*/
public StrategyDbMock add(StrategyDbResponse<T> mockResponse) {
responses.add(mockResponse);
return this;
}
/**
* Adds an expected exception.
*
* @param exception The exception to add.
* @return The strategy where was added.
*/
public StrategyDbMock add(Exception exception) {
responsesException.add(exception);
return this;
}
/**
* Adds a {@link JsonSyntaxException} exception.
*
* @return The strategy where was added.
* @see #add(Exception)
*/
public StrategyDbMock addJsonSyntaxException() {
responsesException.add(new JsonSyntaxException(DETAIL_MESSAGE));
return this;
}
/**
* Adds a {@link SocketException} exception.
*
* @return The strategy where was added.
* @see #add(Exception)
*/
public StrategyDbMock addSocketException() {
responsesException.add(new SocketException(DETAIL_MESSAGE));
return this;
}
/**
* Adds a {@link MalformedURLException} exception.
*
* @return The strategy where was added.
* @see #add(Exception)
*/
public StrategyDbMock addMalformedURLException() {
responsesException.add(new MalformedURLException(DETAIL_MESSAGE));
return this;
}
/**
* Adds a {@link TimeoutException} exception.
*
* @return The strategy where was added.
* @see #add(Exception)
*/
public StrategyDbMock addTimeoutException() {
responsesException.add(new TimeoutException(DETAIL_MESSAGE));
return this;
}
/**
* Adds a {@link IOException} exception.
*
* @return The strategy where was added.
* @see #add(Exception)
*/
public StrategyDbMock addIOException() {
responsesException.add(new IOException(DETAIL_MESSAGE));
return this;
}
/**
* Adds a default {@link Exception}.
*
* @return The strategy where was added.
* @see #add(Exception)
*/
public StrategyDbMock addException() {
responsesException.add(new Exception(DETAIL_MESSAGE));
return this;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof StrategyDbMock)) return false;
StrategyDbMock that = (StrategyDbMock) o;
return responses.equals(that.responses);
}
@Override
public int hashCode() {
return responses.hashCode();
}
}
|
bsteker/bdf2
|
bdf2-rapido/src/main/java/com/bstek/bdf2/rapido/builder/impl/ArgumentsBuilder.java
|
<gh_stars>1-10
package com.bstek.bdf2.rapido.builder.impl;
import java.util.HashMap;
import java.util.Map;
import org.dom4j.Element;
import org.dom4j.tree.BaseElement;
import com.bstek.bdf2.rapido.builder.IBuilder;
import com.bstek.bdf2.rapido.domain.ComponentInfo;
import com.bstek.bdf2.rapido.domain.EntityField;
import com.bstek.bdf2.rapido.domain.Mapping;
import com.bstek.bdf2.rapido.domain.MappingSource;
import com.bstek.bdf2.rapido.domain.PageInfo;
import com.bstek.dorado.idesupport.model.RuleSet;
public class ArgumentsBuilder implements IBuilder {
public Element build(PageInfo page, RuleSet ruleSet) throws Exception {
BaseElement element=new BaseElement("Arguments");
Map<String,Mapping> map=new HashMap<String,Mapping>();
for(ComponentInfo component:page.getComponents()){
this.retriveMapping(component, map);
}
for(Mapping mapping:map.values()){
BaseElement attributeElement=new BaseElement("Argument");
attributeElement.addAttribute("name","arg"+mapping.getId().replace("-", ""));
BaseElement propertyElement=new BaseElement("Property");
propertyElement.addAttribute("name","value");
propertyElement.setText(mapping.getQuerySql());
attributeElement.add(propertyElement);
element.add(attributeElement);
}
return element;
}
private void retriveMapping(ComponentInfo component,Map<String,Mapping> map){
if(component.getEntity()!=null){
for(EntityField ef:component.getEntity().getEntityFields()){
Mapping mapping=ef.getMapping();
if(mapping!=null){
if(mapping.getSource().equals(MappingSource.table) && !map.containsKey(mapping.getId())){
map.put(mapping.getId(),mapping);
}
}else if(ef.getMetaData()!=null){
mapping=ef.getMetaData().getMapping();
if(mapping!=null && mapping.getSource().equals(MappingSource.table) && !map.containsKey(mapping.getId())){
map.put(mapping.getId(),mapping);
}
}
}
}
if(component.getChildren()!=null){
for(ComponentInfo c:component.getChildren()){
this.retriveMapping(c, map);
}
}
}
}
|
angelowolf/sew
|
PersistenciaPatronDAOEleccion/src/DAO/SQLServer/SingletonPoolConnectionSQLServer.java
|
<gh_stars>1-10
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package DAO.SQLServer;
import DAO.MyException;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
/**
*
* @author Angelo
*/
public class SingletonPoolConnectionSQLServer {
private static SingletonPoolConnectionSQLServer spc_instancia;
private BasicDataSource bds;
public static SingletonPoolConnectionSQLServer getInstancia() throws MyException {
if (spc_instancia == null) {
spc_instancia = new SingletonPoolConnectionSQLServer();
}
return spc_instancia;
}
private SingletonPoolConnectionSQLServer() throws MyException {
this.crearPool();
}
private void crearPool() throws MyException {
try {
Properties propiedades = new Properties();
propiedades.load(new FileInputStream("C:/datasource_config_SQLServer.properties"));
bds = BasicDataSourceFactory.createDataSource(propiedades);
} catch (Exception e) {
throw new MyException("Error al crear conexion de SQLServer.", e);
}
}
public Connection getConnection() throws MyException {
try {
return bds.getConnection();
} catch (SQLException e) {
throw new MyException("Error al devolver conexion del pool.", e);
}
}
}
|
ycdtosa/sbgECom
|
common/interfaces/sbgInterfaceSerialUnix.c
|
<reponame>ycdtosa/sbgECom
// Standard headers
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>
#include <sys/ioctl.h>
// sbgCommonLib headers
#include <sbgCommon.h>
#include <interfaces/sbgInterfaceSerial.h>
//----------------------------------------------------------------------//
//- Definitions -//
//----------------------------------------------------------------------//
#define SBG_IF_SERIAL_TX_BUFFER_SIZE (4096u) /*!< Define the transmission buffer size for the serial port. */
#define SBG_IF_SERIAL_RX_BUFFER_SIZE (4096u) /*!< Define the reception buffer size for the serial port. */
//----------------------------------------------------------------------//
//- Private methods declarations -//
//----------------------------------------------------------------------//
/*!
* Returns the right unix baud rate const according to a baud rate value.
*
* \param[in] baudRate The baud rate value (ie 115200).
* \return The Unix baud rate constant.
*/
static uint32_t sbgInterfaceSerialGetBaudRateConst(uint32_t baudRate)
{
uint32_t baudRateConst;
//
// Create the right baud rate value for unix platforms
//
switch (baudRate)
{
case 9600:
baudRateConst = B9600;
break;
case 19200:
baudRateConst = B19200;
break;
#ifdef B38400
case 38400:
baudRateConst = B38400;
break;
#endif
#ifdef B57600
case 57600:
baudRateConst = B57600;
break;
#endif
#ifdef B115200
case 115200:
baudRateConst = B115200;
break;
#endif
#ifdef B230400
case 230400:
baudRateConst = B230400;
break;
#endif
#ifdef B460800
case 460800:
baudRateConst = B460800;
break;
#endif
#ifdef B921600
case 921600:
baudRateConst = B921600;
break;
#endif
#ifdef B1000000
case 1000000:
baudRateConst = B1000000;
break;
#endif
#ifdef B1152000
case 1152000:
baudRateConst = B1152000;
break;
#endif
#ifdef B1500000
case 1500000:
baudRateConst = B1500000;
break;
#endif
#ifdef B2000000
case 2000000:
baudRateConst = B2000000;
break;
#endif
#ifdef B2500000
case 2500000:
baudRateConst = B2500000;
break;
#endif
#ifdef B3000000
case 3000000:
baudRateConst = B3000000;
break;
#endif
#ifdef B3500000
case 3500000:
baudRateConst = B3500000;
break;
#endif
#ifdef B4000000
case 4000000:
baudRateConst = B4000000;
break;
#endif
default:
baudRateConst = baudRate;
}
return baudRateConst;
}
/*!
* Destroy an interface initialized using sbgInterfaceSerialCreate.
*
* \param[in] pInterface Valid handle on an initialized interface.
* \return SBG_NO_ERROR if the interface has been closed and released.
*/
static SbgErrorCode sbgInterfaceSerialDestroy(SbgInterface *pInterface)
{
int *pSerialHandle;
assert(pInterface);
assert(pInterface->type == SBG_IF_TYPE_SERIAL);
//
// Test that we have a valid interface
//
if (pInterface)
{
//
// Get the internal serial handle
//
pSerialHandle = (int*)pInterface->handle;
//
// Close the port com
//
close((*pSerialHandle));
SBG_FREE(pSerialHandle);
pInterface->handle = NULL;
return SBG_NO_ERROR;
}
else
{
return SBG_NULL_POINTER;
}
}
/*!
* Make an interface flush pending input and/or output data.
*
* If flags include SBG_IF_FLUSH_INPUT, all pending input data is discarded.
* If flags include SBG_IF_FLUSH_OUTPUT, the function blocks until all output data has been written out.
*
* \param[in] pInterface Interface instance.
* \param[in] flags Combination of the SBG_IF_FLUSH_INPUT and SBG_IF_FLUSH_OUTPUT flags.
* \return SBG_NO_ERROR if successful.
*/
static SbgErrorCode sbgInterfaceSerialFlush(SbgInterface *pInterface, uint32_t flags)
{
SbgErrorCode errorCode;
int fd;
int result = 0;
assert(pInterface);
assert(pInterface->type == SBG_IF_TYPE_SERIAL);
fd = *((int *)pInterface->handle);
if ((result == 0) && (flags & SBG_IF_FLUSH_INPUT))
{
result = tcflush(fd, TCIFLUSH);
if (result != 0)
{
SBG_LOG_ERROR(SBG_READ_ERROR, "unable to flush input, error:%s", strerror(errno));
}
}
if ((result == 0) && (flags & SBG_IF_FLUSH_OUTPUT))
{
result = tcdrain(fd);
if (result != 0)
{
SBG_LOG_ERROR(SBG_WRITE_ERROR, "unable to flush output, error:%s", strerror(errno));
}
}
if (result == 0)
{
errorCode = SBG_NO_ERROR;
}
else
{
errorCode = SBG_ERROR;
}
return errorCode;
}
/*!
* Change the serial interface baud rate immediatly.
*
* \param[in] handle Valid handle on an initialized interface.
* \param[in] baudRate The new baudrate to apply in bps.
* \return SBG_NO_ERROR if everything is OK
*/
static SbgErrorCode sbgInterfaceSerialChangeBaudrate(SbgInterface *pInterface, uint32_t baudRate)
{
int hSerialHandle;
struct termios options;
uint32_t baudRateConst;
assert(pInterface);
assert(pInterface->type == SBG_IF_TYPE_SERIAL);
//
// Get the internal serial handle
//
hSerialHandle = *((int*)pInterface->handle);
//
// Get the baud rate const for our Unix platform
//
baudRateConst = sbgInterfaceSerialGetBaudRateConst(baudRate);
//
// Retrieve current options
//
if (tcgetattr(hSerialHandle, &options) != -1)
{
//
// Set both input and output baud
//
if ( (cfsetispeed(&options, baudRateConst) == -1) || (cfsetospeed(&options, baudRateConst) == -1) )
{
fprintf(stderr, "sbgInterfaceSerialChangeBaudrate: Unable to set speed.\n");
return SBG_ERROR;
}
//
// Define options
//
if (tcsetattr(hSerialHandle, TCSADRAIN, &options) != -1)
{
return SBG_NO_ERROR;
}
else
{
fprintf(stderr, "sbgInterfaceSerialChangeBaudrate: tcsetattr fails.\n");
return SBG_ERROR;
}
}
else
{
fprintf(stderr, "sbgInterfaceSerialChangeBaudrate: tcgetattr fails.\n");
return SBG_ERROR;
}
}
//----------------------------------------------------------------------//
//- Internal interfaces write/read implementations -//
//----------------------------------------------------------------------//
/*!
* Try to write some data to an interface.
*
* \param[in] pInterface Valid handle on an initialized interface.
* \param[in] pBuffer Pointer on an allocated buffer that contains the data to write
* \param[in] bytesToWrite Number of bytes we would like to write.
* \return SBG_NO_ERROR if all bytes have been written successfully.
*/
static SbgErrorCode sbgInterfaceSerialWrite(SbgInterface *pInterface, const void *pBuffer, size_t bytesToWrite)
{
size_t numBytesLeftToWrite = bytesToWrite;
uint8_t *pCurrentBuffer = (uint8_t*)pBuffer;
ssize_t numBytesWritten;
int hSerialHandle;
assert(pInterface);
assert(pInterface->type == SBG_IF_TYPE_SERIAL);
assert(pBuffer);
//
// Get the internal serial handle
//
hSerialHandle = *((int*)pInterface->handle);
//
// Write the whole buffer
//
while (numBytesLeftToWrite > 0)
{
//
// Write these bytes to the serial interface
//
numBytesWritten = write(hSerialHandle, pCurrentBuffer, numBytesLeftToWrite);
//
// Test the there is no error
//
if (numBytesWritten == -1)
{
if (errno == EAGAIN)
{
sbgSleep(1);
}
else
{
//
// An error has occured during the write
//
fprintf(stderr, "sbgDeviceWrite: Unable to write to our device: %s\n", strerror(errno));
return SBG_WRITE_ERROR;
}
}
else
{
//
// Update the buffer pointer and the number of bytes to write
//
numBytesLeftToWrite -= (size_t)numBytesWritten;
pCurrentBuffer += (size_t)numBytesWritten;
}
}
return SBG_NO_ERROR;
}
/*!
* Try to read some data from an interface.
*
* \param[in] pInterface Valid handle on an initialized interface.
* \param[in] pBuffer Pointer on an allocated buffer that can hold at least bytesToRead bytes of data.
* \param[out] pReadBytes Pointer on an uint32 used to return the number of read bytes.
* \param[in] bytesToRead Number of bytes we would like to read.
* \return SBG_NO_ERROR if no error occurs, please check the number of received bytes.
*/
static SbgErrorCode sbgInterfaceSerialRead(SbgInterface *pInterface, void *pBuffer, size_t *pReadBytes, size_t bytesToRead)
{
SbgErrorCode errorCode;
int hSerialHandle;
ssize_t numBytesRead;
assert(pInterface);
assert(pInterface->type == SBG_IF_TYPE_SERIAL);
assert(pBuffer);
assert(pReadBytes);
//
// Get the internal serial handle
//
hSerialHandle = *((int*)pInterface->handle);
//
// Read our buffer
//
numBytesRead = read(hSerialHandle, pBuffer, bytesToRead);
//
// Check if the read operation was successful
//
if (numBytesRead >= 0)
{
errorCode = SBG_NO_ERROR;
}
else
{
if (errno == EAGAIN)
{
errorCode = SBG_NO_ERROR;
}
else
{
errorCode = SBG_READ_ERROR;
}
numBytesRead = 0;
}
//
// If we can, returns the number of read bytes
//
*pReadBytes = (size_t)numBytesRead;
return errorCode;
}
//----------------------------------------------------------------------//
//- Public methods -//
//----------------------------------------------------------------------//
SbgErrorCode sbgInterfaceSerialCreate(SbgInterface *pInterface, const char *deviceName, uint32_t baudRate)
{
int *pSerialHandle;
struct termios options;
uint32_t baudRateConst;
assert(pInterface);
assert(deviceName);
//
// Always call the underlying zero init method to make sure we can correctly handle SbgInterface evolutions
//
sbgInterfaceZeroInit(pInterface);
//
// Get our baud rate const for our Unix platform
//
baudRateConst = sbgInterfaceSerialGetBaudRateConst(baudRate);
//
// Allocate the serial handle
//
pSerialHandle = (int*)malloc(sizeof(int));
//
// Init the com port
//
(*pSerialHandle) = open(deviceName, O_RDWR | O_NOCTTY | O_NDELAY);
//
// Test that the port has been initialized
//
if ((*pSerialHandle) != -1)
{
//
// Don't block on read call if no data are available
//
if (fcntl((*pSerialHandle), F_SETFL, O_NONBLOCK) != -1)
{
//
// Retreive current options
//
if (tcgetattr((*pSerialHandle), &options) != -1)
{
//
// Define com port options
//
options.c_cflag |= (CLOCAL | CREAD); // Enable the receiver and set local mode...
options.c_cflag &= ~(PARENB|CSTOPB|CSIZE); // No parity, 1 stop bit, mask character size bits
options.c_cflag |= CS8; // Select 8 data bits
options.c_cflag &= ~CRTSCTS; // Disable Hardware flow control
//
// Disable software flow control
//
options.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL|IXON);
//
// We would like raw input
//
options.c_lflag &= ~(ICANON | ECHO | ECHOE | ISIG /*| IEXTEN | ECHONL*/);
options.c_oflag &= ~OPOST;
//
// Set our timeout to 0
//
options.c_cc[VMIN] = 0;
options.c_cc[VTIME] = 1;
//
// Set both input and output baud
//
if ( (cfsetispeed(&options, baudRateConst) != -1) && (cfsetospeed(&options, baudRateConst) != -1) )
{
//
// Define options
//
if (tcsetattr((*pSerialHandle), TCSANOW, &options) != -1)
{
//
// The serial port is ready so create a new serial interface
//
pInterface->handle = (void*)pSerialHandle;
pInterface->type = SBG_IF_TYPE_SERIAL;
//
// Define the interface name
//
sbgInterfaceNameSet(pInterface, deviceName);
//
// Define all overloaded members
//
pInterface->pDestroyFunc = sbgInterfaceSerialDestroy;
pInterface->pReadFunc = sbgInterfaceSerialRead;
pInterface->pWriteFunc = sbgInterfaceSerialWrite;
pInterface->pFlushFunc = sbgInterfaceSerialFlush;
pInterface->pSetSpeedFunc = sbgInterfaceSerialChangeBaudrate;
//
// Purge the communication
//
return sbgInterfaceSerialFlush(pInterface, SBG_IF_FLUSH_ALL);
}
else
{
fprintf(stderr, "sbgInterfaceSerialCreate: tcsetattr fails.\n");
}
}
else
{
fprintf(stderr, "sbgInterfaceSerialCreate: Unable to set speed.\n");
}
}
else
{
fprintf(stderr, "sbgInterfaceSerialCreate: tcgetattr fails.\n");
}
}
else
{
fprintf(stderr, "sbgInterfaceSerialCreate: fcntl fails\n");
}
}
else
{
fprintf(stderr, "sbgInterfaceSerialCreate: Unable to open the com port: %s\n", deviceName);
}
//
// Release the allocated serial handle
//
SBG_FREE(pSerialHandle);
return SBG_ERROR;
}
|
osamhack2020/APP_TookSamPoom_Navy3Generals
|
app/src/main/java/kr/co/softcampus/tooksampoom/Utils/DataNormalizer.java
|
<reponame>osamhack2020/APP_TookSamPoom_Navy3Generals
package kr.co.softcampus.tooksampoom.Utils;
import com.google.mlkit.vision.pose.PoseLandmark;
import java.util.ArrayList;
import java.util.List;
public class DataNormalizer {
private static final int _leftShoulderInd = 11;
private static final int _leftHipInd = 23;
private static final int _leftHandInd = 15;
private static final int _leftAnkleInde = 27;
public static List<Float> NormalizeWithAxisOnBody(List<PoseLandmark> plList) {
return NormalizeOnAxis(plList, _leftShoulderInd, _leftHipInd);
}
public static List<Float> NormalizeWithAxisOnHandToFeet(List<PoseLandmark> plList) {
return NormalizeOnAxis(plList, _leftHandInd, _leftAnkleInde);
}
public static List<Float> NormalizeSitUp(List<PoseLandmark> plList) {
return NormalizeOnAxis(plList, _leftAnkleInde, _leftHipInd);
}
private static List<Float> NormalizeOnAxis(List<PoseLandmark> plList, int startIndex, int endIndex) {
float x1 = (plList.get(startIndex).getPosition().x + plList.get(startIndex + 1).getPosition().x) / 2;
float y1 = (plList.get(startIndex + 1).getPosition().y + plList.get(startIndex + 1).getPosition().y) / 2;
float x2 = (plList.get(endIndex).getPosition().x + plList.get(endIndex).getPosition().x) / 2;
float y2 = (plList.get(endIndex + 1).getPosition().x + plList.get(endIndex + 1).getPosition().x) / 2;
double radian = Math.atan(Double.parseDouble(Float.valueOf((y2 - y1) / (x2 - x1)).toString()));
float xMax = 0;
float yMax = 0;
float xMin = Integer.MAX_VALUE;
float yMin = Integer.MAX_VALUE;
List<Float> xList = new ArrayList<>();
List<Float> yList = new ArrayList<>();
List<Float> probList = new ArrayList<>();
for (PoseLandmark pl : plList) {
float xnew = pl.getPosition().x * (float) Math.cos(radian) + pl.getPosition().y * (float) Math.sin(radian);
float ynew = -1 * pl.getPosition().x *(float) Math.sin(radian) + pl.getPosition().y * (float) Math.cos(radian);
xMax = Math.max(xMax, xnew);
yMax = Math.max(yMax, ynew);
xMin = Math.min(xMin, xnew);
yMin = Math.min(yMin, ynew);
xList.add(xnew);
yList.add(ynew);
probList.add(pl.getInFrameLikelihood());
}
List<Float> ans = new ArrayList<>();
for (float x : xList)
ans.add((x - xMin) / (xMax - xMin));
for (float y : yList)
ans.add((y - yMin) / (yMax - yMin));
ans.addAll(probList);
return ans;
}
}
|
awchisholm/superset
|
superset/advanced_data_type/types.py
|
<filename>superset/advanced_data_type/types.py<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.
from dataclasses import dataclass
from typing import Any, Callable, List, Optional, TypedDict, Union
from sqlalchemy import Column
from sqlalchemy.sql.expression import BinaryExpression
from superset.superset_typing import FilterValues
from superset.utils.core import FilterOperator, FilterStringOperators
class AdvancedDataTypeRequest(TypedDict):
"""
AdvancedDataType request class
"""
advanced_data_type: str
values: List[
Union[FilterValues, None]
] # unparsed value (usually text when passed from text box)
class AdvancedDataTypeResponse(TypedDict, total=False):
"""
AdvancedDataType response
"""
error_message: Optional[str]
values: List[Any] # parsed value (can be any value)
display_value: str # The string representation of the parsed values
valid_filter_operators: List[FilterStringOperators]
@dataclass
class AdvancedDataType:
"""
Used for coverting base type value into an advanced type value
"""
verbose_name: str
description: str
valid_data_types: List[str]
translate_type: Callable[[AdvancedDataTypeRequest], AdvancedDataTypeResponse]
translate_filter: Callable[[Column, FilterOperator, Any], BinaryExpression]
|
LondonOktober/bootstrap-vue
|
docs/layouts/default.js
|
<filename>docs/layouts/default.js
import Footer from '~/components/footer'
import Header from '~/components/header'
export default {
name: 'BVDDefaultLayout',
functional: true,
render: h => [h(Header), h('nuxt'), h(Footer)]
}
|
jasonwee/videoOnCloud
|
src/java/play/learn/java/design/intercepting_filter/Filter.java
|
<reponame>jasonwee/videoOnCloud
package play.learn.java.design.intercepting_filter;
public interface Filter {
/**
* Execute order processing filter.
*/
String execute(Order order);
/**
* Set next filter in chain after this.
*/
void setNext(Filter filter);
/**
* Get next filter in chain after this.
*/
Filter getNext();
/**
* Get last filter in the chain.
*/
Filter getLast();
}
|
kdima001/mesh
|
core/src/main/java/com/gentics/mesh/core/endpoint/admin/consistency/ConsistencyCheckResult.java
|
package com.gentics.mesh.core.endpoint.admin.consistency;
import java.util.ArrayList;
import java.util.List;
import com.gentics.mesh.core.rest.admin.consistency.InconsistencyInfo;
import com.gentics.mesh.core.rest.admin.consistency.InconsistencySeverity;
import com.gentics.mesh.core.rest.admin.consistency.RepairAction;
/**
* POJO of consistency check result.
*/
public class ConsistencyCheckResult {
private static final int MAX_RESULTS = 200;
private long repairCount = 0;
private List<InconsistencyInfo> results = new ArrayList<>(MAX_RESULTS);
public long getRepairCount() {
return repairCount;
}
public List<InconsistencyInfo> getResults() {
return results;
}
/**
* Add inconsistency information to the result.
*
* @param msg
* @param uuid
* @param severity
*/
public void addInconsistency(String msg, String uuid, InconsistencySeverity severity) {
addInconsistency(new InconsistencyInfo().setDescription(msg).setElementUuid(uuid).setSeverity(severity));
}
/**
* Add inconsistency information to the result.
*
* @param info
*/
public void addInconsistency(InconsistencyInfo info) {
if (info.isRepaired()) {
repairCount++;
}
// Keep the list of results small
if (results.size() < MAX_RESULTS) {
results.add(info);
}
}
/**
* Add inconsistency information to the result.
*
* @param msg
* Inconsistency message
* @param uuid
* Uuid of the related element for which the inconsistency was reported
* @param severity
* Severity of the reported inconsistency
* @param repaired
* Was the inconsistency repaired
* @param action
* Is a repair action possible
*/
public void addInconsistency(String msg, String uuid, InconsistencySeverity severity, boolean repaired, RepairAction action) {
addInconsistency(
new InconsistencyInfo().setDescription(msg).setElementUuid(uuid).setSeverity(severity).setRepaired(repaired).setRepairAction(action));
}
/**
* Add the given results into this result.
*
* @param results
* @return Fluent API
*/
public ConsistencyCheckResult merge(ConsistencyCheckResult... results) {
for (ConsistencyCheckResult result : results) {
merge(result);
}
return this;
}
/**
* Merge the two results into this result.
*
* @param result
* @return Fluent API
*/
public ConsistencyCheckResult merge(ConsistencyCheckResult result) {
getResults().addAll(result.getResults());
repairCount += result.getRepairCount();
return this;
}
}
|
AmazingFM/UpperPS
|
Upper_1/Classes/View/cells/UPActivityCell.h
|
<reponame>AmazingFM/UpperPS
//
// UPActivityCell.h
// Upper
//
// Created by 海通证券 on 16/5/18.
// Copyright © 2016年 <EMAIL>. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "UPActivityCellItem.h"
#import "ActivityData.h"
@interface UPTimeLocationView : UIView
- (void)setTime:(NSString *)time andLocation:(NSString *)location;
@end
@interface UILabel (VerticalUpAlignment)
- (void)verticalUpAlignmentWithText:(NSString *)text maxHeight:(CGFloat)maxHeight;
@end
@protocol UPItemButtonDelegate <NSObject>
-(void)onButtonSelected:(UPActivityCellItem *)cellItem withType:(int)type;
@end
@interface HTActivityCell : UITableViewCell
@property (nonatomic, retain) UPActivityCellItem *actCellItem;
@property (nonatomic, retain) id<UPItemButtonDelegate> delegate;
- (void)setActivityItems:(UPBaseCellItem *)item;
@end
|
fittner/SiMA
|
MasonExtentions/src/physics2D/physicalObject/clsStationaryObject2D.java
|
/**
*
*/
package physics2D.physicalObject;
import interfaces.itfEntity;
import interfaces.itfEntityInspectorFactory;
import interfaces.itfGetEntity;
import interfaces.itfSetupFunctions;
import java.awt.image.BufferedImage;
import physical2d.physicalObject.datatypes.eFacialExpression;
import physical2d.physicalObject.datatypes.eSpeechExpression;
import physics2D.shape.clsAnimatedCircleImage;
import sim.engine.SimState;
import sim.engine.Steppable;
import sim.physics2D.shape.Shape;
import sim.portrayal.DrawInfo2D;
import sim.portrayal.Inspector;
import sim.portrayal.LocationWrapper;
import sim.display.GUIState;
import singeltons.clsSingletonMasonGetter;
import singeltons.eImages;
import tools.clsPose;
/**
* Our representative of the mason physics class
*
* @author muchitsch
*
*/
public class clsStationaryObject2D extends sim.physics2D.physicalObject.StationaryObject2D implements Steppable, itfGetEntity, itfSetupFunctions {
/**
*
*/
private static final long serialVersionUID = 915012100712508497L;
private itfEntity moEntity;
private itfEntityInspectorFactory moMasonInspectorFactory = null;
public clsStationaryObject2D(itfEntity poEntity)
{
moEntity = poEntity;
}
/**
* returns the clsEntry
*
* @return
*/
@Override
public itfEntity getEntity() {
return moEntity;
}
@Override
public void setPose(clsPose poPose) {
clsSingletonMasonGetter.getFieldEnvironment().setObjectLocation( this, new sim.util.Double2D(poPose.getPosition().getX(), poPose.getPosition().getY()) );
setPose(poPose.getPosition(), poPose.getAngle());
}
/* (non-Javadoc)
*
* @author deutsch
* 26.02.2009, 12:00:49
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#getPose()
*/
@Override
public clsPose getPose() {
return new clsPose(this.getPosition(), this.getOrientation());
}
/* (non-Javadoc)
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setShape(sim.physics2D.shape.Shape, double)
*/
@Override
public void setShape(Shape poShape, double ignored) {
// TODO Why is there no setShape - corresponding to clsMobileObject2D. Adopt it!
setShape(poShape);
}
/* (non-Javadoc)
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setCoefficients(double, double, double)
* Note: Stationary objects don't support friction and staticFriction, only restitution.
* Use NaN for the former two.
*/
@Override
public void setCoefficients(double mustBeNaN1, double mustBeNaN2,
double poRestitution) {
if (! Double.isNaN(mustBeNaN1) || ! Double.isNaN(mustBeNaN2))
throw new java.lang.UnsupportedOperationException("Cannot specify that argument for stationary objects, use NaN!");
setCoefficientOfRestitution(poRestitution);
}
@Override
@Deprecated
public void step(SimState state) {
//this block should be distributed to different steps
moEntity.sensing();
moEntity.updateInternalState();
moEntity.processing();
moEntity.exec();
}
public Steppable getSteppableSensing() {
return new Steppable() {
private static final long serialVersionUID = 6889902215107604312L;
@Override
public void step(SimState state) {
moEntity.sensing();
moEntity.updateEntityInternals();
}
};
}
public Steppable getSteppableProcessing() {
return new Steppable() {
private static final long serialVersionUID = -5218583360606426073L;
@Override
public void step(SimState state) {
moEntity.processing();
}
};
}
/*
* (non-Javadoc)
*
* supports message handling for the mouse-doubleclick / inspectors
*
* @author langr 25.02.2009, 14:54:30
*
* @see sim.portrayal.SimplePortrayal2D#hitObject(java.lang.Object,
* sim.portrayal.DrawInfo2D)
*/
@Override
public boolean hitObject(Object object, DrawInfo2D range) {
return true;
}
/*
* Assigning customized MASON-inspectors to specific objects The mapping is
* defined in the static method clsInspectorMapping.getInspector()
*
* @author langr 25.03.2009, 14:57:20
*
* @see
* sim.portrayal.SimplePortrayal2D#getInspector(sim.portrayal.LocationWrapper
* , sim.display.GUIState)
*/
@Override
public Inspector getInspector(LocationWrapper wrapper, GUIState state) {
// Override to get constantly updating inspectors = volatile
// TODO: (langr) - testing purpose only! adapt tabs for selected entity
// clsSingletonMasonGetter.getConsole().setView(moEntity.getEntityType().hashCode());
/* if (moMasonInspector == null) {
moMasonInspector = new TabbedInspector();
Inspector oInspector = new clsInspectorEntity(super.getInspector(
wrapper, state), wrapper, state, moEntity);
moMasonInspector.addInspector(oInspector, "ARS Entity Inspector");
}
*/
if (moMasonInspectorFactory == null) {
return super.getInspector(wrapper, state);
}
return moMasonInspectorFactory.getInspector(wrapper, state, super.getInspector(wrapper, state), moEntity);
}
public void setInspectorFactory( itfEntityInspectorFactory poMasonInspector) {
moMasonInspectorFactory = poMasonInspector;
}
/* (non-Javadoc)
*
* @author deutsch
* Jul 24, 2009, 10:37:04 PM
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#getMass()
*/
@Override
public double getMass() {
return java.lang.Double.MAX_VALUE; //stationary objects have infinity mass!
}
/* (non-Javadoc)
*
* @author deutsch
* Jul 24, 2009, 10:37:04 PM
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setMass(double)
*/
@Override
public void setMass(double mass) {
//do nothing - stationary objects have infinite mass!
}
/* (non-Javadoc)
*
* @author muchitsch
* 03.05.2011, 14:53:44
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setOverlay(bw.utils.enums.eOverlay)
*/
@Override
public void setOverlayImage(eImages poOverlay) {
// TODO (muchitsch) - Auto-generated method stub
// TODO do stationary objects need a overlay? not yet if needed later look at implementation of clsMobileObject
}
/* (non-Javadoc)
*
* @since 29.10.2012 21:47:08
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setFacialExpressionOverlayImage(du.enums.eFacialExpression)
*/
@Override
public void setFacialExpressionOverlayImage(eFacialExpression poOverlay) {
// TODO (muchitsch) - Auto-generated method stub
}
/* (non-Javadoc)
*
* @since 24.07.2013 10:48:35
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setCarriedItem(bw.factories.eImages)
*/
@Override
public void setCarriedItem(BufferedImage poOverlay) {
// TODO (herret) - Auto-generated method stub
}
/* (non-Javadoc)
*
* @since 11.08.2013 12:48:06
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setSpeechExpressionOverlayImage(du.enums.eSpeechExpression)
*/
@Override
public void setSpeechExpressionOverlayImage(eSpeechExpression poOverlay) {
// TODO (hinterleitner) - Auto-generated method stub
}
/* (non-Javadoc)
*
* @since 27.08.2013 19:39:46
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setThoughtExpressionOverlayImage(du.enums.eSpeechExpression)
*/
@Override
public void setThoughtExpressionOverlayImage(eSpeechExpression poOverlay) {
// TODO (hinterleitner) - Auto-generated method stub
}
/* (non-Javadoc)
*
* @since 25.09.2013 15:22:00
*
* @see ARSsim.physics2D.physicalObject.itfSetupFunctions#setLifeValue(double)
*/
@Override
public void setLifeValue(double value) {
Shape oShape = this.getShape();
if(oShape instanceof clsAnimatedCircleImage){
((clsAnimatedCircleImage) oShape).setLifeValue(value);
}
}
}
|
rkalman/InvenTree
|
InvenTree/company/admin.py
|
from django.contrib import admin
from import_export.admin import ImportExportModelAdmin
from import_export.resources import ModelResource
from import_export.fields import Field
import import_export.widgets as widgets
from .models import Company
from .models import SupplierPart
from .models import SupplierPriceBreak
from .models import ManufacturerPart, ManufacturerPartAttachment, ManufacturerPartParameter
from part.models import Part
class CompanyResource(ModelResource):
""" Class for managing Company data import/export """
class Meta:
model = Company
skip_unchanged = True
report_skipped = False
clean_model_instances = True
class CompanyAdmin(ImportExportModelAdmin):
resource_class = CompanyResource
list_display = ('name', 'website', 'contact')
search_fields = [
'name',
'description',
]
class SupplierPartResource(ModelResource):
"""
Class for managing SupplierPart data import/export
"""
part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part))
part_name = Field(attribute='part__full_name', readonly=True)
supplier = Field(attribute='supplier', widget=widgets.ForeignKeyWidget(Company))
supplier_name = Field(attribute='supplier__name', readonly=True)
class Meta:
model = SupplierPart
skip_unchanged = True
report_skipped = True
clean_model_instances = True
class SupplierPartAdmin(ImportExportModelAdmin):
resource_class = SupplierPartResource
list_display = ('part', 'supplier', 'SKU')
search_fields = [
'company__name',
'part__name',
'MPN',
'SKU',
]
autocomplete_fields = ('part', 'supplier', 'manufacturer_part',)
class ManufacturerPartResource(ModelResource):
"""
Class for managing ManufacturerPart data import/export
"""
part = Field(attribute='part', widget=widgets.ForeignKeyWidget(Part))
part_name = Field(attribute='part__full_name', readonly=True)
manufacturer = Field(attribute='manufacturer', widget=widgets.ForeignKeyWidget(Company))
manufacturer_name = Field(attribute='manufacturer__name', readonly=True)
class Meta:
model = ManufacturerPart
skip_unchanged = True
report_skipped = True
clean_model_instances = True
class ManufacturerPartAdmin(ImportExportModelAdmin):
"""
Admin class for ManufacturerPart model
"""
resource_class = ManufacturerPartResource
list_display = ('part', 'manufacturer', 'MPN')
search_fields = [
'manufacturer__name',
'part__name',
'MPN',
]
autocomplete_fields = ('part', 'manufacturer',)
class ManufacturerPartAttachmentAdmin(ImportExportModelAdmin):
"""
Admin class for ManufacturerPartAttachment model
"""
list_display = ('manufacturer_part', 'attachment', 'comment')
autocomplete_fields = ('manufacturer_part',)
class ManufacturerPartParameterResource(ModelResource):
"""
Class for managing ManufacturerPartParameter data import/export
"""
class Meta:
model = ManufacturerPartParameter
skip_unchanged = True
report_skipped = True
clean_model_instance = True
class ManufacturerPartParameterAdmin(ImportExportModelAdmin):
"""
Admin class for ManufacturerPartParameter model
"""
resource_class = ManufacturerPartParameterResource
list_display = ('manufacturer_part', 'name', 'value')
search_fields = [
'manufacturer_part__manufacturer__name',
'name',
'value'
]
autocomplete_fields = ('manufacturer_part',)
class SupplierPriceBreakResource(ModelResource):
""" Class for managing SupplierPriceBreak data import/export """
part = Field(attribute='part', widget=widgets.ForeignKeyWidget(SupplierPart))
supplier_id = Field(attribute='part__supplier__pk', readonly=True)
supplier_name = Field(attribute='part__supplier__name', readonly=True)
part_name = Field(attribute='part__part__full_name', readonly=True)
SKU = Field(attribute='part__SKU', readonly=True)
MPN = Field(attribute='part__MPN', readonly=True)
class Meta:
model = SupplierPriceBreak
skip_unchanged = True
report_skipped = False
clean_model_instances = True
class SupplierPriceBreakAdmin(ImportExportModelAdmin):
resource_class = SupplierPriceBreakResource
list_display = ('part', 'quantity', 'price')
autocomplete_fields = ('part',)
admin.site.register(Company, CompanyAdmin)
admin.site.register(SupplierPart, SupplierPartAdmin)
admin.site.register(SupplierPriceBreak, SupplierPriceBreakAdmin)
admin.site.register(ManufacturerPart, ManufacturerPartAdmin)
admin.site.register(ManufacturerPartAttachment, ManufacturerPartAttachmentAdmin)
admin.site.register(ManufacturerPartParameter, ManufacturerPartParameterAdmin)
|
isaacgn/5l-XplorR-Android-App
|
app/src/main/java/com/amaze/filemanager/ui/notifications/NotificationConstants.java
|
<filename>app/src/main/java/com/amaze/filemanager/ui/notifications/NotificationConstants.java
/*
* Copyright (C) 2014-2020 <NAME> <<EMAIL>>, <NAME> <<EMAIL>>,
* <NAME><<EMAIL>>, <NAME> <airwave209gt at gmail.com> and Contributors.
*
* This file is part of Amaze File Manager.
*
* Amaze File Manager is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.amaze.filemanager.ui.notifications;
import com.amaze.filemanager.R;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
/** @author <NAME> <<EMAIL>> on 17/9/2017, at 13:34. */
public class NotificationConstants {
public static final int COPY_ID = 0;
public static final int EXTRACT_ID = 1;
public static final int ZIP_ID = 2;
public static final int DECRYPT_ID = 3;
public static final int ENCRYPT_ID = 4;
public static final int FTP_ID = 5;
public static final int FAILED_ID = 6;
public static final int WAIT_ID = 7;
public static final int TYPE_NORMAL = 0, TYPE_FTP = 1;
public static final String CHANNEL_NORMAL_ID = "normalChannel";
public static final String CHANNEL_FTP_ID = "ftpChannel";
/**
* This creates a channel (API >= 26) or applies the correct metadata to a notification (API < 26)
*/
public static void setMetadata(
Context context, NotificationCompat.Builder notification, int type) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
switch (type) {
case TYPE_NORMAL:
createNormalChannel(context);
break;
case TYPE_FTP:
createFtpChannel(context);
break;
default:
throw new IllegalArgumentException("Unrecognized type:" + type);
}
} else {
switch (type) {
case TYPE_NORMAL:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notification.setCategory(Notification.CATEGORY_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification.setPriority(Notification.PRIORITY_MIN);
}
break;
case TYPE_FTP:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notification.setCategory(Notification.CATEGORY_SERVICE);
notification.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
notification.setPriority(Notification.PRIORITY_MAX);
}
break;
default:
throw new IllegalArgumentException("Unrecognized type:" + type);
}
}
}
/**
* You CANNOT call this from android < O. THis channel is set so it doesn't bother the user, but
* it has importance.
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private static void createFtpChannel(Context context) {
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager.getNotificationChannel(CHANNEL_FTP_ID) == null) {
NotificationChannel mChannel =
new NotificationChannel(
CHANNEL_FTP_ID,
context.getString(R.string.channel_name_ftp),
NotificationManager.IMPORTANCE_HIGH);
// Configure the notification channel.
mChannel.setDescription(context.getString(R.string.channel_description_ftp));
mNotificationManager.createNotificationChannel(mChannel);
}
}
/**
* You CANNOT call this from android < O. THis channel is set so it doesn't bother the user, with
* the lowest importance.
*/
@RequiresApi(api = Build.VERSION_CODES.O)
private static void createNormalChannel(Context context) {
NotificationManager mNotificationManager =
(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
if (mNotificationManager.getNotificationChannel(CHANNEL_NORMAL_ID) == null) {
NotificationChannel mChannel =
new NotificationChannel(
CHANNEL_NORMAL_ID,
context.getString(R.string.channel_name_normal),
NotificationManager.IMPORTANCE_MIN);
// Configure the notification channel.
mChannel.setDescription(context.getString(R.string.channel_description_normal));
mNotificationManager.createNotificationChannel(mChannel);
}
}
}
|
jjssobrinho/FemCourseEigenClass2021
|
headers/Poisson.h
|
//
// Poisson.h
// FemCourse
//
// Created by <NAME> on 24/04/18.
//
#ifndef Poisson_h
#define Poisson_h
#include "MathStatement.h"
///\cond
#include <functional>
///\endcond
/**
@brief Implements a poisson problem in 1-, 2- or 3-dimensions
@ingroup mathstatement
*/
class Poisson : public MathStatement
{
// Permeability matrix
MatrixDouble permeability;
// Force funtion related to Poisson math statement
std::function<void(const VecDouble &co, VecDouble &result)> forceFunction;
std::function<void(const VecDouble &loc, VecDouble &result, MatrixDouble &deriv)> SolutionExact;
public:
enum PostProcVar {ENone, ESol, EDSol, EFlux, EForce, ESolExact, EDSolExact};
// Default constructor of Poisson
Poisson();
// Constructor of Poisson
Poisson(int materialid, MatrixDouble &perm);
// Copy constructor of Poisson
Poisson(const Poisson ©);
// Operator of copy
Poisson &operator=(const Poisson ©);
// Method for creating a copy of the element
virtual Poisson *Clone() const;
// Destructor of Poisson
virtual ~Poisson();
// Return the permeability matrix
MatrixDouble GetPermeability() const;
// Set the permeability matrix
void SetPermeability(const MatrixDouble &perm);
// Return the force function related to Poisson math statement
std::function<void(const VecDouble &co, VecDouble &result)> GetForceFunction() const
{
return forceFunction;
}
// Set the force function related to Poisson math statement
void SetForceFunction(const std::function<void(const VecDouble &co, VecDouble &result)> &f)
{
forceFunction = f;
}
// Set the exact solution related to Poisson math statement
void SetExactSolution(const std::function<void(const VecDouble &loc, VecDouble &result, MatrixDouble &deriv)> &Exact)
{
SolutionExact = Exact;
}
// Return the number of state variables
virtual int NState() const {
return 1;
};
virtual int NEvalErrors() const;
// int Dimension() const {
// return 2;
// }
virtual int VariableIndex(const PostProcVar var) const;
// Return the variable index associated with the name
virtual PostProcVar VariableIndex(const std::string &name);
// Return the number of variables associated with the variable indexed by var. Param var Index variable into the solution, is obtained by calling VariableIndex
virtual int NSolutionVariables(const PostProcVar var);
// Method to implement integral over element's volume
virtual void Contribute(IntPointData &integrationpointdata, double weight , MatrixDouble &EK, MatrixDouble &EF) const;
// Method to implement error over element's volume
virtual void ContributeError(IntPointData &integrationpointdata, VecDouble &u_exact, MatrixDouble &du_exact, VecDouble &errors) const;
// Prepare and print post processing data
virtual void PostProcessSolution(const IntPointData &integrationpointdata, const int var, VecDouble &sol) const;
virtual double Inner(MatrixDouble &S,MatrixDouble &T) const;
};
#endif /* Poisson_h */
|
tingshao/catapult
|
tracing/third_party/oboe/test/specs/parseResponseHeaders.unit.spec.js
|
<reponame>tingshao/catapult
describe("parsing response headers", function() {
// linefeed carriage return
var lfcr = "\u000d\u000a";
it('can parse an empty string', function(){
var parsed = parseResponseHeaders('');
expect(parsed).toEqual({})
})
it('can parse a single header', function(){
var parsed = parseResponseHeaders('x-powered-by: Express');
expect(parsed).toEqual({'x-powered-by':'Express'})
});
it('can parse a value containing ": "', function(){
var parsed = parseResponseHeaders('x-title: Episode 2: Another episode');
expect(parsed).toEqual({'x-title':'Episode 2: Another episode'})
});
it('can parse a value containing lots of colons ": "', function(){
var parsed = parseResponseHeaders('x-title: Episode 2: Another episode: Remastered');
expect(parsed).toEqual({'x-title':'Episode 2: Another episode: Remastered'})
});
it('can parse two values containing lots of colons ": "', function(){
var parsed = parseResponseHeaders('x-title: Episode 2: Another episode: Remastered' + lfcr +
'x-subtitle: This file has: a long title' );
expect(parsed).toEqual({'x-title':'Episode 2: Another episode: Remastered',
'x-subtitle': 'This file has: a long title'})
});
it('can parse several headers', function(){
var subject = "x-powered-by: Express" + lfcr +
"Transfer-Encoding: Identity" + lfcr +
"Connection: keep-alive";
var parsed = parseResponseHeaders(subject);
expect(parsed).toEqual({
"x-powered-by": "Express"
, "Transfer-Encoding": "Identity"
, "Connection": "keep-alive"
})
})
});
|
figassis/isogen
|
generate/iso20022/seev/MeetingEntitlementNotificationV05.go
|
<gh_stars>1-10
package seev
import (
"encoding/xml"
"github.com/figassis/bankiso/iso20022"
)
type Document00300105 struct {
XMLName xml.Name `xml:"urn:iso:std:iso:20022:tech:xsd:seev.003.001.05 Document"`
Message *MeetingEntitlementNotificationV05 `xml:"MtgEntitlmntNtfctn"`
}
func (d *Document00300105) AddMessage() *MeetingEntitlementNotificationV05 {
d.Message = new(MeetingEntitlementNotificationV05)
return d.Message
}
// Scope
// An account servicer sends the MeetingEntitlementNotification to an issuer, its agent, an intermediary or an account owner to advise the entitlement in relation to a shareholders meeting.
// Usage
// This message is sent to advise the quantity of securities held by an account owner. The balance is specified for the securities for which the meeting is taking place.
// This entitlement message is sent by the account servicer or the registrar to an intermediary, the issuer's agent or the issuer. It is also sent between the account servicer and the account owner or the party holding the right to vote.
// The message is also used to amend a previously sent MeetingEntitlementNotification. To notify an update, the RelatedReference must be included in the message.
// This message definition is intended for use with the Business Application Header (head.001.001.01).
type MeetingEntitlementNotificationV05 struct {
// Identifies the meeting entitlement message to be modified.
RelatedReference *iso20022.MessageIdentification `xml:"RltdRef,omitempty"`
// Series of elements which allow to identify a meeting.
MeetingReference *iso20022.MeetingReference7 `xml:"MtgRef"`
// Identifies the security for which the meeting is organised, the account and the positions of the security holder.
Security []*iso20022.SecurityPosition9 `xml:"Scty"`
// Defines the dates determining eligibility.
Eligibility *iso20022.EligibilityDates1 `xml:"Elgblty"`
// Additional information that can not be captured in the structured fields and/or any other specific block.
SupplementaryData []*iso20022.SupplementaryData1 `xml:"SplmtryData,omitempty"`
}
func (m *MeetingEntitlementNotificationV05) AddRelatedReference() *iso20022.MessageIdentification {
m.RelatedReference = new(iso20022.MessageIdentification)
return m.RelatedReference
}
func (m *MeetingEntitlementNotificationV05) AddMeetingReference() *iso20022.MeetingReference7 {
m.MeetingReference = new(iso20022.MeetingReference7)
return m.MeetingReference
}
func (m *MeetingEntitlementNotificationV05) AddSecurity() *iso20022.SecurityPosition9 {
newValue := new(iso20022.SecurityPosition9)
m.Security = append(m.Security, newValue)
return newValue
}
func (m *MeetingEntitlementNotificationV05) AddEligibility() *iso20022.EligibilityDates1 {
m.Eligibility = new(iso20022.EligibilityDates1)
return m.Eligibility
}
func (m *MeetingEntitlementNotificationV05) AddSupplementaryData() *iso20022.SupplementaryData1 {
newValue := new(iso20022.SupplementaryData1)
m.SupplementaryData = append(m.SupplementaryData, newValue)
return newValue
}
func ( d *Document00300105 ) String() (result string, ok bool) { return }
|
jiangshide/sdk
|
eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/project/ApkInstallManager.java
|
<reponame>jiangshide/sdk
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.ide.eclipse.adt.internal.project;
import com.android.ddmlib.AndroidDebugBridge;
import com.android.ddmlib.AndroidDebugBridge.IDebugBridgeChangeListener;
import com.android.ddmlib.AndroidDebugBridge.IDeviceChangeListener;
import com.android.ddmlib.IDevice;
import com.android.ddmlib.MultiLineReceiver;
import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor;
import com.android.ide.eclipse.adt.internal.resources.manager.GlobalProjectMonitor.IProjectListener;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IPath;
import java.util.HashSet;
import java.util.Iterator;
/**
* Registers which apk was installed on which device.
* <p/>
* The goal of this class is to remember the installation of APKs on devices, and provide
* information about whether a new APK should be installed on a device prior to running the
* application from a launch configuration.
* <p/>
* The manager uses {@link IProject} and {@link IDevice} to identify the target device and the
* (project generating the) APK. This ensures that disconnected and reconnected devices will
* always receive new APKs (since the version may not match).
* <p/>
* This is a singleton. To get the instance, use {@link #getInstance()}
*/
public final class ApkInstallManager {
private final static ApkInstallManager sThis = new ApkInstallManager();
/**
* Internal struct to associate a project and a device.
*/
private final static class ApkInstall {
public ApkInstall(IProject project, String packageName, IDevice device) {
this.project = project;
this.packageName = packageName;
this.device = device;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof ApkInstall) {
ApkInstall apkObj = (ApkInstall)obj;
return (device == apkObj.device && project.equals(apkObj.project) &&
packageName.equals(apkObj.packageName));
}
return false;
}
@Override
public int hashCode() {
return (device.getSerialNumber() + project.getName() + packageName).hashCode();
}
final IProject project;
final String packageName;
final IDevice device;
}
/**
* Receiver and parser for the "pm path package" command.
*/
private final static class PmReceiver extends MultiLineReceiver {
boolean foundPackage = false;
@Override
public void processNewLines(String[] lines) {
// if the package if found, then pm will show a line starting with "package:/"
if (foundPackage == false) { // just in case this is called several times for multilines
for (String line : lines) {
if (line.startsWith("package:/")) {
foundPackage = true;
break;
}
}
}
}
@Override
public boolean isCancelled() {
return false;
}
}
/**
* Hashset of the list of installed package. Hashset used to ensure we don't re-add new
* objects for the same app.
*/
private final HashSet<ApkInstall> mInstallList = new HashSet<ApkInstall>();
public static ApkInstallManager getInstance() {
return sThis;
}
/**
* Registers an installation of <var>project</var> onto <var>device</var>
* @param project The project that was installed.
* @param packageName the package name of the apk
* @param device The device that received the installation.
*/
public void registerInstallation(IProject project, String packageName, IDevice device) {
synchronized (mInstallList) {
mInstallList.add(new ApkInstall(project, packageName, device));
}
}
/**
* Returns whether a <var>project</var> was installed on the <var>device</var>.
* @param project the project that may have been installed.
* @param device the device that may have received the installation.
* @return
*/
public boolean isApplicationInstalled(IProject project, String packageName, IDevice device) {
synchronized (mInstallList) {
ApkInstall found = null;
for (ApkInstall install : mInstallList) {
if (project.equals(install.project) && packageName.equals(install.packageName) &&
device == install.device) {
found = install;
break;
}
}
// check the app is still installed.
if (found != null) {
try {
PmReceiver receiver = new PmReceiver();
found.device.executeShellCommand("pm path " + packageName, receiver);
if (receiver.foundPackage == false) {
mInstallList.remove(found);
}
return receiver.foundPackage;
} catch (Exception e) {
// failed to query pm? force reinstall.
return false;
}
}
}
return false;
}
/**
* Resets registered installations for a specific {@link IProject}.
* <p/>This ensures that {@link #isApplicationInstalled(IProject, IDevice)} will always return
* <code>null</code> for this specified project, for any device.
* @param project the project for which to reset all installations.
*/
public void resetInstallationFor(IProject project) {
synchronized (mInstallList) {
Iterator<ApkInstall> iterator = mInstallList.iterator();
while (iterator.hasNext()) {
ApkInstall install = iterator.next();
if (install.project.equals(project)) {
iterator.remove();
}
}
}
}
private ApkInstallManager() {
AndroidDebugBridge.addDeviceChangeListener(mDeviceChangeListener);
AndroidDebugBridge.addDebugBridgeChangeListener(mDebugBridgeListener);
GlobalProjectMonitor.getMonitor().addProjectListener(mProjectListener);
}
private IDebugBridgeChangeListener mDebugBridgeListener = new IDebugBridgeChangeListener() {
/**
* Responds to a bridge change by clearing the full installation list.
*
* @see IDebugBridgeChangeListener#bridgeChanged(AndroidDebugBridge)
*/
@Override
public void bridgeChanged(AndroidDebugBridge bridge) {
// the bridge changed, there is no way to know which IDevice will be which.
// We reset everything
synchronized (mInstallList) {
mInstallList.clear();
}
}
};
private IDeviceChangeListener mDeviceChangeListener = new IDeviceChangeListener() {
/**
* Responds to a device being disconnected by removing all installations related
* to this device.
*
* @see IDeviceChangeListener#deviceDisconnected(IDevice)
*/
@Override
public void deviceDisconnected(IDevice device) {
synchronized (mInstallList) {
Iterator<ApkInstall> iterator = mInstallList.iterator();
while (iterator.hasNext()) {
ApkInstall install = iterator.next();
if (install.device == device) {
iterator.remove();
}
}
}
}
@Override
public void deviceChanged(IDevice device, int changeMask) {
// nothing to do.
}
@Override
public void deviceConnected(IDevice device) {
// nothing to do.
}
};
private IProjectListener mProjectListener = new IProjectListener() {
/**
* Responds to a closed project by resetting all its installation.
*
* @see IProjectListener#projectClosed(IProject)
*/
@Override
public void projectClosed(IProject project) {
resetInstallationFor(project);
}
/**
* Responds to a deleted project by resetting all its installation.
*
* @see IProjectListener#projectDeleted(IProject)
*/
@Override
public void projectDeleted(IProject project) {
resetInstallationFor(project);
}
@Override
public void projectOpened(IProject project) {
// nothing to do.
}
@Override
public void projectOpenedWithWorkspace(IProject project) {
// nothing to do.
}
@Override
public void allProjectsOpenedWithWorkspace() {
// nothing to do.
}
@Override
public void projectRenamed(IProject project, IPath from) {
// project renaming also triggers delete/open events so
// there's nothing to do here (since delete will remove
// whatever's linked to the project from the list).
}
};
}
|
lzw5399/tumbleweed
|
src/util/error.go
|
/**
* @Author: lzw5399
* @Date: 2021/3/27 13:33
* @Desc:
*/
package util
import (
"fmt"
"github.com/pkg/errors"
)
// ErrorType is the type of an error
type ErrorType uint
const (
NoType ErrorType = iota
BadRequest // 400
NotFound // 404
Forbidden // 403
InternalServerError // 500
)
type customError struct {
errorType ErrorType
originalError error
context errorContext
}
type errorContext struct {
Field string
Message string
}
// NewError creates a new customError
func (errorType ErrorType) New(err interface{}) error {
var finalError error
switch err.(type) {
case error:
finalError = err.(error)
case string:
finalError = errors.New(err.(string))
}
return customError{errorType: errorType, originalError: finalError}
}
// NewError creates a new customError with formatted message
func (errorType ErrorType) Newf(msg string, args ...interface{}) error {
return customError{errorType: errorType, originalError: fmt.Errorf(msg, args...)}
}
// Error returns the message of a customError
func (error customError) Error() string {
return error.originalError.Error()
}
// NewError creates a no type error
func NewError(err interface{}) error {
var finalError error
switch err.(type) {
case error:
finalError = err.(error)
case string:
finalError = errors.New(err.(string))
}
return customError{errorType: NoType, originalError: finalError}
}
// Newf creates a no type error with formatted message
func NewErrorf(msg string, args ...interface{}) error {
return customError{errorType: NoType, originalError: errors.New(fmt.Sprintf(msg, args...))}
}
// GetType returns the error type
func GetType(err error) ErrorType {
if customErr, ok := err.(customError); ok {
return customErr.errorType
}
return NoType
}
|
PranavaKP/PranavaCodez
|
mods/minecraft/ParrotCraft/ParrotCraftFabric/src/main/java/com/pranavakp/parrotcraftfabric/registry/init/ModBlocks.java
|
package com.pranavakp.parrotcraftfabric.registry.init;
import com.pranavakp.parrotcraftfabric.ParrotCraftFabric;
import net.fabricmc.fabric.api.object.builder.v1.block.FabricBlockSettings;
import net.fabricmc.fabric.api.tool.attribute.v1.FabricToolTags;
import net.minecraft.block.Block;
import net.minecraft.block.Material;
import net.minecraft.item.PickaxeItem;
import net.minecraft.sound.BlockSoundGroup;
import net.minecraft.util.Identifier;
import net.minecraft.util.registry.Registry;
public class ModBlocks {
public static final Block JUNGLE_ORE = new Block(FabricBlockSettings.of(Material.METAL)
.breakByTool(FabricToolTags.PICKAXES, 4)
.requiresTool()
.strength(5f, 35)
.sounds(BlockSoundGroup.METAL));
public static void registerBlocks(){
Registry.register(Registry.BLOCK, new Identifier(ParrotCraftFabric.MOD_ID, "jungle_ore"), JUNGLE_ORE);
}
}
|
concord-consortium/rigse
|
rails/app/policies/home_policy.rb
|
<reponame>concord-consortium/rigse
class HomePolicy < ApplicationPolicy
def admin?
manager_or_researcher_or_project_researcher?
end
def recent_activity?
teacher?
end
def authoring?
teacher? || manager_or_project_admin?
end
def authoring_site_redirect?
teacher? || manager_or_project_admin?
end
end
|
EwaFengler/RoughSetDiviz
|
RoughSet_Drsa_Ranking_Approximations/src/pl/poznan/put/roughset/reduct/CriteriaIndicesMask.java
|
<filename>RoughSet_Drsa_Ranking_Approximations/src/pl/poznan/put/roughset/reduct/CriteriaIndicesMask.java
package pl.poznan.put.roughset.reduct;
import java.util.stream.IntStream;
public class CriteriaIndicesMask {
int mask;
int noOfCriteria;
public CriteriaIndicesMask(int mask, int noOfCriteria) {
this.mask = mask;
this.noOfCriteria = noOfCriteria;
}
public IntStream getIndicesStream() {
return IntStream.range(0, noOfCriteria).filter(this::isCriterionPresent);
}
private boolean isCriterionPresent(int i) {
int criterionBit = 1 << i;
int presenceInMask = criterionBit & mask;
return presenceInMask != 0;
}
}
|
Prvyx/bilibiliWeb
|
java-bilibili/src/main/java/com/prvyx/controller/user/UserStarDirC.java
|
package com.prvyx.controller.user;
import com.prvyx.model.other.NewStarDir;
import com.prvyx.model.postpojo.NewUserStarDir;
import com.prvyx.model.domain.UserStarDir;
import com.prvyx.service.user.UserStarDirS;
import com.prvyx.utils.SendUtils;
import com.prvyx.utils.entity.DataResult;
import com.prvyx.utils.entity.DataResultImpl;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;
import java.util.Map;
/**
* @program: java-bilibili
* @description:
* @author: Prvyx
* @created: 2022/04/02 18:55
*/
@Controller
@RequestMapping(value = "/api/user")
public class UserStarDirC {
@RequestMapping(value = "/userStarDir.ajax",method = RequestMethod.POST)
@ResponseBody
public String userStarDirs(@RequestBody Map<String,String> dataMap){
String userId= dataMap.get("userId");
String videoId=dataMap.get("videoId");
System.out.println(videoId);
DataResult dataResult=new DataResultImpl();
List<UserStarDir> userStarDirs=new UserStarDirS().getUserStarDirs(userId,videoId);
if(userStarDirs.size()!=0){
dataResult.setStatus(0);
dataResult.setMsg("success");
dataResult.setData(userStarDirs);
}else {
dataResult.setStatus(-1);
dataResult.setMsg("fail");
dataResult.setData(null);
}
return SendUtils.sendDataResult(dataResult);
}
@RequestMapping(value = "/newUserStarDir.ajax",method = RequestMethod.POST)
@ResponseBody
public String newUserStarDirs(@RequestBody NewUserStarDir newUserStarDir){
String userId=newUserStarDir.getUserId();
String videoId=newUserStarDir.getVideoId();
List<NewStarDir> newStarDirs=newUserStarDir.getNewStarDirs();
DataResult dataResult=new DataResultImpl();
if(new UserStarDirS().newUserStarDirs(userId,videoId,newStarDirs)){
dataResult.setStatus(0);
dataResult.setMsg("success");
dataResult.setData(null);
}else {
dataResult.setStatus(-1);
dataResult.setMsg("fail");
dataResult.setData(null);
}
return SendUtils.sendDataResult(dataResult);
}
}
|
MrDelik/core
|
tests/components/monoprice/test_config_flow.py
|
"""Test the Monoprice 6-Zone Amplifier config flow."""
from unittest.mock import patch
from serial import SerialException
from homeassistant import config_entries, data_entry_flow
from homeassistant.components.monoprice.const import (
CONF_SOURCE_1,
CONF_SOURCE_4,
CONF_SOURCE_5,
CONF_SOURCES,
DOMAIN,
)
from homeassistant.const import CONF_PORT
from tests.common import MockConfigEntry
CONFIG = {
CONF_PORT: "/test/port",
CONF_SOURCE_1: "one",
CONF_SOURCE_4: "four",
CONF_SOURCE_5: " ",
}
async def test_form(hass):
"""Test we get the form."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == "form"
assert result["errors"] == {}
with patch(
"homeassistant.components.monoprice.config_flow.get_async_monoprice",
return_value=True,
), patch(
"homeassistant.components.monoprice.async_setup_entry",
return_value=True,
) as mock_setup_entry:
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG
)
await hass.async_block_till_done()
assert result2["type"] == "create_entry"
assert result2["title"] == CONFIG[CONF_PORT]
assert result2["data"] == {
CONF_PORT: CONFIG[CONF_PORT],
CONF_SOURCES: {"1": CONFIG[CONF_SOURCE_1], "4": CONFIG[CONF_SOURCE_4]},
}
assert len(mock_setup_entry.mock_calls) == 1
async def test_form_cannot_connect(hass):
"""Test we handle cannot connect error."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.monoprice.config_flow.get_async_monoprice",
side_effect=SerialException,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "cannot_connect"}
async def test_generic_exception(hass):
"""Test we handle cannot generic exception."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
)
with patch(
"homeassistant.components.monoprice.config_flow.get_async_monoprice",
side_effect=Exception,
):
result2 = await hass.config_entries.flow.async_configure(
result["flow_id"], CONFIG
)
assert result2["type"] == "form"
assert result2["errors"] == {"base": "unknown"}
async def test_options_flow(hass):
"""Test config flow options."""
conf = {CONF_PORT: "/test/port", CONF_SOURCES: {"4": "four"}}
config_entry = MockConfigEntry(
domain=DOMAIN,
data=conf,
)
config_entry.add_to_hass(hass)
with patch(
"homeassistant.components.monoprice.async_setup_entry", return_value=True
):
assert await hass.config_entries.async_setup(config_entry.entry_id)
await hass.async_block_till_done()
result = await hass.config_entries.options.async_init(config_entry.entry_id)
assert result["type"] == data_entry_flow.RESULT_TYPE_FORM
assert result["step_id"] == "init"
result = await hass.config_entries.options.async_configure(
result["flow_id"],
user_input={CONF_SOURCE_1: "one", CONF_SOURCE_4: "", CONF_SOURCE_5: "five"},
)
assert result["type"] == data_entry_flow.RESULT_TYPE_CREATE_ENTRY
assert config_entry.options[CONF_SOURCES] == {"1": "one", "5": "five"}
|
TinkerEdgeR-Android/external_dagger2
|
core/src/main/java/dagger/internal/MembersInjectors.java
|
<filename>core/src/main/java/dagger/internal/MembersInjectors.java
/*
* Copyright (C) 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dagger.internal;
import dagger.MembersInjector;
import javax.inject.Inject;
/**
* Basic {@link MembersInjector} implementations used by the framework.
*
* @author <NAME>
* @since 2.0
*/
public final class MembersInjectors {
/**
* Returns a {@link MembersInjector} implementation that injects no members
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> noOp() {
return (MembersInjector<T>) NoOpMembersInjector.INSTANCE;
}
private static enum NoOpMembersInjector implements MembersInjector<Object> {
INSTANCE;
@Override public void injectMembers(Object instance) {
if (instance == null) {
throw new NullPointerException();
}
}
}
/**
* Returns a {@link MembersInjector} that delegates to the {@link MembersInjector} of its
* supertype. This is useful for cases where a type is known not to have its own {@link Inject}
* members, but must still inject members on its supertype(s).
*
* <p>Note that there is no verification that the type being injected does not have {@link Inject}
* members, so care should be taken to ensure appropriate use.
*/
@SuppressWarnings("unchecked")
public static <T> MembersInjector<T> delegatingTo(MembersInjector<? super T> delegate) {
return (MembersInjector<T>) delegate;
}
private MembersInjectors() {}
}
|
josephwinston/hana
|
include/boost/hana/detail/tuple_cartesian_product.hpp
|
/*!
@file
Defines `boost::hana::detail::tuple_cartesian_product`.
@copyright <NAME> 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
#ifndef BOOST_HANA_DETAIL_TUPLE_CARTESIAN_PRODUCT_HPP
#define BOOST_HANA_DETAIL_TUPLE_CARTESIAN_PRODUCT_HPP
#include <boost/hana/detail/array.hpp>
#include <boost/hana/detail/generate_integer_sequence.hpp>
#include <boost/hana/detail/std/forward.hpp>
#include <boost/hana/detail/std/integer_sequence.hpp>
#include <boost/hana/detail/std/size_t.hpp>
#include <boost/hana/foldable.hpp>
#include <boost/hana/tuple.hpp>
namespace boost { namespace hana { namespace detail {
struct _tuple_cartesian_product {
using Size = detail::std::size_t;
template <unsigned Which, Size ...>
struct indexN;
template <unsigned Which, Size I, Size J>
struct indexN<Which, I, J> {
constexpr auto operator()(...) const {
detail::array<detail::array<Size, I * J>, 2> arrays{};
for (Size i = 0, index = 0; i < I; ++i) {
for (Size j = 0; j < J; ++j, ++index) {
arrays[0][index] = i;
arrays[1][index] = j;
}
}
return arrays[Which];
}
};
template <unsigned Which, Size I, Size J, Size K>
struct indexN<Which, I, J, K> {
constexpr auto operator()(...) const {
detail::array<detail::array<Size, I * J * K>, 3> arrays{};
for (Size i = 0, index = 0; i < I; ++i) {
for (Size j = 0; j < J; ++j) {
for (Size k = 0; k < K; ++k, ++index) {
arrays[0][index] = i;
arrays[1][index] = j;
arrays[2][index] = k;
}
}
}
return arrays[Which];
}
};
template <typename ...T, typename ...U,
Size ...i, Size ...j>
static constexpr auto
cartesian_prod_impl(_tuple<T...> const& a,
_tuple<U...> const& b,
detail::std::index_sequence<i...>,
detail::std::index_sequence<j...>)
{
return hana::make_tuple(hana::make_tuple(
detail::get<i>(a), detail::get<j>(b)
)...);
}
template <typename ...T, typename ...U, typename ...V,
Size ...i, Size ...j, Size ...k>
static constexpr auto
cartesian_prod_impl(_tuple<T...> const& a,
_tuple<U...> const& b,
_tuple<V...> const& c,
detail::std::index_sequence<i...>,
detail::std::index_sequence<j...>,
detail::std::index_sequence<k...>)
{
return hana::make_tuple(hana::make_tuple(
detail::get<i>(a), detail::get<j>(b), detail::get<k>(c)
)...);
}
template <typename ...T, typename ...U,
Size ...i, Size ...j>
static constexpr auto
cartesian_prod_impl_cat2(_tuple<T...> const& a,
_tuple<U...> const& b,
detail::std::index_sequence<i...>,
detail::std::index_sequence<j...>)
{
return hana::make_tuple(hana::concat(
detail::get<i>(a), detail::get<j>(b)
)...);
}
template <typename ...Tuples>
static constexpr decltype(auto)
cartesian_prod_helper_cat2(Tuples&& ...tuples) {
constexpr long long lengths[] = {tuple_detail::size<Tuples>{}...};
constexpr Size total_length = hana::product(lengths);
return cartesian_prod_impl_cat2(
detail::std::forward<Tuples>(tuples)...,
detail::generate_index_sequence<total_length,
indexN<0, tuple_detail::size<Tuples>{}...>
>{},
detail::generate_index_sequence<total_length,
indexN<1, tuple_detail::size<Tuples>{}...>
>{}
);
}
template <Size ...i, typename ...Tuples>
static constexpr decltype(auto)
cartesian_prod_helper(detail::std::index_sequence<i...>, Tuples&& ...tuples) {
constexpr long long lengths[] = {tuple_detail::size<Tuples>{}...};
constexpr Size total_length = hana::product(lengths);
return cartesian_prod_impl(
detail::std::forward<Tuples>(tuples)...,
detail::generate_index_sequence<total_length,
indexN<i, tuple_detail::size<Tuples>{}...>
>{}...
);
}
template <typename Tuple>
constexpr decltype(auto) operator()(Tuple&& tuple) const
{ return hana::transform(detail::std::forward<Tuple>(tuple), hana::make_tuple); }
template <typename ...Tuples>
constexpr decltype(auto) operator()(Tuples&& ...tuples) const {
static_assert(sizeof...(Tuples) == 2 || sizeof...(Tuples) == 3,
"this overload should only pick up 2 and 3 tuples");
return cartesian_prod_helper(
detail::std::make_index_sequence<sizeof...(Tuples)>{},
detail::std::forward<Tuples>(tuples)...
);
}
template <typename A, typename B, typename C, typename D1, typename ...Dn>
constexpr decltype(auto)
operator()(A&& a, B&& b, C&& c, D1&& d1, Dn&& ...dn) const {
return hana::transform( // Flatten to get A x B x C x D1 x ... x Dn
cartesian_prod_helper_cat2( // <- Compute (A x B x C) x (D1 x ... x Dn)
(*this)( // <- Compute A x B x C
detail::std::forward<A>(a),
detail::std::forward<B>(b),
detail::std::forward<C>(c)
),
(*this)( // <- Compute D1 x ... x Dn
detail::std::forward<D1>(d1),
detail::std::forward<Dn>(dn)...
)
)
, id);
}
};
constexpr _tuple_cartesian_product tuple_cartesian_product{};
}}} // end namespace boost::hana::detail
#endif // !BOOST_HANA_DETAIL_TUPLE_CARTESIAN_PRODUCT_HPP
|
francisfs/AndroidStudioProjects
|
findmydevice-master/app/src/main/java/de/nulide/findmydevice/utils/Ringer.java
|
<reponame>francisfs/AndroidStudioProjects
package de.nulide.findmydevice.utils;
import android.content.Context;
import android.content.Intent;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import de.nulide.findmydevice.ui.RingerActivity;
public class Ringer {
public static void ring(Context context, int duration){
Intent ringerActivity = new Intent(context, RingerActivity.class);
ringerActivity.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ringerActivity.putExtra(RingerActivity.RING_DURATION, duration);
context.startActivity(ringerActivity);
}
public static Ringtone getRingtone(Context context, String ringtone) {
AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
audioManager.setStreamVolume(AudioManager.STREAM_ALARM, audioManager.getStreamMaxVolume(AudioManager.STREAM_ALARM), 0);
if (audioManager.getRingerMode() != AudioManager.RINGER_MODE_NORMAL)
audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
Ringtone r = RingtoneManager.getRingtone(context, Uri.parse(ringtone));
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
AudioAttributes aa = new AudioAttributes.Builder()
.setUsage(AudioAttributes.USAGE_ALARM)
.setContentType(AudioAttributes.CONTENT_TYPE_UNKNOWN)
.setFlags(AudioAttributes.FLAG_AUDIBILITY_ENFORCED)
.build();
r.setAudioAttributes(aa);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
r.setLooping(true);
}
return r;
}
public static String getDefaultRingtoneAsString(){
return RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
}
}
|
evandersondev/navedex
|
src/components/Loading/styles.js
|
<gh_stars>0
import styled from 'styled-components'
export const Container = styled.div`
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
display: flex;
align-items: center;
justify-content: center;
z-index: 99;
`
export const Spinner = styled.div`
width: 45px;
height: 45px;
border: 8px solid #9e9e9e22;
border-radius: 50%;
border-top-color: #212121aa;
animation: loading 0.6s linear infinite;
@keyframes loading {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
`
|
opencomputeproject/HWMgmt-DeviceMgr-PSME
|
PSME/common/agent-framework/include/agent-framework/validators/checkers/validity_checker.hpp
|
/*!
* @header{License}
* @copyright Copyright (c) 2016-2017 Intel Corporation.
*
* 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.
*
* @header{Filesystem}
* @file validity_checker.hpp
* */
#pragma once
#include "agent-framework/exceptions/exception.hpp"
#include <memory>
namespace Json {
// Forward declaration
class Value;
}
namespace jsonrpc {
/*! @brief Report assertion failed with message */
bool fail(const char* message);
/*!
* @brief interface to validate value from JSON document.
*
* All validity checkers inherit from this class.
* */
class ValidityChecker {
public:
/*! Internal exception to collect message and field name during validation */
class ValidationException {
public:
/*!
* @brief Constructor.
* @param[in] code GAMI error code.
* @param[in] message Error message.
* @param[in] field_value Value of field.
* @param[in] field Name of field.
* */
explicit ValidationException(agent_framework::exceptions::ErrorCode code, const std::string& message,
const Json::Value& field_value, const std::string& field = {});
/*!
* @brief Append subpath of property to path
* @param[in] path Subpath of the property
* */
void append(const std::string& path);
/*!
* @brief Get exception message
* @return Error message
* */
const std::string& get_message() const {
return m_message;
}
/*!
* @brief Get exception error code
* @return Error Code
* */
agent_framework::exceptions::ErrorCode get_error_code() const {
return m_code;
}
/*!
* @brief Get invalid name of field
* @return Field name
* */
const std::string& get_field() const {
return m_field;
}
/*!
* @brief Get invalid field value
* @return Field value
* */
const Json::Value& get_field_value() const {
return m_field_value;
}
private:
agent_framework::exceptions::ErrorCode m_code{};
std::string m_field{};
const Json::Value m_field_value{};
std::string m_message{};
};
/*! Destructor */
virtual ~ValidityChecker();
/*!
* @brief validation method
* @param value json value to be checked
* @throws InvalidValue/InvalidField exception if not valid
*/
virtual void validate(const Json::Value& value) const noexcept(false);
protected:
/*!
* @brief Default constructor.
*
* Available only for subclasses, this is abstract class.
*/
ValidityChecker() = default;
/*!
* @brief Procedure validator uses special <b>null</b> value to distinguish
* from plain nulls.
*/
friend class ProcedureValidator;
/*!
* @brief special value for fields not in the object, to distinguish from
* plain nulls
* */
static const Json::Value NON_EXISTING_VALUE;
/*! @brief Type alias for custom validity checkers */
using Ptr = std::unique_ptr<ValidityChecker>;
private:
/*! Copy constructor. Not allowed */
ValidityChecker(const ValidityChecker&) = delete;
/*! Assign operator. Not allowed */
ValidityChecker& operator=(const ValidityChecker&) = delete;
};
}
|
Shakhzadov/resource-registry-final
|
web/modules/map_module.js
|
(function(){
'use strict';
angular.module('restApp.map', []);
})();
|
artintexo/exkit
|
ekbase/plaza/msg100desc.h
|
<filename>ekbase/plaza/msg100desc.h
#pragma once
#include "description.h"
class Msg100Desc : public Description {
public:
Msg100Desc();
size_t code;
size_t message;
};
|
Nikita-tech-writer/ignite-4
|
modules/raft/src/test/java/org/apache/ignite/raft/jraft/storage/snapshot/local/LocalSnapshotCopierTest.java
|
<gh_stars>0
/*
* 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.ignite.raft.jraft.storage.snapshot.local;
import java.nio.ByteBuffer;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ForkJoinPool;
import org.apache.ignite.raft.jraft.JRaftUtils;
import org.apache.ignite.raft.jraft.Status;
import org.apache.ignite.raft.jraft.core.Scheduler;
import org.apache.ignite.raft.jraft.core.TimerManager;
import org.apache.ignite.raft.jraft.error.RaftError;
import org.apache.ignite.raft.jraft.option.CopyOptions;
import org.apache.ignite.raft.jraft.option.NodeOptions;
import org.apache.ignite.raft.jraft.option.RaftOptions;
import org.apache.ignite.raft.jraft.option.SnapshotCopierOptions;
import org.apache.ignite.raft.jraft.rpc.GetFileRequestBuilder;
import org.apache.ignite.raft.jraft.rpc.Message;
import org.apache.ignite.raft.jraft.rpc.RaftClientService;
import org.apache.ignite.raft.jraft.rpc.RpcRequests;
import org.apache.ignite.raft.jraft.rpc.RpcResponseClosure;
import org.apache.ignite.raft.jraft.storage.BaseStorageTest;
import org.apache.ignite.raft.jraft.storage.snapshot.Snapshot;
import org.apache.ignite.raft.jraft.storage.snapshot.SnapshotReader;
import org.apache.ignite.raft.jraft.test.TestUtils;
import org.apache.ignite.raft.jraft.util.ByteString;
import org.apache.ignite.raft.jraft.util.Endpoint;
import org.apache.ignite.raft.jraft.util.Utils;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Disabled;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import org.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.eq;
@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
public class LocalSnapshotCopierTest extends BaseStorageTest {
private LocalSnapshotCopier copier;
@Mock
private RaftClientService raftClientService;
private String uri;
private final String hostPort = "localhost:8081";
private final int readerId = 99;
private CopyOptions copyOpts;
private LocalSnapshotMetaTable table;
private LocalSnapshotWriter writer;
private LocalSnapshotReader reader;
private RaftOptions raftOptions;
@Mock
private LocalSnapshotStorage snapshotStorage;
private Scheduler timerManager;
private NodeOptions nodeOptions;
@BeforeEach
public void setup() throws Exception {
this.timerManager = new TimerManager(5);
this.raftOptions = new RaftOptions();
this.writer = new LocalSnapshotWriter(this.path.toString(), this.snapshotStorage, this.raftOptions);
this.reader = new LocalSnapshotReader(this.snapshotStorage, null, new Endpoint("localhost", 8081),
this.raftOptions, this.path.toString());
Mockito.when(this.snapshotStorage.open()).thenReturn(this.reader);
Mockito.when(this.snapshotStorage.create(true)).thenReturn(this.writer);
this.table = new LocalSnapshotMetaTable(this.raftOptions);
this.table.addFile("testFile", raftOptions.getRaftMessagesFactory().localFileMeta().checksum("test").build());
this.table.setMeta(raftOptions.getRaftMessagesFactory().snapshotMeta().lastIncludedIndex(1).lastIncludedTerm(1).build());
this.uri = "remote://" + this.hostPort + "/" + this.readerId;
this.copier = new LocalSnapshotCopier();
this.copyOpts = new CopyOptions();
Mockito.when(this.raftClientService.connect(new Endpoint("localhost", 8081))).thenReturn(true);
nodeOptions = new NodeOptions();
nodeOptions.setCommonExecutor(JRaftUtils.createExecutor("test-executor", Utils.cpus()));
assertTrue(this.copier.init(this.uri, new SnapshotCopierOptions(this.raftClientService, this.timerManager,
this.raftOptions, nodeOptions)));
this.copier.setStorage(this.snapshotStorage);
}
@AfterEach
public void teardown() throws Exception {
copier.close();
timerManager.shutdown();
nodeOptions.getCommonExecutor().shutdown();
}
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void testCancelByRemote() throws Exception {
final CompletableFuture<Message> future = new CompletableFuture<>();
final RpcRequests.GetFileRequest rb = raftOptions.getRaftMessagesFactory()
.getFileRequest()
.readerId(99)
.filename(Snapshot.JRAFT_SNAPSHOT_META_FILE)
.count(Integer.MAX_VALUE)
.offset(0)
.readPartly(true)
.build();
//mock get metadata
ArgumentCaptor<RpcResponseClosure> argument = ArgumentCaptor.forClass(RpcResponseClosure.class);
Mockito.when(
this.raftClientService.getFile(eq(new Endpoint("localhost", 8081)), eq(rb),
eq(this.copyOpts.getTimeoutMs()), argument.capture())).thenReturn(future);
this.copier.start();
assertTrue(TestUtils.waitForArgumentCapture(argument, 5_000));
final RpcResponseClosure<RpcRequests.GetFileResponse> closure = argument.getValue();
closure.run(new Status(RaftError.ECANCELED, "test cancel"));
this.copier.join();
//start timer
final SnapshotReader reader = this.copier.getReader();
assertNull(reader);
assertEquals(RaftError.ECANCELED.getNumber(), this.copier.getCode());
assertEquals("test cancel", this.copier.getErrorMsg());
}
@Test
@Disabled("https://issues.apache.org/jira/browse/IGNITE-16620")
public void testInterrupt() throws Exception {
final CompletableFuture<Message> future = new CompletableFuture<>();
final RpcRequests.GetFileRequest rb = raftOptions.getRaftMessagesFactory()
.getFileRequest()
.readerId(99)
.filename(Snapshot.JRAFT_SNAPSHOT_META_FILE)
.count(Integer.MAX_VALUE)
.offset(0)
.readPartly(true)
.build();
//mock get metadata
ArgumentCaptor<RpcResponseClosure> argument = ArgumentCaptor.forClass(RpcResponseClosure.class);
Mockito.when(
this.raftClientService.getFile(eq(new Endpoint("localhost", 8081)), eq(rb),
eq(this.copyOpts.getTimeoutMs()), argument.capture())).thenReturn(future);
this.copier.start();
Utils.runInThread(ForkJoinPool.commonPool(), () -> LocalSnapshotCopierTest.this.copier.cancel());
this.copier.join();
//start timer
final SnapshotReader reader = this.copier.getReader();
assertNull(reader);
assertEquals(RaftError.ECANCELED.getNumber(), this.copier.getCode());
assertEquals("Cancel the copier manually.", this.copier.getErrorMsg());
}
@Test
@SuppressWarnings({"rawtypes", "unchecked"})
public void testStartJoinFinishOK() throws Exception {
final CompletableFuture<Message> future = new CompletableFuture<>();
final GetFileRequestBuilder rb = raftOptions.getRaftMessagesFactory().getFileRequest()
.readerId(99)
.filename(Snapshot.JRAFT_SNAPSHOT_META_FILE)
.count(Integer.MAX_VALUE)
.offset(0)
.readPartly(true);
//mock get metadata
ArgumentCaptor<RpcResponseClosure> argument = ArgumentCaptor.forClass(RpcResponseClosure.class);
Mockito.when(
this.raftClientService.getFile(eq(new Endpoint("localhost", 8081)), eq(rb.build()),
eq(this.copyOpts.getTimeoutMs()), argument.capture())).thenReturn(future);
this.copier.start();
assertTrue(TestUtils.waitForArgumentCapture(argument, 5_000));
RpcResponseClosure<RpcRequests.GetFileResponse> closure = argument.getValue();
final ByteBuffer metaBuf = this.table.saveToByteBufferAsRemote();
RpcRequests.GetFileResponse response = raftOptions.getRaftMessagesFactory()
.getFileResponse()
.readSize(metaBuf.remaining())
.eof(true)
.data(new ByteString(metaBuf))
.build();
closure.setResponse(response);
//mock get file
argument = ArgumentCaptor.forClass(RpcResponseClosure.class);
rb.filename("testFile");
rb.count(this.raftOptions.getMaxByteCountPerRpc());
Mockito.when(
this.raftClientService.getFile(eq(new Endpoint("localhost", 8081)), eq(rb.build()),
eq(this.copyOpts.getTimeoutMs()), argument.capture())).thenReturn(future);
closure.run(Status.OK());
assertTrue(TestUtils.waitForArgumentCapture(argument, 5_000));
closure = argument.getValue();
response = raftOptions.getRaftMessagesFactory()
.getFileResponse()
.readSize(100)
.eof(true)
.data(new ByteString(new byte[100]))
.build();
closure.setResponse(response);
closure.run(Status.OK());
this.copier.join();
final SnapshotReader reader = this.copier.getReader();
assertSame(this.reader, reader);
assertEquals(1, this.writer.listFiles().size());
assertTrue(this.writer.listFiles().contains("testFile"));
}
}
|
agwlvssainokuni/springapp3
|
corelib/fundamental-mail/src/main/java/cherry/fundamental/mail/queue/FileAttachmentStore.java
|
/*
* Copyright 2019 agwlvssainokuni
*
* 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 cherry.fundamental.mail.queue;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.UncheckedIOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.DumperOptions.FlowStyle;
import org.yaml.snakeyaml.DumperOptions.LineBreak;
import org.yaml.snakeyaml.Yaml;
import cherry.fundamental.mail.Attachment;
public class FileAttachmentStore implements AttachmentStore {
private final File basedir;
private final String pattern;
private final String listFile;
public FileAttachmentStore(File basedir, String pattern, String listFile) {
this.basedir = basedir;
this.pattern = pattern;
this.listFile = listFile;
}
@Override
public void save(long messageId, Attachment... attachments) {
if (attachments.length <= 0) {
return;
}
File destdir = getDestdir(messageId);
destdir.mkdirs();
List<Item> list = new ArrayList<>(attachments.length);
for (int i = 0; i < attachments.length; i++) {
Attachment a = attachments[i];
String name = Integer.toString(i);
File destfile = new File(destdir, name);
try (InputStream in = getInputStream(a); OutputStream out = new FileOutputStream(destfile)) {
byte[] buff = new byte[1024];
int len;
while ((len = in.read(buff)) > 0) {
out.write(buff, 0, len);
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
Item item = new Item();
item.setFilename(a.getFilename());
item.setContentType(a.getContentType());
item.setName(name);
list.add(item);
}
DumperOptions opts = new DumperOptions();
opts.setDefaultFlowStyle(FlowStyle.BLOCK);
opts.setLineBreak(LineBreak.WIN);
Yaml yaml = new Yaml(opts);
try (OutputStream out = new FileOutputStream(new File(destdir, listFile));
Writer writer = new OutputStreamWriter(out, StandardCharsets.UTF_8)) {
yaml.dump(list, writer);
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
@Override
public List<AttachedEntry> get(long messageId) {
File destdir = getDestdir(messageId);
if (!destdir.isDirectory()) {
return Collections.emptyList();
}
File f = new File(destdir, listFile);
if (!f.isFile()) {
return Collections.emptyList();
}
Yaml yaml = new Yaml();
try (InputStream in = new FileInputStream(f); Reader r = new InputStreamReader(in, StandardCharsets.UTF_8)) {
List<Item> list = yaml.load(r);
return list.stream().map(item -> {
return new AttachedEntry(item.getFilename(), item.getContentType(), new File(destdir, item.getName()));
}).collect(Collectors.toList());
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
@Override
public void delete(long messageId) {
try {
File destdir = getDestdir(messageId);
if (!destdir.exists()) {
return;
}
File f = new File(destdir, listFile);
if (f.isFile()) {
Yaml yaml = new Yaml();
try (InputStream in = new FileInputStream(f);
Reader r = new InputStreamReader(in, StandardCharsets.UTF_8)) {
List<Item> l = yaml.load(r);
for (Item item : l) {
Files.delete(new File(destdir, item.getName()).toPath());
}
}
Files.delete(f.toPath());
}
String[] l = destdir.list();
if (l == null || l.length == 0) {
Files.delete(destdir.toPath());
}
} catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
private NumberFormat getFormatter() {
return new DecimalFormat(pattern);
}
private File getDestdir(long messageId) {
String destname = getFormatter().format(messageId);
return new File(basedir, destname);
}
private InputStream getInputStream(Attachment a) throws FileNotFoundException {
if (a.getFile() != null) {
return new FileInputStream(a.getFile());
} else {
return a.getStream();
}
}
public static class Item {
private String filename;
private String contentType;
private String name;
public String getFilename() {
return filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
|
fador/kvazaar
|
src/extras/crypto.h
|
#ifndef CRYPTO_H_
#define CRYPTO_H_
#include "global.h"
#include "../cfg.h"
#include <stdio.h>
#include <math.h>
#ifdef KVZ_SEL_ENCRYPTION
#define STUBBED extern
#else
#define STUBBED static
#endif
#define AESEncryptionStreamMode 1
#ifdef __cplusplus
extern "C" {
#endif
typedef struct crypto_handle_t crypto_handle_t;
STUBBED crypto_handle_t* kvz_crypto_create(const kvz_config *cfg);
STUBBED void kvz_crypto_decrypt(crypto_handle_t* hdl,
const uint8_t *in_stream,
int size_bits,
uint8_t *out_stream);
STUBBED void kvz_crypto_delete(crypto_handle_t **hdl);
#if AESEncryptionStreamMode
STUBBED unsigned kvz_crypto_get_key(crypto_handle_t *hdl, int num_bits);
#endif
#ifdef __cplusplus
}
#endif
#undef STUBBED
#ifndef KVZ_SEL_ENCRYPTION
// Provide static stubs to allow linking without libcryptopp and allows us
// to avoid sprinkling ifdefs everywhere and having a bunch of code that's
// not compiled during normal development.
// Provide them in the header so we can avoid compiling the cpp file, which
// means we don't need a C++ compiler when crypto is not enabled.
static INLINE crypto_handle_t* kvz_crypto_create(const kvz_config *cfg)
{
return NULL;
}
static INLINE void kvz_crypto_decrypt(crypto_handle_t* hdl,
const uint8_t *in_stream,
int size_bits,
uint8_t *out_stream)
{}
static INLINE void kvz_crypto_delete(crypto_handle_t **hdl)
{}
#if AESEncryptionStreamMode
static INLINE unsigned kvz_crypto_get_key(crypto_handle_t *hdl, int num_bits)
{
return 0;
}
#endif
#endif // KVZ_SEL_ENCRYPTION
#endif // CRYPTO_H_
|
fura2/competitive-programming-library
|
library/template.hpp
|
#pragma once
#include <cassert>
#include <cctype>
#include <chrono>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <algorithm>
#include <deque>
#include <functional>
#include <iostream>
#include <limits>
#include <map>
#include <numeric>
#include <queue>
#include <random>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#define rep(i,n) for(int i=0;i<(n);i++)
using namespace std;
using lint=long long;
|
si-ran/breakout
|
frontend/src/main/scala/com/neo/sk/breaker/front/breaker/WebSocketClient.scala
|
<gh_stars>0
package com.neo.sk.breaker.front.breaker
import com.neo.sk.breaker.front.common.Routes
import com.neo.sk.breaker.front.utils.byteObject.MiddleBufferInJs
import com.neo.sk.breaker.shared.ptcl.protocol.BreakerEvent._
import org.scalajs.dom
import org.scalajs.dom.raw._
class WebSocketClient(
connectSuccessCallback: Event => Unit,
connectErrorCallback:Event => Unit,
messageHandler:MessageEvent => Unit,
closeCallback:Event => Unit
) {
import io.circe.generic.auto._
import io.circe.syntax._
private var wsSetup = false
private var websocketStreamOpt : Option[WebSocket] = None
def getWsState = wsSetup
def getWebSocketUri(name:String): String = {
val wsProtocol = if (dom.document.location.protocol == "https:") "wss" else "ws"
s"$wsProtocol://${dom.document.location.host}${Routes.wsJoinGameUrl(name)}"
}
private val sendBuffer:MiddleBufferInJs = new MiddleBufferInJs(2048)
def sendByteMsg(msg: GameFrontEvent): Unit = {
import com.neo.sk.breaker.front.utils.byteObject.ByteObject._
websocketStreamOpt.foreach{s =>
s.send(msg.fillMiddleBuffer(sendBuffer).result())
}
}
def sendTextMsg(msg: String): Unit ={
websocketStreamOpt.foreach{ s =>
s.send(msg)
}
}
def setup(name:String):Unit = {
if(wsSetup){
println(s"websocket已经启动")
}else{
val websocketStream = new WebSocket(getWebSocketUri(name))
websocketStreamOpt = Some(websocketStream)
websocketStream.onopen = { (event: Event) =>
wsSetup = true
connectSuccessCallback(event)
}
websocketStream.onerror = { (event: Event) =>
wsSetup = false
websocketStreamOpt = None
connectErrorCallback(event)
}
websocketStream.onmessage = { (event: MessageEvent) =>
messageHandler(event)
}
websocketStream.onclose = { (event: Event) =>
wsSetup = false
websocketStreamOpt = None
closeCallback(event)
}
}
}
}
|
h-hys/rk2108_202012_SDK
|
third_party/audio/audio_server/extcodec/opencore-opus/silk/NLSF2A.c
|
/***********************************************************************
Copyright (c) 2006-2011, Skype Limited. 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 Internet Society, IETF or IETF Trust, nor the
names of specific 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.
***********************************************************************/
#if 1
#include "config.h"
#endif
/* conversion between prediction filter coefficients and LSFs */
/* order should be even */
/* a piecewise linear approximation maps LSF <-> cos(LSF) */
/* therefore the result is not accurate LSFs, but the two */
/* functions are accurate inverses of each other */
#include "SigProc_FIX.h"
#include "tables.h"
#define QA 16
/* helper function for NLSF2A(..) */
static OPUS_INLINE void silk_NLSF2A_find_poly(
opus_int32 *out, /* O intermediate polynomial, QA [dd+1] */
const opus_int32 *cLSF, /* I vector of interleaved 2*cos(LSFs), QA [d] */
opus_int dd /* I polynomial order (= 1/2 * filter order) */
)
{
opus_int k, n;
opus_int32 ftmp;
out[0] = silk_LSHIFT( 1, QA );
out[1] = -cLSF[0];
for( k = 1; k < dd; k++ ) {
ftmp = cLSF[2*k]; /* QA*/
out[k+1] = silk_LSHIFT( out[k-1], 1 ) - (opus_int32)silk_RSHIFT_ROUND64( silk_SMULL( ftmp, out[k] ), QA );
for( n = k; n > 1; n-- ) {
out[n] += out[n-2] - (opus_int32)silk_RSHIFT_ROUND64( silk_SMULL( ftmp, out[n-1] ), QA );
}
out[1] -= ftmp;
}
}
/* compute whitening filter coefficients from normalized line spectral frequencies */
void silk_NLSF2A(
opus_int16 *a_Q12, /* O monic whitening filter coefficients in Q12, [ d ] */
const opus_int16 *NLSF, /* I normalized line spectral frequencies in Q15, [ d ] */
const opus_int d, /* I filter order (should be even) */
int arch /* I Run-time architecture */
)
{
/* This ordering was found to maximize quality. It improves numerical accuracy of
silk_NLSF2A_find_poly() compared to "standard" ordering. */
static const unsigned char ordering16[16] = {
0, 15, 8, 7, 4, 11, 12, 3, 2, 13, 10, 5, 6, 9, 14, 1
};
static const unsigned char ordering10[10] = {
0, 9, 6, 3, 4, 5, 8, 1, 2, 7
};
const unsigned char *ordering;
opus_int k, i, dd;
opus_int32 cos_LSF_QA[ SILK_MAX_ORDER_LPC ];
opus_int32 P[ SILK_MAX_ORDER_LPC / 2 + 1 ], Q[ SILK_MAX_ORDER_LPC / 2 + 1 ];
opus_int32 Ptmp, Qtmp, f_int, f_frac, cos_val, delta;
opus_int32 a32_QA1[ SILK_MAX_ORDER_LPC ];
silk_assert( LSF_COS_TAB_SZ_FIX == 128 );
celt_assert( d==10 || d==16 );
/* convert LSFs to 2*cos(LSF), using piecewise linear curve from table */
ordering = d == 16 ? ordering16 : ordering10;
for( k = 0; k < d; k++ ) {
silk_assert( NLSF[k] >= 0 );
/* f_int on a scale 0-127 (rounded down) */
f_int = silk_RSHIFT( NLSF[k], 15 - 7 );
/* f_frac, range: 0..255 */
f_frac = NLSF[k] - silk_LSHIFT( f_int, 15 - 7 );
silk_assert(f_int >= 0);
silk_assert(f_int < LSF_COS_TAB_SZ_FIX );
/* Read start and end value from table */
cos_val = silk_LSFCosTab_FIX_Q12[ f_int ]; /* Q12 */
delta = silk_LSFCosTab_FIX_Q12[ f_int + 1 ] - cos_val; /* Q12, with a range of 0..200 */
/* Linear interpolation */
cos_LSF_QA[ordering[k]] = silk_RSHIFT_ROUND( silk_LSHIFT( cos_val, 8 ) + silk_MUL( delta, f_frac ), 20 - QA ); /* QA */
}
dd = silk_RSHIFT( d, 1 );
/* generate even and odd polynomials using convolution */
silk_NLSF2A_find_poly( P, &cos_LSF_QA[ 0 ], dd );
silk_NLSF2A_find_poly( Q, &cos_LSF_QA[ 1 ], dd );
/* convert even and odd polynomials to opus_int32 Q12 filter coefs */
for( k = 0; k < dd; k++ ) {
Ptmp = P[ k+1 ] + P[ k ];
Qtmp = Q[ k+1 ] - Q[ k ];
/* the Ptmp and Qtmp values at this stage need to fit in int32 */
a32_QA1[ k ] = -Qtmp - Ptmp; /* QA+1 */
a32_QA1[ d-k-1 ] = Qtmp - Ptmp; /* QA+1 */
}
/* Convert int32 coefficients to Q12 int16 coefs */
silk_LPC_fit( a_Q12, a32_QA1, 12, QA + 1, d );
for( i = 0; silk_LPC_inverse_pred_gain( a_Q12, d, arch ) == 0 && i < MAX_LPC_STABILIZE_ITERATIONS; i++ ) {
/* Prediction coefficients are (too close to) unstable; apply bandwidth expansion */
/* on the unscaled coefficients, convert to Q12 and measure again */
silk_bwexpander_32( a32_QA1, d, 65536 - silk_LSHIFT( 2, i ) );
for( k = 0; k < d; k++ ) {
a_Q12[ k ] = (opus_int16)silk_RSHIFT_ROUND( a32_QA1[ k ], QA + 1 - 12 ); /* QA+1 -> Q12 */
}
}
}
|
majk1/netbeans-mmd-plugin
|
mind-map/mind-map-model/src/main/java/com/igormaznitsa/mindmap/model/logger/LoggerFactory.java
|
/*
* Copyright 2015-2018 <NAME>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.igormaznitsa.mindmap.model.logger;
import static com.igormaznitsa.meta.common.utils.Assertions.assertNotNull;
import com.igormaznitsa.mindmap.model.logger.impl.JavaLoggerServiceImpl;
import java.util.Iterator;
import java.util.ServiceLoader;
import javax.annotation.Nonnull;
public final class LoggerFactory {
private static final LoggerService LOGGER_SERVICE;
static {
final ServiceLoader<LoggerService> service =
ServiceLoader.load(LoggerService.class, LoggerFactory.class.getClassLoader());
service.reload();
final Iterator<LoggerService> iterator = service.iterator();
LOGGER_SERVICE = iterator.hasNext() ? iterator.next() : new JavaLoggerServiceImpl();
LOGGER_SERVICE.getLogger(LoggerFactory.class)
.info("Detected MindMap Logger Service: " + LOGGER_SERVICE.getClass().getName());
}
@Nonnull
public static Logger getLogger(@Nonnull final Class<?> klazz) {
return LOGGER_SERVICE.getLogger(assertNotNull(klazz));
}
@Nonnull
public static Logger getLogger(@Nonnull final String name) {
return LOGGER_SERVICE.getLogger(assertNotNull(name));
}
}
|
sjamboro/kogito-runtimes
|
integration-tests/integration-tests-quarkus-norest/src/test/java/org/kie/kogito/quarkus/jbpm/ProcessTest.java
|
/*
* Copyright 2021 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kie.kogito.quarkus.jbpm;
import java.util.HashMap;
import java.util.Map;
import javax.inject.Inject;
import javax.inject.Named;
import org.junit.jupiter.api.Test;
import org.kie.kogito.Model;
import org.kie.kogito.internal.process.runtime.KogitoProcessInstance;
import org.kie.kogito.process.Process;
import org.kie.kogito.process.ProcessInstance;
import io.quarkus.test.junit.QuarkusTest;
import static org.junit.jupiter.api.Assertions.assertEquals;
@QuarkusTest
public class ProcessTest {
@Inject
@Named("tests")
Process<? extends Model> process;
@Test
public void testProcess() {
Model m = process.createModel();
Map<String, Object> parameters = new HashMap<>();
m.fromMap(parameters);
ProcessInstance<?> processInstance = process.createInstance(m);
processInstance.start();
assertEquals(KogitoProcessInstance.STATE_COMPLETED, processInstance.status());
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.