repo_name
stringlengths 6
101
| path
stringlengths 4
300
| text
stringlengths 7
1.31M
|
|---|---|---|
kapeels/ohmage-server
|
src/org/ohmage/query/ISurveyUploadQuery.java
|
<gh_stars>10-100
/*******************************************************************************
* Copyright 2012 The Regents of the University of California
*
* 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.ohmage.query;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import org.ohmage.domain.Audio;
import org.ohmage.domain.IMedia;
import org.ohmage.domain.Image;
import org.ohmage.domain.Video;
import org.ohmage.domain.campaign.SurveyResponse;
import org.ohmage.exception.DataAccessException;
public interface ISurveyUploadQuery {
/**
* Inserts surveys into survey_response, prompt_response, and
* url_based_resource (if the payload contains images). Any images are also
* persisted to the file system. The entire persistence process is wrapped
* in one giant transaction.
*
* @param user
* The owner of the survey upload.
* @param client
* The software client that performed the upload.
* @param campaignUrn
* The campaign for the survey upload.
* @param surveyUploadList
* The surveys to persist.
* @param bufferedImageMap
* The images to persist.
* @param videoContentsMap
* The videos to persist.
* @param audioContentsMap
* The audio files to persist.
* @param documentContentsMap
* @return Returns a List of Integers representing the ids of duplicate
* surveys.
* @throws DataAccessException
* If any IO error occurs.
*/
List<Integer> insertSurveys(
final String username,
final String client,
final String campaignUrn,
final List<SurveyResponse> surveyUploadList,
final Map<UUID, Image> bufferedImageMap,
final Map<UUID, Video> videoContentsMap,
final Map<UUID, Audio> audioContentsMap,
final Map<UUID, IMedia> documentContentsMap)
throws DataAccessException;
/**
* Update survey_response, prompt_response, and
* url_based_resource (if the payload contains media objects).
* Any updated media objects are also persisted to the file system.
* The entire persistence process is wrapped in one giant transaction.
*
* @param user
* The owner of the survey upload.
* @param client
* The software client that performed the upload.
* @param campaignUrn
* The campaign for the survey upload.
* @param surveyUploadList
* The surveys to persist.
* @param bufferedImageMap
* The images to persist.
* @param videoContentsMap
* The videos to persist.
* @param audioContentsMap
* The audio files to persist.
* @param documentContentsMap
* @return Returns a List of Integers representing the ids of duplicate
* surveys.
* @throws DataAccessException
* If any IO error occurs.
*/
void updateSurveys(
final String username,
final String client,
final String campaignUrn,
final List<SurveyResponse> surveyUploadList,
final Map<UUID, Image> bufferedImageMap,
final Map<UUID, Video> videoContentsMap,
final Map<UUID, Audio> audioContentsMap,
final Map<UUID, IMedia> documentContentsMap,
final Map<UUID, SurveyResponse> existingResponseMap)
throws DataAccessException;
}
|
TerikKek/Chuu
|
src/main/java/core/apis/spotify/SpotifySingleton.java
|
package core.apis.spotify;
public class SpotifySingleton {
private static Spotify instance;
private static String secret;
private static String clientID;
private SpotifySingleton() {
}
//Not pretty
public static void init(String secret2, String clientID2) {
secret = secret2;
clientID = clientID2;
}
public static synchronized Spotify getInstance() {
if (instance == null) {
instance = new Spotify(secret, clientID);
}
return instance;
}
}
|
ampan98/tp
|
src/main/java/seedu/address/commons/core/Messages.java
|
package seedu.address.commons.core;
/**
* Container for user visible messages.
*/
public class Messages {
public static final String MESSAGE_UNKNOWN_COMMAND = "Unknown command";
public static final String MESSAGE_INVALID_COMMAND_FORMAT = "Invalid command format! \n%1$s";
public static final String MESSAGE_INVALID_PERSON_DISPLAYED_INDEX = "The person index provided is invalid";
public static final String MESSAGE_PERSONS_LISTED_OVERVIEW = "%1$d persons listed!";
public static final String MESSAGE_INVALID_START_INDEX = "Start index must be "
+ "strictly smaller than the end index.";
public static final String MESSAGE_INVALID_END_INDEX = "End index cannot be larger than the "
+ "number of contacts in the list";
}
|
dschien/energy-aggregator
|
prefect/models.py
|
<gh_stars>1-10
from django.db import models
from ep.models import Unit, Device
__author__ = 'mitchell'
class PrefectDeviceParameterType(object):
CURRENT_TEMP = 'TS'
SETPOINT_TEMP = 'TH'
PIR = 'PR'
PREFECT_TEMPERATURE_ADJUSTMENT = 'TA'
RELAY_ONE = 'R1'
RELAY_TWO = 'R2'
ENERGY_CONSUMPTION = 'EC'
class PrefectDeviceType(object):
THERMOSTAT = 'TH'
PIR = 'PR'
RELAY = 'RL'
devicetype_description_map = {
PrefectDeviceType.THERMOSTAT: 'Thermostat',
PrefectDeviceType.PIR: 'PIR',
PrefectDeviceType.RELAY: 'Prefect Relay',
}
device_to_deviceparameter_type_map = {
PrefectDeviceType.THERMOSTAT: [PrefectDeviceParameterType.SETPOINT_TEMP, PrefectDeviceParameterType.CURRENT_TEMP],
PrefectDeviceType.PIR: [PrefectDeviceParameterType.PIR],
PrefectDeviceType.RELAY: [PrefectDeviceParameterType.RELAY_ONE, PrefectDeviceParameterType.RELAY_TWO,
PrefectDeviceParameterType.ENERGY_CONSUMPTION],
}
unit_map = {
PrefectDeviceParameterType.CURRENT_TEMP: Unit.CELSIUS,
PrefectDeviceParameterType.SETPOINT_TEMP: Unit.CELSIUS,
PrefectDeviceParameterType.PIR: Unit.NO_UNIT,
PrefectDeviceParameterType.RELAY_ONE: Unit.NO_UNIT,
PrefectDeviceParameterType.RELAY_TWO: Unit.NO_UNIT,
PrefectDeviceParameterType.ENERGY_CONSUMPTION: Unit.KWH
}
device_parameter_type_description_map = {
PrefectDeviceParameterType.PIR: 'PIR',
PrefectDeviceParameterType.CURRENT_TEMP: 'current_temperature',
PrefectDeviceParameterType.SETPOINT_TEMP: 'temperature_setpoint',
PrefectDeviceParameterType.RELAY_ONE: 'relay_1_state',
PrefectDeviceParameterType.RELAY_TWO: 'relay_2_state',
PrefectDeviceParameterType.ENERGY_CONSUMPTION: 'calculated_energy_consumption',
}
class PrefectDeviceParameterConfiguration(models.Model):
device = models.ForeignKey(Device, related_name='configuration')
power_consumption = models.DecimalField(null=False, decimal_places=2, max_digits=7)
line = models.CharField(max_length=2, null=False)
def __str__(self):
return "(%s, Line %s)" % (self.power_consumption, self.line)
class Meta:
verbose_name = 'Prefect Device Configuration'
|
cilidm/mybed
|
app/system/service/user/user_service.go
|
package user
import (
"encoding/json"
"github.com/gin-contrib/sessions"
"github.com/gin-gonic/gin"
"mybedv2/app/helper/e"
"mybedv2/app/helper/util/calculate"
"mybedv2/app/helper/util/pathdir"
userModel "mybedv2/app/system/model/user"
"strconv"
"time"
)
//获取用户当前空间使用率
func GetUserMemPer(userId, mem int64) float64 {
totalSize, err := userModel.GetImgdataSize(userId)
if err != nil {
return 0
}
return calculate.Decimal((float64(totalSize) / float64(mem*1024*1024)) * 100) //默认单位mb 这里要转换成byte
}
func GetUserTmpImgName(c *gin.Context) string {
userId := GetUserId(c)
tmpName := strconv.FormatInt(userId, 10) + "_" + time.Now().Format(e.TimeFormatDir) + ".jpg"
return tmpName
}
func GetUserTmpImgDir(c *gin.Context) string {
userId := GetUserId(c)
tmpDir := "static/upload/" + strconv.FormatInt(userId, 10) + "/" + time.Now().Format(e.DayTimeFormatDir)
pathdir.PathExists(tmpDir)
return tmpDir
}
// 保存用户信息到session
func SaveUserToSession(user userModel.Entity, c *gin.Context) error {
session := sessions.Default(c)
session.Set(e.UserId, user.ID)
if IsAdmin(int64(user.ID)) {
user.Level = 99
}
tmp, _ := json.Marshal(user)
session.Set(e.UserSessionInfo, string(tmp))
return session.Save()
}
// 判断是否是系统管理员
func IsAdmin(userId int64) bool {
var userEntity userModel.Entity
u, err := userEntity.FindById(userId)
if err != nil {
return false
}
if u.Level == 99 {
return true
} else {
return false
}
}
func GetUserId(c *gin.Context) (authId int64) {
s := sessions.Default(c)
authStr := s.Get(e.UserId)
if authStr == nil {
authStr = 0
}
if _, ok := authStr.(int); ok == true {
authId = int64(authStr.(int))
} else {
authId = 0
}
return authId
}
//判断是否登陆
func IsLogin(c *gin.Context) bool {
session := sessions.Default(c)
uid := session.Get(e.UserId)
if uid != nil && uid != 0 {
return true
}
return false
}
func Logout(c *gin.Context) error {
session := sessions.Default(c)
session.Delete(e.UserId)
session.Delete(e.UserSessionInfo)
return session.Save()
}
|
mrinalini-m/data_structures_and_algorithms
|
leetcode/array_string/0036_valid_sudoku.js
|
<filename>leetcode/array_string/0036_valid_sudoku.js<gh_stars>1-10
/**
* @param {character[][]} board
* @return {boolean}
*/
var isValidSudoku = function(board) {
for (let row = 0; row < 9; row++) {
const hasNumInRow = {}
for (let col = 0; col < 9; col++) {
const elem = board[row][col]
if (hasNumInRow[elem] && elem !== '.') {
return false
}
hasNumInRow[board[row][col]] = true
}
}
for (let col = 0; col < 9; col++) {
const hasNumInCol = {}
for (let row = 0; row < 9; row++) {
const elem = board[row][col]
if (hasNumInCol[elem] && elem !== '.') {
return false
}
hasNumInCol[elem] = true
}
}
for (let row = 0; row < 9; row += 3) {
for (let col = 0; col < 9; col += 3) {
const hasNumInSquare = {}
for (let i = row; i < row + 3; i++) {
for (let j = col; j < col + 3; j++) {
const elem = board[i][j]
if (hasNumInSquare[elem] && elem !== '.') {
return false
}
hasNumInSquare[board[i][j]] = true
}
}
}
}
return true
}
const board1 = [
['5', '3', '.', '.', '7', '.', '.', '.', '.'],
['6', '5', '.', '1', '9', '.', '.', '.', '.'],
['.', '9', '8', '.', '.', '.', '.', '6', '.'],
['8', '.', '.', '.', '6', '.', '.', '.', '3'],
['4', '.', '.', '8', '.', '3', '.', '.', '1'],
['7', '.', '.', '.', '2', '.', '.', '.', '6'],
['.', '6', '.', '.', '.', '.', '2', '8', '.'],
['.', '.', '.', '4', '1', '9', '.', '.', '5'],
['.', '.', '.', '.', '8', '.', '.', '7', '9']
]
const board2 = [
['.', '8', '7', '6', '5', '4', '3', '2', '1'],
['2', '.', '.', '.', '.', '.', '.', '.', '.'],
['3', '.', '.', '.', '.', '.', '.', '.', '.'],
['4', '.', '.', '.', '.', '.', '.', '.', '.'],
['5', '.', '.', '.', '.', '.', '.', '.', '.'],
['6', '.', '.', '.', '.', '.', '.', '.', '.'],
['7', '.', '.', '.', '.', '.', '.', '.', '.'],
['8', '.', '.', '.', '.', '.', '.', '.', '.'],
['9', '.', '.', '.', '.', '.', '.', '.', '.']
]
const board3 = [
['.', '.', '4', '.', '.', '.', '6', '3', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['5', '.', '.', '.', '.', '.', '.', '9', '.'],
['.', '.', '.', '5', '6', '.', '.', '.', '.'],
['4', '.', '3', '.', '.', '.', '.', '.', '1'],
['.', '.', '.', '7', '.', '.', '.', '.', '.'],
['.', '.', '.', '5', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.'],
['.', '.', '.', '.', '.', '.', '.', '.', '.']
]
console.log(isValidSudoku(board1))
console.log(isValidSudoku(board2))
console.log(isValidSudoku(board3))
|
drjohnnyfever1/DragonFlyBSD
|
usr.sbin/fstyp/exfat.c
|
<filename>usr.sbin/fstyp/exfat.c
/*
* Copyright (c) 2017 <NAME> <<EMAIL>>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "fstyp.h"
struct exfat_vbr {
char ev_jmp[3];
char ev_fsname[8];
char ev_zeros[53];
uint64_t ev_part_offset;
uint64_t ev_vol_length;
uint32_t ev_fat_offset;
uint32_t ev_fat_length;
uint32_t ev_cluster_offset;
uint32_t ev_cluster_count;
uint32_t ev_rootdir_cluster;
uint32_t ev_vol_serial;
uint16_t ev_fs_revision;
uint16_t ev_vol_flags;
uint8_t ev_log_bytes_per_sect;
uint8_t ev_log_sect_per_clust;
uint8_t ev_num_fats;
uint8_t ev_drive_sel;
uint8_t ev_percent_used;
} __packed;
int
fstyp_exfat(FILE *fp, char *label, size_t size)
{
struct exfat_vbr *ev;
ev = (struct exfat_vbr *)read_buf(fp, 0, 512);
if (ev == NULL || strncmp(ev->ev_fsname, "EXFAT ", 8) != 0)
goto fail;
/*
* Reading the volume label requires walking the root directory to look
* for a special label file. Left as an exercise for the reader.
*/
free(ev);
return (0);
fail:
free(ev);
return (1);
}
|
thierrymarianne/contrib-matterfoss-webapp
|
actions/views/posts.js
|
<reponame>thierrymarianne/contrib-matterfoss-webapp
// Copyright (c) 2015-present Mattermost, Inc. All Rights Reserved.
// See LICENSE.txt for license information.
import * as PostActions from 'matterfoss-redux/actions/posts';
import {logError} from 'matterfoss-redux/actions/errors';
import {ActionTypes, AnnouncementBarTypes} from 'utils/constants';
export function editPost(post) {
return async (dispatch, getState) => {
const result = await PostActions.editPost(post)(dispatch, getState);
// Send to error bar if it's an edit post error about time limit.
if (result.error && result.error.server_error_id === 'api.post.update_post.permissions_time_limit.app_error') {
dispatch(logError({type: AnnouncementBarTypes.ANNOUNCEMENT, message: result.error.message}, true));
}
return result;
};
}
export function selectAttachmentMenuAction(postId, actionId, cookie, dataSource, text, value) {
return async (dispatch) => {
dispatch({
type: ActionTypes.SELECT_ATTACHMENT_MENU_ACTION,
postId,
data: {
[actionId]: {
text,
value,
},
},
});
dispatch(PostActions.doPostActionWithCookie(postId, actionId, cookie, value));
return {data: true};
};
}
|
shivanib01/codes
|
oj/sp/DANGER.cpp
|
<reponame>shivanib01/codes
/*
* Created by
* <NAME> <<EMAIL>>
*/
#include<iostream>
#include<cmath>
using namespace std;
int64_t LowPowTwo(int64_t n){
int64_t a=1;
while(a<=n)
a=a<<1;
return a>>1;
}
int main()
{
string s;
while(cin>>s && s!="00e0"){
int64_t num=s[0]-'0';
num=num*10;
num=num+(s[1]-'0');
num=num*pow(10,s[3]-'0');
int64_t p=LowPowTwo(num);
p=1+(num-p)*2;
cout<<p<<"\n";
}
}
|
Matthewmob/mobsin-game-engine
|
src/math/radians.js
|
<gh_stars>1-10
/**
* Convert degrees to radians.
*
* @memberof Whirl.math
*
* @param {number} degrees Value in degrees.
* @returns {number}
*
* @example
* Whirl.math.radians(45); // 0.7853981633974483
* Whirl.math.radians(90); // 1.5707963267948966
* Whirl.math.radians(360); // 6.283185307179586
*/
const radians = (deg) => (deg * Math.PI) / 180;
export default radians;
|
weibei/weibwei-lib-java
|
weibei-bouncycastle/src/main/java/org/weibei/bouncycastle/jce/provider/PKIXAttrCertPathValidatorSpi.java
|
<filename>weibei-bouncycastle/src/main/java/org/weibei/bouncycastle/jce/provider/PKIXAttrCertPathValidatorSpi.java
package org.weibei.bouncycastle.jce.provider;
import java.security.InvalidAlgorithmParameterException;
import java.security.cert.CertPath;
import java.security.cert.CertPathParameters;
import java.security.cert.CertPathValidatorException;
import java.security.cert.CertPathValidatorResult;
import java.security.cert.CertPathValidatorSpi;
import java.security.cert.X509Certificate;
import java.util.Date;
import java.util.Set;
import org.weibei.bouncycastle.jce.exception.ExtCertPathValidatorException;
import org.weibei.bouncycastle.util.Selector;
import org.weibei.bouncycastle.x509.ExtendedPKIXParameters;
import org.weibei.bouncycastle.x509.X509AttributeCertStoreSelector;
import org.weibei.bouncycastle.x509.X509AttributeCertificate;
/**
* CertPathValidatorSpi implementation for X.509 Attribute Certificates la RFC 3281.
*
* @see org.weibei.bouncycastle.x509.ExtendedPKIXParameters
*/
public class PKIXAttrCertPathValidatorSpi
extends CertPathValidatorSpi
{
/**
* Validates an attribute certificate with the given certificate path.
*
* <p>
* <code>params</code> must be an instance of
* <code>ExtendedPKIXParameters</code>.
* <p>
* The target constraints in the <code>params</code> must be an
* <code>X509AttributeCertStoreSelector</code> with at least the attribute
* certificate criterion set. Obey that also target informations may be
* necessary to correctly validate this attribute certificate.
* <p>
* The attribute certificate issuer must be added to the trusted attribute
* issuers with {@link ExtendedPKIXParameters#setTrustedACIssuers(Set)}.
*
* @param certPath The certificate path which belongs to the attribute
* certificate issuer public key certificate.
* @param params The PKIX parameters.
* @return A <code>PKIXCertPathValidatorResult</code> of the result of
* validating the <code>certPath</code>.
* @throws InvalidAlgorithmParameterException if <code>params</code> is
* inappropriate for this validator.
* @throws CertPathValidatorException if the verification fails.
*/
public CertPathValidatorResult engineValidate(CertPath certPath,
CertPathParameters params) throws CertPathValidatorException,
InvalidAlgorithmParameterException
{
if (!(params instanceof ExtendedPKIXParameters))
{
throw new InvalidAlgorithmParameterException(
"Parameters must be a "
+ ExtendedPKIXParameters.class.getName() + " instance.");
}
ExtendedPKIXParameters pkixParams = (ExtendedPKIXParameters) params;
Selector certSelect = pkixParams.getTargetConstraints();
if (!(certSelect instanceof X509AttributeCertStoreSelector))
{
throw new InvalidAlgorithmParameterException(
"TargetConstraints must be an instance of "
+ X509AttributeCertStoreSelector.class.getName() + " for "
+ this.getClass().getName() + " class.");
}
X509AttributeCertificate attrCert = ((X509AttributeCertStoreSelector) certSelect)
.getAttributeCert();
CertPath holderCertPath = RFC3281CertPathUtilities.processAttrCert1(attrCert, pkixParams);
CertPathValidatorResult result = RFC3281CertPathUtilities.processAttrCert2(certPath, pkixParams);
X509Certificate issuerCert = (X509Certificate) certPath
.getCertificates().get(0);
RFC3281CertPathUtilities.processAttrCert3(issuerCert, pkixParams);
RFC3281CertPathUtilities.processAttrCert4(issuerCert, pkixParams);
RFC3281CertPathUtilities.processAttrCert5(attrCert, pkixParams);
// 6 already done in X509AttributeCertStoreSelector
RFC3281CertPathUtilities.processAttrCert7(attrCert, certPath, holderCertPath, pkixParams);
RFC3281CertPathUtilities.additionalChecks(attrCert, pkixParams);
Date date = null;
try
{
date = CertPathValidatorUtilities
.getValidCertDateFromValidityModel(pkixParams, null, -1);
}
catch (AnnotatedException e)
{
throw new ExtCertPathValidatorException(
"Could not get validity date from attribute certificate.", e);
}
RFC3281CertPathUtilities.checkCRLs(attrCert, pkixParams, issuerCert, date, certPath.getCertificates());
return result;
}
}
|
SUSE/cf-usb
|
lib/csm/csm.go
|
<reponame>SUSE/cf-usb<gh_stars>1-10
package csm
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"net/http"
"net/url"
"strings"
"github.com/SUSE/cf-usb/lib/csm/client/connection"
"github.com/SUSE/cf-usb/lib/csm/client/status"
"github.com/SUSE/cf-usb/lib/csm/client/workspace"
"github.com/SUSE/cf-usb/lib/csm/models"
"github.com/go-openapi/runtime"
runtimeClient "github.com/go-openapi/runtime/client"
"github.com/go-openapi/strfmt"
"github.com/pivotal-golang/lager"
)
type csmClient struct {
logger lager.Logger
workspaceCient *workspace.Client
connectionClient *connection.Client
statusClient *status.Client
authInfoWriter runtime.ClientAuthInfoWriter
loggedIn bool
}
//NewCSMClient instantiates a new csmClient
func NewCSMClient(logger lager.Logger) CSM {
csm := csmClient{}
csm.logger = logger
csm.loggedIn = false
return &csm
}
func (csm *csmClient) Login(targetEndpoint string, token string, caCert string, skipSSLValidation bool) error {
csm.logger.Info("csm-login", lager.Data{"endpoint": targetEndpoint})
target, err := url.Parse(targetEndpoint)
if err != nil {
return err
}
transport := runtimeClient.New(target.Host, "/", []string{target.Scheme})
if skipSSLValidation {
transport.Transport = &http.Transport{TLSClientConfig: &tls.Config{InsecureSkipVerify: true}}
} else {
if strings.TrimSpace(caCert) != "" {
caCertPool := x509.NewCertPool()
caCertPool.AppendCertsFromPEM([]byte(caCert))
transport.Transport = &http.Transport{TLSClientConfig: &tls.Config{RootCAs: caCertPool}}
}
}
csm.workspaceCient = workspace.New(transport, strfmt.Default)
csm.statusClient = status.New(transport, strfmt.Default)
csm.connectionClient = connection.New(transport, strfmt.Default)
csm.authInfoWriter = runtimeClient.APIKeyAuth("x-csm-token", "header", token)
csm.loggedIn = true
return nil
}
func (csm *csmClient) CreateWorkspace(workspaceID string) error {
if !csm.loggedIn {
return errors.New("Not logged in")
}
csm.logger.Info("csm-create-workspace", lager.Data{"workspaceID": workspaceID})
request := models.ServiceManagerWorkspaceCreateRequest{
WorkspaceID: &workspaceID,
}
params := workspace.CreateWorkspaceParams{}
params.CreateWorkspaceRequest = &request
_, err := csm.workspaceCient.CreateWorkspace(¶ms, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*workspace.CreateWorkspaceDefault)
if !ok {
return err
}
return fmt.Errorf(*csmError.Payload.Message)
}
return nil
}
func (csm *csmClient) WorkspaceExists(workspaceID string) (bool, bool, error) {
if !csm.loggedIn {
return false, false, errors.New("Not logged in")
}
csm.logger.Info("csm-workspace-exists", lager.Data{"workspaceID": workspaceID})
params := workspace.GetWorkspaceParams{}
params.WorkspaceID = workspaceID
response, err := csm.workspaceCient.GetWorkspace(¶ms, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*workspace.GetWorkspaceDefault)
if !ok {
return false, false, err
}
if csmError.Code() == http.StatusNotFound {
return false, false, nil
}
return false, false, fmt.Errorf(*csmError.Payload.Message)
}
if response != nil {
if response.Payload != nil {
if response.Payload.ProcessingType != nil && response.Payload.Status != nil {
if *response.Payload.ProcessingType == "none" && *response.Payload.Status == "none" {
return false, true, nil
}
}
}
}
return true, false, nil
}
func (csm *csmClient) DeleteWorkspace(workspaceID string) error {
if !csm.loggedIn {
return errors.New("Not logged in")
}
csm.logger.Info("csm-delete-workspace", lager.Data{"workspaceID": workspaceID})
params := workspace.DeleteWorkspaceParams{}
params.WorkspaceID = workspaceID
_, err := csm.workspaceCient.DeleteWorkspace(¶ms, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*workspace.DeleteWorkspaceDefault)
if !ok {
return err
}
return fmt.Errorf(*csmError.Payload.Message)
}
//TODO: does not throw an error if the workspace does not exist
return nil
}
func (csm *csmClient) CreateConnection(workspaceID, connectionID string) (interface{}, error) {
if !csm.loggedIn {
return nil, errors.New("Not logged in")
}
csm.logger.Info("csm-create-connection", lager.Data{"workspaceID": workspaceID, "connectionID": connectionID})
params := connection.CreateConnectionParams{}
params.WorkspaceID = workspaceID
request := models.ServiceManagerConnectionCreateRequest{
ConnectionID: &connectionID,
}
params.ConnectionCreateRequest = &request
response, err := csm.connectionClient.CreateConnection(¶ms, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*connection.CreateConnectionDefault)
if !ok {
return nil, err
}
return nil, fmt.Errorf(*csmError.Payload.Message)
}
if response.Payload.Details == nil {
response.Payload.Details = map[string]interface{}{}
}
return response.Payload.Details, nil
}
func (csm *csmClient) ConnectionExists(workspaceID, connectionID string) (bool, bool, error) {
if !csm.loggedIn {
return false, false, errors.New("Not logged in")
}
csm.logger.Info("csm-connection-exists", lager.Data{"workspaceID": workspaceID, "connectionID": connectionID})
params := connection.GetConnectionParams{
WorkspaceID: workspaceID,
ConnectionID: connectionID,
}
response, err := csm.connectionClient.GetConnection(¶ms, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*connection.GetConnectionDefault)
if !ok {
return false, false, err
}
if csmError.Code() == http.StatusNotFound {
return false, false, nil
}
return false, false, fmt.Errorf(*csmError.Payload.Message)
}
if response != nil {
if response.Payload != nil {
if response.Payload.ProcessingType != nil && response.Payload.Status != nil {
if *response.Payload.ProcessingType == "none" && *response.Payload.Status == "none" {
return false, true, nil
}
}
}
}
return true, false, nil
}
func (csm *csmClient) DeleteConnection(workspaceID, connectionID string) error {
if !csm.loggedIn {
return errors.New("Not logged in")
}
csm.logger.Info("csm-delete-connection", lager.Data{"workspaceID": workspaceID, "connectionID": connectionID})
params := connection.DeleteConnectionParams{
WorkspaceID: workspaceID,
ConnectionID: connectionID,
}
_, err := csm.connectionClient.DeleteConnection(¶ms, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*connection.DeleteConnectionDefault)
if !ok {
return err
}
return fmt.Errorf(*csmError.Payload.Message)
}
//TODO: in CSM this passes all the time, it does not take into consideration if a connection exists
return nil
}
func (csm *csmClient) GetStatus() (string, error) {
if !csm.loggedIn {
return "", errors.New("Not logged in")
}
params := status.NewStatusParams()
response, err := csm.statusClient.Status(params, csm.authInfoWriter)
if err != nil {
csmError, ok := err.(*status.StatusDefault)
if !ok {
return "", err
}
return "", fmt.Errorf(*csmError.Payload.Message)
}
csm.logger.Info("status-response", lager.Data{"Status ": response.Payload.Status, "Message": response.Payload.Message, "Processing Type": response.Payload.ProcessingType})
if response != nil {
if *response.Payload.Status == "failed" {
errTrace := *response.Payload.Message
for _, diag := range response.Payload.Diagnostics {
csm.logger.Debug("status-response-diagnostics", lager.Data{"Status": diag.Status, "Message": diag.Message, "Name": diag.Name, "Description": diag.Description})
errTrace = errTrace + fmt.Sprintf("\n Status: %s, Name: %s, Description: %s, Message: %s", *diag.Status, *diag.Name, *diag.Description, *diag.Message)
}
return "", fmt.Errorf(errTrace)
}
}
return response.Payload.ServiceType, nil
}
|
light0x00/mybatis-ext
|
mybatis-ext-core/src/main/java/io/github/light0x00/mybatisext/sql/WhereCondition.java
|
package io.github.light0x00.mybatisext.sql;
import io.github.light0x00.mybatisext.toolkit.StringUtils;
import java.util.function.Consumer;
/**
* @author light
* @since 2022/2/20
*/
abstract class WhereCondition<R extends ConditionBuilder<R>> extends ConditionBuilder<R> {
public String getSqlWhere(String paramSymbol) {
String sqlCondition = getSqlCondition(paramSymbol);
return StringUtils.isBlank(sqlCondition) ? "" : "where " + sqlCondition;
}
public String getSqlWhere() {
return getSqlWhere("");
}
public R where() {
return thisAsR();
}
public R where(Consumer<WhereCondition<R>> whereConditionConsumer) {
whereConditionConsumer.accept(this);
return thisAsR();
}
}
|
GuillemD/PendingNameEngine2
|
PendingNameEngine/ComponentAudioSource.h
|
#ifndef _AUDIO_SOURCE_H_
#define _AUDIO_SOURCE_H_
#include "Component.h"
#include "Wwise.h"
#include "WWISE/AK/Wwise_IDs.h"
class WwiseGO;
class ComponentAudioSource :
public Component
{
public:
ComponentAudioSource(GameObject* p);
~ComponentAudioSource();
bool Update();
Wwise::WwiseGO* GetSoundObject() const;
AkUniqueID GetSoundId() const;
void SetSoundId(AkUniqueID id);
private:
Wwise::WwiseGO* sound_object = nullptr;
AkUniqueID object_id = 0;
};
#endif // !_AUDIO_SOURCE_H_
|
LeeBaekHaeng/god.com390
|
god.test/src/test/java/god/test/java/lang/clazz/A54_getMethods.java
|
package god.test.java.lang.clazz;
import java.lang.reflect.Method;
import org.apache.commons.lang3.SystemUtils;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class A54_getMethods {
protected Logger egovLogger = LoggerFactory.getLogger(A54_getMethods.class);
@Test
public void test() throws Exception {
// String className = Class.class.getName();
String className = egovframework.com.cmm.service.EgovCmmUseService.class.getName();
egovLogger.debug("getName: {}", className);
Class<?> c = Class.forName(className);
Method m[] = c.getMethods();
StringBuffer sb = new StringBuffer(SystemUtils.LINE_SEPARATOR);
for (int i = 0; i < m.length; i++) {
// if (m[i].getName().indexOf("Methods") == -1) {
// continue;
// }
egovLogger.debug("method: {}", m[i].toString());
egovLogger.debug("getName: {}", m[i].getName());
sb.append("A");
sb.append(i + 1);
sb.append("_");
sb.append(m[i].getName());
sb.append(SystemUtils.LINE_SEPARATOR);
}
egovLogger.debug(sb.toString());
}
}
|
EliahKagan/old-practice-snapshot
|
main/course-schedule-ii/course-schedule-ii-kahn-nocyclic.java
|
<filename>main/course-schedule-ii/course-schedule-ii-kahn-nocyclic.java
class Solution {
public int[] findOrder(final int numCourses, final int[][] prerequisites) {
return buildPrerequisitesGraph(numCourses, prerequisites)
.topologicalSort();
}
private static Graph buildPrerequisitesGraph(final int numCourses,
final int[][] prerequisites) {
final Graph graph = new Graph(numCourses);
for (final int[] edge : prerequisites) graph.addEdge(edge[1], edge[0]);
return graph;
}
}
/** A directed graph. */
final class Graph {
Graph(final int vertexCount) {
adj = new ArrayList<>(vertexCount);
while (adj.size() != vertexCount) adj.add(new ArrayList<Integer>());
inorders = new int[vertexCount];
}
void addEdge(final int src, final int dest) {
adj.get(src).add(dest);
++inorders[dest];
}
int[] topologicalSort() {
checkAndUnsetTopologicalSortPrecondition();
final int[] out = new int[adj.size()];
int outpos = 0;
for (final Queue<Integer> roots = getRoots(); !roots.isEmpty(); ) {
final int src = roots.remove();
for (final int dest : adj.get(src))
if (--inorders[dest] == 0) roots.add(dest);
out[outpos++] = src;
}
checkTopologicalSortOutputSize(outpos);
return out;
}
private Queue<Integer> getRoots() {
final Queue<Integer> roots = new ArrayDeque<>();
for (int src = 0; src != adj.size(); ++src)
if (inorders[src] == 0) roots.add(src);
return roots;
}
private void checkAndUnsetTopologicalSortPrecondition() {
if (ranTopologicalSort)
throw new IllegalStateException("already ran topological sort");
ranTopologicalSort = true;
}
private void checkTopologicalSortOutputSize(final int outpos) {
if (outpos != adj.size()) {
throw new IllegalStateException(
"can't topologically sort a cyclic graph");
}
}
final List<List<Integer>> adj;
final int[] inorders;
boolean ranTopologicalSort = false;
}
|
hunter-packages/crashpad
|
util/net/http_body.cc
|
<filename>util/net/http_body.cc
// Copyright 2014 The Crashpad Authors. 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.
#include "util/net/http_body.h"
#include <string.h>
#include <algorithm>
#include <limits>
#include "base/logging.h"
#include "base/stl_util.h"
#include "util/misc/implicit_cast.h"
namespace crashpad {
StringHTTPBodyStream::StringHTTPBodyStream(const std::string& string)
: HTTPBodyStream(), string_(string), bytes_read_() {
}
StringHTTPBodyStream::~StringHTTPBodyStream() {
}
FileOperationResult StringHTTPBodyStream::GetBytesBuffer(uint8_t* buffer,
size_t max_len) {
size_t num_bytes_remaining = string_.length() - bytes_read_;
if (num_bytes_remaining == 0) {
return num_bytes_remaining;
}
size_t num_bytes_returned = std::min(
std::min(num_bytes_remaining, max_len),
implicit_cast<size_t>(std::numeric_limits<FileOperationResult>::max()));
memcpy(buffer, &string_[bytes_read_], num_bytes_returned);
bytes_read_ += num_bytes_returned;
return num_bytes_returned;
}
FileHTTPBodyStream::FileHTTPBodyStream(const base::FilePath& path)
: HTTPBodyStream(), path_(path), file_(), file_state_(kUnopenedFile) {
}
FileHTTPBodyStream::~FileHTTPBodyStream() {
}
FileOperationResult FileHTTPBodyStream::GetBytesBuffer(uint8_t* buffer,
size_t max_len) {
switch (file_state_) {
case kUnopenedFile:
file_.reset(LoggingOpenFileForRead(path_));
if (!file_.is_valid()) {
file_state_ = kFileOpenError;
return -1;
}
file_state_ = kReading;
break;
case kFileOpenError:
return -1;
case kClosedAtEOF:
return 0;
case kReading:
break;
}
FileOperationResult rv = ReadFile(file_.get(), buffer, max_len);
if (rv == 0) {
file_.reset();
file_state_ = kClosedAtEOF;
} else if (rv < 0) {
PLOG(ERROR) << "read";
}
return rv;
}
CompositeHTTPBodyStream::CompositeHTTPBodyStream(
const CompositeHTTPBodyStream::PartsList& parts)
: HTTPBodyStream(), parts_(parts), current_part_(parts_.begin()) {
}
CompositeHTTPBodyStream::~CompositeHTTPBodyStream() {
base::STLDeleteContainerPointers(parts_.begin(), parts_.end());
}
FileOperationResult CompositeHTTPBodyStream::GetBytesBuffer(uint8_t* buffer,
size_t buffer_len) {
FileOperationResult max_len = std::min(
buffer_len,
implicit_cast<size_t>(std::numeric_limits<FileOperationResult>::max()));
FileOperationResult bytes_copied = 0;
while (bytes_copied < max_len && current_part_ != parts_.end()) {
FileOperationResult this_read =
(*current_part_)
->GetBytesBuffer(buffer + bytes_copied, max_len - bytes_copied);
if (this_read == 0) {
// If the current part has returned 0 indicating EOF, advance the current
// part and try again.
++current_part_;
} else if (this_read < 0) {
return this_read;
}
bytes_copied += this_read;
}
return bytes_copied;
}
} // namespace crashpad
|
WarrenDev3190/sepsisDog
|
src/app/helpers/helpers.js
|
const getIn = (path, obj) => {
const [first, ...rest] = path.split(".")
return rest.length ?
getIn(rest.join('.'),obj[first]) :
obj[first]
}
const compose = (fn, ...rest) =>
rest.length ?
(...args) => fn(compose(...rest)(...args)) :
fn
const paginate = (a, c, acc) =>
a.length ?
paginate(a.slice(c),c,[...acc,a.slice(0,c)]) :
acc
const mapToPatientStatus = state => {
const patientStatus = state.patientStatus
const {
isFetching,
lastUpdated,
patients
} = patientStatus
return {
isFetching,
lastUpdated,
patients
}
}
export {
getIn,
compose,
mapToPatientStatus,
paginate
}
|
mfkiwl/Orekit
|
src/test/java/org/orekit/models/earth/atmosphere/data/CommonLineReaderTest.java
|
<reponame>mfkiwl/Orekit<gh_stars>0
/* Copyright 2002-2022 CS GROUP
* Licensed to CS GROUP (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS 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.orekit.models.earth.atmosphere.data;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.orekit.Utils;
import org.orekit.data.DataSource;
public class CommonLineReaderTest {
@Before
public void setUp() {
Utils.setDataRoot("regular-data:atmosphere");
}
@Test
public void testParsing() throws IOException, URISyntaxException {
final String name = "DTCFILE_CommonLineReaderTest.txt";
URL url = CommonLineReaderTest.class.getClassLoader().getResource("atmosphere/"+name);
DataSource ds = new DataSource(Paths.get(url.toURI()).toString());
try (InputStream is = ds.getOpener().openStreamOnce();
InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
BufferedReader br = new BufferedReader(isr)) {
CommonLineReader reader = new CommonLineReader(br);
reader.readLine();
Assert.assertTrue(reader.isEmptyLine());
reader.readLine();
Assert.assertEquals(reader.getLine(), "DTC 2003 360 50 17 17 17 38 38 38 74 74 74 74 74 74 31 31 31 38 38 38 38 38 38 44 44");
Assert.assertEquals(reader.getLineNumber(), 2);
Assert.assertFalse(reader.isEmptyLine());
}
}
}
|
Zahnstocher/OsmAnd-ios
|
Sources/Controllers/2.0/OAGPXRouteGroupsViewController.h
|
<filename>Sources/Controllers/2.0/OAGPXRouteGroupsViewController.h
//
// OAGPXRouteGroupsViewController.h
// OsmAnd
//
// Created by <NAME> on 10/07/15.
// Copyright (c) 2015 OsmAnd. All rights reserved.
//
#import "OASuperViewController.h"
@protocol OAGPXRouteGroupsViewControllerDelegate <NSObject>
- (void)routeGroupsChanged;
@end
@interface OAGPXRouteGroupsViewController : OASuperViewController<UITableViewDataSource, UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *titleView;
@property (weak, nonatomic) IBOutlet UIButton *cancelButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;
@property (weak, nonatomic) id<OAGPXRouteGroupsViewControllerDelegate> delegate;
@end
|
physicalist/homebrew-cask
|
Casks/epub-to-pdf.rb
|
<gh_stars>1-10
cask 'epub-to-pdf' do
version '3.1'
sha256 'dcfc59d57f756802e844614b7dae43bca67284ec85fe6b909f244e41f20987b3'
# googleapis.com/google-code-archive-downloads/v2/code.google.com/epub-2-pdf was verified as official when first introduced to the cask
url "https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/epub-2-pdf/e2p-#{version.major}.dmg"
name 'epub-2-pdf'
homepage 'https://code.google.com/archive/p/epub-2-pdf'
app 'epub-to-pdf.app'
caveats do
discontinued
end
end
|
AnushaVutti/PIE_final
|
search-service/src/main/java/com/stackroute/pie/repository/SearchValueRepository.java
|
package com.stackroute.pie.repository;
import com.stackroute.pie.domain.SearchPDM;
import org.springframework.data.mongodb.repository.MongoRepository;
public interface SearchValueRepository extends MongoRepository<SearchPDM,String> {
SearchPDM save(SearchPDM searchPDM);
SearchPDM findBySearchValue(String searchValue);
}
|
pwr-pbrwio/PBR20M2
|
projects/checkstyle/src/test/resources/com/puppycrawl/tools/checkstyle/checks/design/innertypelast/InputInnerTypeLastClassRootClass.java
|
package com.puppycrawl.tools.checkstyle.checks.design.innertypelast;
public enum InputInnerTypeLastClassRootClass {
ALWAYS(Bits.YES), NEVER(Bits.NO);
private interface Bits {
public static final int YES = 1;
public static final int NO = 4;
}
private final int bits;
private InputInnerTypeLastClassRootClass(int bits) {
this.bits = bits;
}
}
|
fossabot/FlyLab
|
examples/demo-c++(11-14-17-20)/7.thread.cpp
|
<filename>examples/demo-c++(11-14-17-20)/7.thread.cpp
#include <iostream>
#include <thread>
void foo() {
std::cout << "hello world" << std::endl;
}
int main() {
std::thread t(foo);
t.join();
return 0;
}
|
dsofowote/KW-Tool
|
keywordTool/pubfiles/src/code/himediadeutschland/126643/default.js
|
integration.meta = {
'sectionID' : '126643',
'siteName' : 'Journal Des Femmes - Desktop - (BE)',
'platform' : 'desktop'
};
integration.testParams = {
/* No Screen Resolution check */
'desktop_resolution' : [0]
};
integration.flaggedTests = [];
integration.params = {
'mf_siteId' : '706942',
'plr_PageAlignment' : 'center',
'plr_ContentW': 1300,
'plr_ContentType': 'PAGESKINEXPRESS',
'plr_UseFullVersion': true,
'plr_UseCreativeSettings': true,
'plr_HideElementsByID' : '',
'plr_HideElementsByClass' : ''
};
integration.on('adCallResult', function(e) {
if (e.data.hasSkin) {
}
});
integration.on('adCallResult', function(e) {
if (e.data.hasSkin) {
$("head").append("<style>#sidebar_follower{display:none}</style>");
$(".page").css({
"overflow-x" : "hidden"
});
$("body").css({
"background-image": "none",
"padding-bottom": integration.base.getCfg("plr_FrameBottom").plr_FrameBottom + "px"
});
$(".ism-frame").css({
"z-index" : "151"
});
$("#ba_x02").css({
"width": "1000px",
"margin": "0 auto"
});
$("header, footer").css({
"max-width": "1300px",
"margin": "0 auto"
});
$(".ccmcss_oic").css({
"z-index": "1"
});
}
});
/**** Raise Z-index of PageSkin ****/
integration.on("adServed", function(e) {
$(".ism-frame").parent().css({
"z-index" : "11001"
});
});
|
dmgerman/hadoop
|
hadoop-common-project/hadoop-minikdc/src/test/java/org/apache/hadoop/minikdc/TestChangeOrgNameAndDomain.java
|
begin_unit|revision:0.9.5;language:Java;cregit-version:0.0.1
begin_comment
comment|/** * 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. */
end_comment
begin_package
DECL|package|org.apache.hadoop.minikdc
package|package
name|org
operator|.
name|apache
operator|.
name|hadoop
operator|.
name|minikdc
package|;
end_package
begin_import
import|import
name|java
operator|.
name|util
operator|.
name|Properties
import|;
end_import
begin_class
DECL|class|TestChangeOrgNameAndDomain
specifier|public
class|class
name|TestChangeOrgNameAndDomain
extends|extends
name|TestMiniKdc
block|{
annotation|@
name|Override
DECL|method|createMiniKdcConf ()
specifier|public
name|void
name|createMiniKdcConf
parameter_list|()
block|{
name|super
operator|.
name|createMiniKdcConf
argument_list|()
expr_stmt|;
name|Properties
name|properties
init|=
name|getConf
argument_list|()
decl_stmt|;
name|properties
operator|.
name|setProperty
argument_list|(
name|MiniKdc
operator|.
name|ORG_NAME
argument_list|,
literal|"APACHE"
argument_list|)
expr_stmt|;
name|properties
operator|.
name|setProperty
argument_list|(
name|MiniKdc
operator|.
name|ORG_DOMAIN
argument_list|,
literal|"COM"
argument_list|)
expr_stmt|;
block|}
block|}
end_class
end_unit
|
mjjq/ballEngine
|
source/Simulation/classUniverse.cpp
|
#include <iostream>
#include <SFML/Graphics.hpp>
#include <cmath>
#include <thread>
#include <limits>
#include <tuple>
#include "classUniverse.h"
#include "Math.h"
#include "stringConversion.h"
/*void BallUniverse::spawnNewObject(ObjectProperties init)
{
sf::Vector2f position = init._position;
if(!(position.x < 0 ||
position.y < 0 ||
position.x> worldSizeX ||
position.y> worldSizeY))
{
if(!init.isStatic)
{
switch(init.type)
{
case ObjectType::Ball :
{
std::unique_ptr<Ball > newBall = std::make_unique<Ball >(init);
dynamicObjects.push_back(std::move(newBall));
numOfBalls++;
break;
}
case ObjectType::Polygon :
{
std::unique_ptr<Polygon > newPoly = std::make_unique<Polygon >(init);
dynamicObjects.push_back(std::move(newPoly));
numOfBalls++;
break;
}
case ObjectType::Capsule :
{
std::unique_ptr<Capsule > newCapsule = std::make_unique<Capsule >(init);
dynamicObjects.push_back(std::move(newCapsule));
numOfBalls++;
break;
}
default:
break;
}
}
else
{
init._mass = 1e+15;
switch(init.type)
{
case ObjectType::Ball:
{
std::unique_ptr<Ball > newBall = std::make_unique<Ball >(init);
staticObjects.push_back(std::move(newBall));
break;
}
case ObjectType::Polygon:
{
std::unique_ptr<Polygon > newPoly = std::make_unique<Polygon >(init);
staticObjects.push_back(std::move(newPoly));
break;
}
case ObjectType::Capsule:
{
std::unique_ptr<Capsule > newCapsule = std::make_unique<Capsule >(init);
staticObjects.push_back(std::move(newCapsule));
break;
}
default:
break;
}
}
}
}*/
void BallUniverse::spawnNewObject(ObjectProperties init)
{
/*sf::Vector2f position = init._position;
if(!(position.x < 0 ||
position.y < 0 ||
position.x> worldSizeX ||
position.y> worldSizeY))
{
if(!init._isStatic)
{
switch(init.type)
{
case ObjectType::Ball :
{
dynamicObjects.push_back(new Ball(init));
numOfBalls++;
break;
}
case ObjectType::Polygon :
{
dynamicObjects.push_back(new Polygon(init));
numOfBalls++;
break;
}
case ObjectType::Capsule :
{
dynamicObjects.push_back(new Capsule(init));
numOfBalls++;
break;
}
default:
break;
}
}
else
{
init._mass = 1e+15;
switch(init.type)
{
case ObjectType::Ball:
{
staticObjects.push_back(new Ball(init));
break;
}
case ObjectType::Polygon:
{
staticObjects.push_back(new Polygon(init));
break;
}
case ObjectType::Capsule:
{
staticObjects.push_back(new Capsule(init));
break;
}
default:
break;
}
}
}*/
}
/*void BallUniverse::spawnNewObject(std::unique_ptr<PhysicsObject> obj)
{
dynamicObjects.emplace_back(std::move(obj));
++numOfBalls;
}*/
//void resetAndCheckBounce(std::vector<Ball>)
/**
Updates the velocity of the current ball by calculating forces on the ball.
@param dt The simulation timestep.
@param &otherBall The other ball to interact with.
@return Void.
*/
void BallUniverse::updateFirstVelocity(Integrators _integType, float _dt, PhysicsObject* obj1, PhysicsObject* obj2)
{
sf::Vector2f relVec = obj1->getPosition() + obj1->getCoM() - (obj2->getPosition() + obj2->getCoM());
float r2 = Math::square(relVec);
float totalR = obj1->getMinSize()+obj2->getMinSize();
if(r2 > totalR*totalR)
{
//nStepVelocity = {0,0};
float G = 1;
float M = obj2->getMass();
sf::Vector2f firstVelocity = obj1->getVelocity();
sf::Vector2f secondVelocity = obj2->getVelocity();
std::pair<sf::Vector2f,sf::Vector2f> solution;
switch(_integType)
{
case(Integrators::INTEG_EULER):
solution = integrators::eulerMethod(relVec, _dt, M, G);
break;
case(Integrators::INTEG_SEM_IMP_EULER):
solution = integrators::semImpEulerMethod(relVec, _dt, M, G);
break;
case(Integrators::INTEG_RK4):
solution = integrators::RK4Method2ndODE(relVec, firstVelocity, secondVelocity, _dt, M, G);
break;
case(Integrators::INTEG_VERLET):
solution = integrators::verletMethod(relVec, firstVelocity, secondVelocity, _dt, M, G);
break;
case(Integrators::LAST):
default:
break;
}
obj1->addSolvedVelocity(solution.first, solution.second);
/*cStepModVelocity += solution.first;
nStepVelocity += solution.second;*/
}
}
void BallUniverse::updateAllObjects(bool _enableForces, float _dt)
{
if(_enableForces==true)
for(auto iter1 = dynamicObjects.begin(); iter1 != dynamicObjects.end(); ++iter1)
for(auto iter2 = dynamicObjects.begin(); iter2 != dynamicObjects.end(); ++iter2)
if(&iter1 != &iter2 && !(*iter1)->ignoresGravity() && !(*iter2)->ignoresGravity())
updateFirstVelocity(intEnum, _dt, (*iter1), (*iter2));
if(universalGravity==true)
for(auto iter = dynamicObjects.begin(); iter != dynamicObjects.end(); iter++)
{
if(!(*iter)->ignoresGravity())
{
std::pair<sf::Vector2f,sf::Vector2f> solution;
solution = integrators::verletMethod(_dt, uGravityDir);
(*iter)->addSolvedVelocity(solution.first, solution.second);
}
}
}
/**
Checks if the ball is about to intersect the world boundary and executes a
damped collision.
@param worldSizeX The x-component size of the simulation world.
@param worldSizeY The y-component size of the simulation world.
@return Void.
*/
bool BallUniverse::checkForBounce(PhysicsObject* object)
{
sf::Vector2f shapePos = object->getPosition();
float shapeRadius = 0.0f;
sf::Vector2f velocity = object->getVelocity();
if(((shapePos.x+shapeRadius >= worldSizeX) && (velocity.x>=0))
|| ((shapePos.x-shapeRadius <= 0 && (velocity.x<=0))))
{
object->setVelocity({-velocity.x, velocity.y});
return true;
}
else if(((shapePos.y+shapeRadius >= worldSizeY) && (velocity.y>=0))
|| ((shapePos.y-shapeRadius <= 0 && (velocity.y<=0))))
{
object->setVelocity({velocity.x, -velocity.y});
return true;
}
return false;
}
void BallUniverse::calcCollTimes()
{
for(unsigned int i=0;i<colliderArray.getHeight();++i)
for(unsigned int j=i+1;j<colliderArray.getWidth();++j)
//if(i!=j)
{
/*if(dynamicObjects.at(i).getDistance(dynamicObjects.at(j)) < 0.99*(dynamicObjects.at(i).getRadius() + dynamicObjects.at(j).getRadius()))
{
std::cout << "Overlapping balls " << i << " " << j << " at " << dynamicObjects.at(i).sf::CircleShape::getPosition() << " \n";
std::cout << //colliderArray.getElementValue(i,j) << "\n";
}*/
//float tColl = Collisions::timeToCollision(dynamicObjects.at(i).get(), dynamicObjects.at(j).get());
//colliderArray.setElementValue(j,i, tColl);
}
for(unsigned int i=0; i<staticCollArray.getHeight(); ++i)
for(unsigned int j=0; j<staticCollArray.getWidth(); ++j)
{
//float tColl = Collisions::timeToCollision(dynamicObjects.at(i).get(), staticObjects.at(j).get());
//staticCollArray.setElementValue(j,i, tColl);
}
}
void BallUniverse::findShortestCollTime()
{
int xDyn = 0;
int yDyn = 0;
int xStat = 0;
int yStat = 0;
float collTupleDyn = colliderArray.getMatrixMin(xDyn, yDyn);
float collTupleStat = staticCollArray.getMatrixMin(xStat, yStat);
////colliderArray.printMatrix(); std::cout << "\n";
////staticCollArray.printMatrix(); std::cout << "\n";
if(collTupleDyn < collTupleStat)
{
//std::cout << "Dyn\n";
collWithStatic = false;
timeToNextColl = collTupleDyn;
collider1 = xDyn;
collider2 = yDyn;
}
else
{
//std::cout << "stat\n";
collWithStatic = true;
timeToNextColl = collTupleStat;
collider1 = xStat;
collider2 = yStat;
}
//std::cout << timeToNextColl << ": " << collider1 << " " << collider2 << "\n";
}
void BallUniverse::collTimeForBall(unsigned int index)
{
for(unsigned int i=0; i<dynamicObjects.size(); ++i)
{
if(index < i)
{
//if(dynamicObjects.at(index).getRadius() +
// 2.0*dynamicObjects.at(index).getRelSpeed(dynamicObjects.at(i))*dt >
// dynamicObjects.at(index).getDistance(dynamicObjects.at(i)))
//{
//float tColl = Collisions::timeToCollision(dynamicObjects.at(index).get(), dynamicObjects.at(i).get());
//colliderArray.setElementValue(i, index, tColl);
//}
//else
// //colliderArray.setElementValue(index, i, std::numeric_limits<float>::quiet_NaN());
}
else if(index > i)
{
//float tColl = Collisions::timeToCollision(dynamicObjects.at(index).get(), dynamicObjects.at(i).get());
//colliderArray.setElementValue(index, i, tColl);
}
}
for(unsigned int i=0; i<staticCollArray.getWidth(); ++i)
{
//float tColl = Collisions::timeToCollision(dynamicObjects.at(index).get(), staticObjects.at(i).get());
//staticCollArray.setElementValue(i, index, tColl);
}
}
void BallUniverse::removeBall(int index)
{
if(std::abs(index) < (int)dynamicObjects.size())
{
if(index >=0)
{
//dynamicObjects.erase(dynamicObjects.begin() + index);
delete dynamicObjects[index];
}
else if(index < 0)
{
delete dynamicObjects[dynamicObjects.size() + index];
//dynamicObjects.erase(dynamicObjects.end() + index + 1);
}
numOfBalls--;
//colliderArray.removeEndRow();
//colliderArray.removeColumnQuick(std::numeric_limits<float>::quiet_NaN());
////staticCollArray.removeEndRow();
if(enable_collisions)
calcCollTimes();
}
else if(index == -1 && dynamicObjects.size() == 1)
{
numOfBalls = 0;
dynamicObjects.clear();
//colliderArray.clearMatrix();
////staticCollArray.removeEndRow();
}
clearArbiters();
//broadPhase();
}
void BallUniverse::removeRect(int index)
{
if(std::abs(index) < (int)staticObjects.size())
{
if(index >= 0)
staticObjects.erase(staticObjects.begin() + index);
else if(index < 0)
staticObjects.erase(staticObjects.end() + index + 1);
//staticCollArray.removeColumnQuick(std::numeric_limits<float>::quiet_NaN());
if(enable_collisions)
calcCollTimes();
}
else if(index == -1 && staticObjects.size() == 1)
{
staticObjects.clear();
//staticCollArray.removeColumnQuick(std::numeric_limits<float>::quiet_NaN());
}
clearArbiters();
broadPhase();
}
void BallUniverse::broadPhase()
{
//float dtR = dt;
for(unsigned int i=0; i<dynamicObjects.size(); ++i)
{
PhysicsObject* obji = dynamicObjects[i];
if(obji->getCollisionsEnabled())
{
for(unsigned int j=i+1; j<dynamicObjects.size(); ++j)
{
//std::cout << i << " " << j << "\n";
PhysicsObject* objj = dynamicObjects[j];
if(objj->getCollisionsEnabled() &&
(obji->getCollisionGroup().isOfSameGroup(objj->getCollisionGroup())))
{
Arbiter newArb(obji, objj);
ArbiterKey key(obji, objj);
if(newArb.numContacts > 0)
{
ArbIter iter = arbiters.find(key);
if(iter == arbiters.end())
{
addArbiter(ArbPair(key, newArb));
//obji->contactData.insert(objj)
}
else
iter->second.update();
}
else
{
if(obji->isBullet() || objj->isBullet())
{
//float newDt = Collisions::timeToCollision(obji, objj);
//if(newDt < dtR)
}
else
eraseArbiter(key);
}
}
}
}
}
for(unsigned int i=0; i<dynamicObjects.size(); ++i)
{
PhysicsObject* obji = dynamicObjects[i];
if(obji->getCollisionsEnabled())
{
for(unsigned int j=0; j<staticObjects.size(); ++j)
{
PhysicsObject* objj = staticObjects[j];
if(objj->getCollisionsEnabled() &&
(obji->getCollisionGroup().isOfSameGroup(objj->getCollisionGroup())))
{
Arbiter newArb(obji, objj);
ArbiterKey key(obji, objj);
if(newArb.numContacts > 0)
{
ArbIter iter = arbiters.find(key);
if(iter == arbiters.end())
{
addArbiter(ArbPair(key, newArb));
}
else
iter->second.update();
}
else
eraseArbiter(key);
}
}
}
}
}
float BallUniverse::physicsLoop(float _dt)
{
//float dtR = dt;
//float epsilon = 1e-5;
for(unsigned int i=0; i<dynamicObjects.size(); ++i)
{
//dynamicObjects[i].resetToCollided();
checkForBounce(dynamicObjects[i]);
//if( checkForBounce(dynamicObjects[i].get()) && enable_collisions)
//collTimeForBall(i);
}
broadPhase();
universeSub.notify(*this, Event{EventType::Character_Contact});
universeSub.notify(*this, Event{EventType::Projectile_Contact});
updateAllObjects(enable_forces, _dt);
for(ArbIter arb = arbiters.begin(); arb != arbiters.end(); ++arb)
{
arb->second.PreStep(1.0f/_dt);
}
jointManager.preStep(1.0f/_dt);
for (int i = 0; i < 10; ++i)
{
for (ArbIter arb = arbiters.begin(); arb != arbiters.end(); ++arb)
{
arb->second.ApplyImpulse();
}
jointManager.applyImpulse();
}
//std::cout << "hello\n";
//std::cout << arbiters.size() <<"\n";
for(unsigned int i=0; i<dynamicObjects.size(); ++i)
{
dynamicObjects[i]->updatePosition(_dt);
}
currentTime += _dt;
return _dt;
}
void BallUniverse::universeLoop(sf::Time frameTime, sf::Time frameLimit)
{
//if(!isPaused)
//{
//accumulator += 120*dt*frameTime.asSeconds();((frameTime<frameLimit)?frameTime:frameLimit).asSeconds();
/*int limiting = 0;
int maxLimit = 1000;
float dtR = dt;
while(accumulator >= dt && limiting < maxLimit)
{
thresholdTimer.restart();
std::cout << "Before: " << limiting << "\n";
dtR = physicsLoop();
accumulator -= dtR;
std::cout << "After: " << limiting << "\n";
std::cout << "After: " << thresholdTimer.getElapsedTime().asSeconds() << "\n\n";
sampleAllPositions();
if(thresholdTimer.getElapsedTime().asSeconds() > frameLimit.asSeconds()*dtR)
++limiting;
}
playerInput.first = false;
calcTotalKE(dynamicObjects);
calcTotalMomentum(dynamicObjects);
calcTotalGPE(dynamicObjects);
calcTotalEnergy();
if( (limiting == maxLimit) && (accumulator >= dt) )
{
accumulator = 0.0f;
std::cout << "Limit\n";
if(frameTime.asSeconds() > 1.0f)
isPaused = true;
}
}*/
}
void BallUniverse::sampleAllPositions()
{
/*if(timeToNextSample - dt <= 0)
{
for(auto iter = dynamicObjects.begin(); iter != dynamicObjects.end(); ++iter)
if((**iter).getSamplePrevPosBool())
(**iter).sampleNextPosition();
timeToNextSample = sampledt;
//std::cout << timeToNextSample << "\n";
}
else
timeToNextSample -= dt;
for(auto iter = dynamicObjects.begin(); iter != dynamicObjects.end(); ++iter)
if((**iter).getSamplePrevPosBool())
(**iter).sampleCurrentPosition();*/
}
void BallUniverse::drawSampledPositions(sf::RenderWindow &window) //No longer very CPU intensive
{
for(auto iter = dynamicObjects.begin(); iter != dynamicObjects.end(); ++iter)
{
if((**iter).getSamplePrevPosBool())
{
std::deque<sf::Vector2f> previousPositions = (**iter).getPreviousPositions();
if(previousPositions.size() > 1)
{
int colorGradient = previousPositions.size();
sf::VertexArray lines(sf::LinesStrip, previousPositions.size());
sf::Color color;
for(unsigned int j=0; j<previousPositions.size(); ++j)
{
if((**iter).getIsPlayer())
color = {255,255,0,static_cast<sf::Uint8>(255*j/colorGradient)};
else
color = {255,255,255,static_cast<sf::Uint8>(255*j/colorGradient)};
lines[j].position = previousPositions.at(j);
lines[j].color = color;
//line[0] = sf::Vertex(static_cast<sf::Vector2f>(previousPositions.at(i)),color);
//line[1] = sf::Vertex(static_cast<sf::Vector2f>(previousPositions.at(i+1)),color);
//window.draw(line, 2, sf::Lines);
}
window.draw(lines);
}
}
}
}
void BallUniverse::calcTotalKE(std::vector<PhysicsObject* > &_dynamicObjects)
{
totalKE = 0;
float KE{0};
for(auto iter1 = _dynamicObjects.begin(); iter1 != _dynamicObjects.end(); ++iter1)
KE += (**iter1).getKE();
totalKE = KE;
}
void BallUniverse::calcTotalGPE(std::vector<PhysicsObject* > &_dynamicObjects)
{
totalGPE = 0;
if(_dynamicObjects.size()>1)
{
float GPE{0};
for(auto iter1 = _dynamicObjects.begin(); iter1 != _dynamicObjects.end(); ++iter1)
for(auto iter2 = _dynamicObjects.begin(); iter2 != _dynamicObjects.end(); ++iter2)
if(&iter1 != &iter2)
GPE+=(**iter1).getGPE(*iter2)/2.0f;
totalGPE = GPE;
}
}
void BallUniverse::calcTotalEnergy()
{
totalEnergy = totalKE + totalGPE;
}
void BallUniverse::calcTotalMomentum(std::vector<PhysicsObject* > &_dynamicObjects)
{
sf::Vector2f momentum{0,0};
for(auto iter1 = _dynamicObjects.begin(); iter1 != _dynamicObjects.end(); ++iter1)
momentum += (**iter1).getMomentum();
totalMomentum = momentum;
}
void BallUniverse::createBallGrid(int numWide, int numHigh, float spacing, sf::Vector2f centralPosition, sf::Vector2f init_velocity, float ballMass, float ballRadius)
{
if(spacing < 2.5*ballRadius)
spacing = 2.5*ballRadius;
//if(!)
{
for(int i=-numWide/2; i<=numWide/2; ++i)
for(int j=-numHigh/2; j<=numHigh/2; ++j)
{
//sf::Vector2f offsetPosition = {i*spacing,j*spacing};
/*spawnNewBall({centralPosition + offsetPosition,
init_velocity,
{ballRadius, 0.0f},
ballMass,
0.0f,
1.0f,
0.0f,
0.0f});*/
//std::cout << i << " " << j << "\n";
}
}
}
void BallUniverse::createAltBallGrid(int numWide, int numHigh, float spacing, sf::Vector2f centralPosition, sf::Vector2f init_velocity, float ballMass, float ballRadius)
{
if(spacing < 2.5*ballRadius)
spacing = 2.5*ballRadius;
//if(!)
{
for(int i=-numWide/2; i<=numWide/2; ++i)
for(int j=-numHigh/2; j<=numHigh/2; ++j)
{
//sf::Vector2f offsetPosition = {i*spacing,j*spacing};
//spawnNewBall(centralPosition + offsetPosition, init_velocity, ballRadius, pow(-1,i)*ballMass);
//std::cout << i << " " << j << "\n";
}
}
}
void BallUniverse::createSPSys(sf::Vector2f centralPosition, sf::Vector2f initVelocity)
{
//spawnNewBall(centralPosition, initVelocity, 50, 1000);
//spawnNewBall(centralPosition+sf::Vector2f{0.0f, 100.0f}, initVelocity+sf::Vector2f{3.0f, 0.0f}, 10, 1);
//spawnNewBall(centralPosition+sf::Vector2f{0.0f, -200.0f}, initVelocity+sf::Vector2f{-2.0f, 0.0f}, 10, 1);
/*spawnNewBall({worldSizeX/2.0f, worldSizeY/2.0f}, {0,0}, 50, 1000);
spawnNewBall({worldSizeX/2.0f + 200.0f, worldSizeY/2}, {5,0}, 50, 1000);
spawnNewBall({worldSizeX/2 - 201, worldSizeY/2}, {-5,0}, 50, 1000);*/
//spawnStaticRect(centralPosition, 300.0f*initVelocity.x, 300.0f*initVelocity.y);
//spawnNewRect(centralPosition, 50.0f, 50.0f, initVelocity, 5.0f);
//std::cout << "Size: " << staticObjects.size() << "\n";
////staticCollArray.printMatrix();
//std::cout << "\n";
}
sf::Vector2i BallUniverse::getWorldSize()
{
sf::Vector2i wSize = {worldSizeX,worldSizeY};
return wSize;
}
void BallUniverse::incSimStep(float delta)
{
// if(delta>0)
// dt+=delta;
}
void BallUniverse::decSimStep(float delta)
{
// if(delta>0 && dt>delta)
// dt-=delta;
}
void BallUniverse::setSimStep(float delta)
{
// if(delta > 0)
// dt = delta;
}
void BallUniverse::toggleSimPause()
{
if(isPaused)
isPaused = false;
//setSimStep(previousDt);
else
isPaused = true;
//setSimStep(0);
}
void BallUniverse::drawBalls(sf::RenderWindow &windowRef)
{
//if(enable_trajectories)
drawSampledPositions(windowRef);
/*for(auto iter = dynamicObjects.begin(); iter != dynamicObjects.end(); ++iter)
(**iter).draw(windowRef);
for(auto iter = staticObjects.begin(); iter != staticObjects.end(); ++iter)
(**iter).draw(windowRef);*/
}
void BallUniverse::toggleCollisions()
{
if(enable_collisions)
enable_collisions = false;
else
enable_collisions = true;
}
void BallUniverse::toggleForces()
{
if(enable_forces)
enable_forces = false;
else
enable_forces = true;
}
void BallUniverse::toggleUGravity()
{
if(universalGravity)
universalGravity = false;
else
universalGravity = true;
}
void BallUniverse::toggleRK4()
{
int current = static_cast<int>(intEnum);
int size = static_cast<int>(Integrators::LAST);
current = (current+1)%size;
//std::cout << "Int Type: " << current << "\n";
intEnum = static_cast<Integrators>(current);
//temp=temp+1;
}
void BallUniverse::changeBallColour()
{
/*for(Ball &ball : dynamicObjects)
{
if(ball.sf::CircleShape::getPosition().x > worldSizeX/2)
ball.setFillColor(sf::Color::Red);
else
ball.setFillColor(sf::Color::Green);
}*/
}
void BallUniverse::clearSimulation()
{
dynamicObjects.clear();
staticObjects.clear();
//colliderArray.clearMatrix();
//staticCollArray.clearMatrix();
numOfBalls = 0;
clearArbiters();
jointManager.clear();
}
const int& BallUniverse::getWorldSizeX()
{
return worldSizeX;
}
std::string BallUniverse::getNumOfBalls()
{
return std::to_string(numOfBalls);
}
std::string BallUniverse::getCollisionsEnabled()
{
return std::to_string(enable_collisions);
}
std::string BallUniverse::getUGravityEnabled()
{
return std::to_string(universalGravity);
}
std::string BallUniverse::getForcesEnabled()
{
return std::to_string(enable_forces);
}
std::string BallUniverse::getTotalKE()
{
return std::to_string(totalKE);
}
std::string BallUniverse::getTotalEnergy()
{
return std::to_string(totalEnergy);
}
std::string BallUniverse::getTotalMomentum()
{
return to_string(totalMomentum);
}
sf::Vector2f BallUniverse::getObjPosition(unsigned int i)
{
if(dynamicObjects.size()>i && i>=0)
return dynamicObjects.at(i)->getPosition();
return sf::Vector2f{std::numeric_limits<float>::quiet_NaN(),
std::numeric_limits<float>::quiet_NaN()};
}
std::string BallUniverse::getTimeStep()
{
return std::to_string(0.0f);
// return std::to_string(dt);
}
std::string BallUniverse::getUseRK4()
{
return to_string(intEnum);
}
std::string BallUniverse::getBallSpeed(unsigned int index)
{
if(index < dynamicObjects.size() && index >= 0)
return std::to_string(dynamicObjects.at(index)->getSpeed());
return "dynamicObjects index out of range";
}
int BallUniverse::getNumTimesColld(unsigned int index)
{
if(index < dynamicObjects.size() && index >= 0)
return dynamicObjects.at(index)->getNumCollTimes();
return -1;
}
void BallUniverse::toggleTrajectories()
{
if(enable_trajectories)
{
enable_trajectories = false;
for(int i=0; (unsigned)i<dynamicObjects.size(); ++i)
dynamicObjects.at(i)->setSamplePrevPosBool(false);
}
else
{
enable_trajectories = true;
for(int i=0; (unsigned)i<dynamicObjects.size(); ++i)
dynamicObjects.at(i)->setSamplePrevPosBool(true);
}
}
void BallUniverse::togglePlayerTraj()
{
}
void BallUniverse::splitBalls(int ballIndex, float relDirection, float speed)
{
/*ballIndex = currentPlayer;
float initialRadius = dynamicObjects.at(ballIndex).getRadius();
std::cout << initialRadius << "\n";
float r2limit = 5;
float r2factor = 0.15;
float r2 = r2factor*initialRadius;
if(r2 < r2limit)
r2 = r2limit;
if(r2 < initialRadius)
{
float r1 = pow(initialRadius*initialRadius - r2*r2, 0.5);
if(r1 > r2)
{
sf::Vector2f initialVelocity = dynamicObjects.at(ballIndex).getVelocity();
sf::Vector2f v2;
if(initialVelocity.x < 1e-10 && initialVelocity.y < 1e-10)
v2 = speed*sfVectorMath::rotate({0,-1}, relDirection);
else
v2 = sfVectorMath::rotate(speed*sfVectorMath::norm(initialVelocity), relDirection);
sf::Vector2f v1 = - (r2/r1)*(r2/r1)*v2;
dynamicObjects.at(ballIndex).setRadius(r1);
dynamicObjects.at(ballIndex).setOrigin({r1,r1});
dynamicObjects.at(ballIndex).setVelocity(v1 + initialVelocity);
sf::Vector2f pos1 = sfVectorMath::rotate(1.01f*initialRadius*sfVectorMath::norm(initialVelocity), relDirection) +
dynamicObjects.at(ballIndex).sf::CircleShape::getPosition();
spawnNewBall(pos1, v2 + initialVelocity, r2, r2);
}
}*/
}
void BallUniverse::applyUGravity()
{
for(auto iter = dynamicObjects.begin(); iter != dynamicObjects.end(); ++iter)
{
//(*iter)->applyExternalImpulse(uGravityDir, dt);
}
}
void BallUniverse::createExplosion(sf::Vector2f position,
float radiusOfEffect,
float strength)
{
ObjectProperties tempProps;
tempProps._position = position;
tempProps._vertices = {sf::Vertex{{0.0f, 0.0f}}};
for(int i=0; i<(int)dynamicObjects.size(); ++i)
{
Polygon tempObject(tempProps);
tempObject.setMomentInertia(1.0f);
Edge GJKResult = GJK::getClosestPoints(dynamicObjects[i], &tempObject);
float distanceSq = Math::square(GJKResult.v2 - GJKResult.v1);
float minDistance = 0.0f;
if(strength < 0.0f)
{
minDistance = 1.0f;
}
/*if(distanceSq < radiusOfEffect*radiusOfEffect && distanceSq > minDistance)
{
float factor = std::min(strength, strength/sqrtf(distanceSq));
sf::Vector2f sepVector = factor*(GJKResult.v2 - GJKResult.v1);
tempObject.setVelocity(dynamicObjects[i]->getVelocity() - sepVector);
Arbiter tempArb{dynamicObjects[i], &tempObject};
Contact tempContact;
tempContact.normal = Math::norm(GJKResult.v1 - GJKResult.v2);
tempContact.position = GJKResult.v1;
tempContact.rA = tempContact.position - dynamicObjects[i]->getPosition();
tempContact.rB = {0.0f, 0.0f};
tempArb.contacts.push_back(tempContact);
tempArb.PreStep(1.0f/dt);
tempArb.ApplyImpulse();
dynamicObjects[i]->addSolvedVelocity(factor*tempContact.normal,
factor*tempContact.normal);
}*/
}
}
void BallUniverse::newJoint(int index1, sf::Vector2f const & position)
{
if(index1 < (int)dynamicObjects.size())
{
Joint* newJoint = new SocketJointSingle({dynamicObjects[index1]},
[position, this](){return position + 500.0f * sf::Vector2f{sinf(0.03f * currentTime), 0.0f};}
);
}
}
void BallUniverse::newObserver(Observer* obs)
{
universeSub.addObserver(obs);
}
void BallUniverse::onNotify(Component& entity, Event event, Container* data)
{
switch(event.type)
{
case(EventType::New_PhysicsObj):
{
PhysicsObject* obj = (PhysicsObject*)&entity;
if(!obj->getIsStatic())
{
dynamicObjects.push_back(obj);
numOfBalls++;
}
else
{
staticObjects.push_back(obj);
}
break;
}
case(EventType::Delete_PhysicsObj):
{
PhysicsObject* obj = (PhysicsObject*)&entity;
for(int i=0; i<(int)dynamicObjects.size(); ++i)
{
if(obj == dynamicObjects[i])
{
dynamicObjects.erase(dynamicObjects.begin() + i);
numOfBalls--;
clearArbiters();
}
}
for(int i=0; i<(int)staticObjects.size(); ++i)
{
if(obj == staticObjects[i])
{
staticObjects.erase(staticObjects.begin() + i);
clearArbiters();
}
}
break;
}
default:
break;
}
}
void BallUniverse::addArbiter(ArbPair const & arbPair)
{
arbiters.insert(arbPair);
}
void BallUniverse::clearArbiters()
{
for(auto it = arbiters.begin(); it != arbiters.end(); ++it)
{
it->first.obj1->clearContactData();
it->first.obj2->clearContactData();
}
arbiters.clear();
}
void BallUniverse::eraseArbiter(ArbiterKey const & key)
{
key.obj1->removeContactData(key.obj2);
key.obj2->removeContactData(key.obj1);
arbiters.erase(key);
}
BallUniverse::BallUniverse(int _worldSizeX,
int _worldSizeY,
bool _force,
bool _collision) :
worldSizeX{_worldSizeX},
worldSizeY{_worldSizeY},
enable_forces{_force},
enable_collisions{_collision}
{
PhysicsObject::engineNotify.addObserver(this);
}
BallUniverse::~BallUniverse()
{
PhysicsObject::engineNotify.removeObserver(this);
}
|
leaderli/li-runner-flow
|
node_modules/@antv/x6/lib/shape/standard/rect-headered.js
|
<reponame>leaderli/li-runner-flow<filename>node_modules/@antv/x6/lib/shape/standard/rect-headered.js
"use strict";
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HeaderedRect = void 0;
var node_1 = require("../../model/node");
var base_1 = require("../base");
exports.HeaderedRect = node_1.Node.define({
shape: 'rect-headered',
markup: [
{
tagName: 'rect',
selector: 'body',
},
{
tagName: 'rect',
selector: 'header',
},
{
tagName: 'text',
selector: 'headerText',
},
{
tagName: 'text',
selector: 'bodyText',
},
],
attrs: {
body: __assign(__assign({}, base_1.Base.bodyAttr), { refWidth: '100%', refHeight: '100%' }),
header: __assign(__assign({}, base_1.Base.bodyAttr), { refWidth: '100%', height: 30, stroke: '#000000' }),
headerText: __assign(__assign({}, base_1.Base.labelAttr), { refX: '50%', refY: 15, fontSize: 16 }),
bodyText: __assign(__assign({}, base_1.Base.labelAttr), { refY2: 15 }),
},
});
//# sourceMappingURL=rect-headered.js.map
|
VincentWei/mdolphin-core
|
Source/WebCore/platform/graphics/mg/GraphicsContextCairo.h
|
/*
* Copyright (C) 2003, 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
* Copyright (C) 2008-2009 Torch Mobile, Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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.
*/
#ifndef GraphicsContextCairo_h
#define GraphicsContextCairo_h
#include "GraphicsContext.h"
#include <cairo.h>
namespace WebCore {
class AffineTransform;
class GraphicsContextPlatformPrivateCairo;
class ImageBuffer;
class KURL;
class Path;
class ContextShadow;
class PlatformContextCairo;
class GraphicsContextCairo : public GraphicsContext{
public:
GraphicsContextCairo(cairo_t* cr);
GraphicsContextCairo(PlatformContextCairo*);
~GraphicsContextCairo();
void platformInit(PlatformContextCairo* platformContext);
void platformDestroy();
bool isCairoCanvas() {return true;}
static void calculateShadowBufferDimensions(IntSize& shadowBufferSize, FloatRect& shadowRect, float& kernelSize, const FloatRect& sourceRect, const IntSize& shadowSize, int shadowBlur);
AffineTransform getCTM() const;
HDC* platformContext() const;
void savePlatformState();
void restorePlatformState();
void drawRect(const IntRect& rect);
void drawLine(const IntPoint& point1, const IntPoint& point2);
void drawEllipse(const IntRect& rect);
void strokeArc(const IntRect& rect, int startAngle, int angleSpan);
void drawConvexPolygon(size_t npoints, const FloatPoint* points, bool shouldAntialias);
void fillPath(const Path&);
void strokePath(const Path&);
void fillRect(const FloatRect& rect);
void fillRect(const FloatRect& rect, const Color& color, ColorSpace colorSpace);
void clip(const FloatRect& rect);
void clipPath(const Path&, WindRule);
void drawFocusRing(const Path& paths, int width, int offset, const Color& color);
void drawFocusRing(const Vector<IntRect>& rects, int width, int /* offset */, const Color& color);
void drawLineForText(const FloatPoint& origin, float width, bool printing);
void drawLineForMisspellingOrBadGrammar(const IntPoint& origin, int width, bool grammar);
FloatRect roundToDevicePixels(const FloatRect& frect, RoundingMode);
void translate(float x, float y);
IntPoint origin();
void setPlatformFillColor(const Color& col, ColorSpace colorSpace);
void setPlatformStrokeColor(const Color& col, ColorSpace colorSpace);
void setPlatformStrokeThickness(float strokeThickness);
void setPlatformStrokeStyle(StrokeStyle strokeStyle);
void setURLForRect(const KURL& link, const IntRect& destRect);
void concatCTM(const AffineTransform& transform);
void addInnerRoundedRectClip(const IntRect& rect, int thickness);
void clipToImageBuffer(const FloatRect& rect, const ImageBuffer* imageBuffer);
void setPlatformShadow(const FloatSize& size, float, const Color&, ColorSpace);
void createPlatformShadow(PassOwnPtr<ImageBuffer> buffer, const Color& shadowColor, const FloatRect& shadowRect, float kernelSize);
void clearPlatformShadow();
void beginTransparencyLayer(float opacity);
void endTransparencyLayer();
void clearRect(const FloatRect& rect);
void strokeRect(const FloatRect& rect, float width);
void setLineCap(LineCap lineCap);
void setLineDash(const DashArray& dashes, float dashOffset);
void setLineJoin(LineJoin lineJoin);
void setMiterLimit(float miter);
void setAlpha(float alpha);
float getAlpha();
void setCompositeOperation(CompositeOperator op);
void beginPath();
void addPath(const Path& path);
void clip(const Path& path);
void canvasClip(const Path& path);
void clipOut(const Path& path);
void rotate(float radians);
void scale(const FloatSize& size);
void clipOut(const IntRect& r);
void clipOutEllipseInRect(const IntRect& r);
void fillRoundedRect(const IntRect& r, const IntSize& topLeft, const IntSize& topRight, const IntSize& bottomLeft, const IntSize& bottomRight, const Color& color, ColorSpace colorSpace);
void setPlatformShouldAntialias(bool enable);
void setImageInterpolationQuality(InterpolationQuality);
InterpolationQuality imageInterpolationQuality() const;
//added for upgrade
ContextShadow* contextShadow();
void clipConvexPolygon(size_t numPoints, const FloatPoint*, bool antialias = true);
void drawLineForTextChecking(const FloatPoint&, float width, TextCheckingLineStyle);
void setCTM(const AffineTransform&);
void setPlatformCompositeOperation(CompositeOperator);
private:
GraphicsContextPlatformPrivateCairo *m_pdata;
};
} // namespace WebCore
#endif // GraphicsContextCairo_h
|
jjhesk/KickAssSlidingMenu
|
slideOutMenu/menux/src/main/java/mxh/kickassmenu/layoutdesigns/app/SlidingAppCompactActivity.java
|
package mxh.kickassmenu.layoutdesigns.app;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.IdRes;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import mxh.kickassmenu.R;
import mxh.kickassmenu.Util.xmlViews.ControlableFrame;
import mxh.kickassmenu.gestured.SlidingMenu;
import mxh.kickassmenu.gestured.app.SlidingAppCompactActivityBase;
import mxh.kickassmenu.menucontent.MenuBuildHelper;
import mxh.kickassmenu.menucontent.internalChangeInFragment;
import mxh.kickassmenu.menucontent.materialMenuConstructorFragmentBase;
/**
* Created by hesk on 22/6/15.
*/
public abstract class SlidingAppCompactActivity<Frag> extends SlidingAppCompactActivityBase implements internalChangeInFragment<Frag> {
/**
* the control frame to display the blocked content or not.
*/
protected ControlableFrame content_frame;
protected Frag currentFragmentNow, rightMenuFragment;
/**
* get the first menu fragment and this is opened for free developments
*
* @return the fragment object
*/
protected abstract Frag getFirstMenuFragment();
/**
* this is the setting point for making all menu slider behavior, please also see from the previous setting library page developed by Jeremyfeinstein @link https://github.com/jfeinstein10/SlidingMenu/blob/master/example/src/com/jeremyfeinstein/slidingmenu/example/BaseActivity.java
*
* @param sm the initialized sliding menu object for reconfigurations
*/
protected abstract void customizeSlideMenuEdge(final SlidingMenu sm);
/**
* setting the default main activity layout ID and this is normally had presented in the library and no need change unless there is a customization need for different layout ID
*
* @return resource id
*/
protected int getDefaultMainActivityLayoutId() {
return BODY_LAYOUT.actionbar.getResID();
}
/**
* @return when @link{getDefaultMainActivityLayoutId} is using user specified layout and such layout contains custom action bar or custom action tool bar then this function must return TRUE to enable the configuration of the tool bar
*/
protected boolean forceConfigureToolBar() {
return false;
}
/**
* setting the first initial fragment at the beginning
*
* @return generic type fragment
*/
protected abstract Frag getInitFragment();
/**
*
* the location to setup and configure the toolbar widget under AppCompat V7
*
* @param mxToolBarV7 Toolbar object
*/
protected void configToolBar(final Toolbar mxToolBarV7) {
mxToolBarV7.setNavigationIcon(R.drawable.ic_action_menu_drawer);
mxToolBarV7.setTitle(getTitle());
}
/**
* when the fragment is changed now and it will notify the function for user specific operations
*
* @param new_fragment_change_now the generic fragment type
*/
protected void notifyOnBodyFragmentChange(Frag new_fragment_change_now) {
}
/**
* to produce the menu by layout inflation
*
* @return int with resource id
*/
protected int getRmenu() {
return -1;
}
private Frag getOldFragment(Frag fragment, @IdRes int frame_location) throws Exception {
if (fragment instanceof Fragment) {
return (Frag) this.getFragmentManager().findFragmentById(frame_location);
} else if (fragment instanceof android.support.v4.app.Fragment) {
return (Frag) this.getSupportFragmentManager().findFragmentById(frame_location);
} else {
throw new Exception("The input fragment is not a valid Fragment. ");
}
}
private void setRightSideFragment(Frag fragment, @Nullable Bundle savestate) {
setBehindContentView(R.layout.menu_frame);
try {
if (savestate != null) {
setPrimaryMenuFragment(fragment, getOldFragment(fragment, R.id.menu_frame));
} else {
setPrimaryMenuFragment(fragment, null);
}
} catch (RuntimeException e) {
Log.d("RIGHTSIDE", e.getMessage());
} catch (Exception e) {
Log.d("RIGHTSIDE", e.getMessage());
}
}
protected void setUnblock() {
if (content_frame != null) {
content_frame.noBlock();
}
}
protected void setBlockEnableWithColor(@ColorRes int mdrawble) {
if (content_frame != null) {
content_frame.setDimColor(mdrawble);
}
}
protected void setBlockEnableWithDrawable(@DrawableRes int mdrawble) {
if (content_frame != null) {
content_frame.setDimDrawble(mdrawble);
}
}
private void initMainContentFragment(Frag fragment, Bundle savestate) {
setContentView(getDefaultMainActivityLayoutId());
initToolBar(getDefaultMainActivityLayoutId());
try {
content_frame = (ControlableFrame) findViewById(R.id.aslib_main_frame_body);
} catch (Exception e) {
}
if (savestate == null) {
setFragment(fragment, getTitle().toString(), null, false);
} else {
final Frag oldfragment = (Frag) this.getFragmentManager().findFragmentById(R.id.aslib_main_frame_body);
setFragment(fragment, getTitle().toString(), oldfragment);
}
}
private void initToolBar(final @LayoutRes int resId) {
final Toolbar widgetToolBar = (Toolbar) findViewById(R.id.aslib_toolbar);
try {
if (BODY_LAYOUT.isToolbarOn(resId) || forceConfigureToolBar()) {
if (widgetToolBar != null) {
configToolBar(widgetToolBar);
setSupportActionBar(widgetToolBar);
}
}
} catch (Exception e) {
if (forceConfigureToolBar() && widgetToolBar != null) {
//this will be using the custom layouts
configToolBar(widgetToolBar);
}
}
}
public void setinternalChangeNoToggle(Frag section, String title) {
setinternalChange(section, title, currentFragmentNow, false);
}
@Override
public void setinternalChange(Frag section, String title) {
setFragment(section, title);
}
@Override
public void setinternalChange(Frag section, String title, Frag previousFragment, boolean closedrawer) {
setFragment(section, title, previousFragment, closedrawer);
}
@Override
public void setinternalChange(Frag section, String title, Frag previousFragment) {
setFragment(section, title, previousFragment);
}
public void setFragment(Frag fragment, String title, Frag old_fragment) {
setFragment(fragment, title, old_fragment, true);
}
public void setFragment(Frag fragment, String title) {
setFragment(fragment, title, null, true);
}
/**
* require android-support-v4 import and the regular android fragment
*
* @param fragment the unknown typed fragment
* @param oldFragment the previous fragment
*/
private void setPrimaryMenuFragment(Frag fragment, Frag oldFragment) throws RuntimeException, Exception {
rightMenuFragment = fragment;
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// before honeycomb there is not android.app.Fragment
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (oldFragment != null && oldFragment != fragment)
ft.remove((android.support.v4.app.Fragment) oldFragment);
ft.replace(R.id.menu_frame, (android.support.v4.app.Fragment) fragment).commit();
} else if (fragment instanceof Fragment) {
if (oldFragment instanceof android.support.v4.app.Fragment)
throw new RuntimeException("You should use only one type of Fragment");
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (oldFragment != null && fragment != oldFragment)
ft.remove((Fragment) oldFragment);
ft.replace(R.id.menu_frame, (Fragment) fragment).commit();
} else if (fragment instanceof android.support.v4.app.Fragment) {
if (oldFragment instanceof Fragment)
throw new RuntimeException("You should use only one type of Fragment");
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (oldFragment != null && oldFragment != fragment)
ft.remove((android.support.v4.app.Fragment) oldFragment);
ft.replace(R.id.menu_frame, (android.support.v4.app.Fragment) fragment).commit();
} else
throw new RuntimeException("Fragment must be android.app.Fragment or android.support.v4.app.Fragment");
}
/**
* require android-support-v4 import and the regular android fragment
*
* @param fragment the unknown typed fragment
* @param title the string in title
* @param oldFragment the previous fragment
* @param closeDrawer if it needs to close the drawer after the new fragment has been rendered
*/
public void setFragment(Frag fragment, String title, Frag oldFragment, boolean closeDrawer) {
currentFragmentNow = fragment;
setTitle(title);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// before honeycomb there is not android.app.Fragment
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (oldFragment != null && oldFragment != fragment)
ft.remove((android.support.v4.app.Fragment) oldFragment);
ft.replace(R.id.aslib_main_frame_body, (android.support.v4.app.Fragment) fragment).commit();
} else if (fragment instanceof Fragment) {
if (oldFragment instanceof android.support.v4.app.Fragment)
throw new RuntimeException("You should use only one type of Fragment");
FragmentTransaction ft = getFragmentManager().beginTransaction();
if (oldFragment != null && fragment != oldFragment)
ft.remove((Fragment) oldFragment);
ft.replace(R.id.aslib_main_frame_body, (Fragment) fragment).commit();
} else if (fragment instanceof android.support.v4.app.Fragment) {
if (oldFragment instanceof Fragment)
throw new RuntimeException("You should use only one type of Fragment");
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (oldFragment != null && oldFragment != fragment)
ft.remove((android.support.v4.app.Fragment) oldFragment);
ft.replace(R.id.aslib_main_frame_body, (android.support.v4.app.Fragment) fragment).commit();
} else
throw new RuntimeException("Fragment must be android.app.Fragment or android.support.v4.app.Fragment");
if (closeDrawer)
getSlidingMenu().toggle(true);
notifyOnBodyFragmentChange(currentFragmentNow);
}
/* public void setRightSideFragment(F fragment, Bundle savedstate) {
currentFragmentNow = fragment;
// set the Behind View
setBehindContentView(R.layout.menu_frame);
if (savedstate == null) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
// before honeycomb there is not android.app.Fragment
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.menu_frame, (android.support.v4.app.Fragment) fragment).commit();
} else if (fragment instanceof android.app.Fragment) {
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.menu_frame, (android.app.Fragment) fragment).commit();
} else if (fragment instanceof android.support.v4.app.Fragment) {
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.menu_frame, (android.support.v4.app.Fragment) fragment).commit();
} else
throw new RuntimeException("Fragment must be android.app.Fragment or android.support.v4.app.Fragment");
*/
/*
} else {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
} else if (fragment instanceof android.app.Fragment) {
mFrag = getFragmentManager().findFragmentById(R.id.menu_frame);
} else if (fragment instanceof android.support.v4.app.Fragment) {
mFrag = getSupportFragmentManager().findFragmentById(R.id.menu_frame);
} else
throw new RuntimeException("Fragment must be android.app.Fragment or android.support.v4.app.Fragment");
}
}*/
@Override
public void onCreate(Bundle sved) {
super.onCreate(sved);
setRightSideFragment(getFirstMenuFragment(), sved);
customizeSlideMenuEdge(getSlidingMenu());
initMainContentFragment(getInitFragment(), sved);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
toggle();
return true;
// case R.id.github:
// Util.goToGitHub(this);
// return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (getRmenu() > -1) {
getMenuInflater().inflate(getRmenu(), menu);
}
return true;
}
/**
* there are some presets for the main layout configurations
* - noactionbar : there is consist of layout resource IDs of +id(main_frame_body)
* - actionbar : there is consist of layout resource IDs of +id(main_frame_body) and +id(mxtoolbar)
* - overlayactionbar : there is consist of layout resource IDs of +id(main_frame_body) and +id(mxtoolbar)
*/
public enum BODY_LAYOUT {
overlayactionbar(R.layout.template_nomoframedactionba, true),
noactionbar(R.layout.template_noactionbar, false),
actionbar(R.layout.template_nonoactionbarframer, true),
singlepullslide(R.layout.template_custom_slideout_single_article, true),
singelsimple(R.layout.template_adjus_simple, true);
private int id;
private boolean mhastoolbar;
BODY_LAYOUT(@LayoutRes int layoutId, boolean hasToolBar) {
id = layoutId;
mhastoolbar = hasToolBar;
}
public boolean hasToolBarInside() {
return mhastoolbar;
}
public int getResID() {
return id;
}
public static boolean compareSymbol(final int Ordinal, final BODY_LAYOUT symbol) {
return symbol.ordinal() == Ordinal;
}
public static BODY_LAYOUT fromLayoutId(final @LayoutRes int id) throws Exception {
final int e = BODY_LAYOUT.values().length;
for (int i = 0; i < e; i++) {
final BODY_LAYOUT h = BODY_LAYOUT.values()[i];
if (h.getResID() == id) {
return h;
}
}
throw new Exception("not found from this layout Id");
}
public static boolean isToolbarOn(final @LayoutRes int id) throws Exception {
return BODY_LAYOUT.fromLayoutId(id).hasToolBarInside();
}
}
@Override
public void onBackPressed() {
if (rightMenuFragment instanceof materialMenuConstructorFragmentBase) {
final MenuBuildHelper helper = ((materialMenuConstructorFragmentBase) rightMenuFragment).NavBuilder();
switch (helper.getBackPattern()) {
default:
case materialMenuConstructorFragmentBase.BACKPATTERN_BACK_ANYWHERE:
super.onBackPressed();
break;
//TODO: need to use these switches below
/* case materialMenuConstructorFragmentBase.BACKPATTERN_BACK_TO_START_INDEX:
MaterialSection section = (MaterialSection) helper.getMENU().getItems().get(helper.getMENU().getStartIndex());
if (currentSection == section)
super.onBackPressed();
else {
//section.select();
onClick(section, section.getView());
}
break;
case materialMenuConstructorFragmentBase.BACKPATTERN_CUSTOM:
MaterialSection backedSection = backToSection(getCurrentSection());
if (currentSection == backedSection) {
if (backedSection.getTarget() != MaterialSection.TARGET_FRAGMENT) {
super.onBackPressed();
} else {
if (currentFragmentNow == backedSection.getTargetFragment()) {
super.onBackPressed();
} else {
}
}
} else {
if (backedSection.getTarget() != MaterialSection.TARGET_FRAGMENT) {
throw new RuntimeException("The restored section must have a fragment as target");
}
onClick(backedSection, backedSection.getView());
}
break;
case materialMenuConstructorFragmentBase.BACKPATTERN_LAST_SECTION:
if (sectionLastBackPatternList.size() == 0) {
super.onBackPressed();
}
while (sectionLastBackPatternList.size() > 0) {
// get section position
int posSection = currentMenu.getSectionPosition(sectionLastBackPatternList.get(sectionLastBackPatternList.size() - 1));
// remove last section
sectionLastBackPatternList.remove(sectionLastBackPatternList.size() - 1);
// if section found in the menu, load the section
if (posSection != -1) {
reloadMenu(posSection, false);
break;
}
}
break;*/
}
}
}
}
|
vuonghv/brs
|
apps/requestbooks/models.py
|
from django.db import models
from apps.users.models import UserProfile
from apps.categories.models import Category
class RequestedBook(models.Model):
WAITING = 1
CANCELED = 2
APPROVED = 3
DISAPPROVED = 4
STATUS_CHOICES = (
(WAITING, 'Waiting'),
(CANCELED, 'Canceled'),
(APPROVED, 'Approved'),
(DISAPPROVED, 'Disapproved'),
)
title = models.CharField(max_length=255)
description = models.TextField(blank=True, default='')
user_profile = models.ForeignKey(UserProfile)
requested_time = models.DateTimeField(auto_now_add=True)
categories = models.ManyToManyField(Category, related_name='requests')
status = models.IntegerField(choices=STATUS_CHOICES, default=WAITING)
class Meta:
db_table = 'request'
def __str__(self):
return self.title
def is_canceled(self):
return self.status == RequestedBook.CANCELED
def is_waiting(self):
return self.status == RequestedBook.WAITING
|
Yucukof/edu-antlr4-toy-parser-to-nbc
|
src/main/java/be/unamur/info/b314/compiler/nbc/instructions/InstructionControlJMP.java
|
<filename>src/main/java/be/unamur/info/b314/compiler/nbc/instructions/InstructionControlJMP.java
package be.unamur.info.b314.compiler.nbc.instructions;
import be.unamur.info.b314.compiler.nbc.keywords.ControlFlow;
import be.unamur.info.b314.compiler.nbc.keywords.Keyword;
import be.unamur.info.b314.compiler.nbc.program.Label;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.SuperBuilder;
/**
* @author <NAME>
*/
@Data
@SuperBuilder
@EqualsAndHashCode(callSuper = true)
public class InstructionControlJMP extends InstructionControl {
private final Keyword keyword = ControlFlow.JMP;
public static InstructionControlJMP to(Label label) {
return InstructionControlJMP.builder()
.destination(label)
.build();
}
@Override
public String toString() {
return keyword.getToken() + " " + getDestination().getName();
}
@Override
public boolean isValid() {
return getDestination() != null && getDestination().isValid();
}
}
|
azadmanesh/jt-tracer
|
core/src/main/java/org/jruby/ir/passes/AddCallProtocolInstructions.java
|
package org.jruby.ir.passes;
import org.jruby.ir.*;
import org.jruby.ir.instructions.*;
import org.jruby.runtime.Signature;
import org.jruby.ir.operands.ImmutableLiteral;
import org.jruby.ir.operands.Label;
import org.jruby.ir.operands.Operand;
import org.jruby.ir.operands.Self;
import org.jruby.ir.operands.TemporaryVariable;
import org.jruby.ir.operands.Variable;
import org.jruby.ir.representations.BasicBlock;
import org.jruby.ir.representations.CFG;
import java.util.ListIterator;
public class AddCallProtocolInstructions extends CompilerPass {
@Override
public String getLabel() {
return "Add Call Protocol Instructions (push/pop of dyn-scope, frame, impl-class values)";
}
private boolean explicitCallProtocolSupported(IRScope scope) {
return scope instanceof IRMethod
|| (scope instanceof IRClosure && !(scope instanceof IREvalScript))
|| (scope instanceof IRModuleBody && !(scope instanceof IRMetaClassBody));
}
/*
* Since the return is now going to be preceded by a pops of bindings/frames,
* the return value should continue to be valid after those pops.
* If not, introduce a copy into a tmp-var before the pops and use the tmp-var
* to return the right value.
*/
private void fixReturn(IRScope scope, ReturnBase i, ListIterator<Instr> instrs) {
Operand retVal = i.getReturnValue();
if (!(retVal instanceof ImmutableLiteral || retVal instanceof TemporaryVariable)) {
TemporaryVariable tmp = scope.createTemporaryVariable();
CopyInstr copy = new CopyInstr(tmp, retVal);
i.updateReturnValue(tmp);
instrs.previous();
instrs.add(copy);
instrs.next();
}
}
private void popSavedState(IRScope scope, boolean isGEB, boolean requireBinding, boolean requireFrame, Variable savedViz, Variable savedFrame, ListIterator<Instr> instrs) {
if (scope instanceof IRClosure && isGEB) {
// Add before RethrowSavedExcInLambdaInstr
instrs.previous();
}
if (requireBinding) instrs.add(new PopBindingInstr());
if (scope instanceof IRClosure) {
if (scope.needsFrame()) {
instrs.add(new RestoreBindingVisibilityInstr(savedViz));
instrs.add(new PopBlockFrameInstr(savedFrame));
}
} else {
if (requireFrame) instrs.add(new PopMethodFrameInstr());
}
}
@Override
public Object execute(IRScope scope, Object... data) {
// IRScriptBody do not get explicit call protocol instructions right now.
// They dont push/pop a frame and do other special things like run begin/end blocks.
// So, for now, they go through the runtime stub in IRScriptBody.
//
// Add explicit frame and binding push/pop instrs ONLY for methods -- we cannot handle this in closures and evals yet
// If the scope uses $_ or $~ family of vars, has local load/stores, or if its binding has escaped, we have
// to allocate a dynamic scope for it and add binding push/pop instructions.
if (!explicitCallProtocolSupported(scope)) return null;
CFG cfg = scope.getCFG();
// For now, we always require frame for closures
boolean requireFrame = scope.needsFrame();
boolean requireBinding = scope.needsBinding();
if (scope instanceof IRClosure || requireBinding || requireFrame) {
BasicBlock entryBB = cfg.getEntryBB();
Variable savedViz = null, savedFrame = null;
if (scope instanceof IRClosure) {
savedViz = scope.createTemporaryVariable();
savedFrame = scope.createTemporaryVariable();
// FIXME: Hacky...need these to come before other stuff in entryBB so we insert instead of add
int insertIndex = 0;
if (scope.needsFrame()) {
entryBB.insertInstr(insertIndex++, new SaveBindingVisibilityInstr(savedViz));
entryBB.insertInstr(insertIndex++, new PushBlockFrameInstr(savedFrame, scope.getName()));
}
// NOTE: Order of these next two is important, since UBESI resets state PBBI needs.
if (requireBinding) {
entryBB.insertInstr(insertIndex++, new PushBlockBindingInstr());
}
entryBB.insertInstr(insertIndex++, new UpdateBlockExecutionStateInstr(Self.SELF));
BasicBlock prologueBB = createPrologueBlock(cfg);
// Add the right kind of arg preparation instruction
Signature sig = ((IRClosure)scope).getSignature();
int arityValue = sig.arityValue();
if (arityValue == 0) {
prologueBB.addInstr(PrepareNoBlockArgsInstr.INSTANCE);
} else {
if (sig.isFixed()) {
if (arityValue == 1) {
prologueBB.addInstr(PrepareSingleBlockArgInstr.INSTANCE);
} else {
prologueBB.addInstr(PrepareFixedBlockArgsInstr.INSTANCE);
}
} else {
prologueBB.addInstr(PrepareBlockArgsInstr.INSTANCE);
}
}
} else {
if (requireFrame) entryBB.addInstr(new PushMethodFrameInstr(scope.getName()));
if (requireBinding) entryBB.addInstr(new PushMethodBindingInstr());
}
// SSS FIXME: We are doing this conservatively.
// Only scopes that have unrescued exceptions need a GEB.
//
// Allocate GEB if necessary for popping
BasicBlock geb = cfg.getGlobalEnsureBB();
boolean gebProcessed = false;
if (geb == null) {
Variable exc = scope.createTemporaryVariable();
geb = new BasicBlock(cfg, Label.getGlobalEnsureBlockLabel());
geb.addInstr(new ReceiveJRubyExceptionInstr(exc)); // JRuby Implementation exception handling
geb.addInstr(new ThrowExceptionInstr(exc));
cfg.addGlobalEnsureBB(geb);
}
// Pop on all scope-exit paths
for (BasicBlock bb: cfg.getBasicBlocks()) {
Instr i = null;
ListIterator<Instr> instrs = bb.getInstrs().listIterator();
while (instrs.hasNext()) {
i = instrs.next();
// Breaks & non-local returns in blocks will throw exceptions
// and pops for them will be handled in the GEB
if (!bb.isExitBB() && i instanceof ReturnInstr) {
if (requireBinding) fixReturn(scope, (ReturnInstr)i, instrs);
// Add before the break/return
i = instrs.previous();
popSavedState(scope, bb == geb, requireBinding, requireFrame, savedViz, savedFrame, instrs);
if (bb == geb) gebProcessed = true;
break;
}
}
if (bb.isExitBB() && !bb.isEmpty()) {
// Last instr could be a return -- so, move iterator one position back
if (i != null && i instanceof ReturnInstr) {
if (requireBinding) fixReturn(scope, (ReturnInstr)i, instrs);
instrs.previous();
}
popSavedState(scope, bb == geb, requireBinding, requireFrame, savedViz, savedFrame, instrs);
if (bb == geb) gebProcessed = true;
} else if (!gebProcessed && bb == geb) {
// Add before throw-exception-instr which would be the last instr
if (i != null) {
// Assumption: Last instr should always be a control-transfer instruction
assert i.getOperation().transfersControl(): "Last instruction of GEB in scope: " + scope + " is " + i + ", not a control-xfer instruction";
instrs.previous();
}
popSavedState(scope, true, requireBinding, requireFrame, savedViz, savedFrame, instrs);
}
}
}
/*
if (scope instanceof IRClosure) {
System.out.println(scope + " after acp: " + cfg.toStringInstrs());
}
*/
// This scope has an explicit call protocol flag now
scope.setExplicitCallProtocolFlag();
// LVA information is no longer valid after the pass
// FIXME: Grrr ... this seems broken to have to create a new object to invalidate
(new LiveVariableAnalysis()).invalidate(scope);
return null;
}
// We create an extra BB after entryBB for some ACP instructions which can possibly throw
// an exception. We want to keep them out of entryBB so we have a safe place to put
// stuff before exception without needing to worry about weird flow control.
// FIXME: We need to centralize prologue logic in case there's other places we want to use it
private BasicBlock createPrologueBlock(CFG cfg) {
BasicBlock entryBB = cfg.getEntryBB();
BasicBlock oldStart = cfg.getOutgoingDestinationOfType(entryBB, CFG.EdgeType.FALL_THROUGH);
BasicBlock prologueBB = new BasicBlock(cfg, cfg.getScope().getNewLabel());
cfg.removeEdge(entryBB, oldStart);
cfg.addBasicBlock(prologueBB);
cfg.addEdge(entryBB, prologueBB, CFG.EdgeType.FALL_THROUGH);
cfg.addEdge(prologueBB, oldStart, CFG.EdgeType.FALL_THROUGH);
// If there's already a GEB, make sure we have an edge to it and use it to rescue these instrs
if (cfg.getGlobalEnsureBB() != null) {
BasicBlock geb = cfg.getGlobalEnsureBB();
cfg.addEdge(prologueBB, geb, CFG.EdgeType.EXCEPTION);
cfg.setRescuerBB(prologueBB, geb);
}
return prologueBB;
}
@Override
public boolean invalidate(IRScope scope) {
// Cannot add call protocol instructions after we've added them once.
return false;
}
}
|
FreCap/sql
|
core/src/test/java/com/amazon/opendistroforelasticsearch/sql/expression/datetime/IntervalClauseTest.java
|
/*
* Copyright 2020 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the "license" file accompanying this file. This file 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.amazon.opendistroforelasticsearch.sql.expression.datetime;
import static com.amazon.opendistroforelasticsearch.sql.data.model.ExprValueUtils.intervalValue;
import static com.amazon.opendistroforelasticsearch.sql.data.model.ExprValueUtils.missingValue;
import static com.amazon.opendistroforelasticsearch.sql.data.model.ExprValueUtils.nullValue;
import static com.amazon.opendistroforelasticsearch.sql.data.type.ExprCoreType.INTEGER;
import static com.amazon.opendistroforelasticsearch.sql.data.type.ExprCoreType.INTERVAL;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.when;
import com.amazon.opendistroforelasticsearch.sql.data.model.ExprValue;
import com.amazon.opendistroforelasticsearch.sql.exception.ExpressionEvaluationException;
import com.amazon.opendistroforelasticsearch.sql.expression.DSL;
import com.amazon.opendistroforelasticsearch.sql.expression.Expression;
import com.amazon.opendistroforelasticsearch.sql.expression.ExpressionTestBase;
import com.amazon.opendistroforelasticsearch.sql.expression.FunctionExpression;
import com.amazon.opendistroforelasticsearch.sql.expression.env.Environment;
import java.time.Duration;
import java.time.Period;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
@ExtendWith(MockitoExtension.class)
public class IntervalClauseTest extends ExpressionTestBase {
@Mock
Environment<Expression, ExprValue> env;
@Mock
Expression nullRef;
@Mock
Expression missingRef;
@Test
public void microsecond() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("microsecond"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Duration.ofNanos(1000)), expr.valueOf(env));
}
@Test
public void second() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("second"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Duration.ofSeconds(1)), expr.valueOf(env));
}
@Test
public void minute() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("minute"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Duration.ofMinutes(1)), expr.valueOf(env));
}
@Test
public void hour() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("HOUR"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Duration.ofHours(1)), expr.valueOf(env));
}
@Test
public void day() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("day"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Duration.ofDays(1)), expr.valueOf(env));
}
@Test
public void week() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("week"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Period.ofWeeks(1)), expr.valueOf(env));
}
@Test
public void month() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("month"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Period.ofMonths(1)), expr.valueOf(env));
}
@Test
public void quarter() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("quarter"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Period.ofMonths(3)), expr.valueOf(env));
}
@Test
public void year() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("year"));
assertEquals(INTERVAL, expr.type());
assertEquals(intervalValue(Period.ofYears(1)), expr.valueOf(env));
}
@Test
public void unsupported_unit() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("year_month"));
assertThrows(ExpressionEvaluationException.class, () -> expr.valueOf(env),
"interval unit year_month is not supported");
}
@Test
public void to_string() {
FunctionExpression expr = dsl.interval(DSL.literal(1), DSL.literal("day"));
assertEquals("interval(1, \"day\")", expr.toString());
}
@Test
public void null_value() {
when(nullRef.type()).thenReturn(INTEGER);
when(nullRef.valueOf(env)).thenReturn(nullValue());
FunctionExpression expr = dsl.interval(nullRef, DSL.literal("day"));
assertEquals(INTERVAL, expr.type());
assertEquals(nullValue(), expr.valueOf(env));
}
@Test
public void missing_value() {
when(missingRef.type()).thenReturn(INTEGER);
when(missingRef.valueOf(env)).thenReturn(missingValue());
FunctionExpression expr = dsl.interval(missingRef, DSL.literal("day"));
assertEquals(INTERVAL, expr.type());
assertEquals(missingValue(), expr.valueOf(env));
}
}
|
zuesgooogle/game-server
|
src/main/java/com/simplegame/server/bus/role/export/IncrExpResp.java
|
package com.simplegame.server.bus.role.export;
public class IncrExpResp {
private int upgradeCount;
private Long realIncr;
public IncrExpResp() {
}
public IncrExpResp(int paramInt, Long paramLong) {
this.upgradeCount = paramInt;
this.realIncr = paramLong;
}
public int getUpgradeCount() {
return this.upgradeCount;
}
public Long getRealIncr() {
return this.realIncr;
}
}
|
Iceymann18777/sex_for_any
|
public/js/obi.js
|
<gh_stars>1-10
var l = true;
var tt = true;
var f = document.forms.obi;
f.addEventListener('submit', on_obi, false);
function do_reg(el){
if(l){
regelDiv.style.display = "inline-block"
l = false;
}else{
regelDiv.style.display = "none";l = true;
suka2.style.display = "none";
suka1.style.display = "block";
tt=true;
}
}
function remdas(){
regelDiv.style.display = "none";
l = true;
suka2.style.display = "none";
suka1.style.display = "block";
tt = true;
}
function ba(){
if(tt){
suka1.style.display = "none";
suka2.style.display = "block";
tt = false;
}else{
suka2.style.display = "none";
suka1.style.display = "block";
tt = true;
}
}
function on_obi(ev){
ev.preventDefault();
try{
var f3 = ev.target.nid.value;
var f5 = (ev.target.admin.value == "true" ? true: false);
var f1 = esci(ev.target.nick.value);
//var f2=(f5?ev.target.msg.value:esci(ev.target.msg.value))+(f3?'<br><a class="aprofi" href="/webrtc/'+f3+'">Мой профайл</a>':'') ;
var f4;
if(f5){
f4 = ev.target.zakrep.checked;
}
var f2 = (f5 ? ev.target.msg.value: esci(ev.target.msg.value)) + (f3 && !f4 ? '<br><a class="aprofi" href="/webrtc/'+f3+'">' + (yourLang.value == 'ru' ? 'Мой профайл' : 'My profile') + '</a>':'') ;
let d = {};
d.nick = f1;
d.msg = f2;
d.zakrep = f4;
//alert(f4);
vax(ev.target.method, ev.target.action, d, on_obi_saved, on_obi_err, ev.target, false);
ev.target.className = "puls";
}catch(e){alert(e);}
}
function on_obi_saved(l, ev){
console.log(l);
ev.className = "";
let s = (yourLang.value == 'ru' ? 'Объявление сохранено.' : 'Message saved.');
note({content: s, type:"info", time: 6});
//l.nick msg
//<div data-id="${el.id}" class="chelobi"><header><b>${el.bnick}</b></header><p class="chelp">${el.msg}</p>
//<div>${moment(el.ati).format('YYYY-MM-DD hh:mm')}</div>
var div = document.createElement('div');
div.setAttribute('data-id', l.id);
div.className = "chelobi";
div.innerHTML = '<header><b>' + l.nick + '</b></header><p class="chelp">' + l.msg + '</p><button class="del-obi" data-vid="' + l.id + '" onclick="del_obi2(this);">' + (yourLang.value == 'ru' ? 'удалить объявление' : 'remove message') + '</button>';
fuckSection.appendChild(div);
}
function del_obi(el){
var id = el.getAttribute('data-vid');
if(!id)return;
let d = {};
d.id=id;
vax("post", "/api/del_obi", d, on_obi_del, on_obi_err, el, false);
el.className = "puls";
}
function on_obi_del(l, ev){
ev.className = "";
note({content: l.info, type: "info", time: 5});
var f2 = document.querySelector('[data-id="' + l.id + '"]');
if(f2)f2.remove();
}
function del_obi2(el){
var id = el.getAttribute('data-vid');
if(!id)return;
let d = {};
d.id=id;
vax("post", "/api/cust_del_obi", d, on_obi_del, on_obi_err, el, false);
el.className = "puls";
}
function on_obi_err(l, ev){
//alert(l);
ev.className = "";
note({content: l, type: "error", time: 5});
}
function finput(el){
var fi = el.getAttribute('maxlength');
var fi2 = el.value.length;
fspan.textContent = Number(fi) - fi2;
}
|
mrabine/join
|
join/core/src/error.cpp
|
<reponame>mrabine/join<gh_stars>1-10
/**
* MIT License
*
* Copyright (c) 2021 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
// libjoin.
#include <join/error.hpp>
using join::Errc;
using join::ErrorCategory;
/// last error.
thread_local std::error_code join::lastError;
// =========================================================================
// CLASS : ErrorCategory
// METHOD : name
// =========================================================================
const char* ErrorCategory::name () const noexcept
{
return "libjoin";
}
// =========================================================================
// CLASS : ErrorCategory
// METHOD : name
// =========================================================================
std::string ErrorCategory::message (int code) const
{
switch (static_cast <Errc> (code))
{
case Errc::InUse:
return "already in use";
case Errc::InvalidParam:
return "invalid parameters";
case Errc::ConnectionRefused:
return "connection refused";
case Errc::ConnectionClosed:
return "connection closed";
case Errc::TimedOut:
return "timer expired";
case Errc::PermissionDenied:
return "operation not permitted";
case Errc::OutOfMemory:
return "cannot allocate memory";
case Errc::OperationFailed:
return "operation failed";
case Errc::NotFound:
return "resource not found";
case Errc::MessageUnknown:
return "message unknown";
case Errc::MessageTooLong:
return "message too long";
case Errc::TemporaryError:
return "temporary error";
case Errc::UnknownError:
return "unknown error";
default:
return "success";
}
}
// =========================================================================
// CLASS : ErrorCategory
// METHOD : equivalent
// =========================================================================
bool ErrorCategory::equivalent (const std::error_code& code, int condition) const noexcept
{
switch (static_cast <Errc> (condition))
{
case Errc::InUse:
return code == std::errc::already_connected ||
code == std::errc::connection_already_in_progress ||
code == std::errc::address_in_use;
case Errc::InvalidParam:
return code == std::errc::no_such_file_or_directory ||
code == std::errc::address_family_not_supported ||
code == std::errc::invalid_argument ||
code == std::errc::protocol_not_supported ||
code == std::errc::bad_file_descriptor ||
code == std::errc::not_a_socket ||
code == std::errc::bad_address ||
code == std::errc::no_protocol_option ||
code == std::errc::destination_address_required ||
code == std::errc::operation_not_supported;
case Errc::ConnectionRefused:
return code == std::errc::connection_refused ||
code == std::errc::network_unreachable;
case Errc::ConnectionClosed:
return code == std::errc::connection_reset ||
code == std::errc::not_connected ||
code == std::errc::broken_pipe;
case Errc::TimedOut:
return code == std::errc::timed_out;
case Errc::PermissionDenied:
return code == std::errc::permission_denied ||
code == std::errc::operation_not_permitted;
case Errc::OutOfMemory:
return code == std::errc::too_many_files_open ||
code == std::errc::too_many_files_open_in_system ||
code == std::errc::no_buffer_space ||
code == std::errc::not_enough_memory ||
code == std::errc::no_lock_available;
case Errc::MessageUnknown:
return code == std::errc::no_message ||
code == std::errc::bad_message ||
code == std::errc::no_message_available;
case Errc::MessageTooLong:
return code == std::errc::message_size;
case Errc::TemporaryError:
return code == std::errc::interrupted ||
code == std::errc::resource_unavailable_try_again ||
code == std::errc::operation_in_progress;
default:
return false;
}
}
// =========================================================================
// CLASS :
// METHOD : getErrorCategory
// =========================================================================
const std::error_category& join::getErrorCategory ()
{
static ErrorCategory instance;
return instance;
}
// =========================================================================
// CLASS :
// METHOD : make_error_code
// =========================================================================
std::error_code join::make_error_code (join::Errc code)
{
return std::error_code (static_cast <int> (code), getErrorCategory ());
}
// =========================================================================
// CLASS :
// METHOD : make_error_condition
// =========================================================================
std::error_condition join::make_error_condition (join::Errc code)
{
return std::error_condition (static_cast <int> (code), getErrorCategory ());
}
|
PhilDore11/outbreak-summary-report-manager
|
client/app.js
|
<reponame>PhilDore11/outbreak-summary-report-manager
'use strict';
angular.module('app', [
'ngResource',
'ngMessages',
'ngMaterial',
'md.data.table',
'ui.router',
'satellizer',
'mdSteppers',
'app.home',
'app.reports'
])
.config(function($mdThemingProvider, $urlRouterProvider, $httpProvider) {
$mdThemingProvider.theme('default')
.primaryPalette('blue')
.accentPalette('grey')
.warnPalette('red');
$urlRouterProvider.otherwise('/home');
// http://aboutcode.net/2013/07/27/json-date-parsing-angularjs.html
var regexIso8601 = /^(\d{4}|\+\d{6})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2}):(\d{2})\.(\d{1,})(Z|([\-+])(\d{2}):(\d{2}))?)?)?)?$/;
function convertDateStringsToDates(input) {
// Ignore things that aren't objects.
if (typeof input !== 'object') {
return input;
}
for (var key in input) {
if (!input.hasOwnProperty(key)) {
continue;
}
var value = input[key];
var match;
// Check for string properties which look like dates.
if (typeof value === 'string' && (match = value.match(regexIso8601))) {
var milliseconds = Date.parse(match[0]);
if (!isNaN(milliseconds)) {
input[key] = new Date(milliseconds);
}
} else if (typeof value === 'object') {
// Recurse into object
convertDateStringsToDates(value);
}
}
}
$httpProvider.defaults.transformResponse.push(function(responseData) {
convertDateStringsToDates(responseData);
return responseData;
});
Date.prototype.addDays = function(days) {
var dat = new Date(this.valueOf());
dat.setDate(dat.getDate() + days);
return dat;
};
});
|
bzxy/cydia
|
iOSOpenDev/frameworks/StoreServices.framework/Headers/SSDownloadAuthenticationChallengeSender.h
|
<filename>iOSOpenDev/frameworks/StoreServices.framework/Headers/SSDownloadAuthenticationChallengeSender.h
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/StoreServices.framework/StoreServices
*/
#import <StoreServices/NSURLAuthenticationChallengeSender.h>
#import <StoreServices/StoreServices-Structs.h>
#import <StoreServices/XXUnknownSuperclass.h>
@class SSDownloadAuthenticationSession;
__attribute__((visibility("hidden")))
@interface SSDownloadAuthenticationChallengeSender : XXUnknownSuperclass <NSURLAuthenticationChallengeSender> {
@private
dispatch_queue_s *_dispatchQueue; // 4 = 0x4
SSDownloadAuthenticationSession *_session; // 8 = 0x8
}
@property(readonly, assign) SSDownloadAuthenticationSession *authenticationSession; // G=0x428c9;
- (void)useCredential:(id)credential forAuthenticationChallenge:(id)authenticationChallenge; // 0x42b25
- (void)rejectProtectionSpaceAndContinueWithChallenge:(id)challenge; // 0x42af5
- (void)performDefaultHandlingForAuthenticationChallenge:(id)authenticationChallenge; // 0x42ac5
- (void)continueWithoutCredentialForAuthenticationChallenge:(id)authenticationChallenge; // 0x42a95
- (void)cancelAuthenticationChallenge:(id)challenge; // 0x42a65
// declared property getter: - (id)authenticationSession; // 0x428c9
- (void)dealloc; // 0x42869
- (id)initWithAuthenticationSession:(id)authenticationSession; // 0x427f5
@end
|
benhj/arrow
|
src/statements/IfStatement.hpp
|
/// (c) <NAME> 2019 - present
#pragma once
#include "ElseIfStatement.hpp"
#include "ElseStatement.hpp"
#include "Statement.hpp"
#include "lexer/Token.hpp"
#include "expressions/Expression.hpp"
#include <memory>
#include <vector>
namespace arrow {
/// Note, an IfStatement can contain optional
/// ElseIfStatement parts an an optional
/// ElseStatement part
class IfStatement : public Statement
{
public:
IfStatement(long const lineNumber);
IfStatement & withToken(Token token);
IfStatement & withExpression(std::shared_ptr<Expression> expression);
std::shared_ptr<Expression> const & getExpression() const;
IfStatement & withInnerStatement(std::shared_ptr<Statement> innerStatement);
void addElseIfPart(std::shared_ptr<ElseIfStatement> elseIfPart);
IfStatement & withElsePart(std::shared_ptr<ElseStatement> elsePart);
std::string toString() const override;
std::shared_ptr<StatementEvaluator> getEvaluator() const override;
std::shared_ptr<Statement> const & getInnerStatement() const;
std::vector<std::shared_ptr<ElseIfStatement>> const & getElseIfParts() const;
std::shared_ptr<ElseStatement> const & getElsePart() const;
private:
Token m_keywordToken; // the if keyword
std::shared_ptr<Expression> m_expression;
std::shared_ptr<Statement> m_innerStatement;
std::vector<std::shared_ptr<ElseIfStatement>> m_elseIfParts;
std::shared_ptr<ElseStatement> m_elsePart;
};
}
|
jarekankowski/pegasus_spyware
|
sample5/recompiled_java/sources/com/network/h/i.java
|
package com.network.h;
/* access modifiers changed from: package-private */
public final class i implements Runnable {
/* renamed from: a reason: collision with root package name */
final /* synthetic */ byte[] f150a;
i(byte[] bArr) {
this.f150a = bArr;
}
/* JADX WARNING: Removed duplicated region for block: B:10:0x006a A[SYNTHETIC, Splitter:B:10:0x006a] */
/* JADX WARNING: Removed duplicated region for block: B:13:0x006f A[Catch:{ Throwable -> 0x0089 }] */
/* Code decompiled incorrectly, please refer to instructions dump. */
public final void run() {
/*
// Method dump skipped, instructions count: 144
*/
throw new UnsupportedOperationException("Method not decompiled: com.network.h.i.run():void");
}
}
|
ilkka-rautiainen/e-getkanban
|
backend/src/main/java/fi/aalto/ekanban/services/dice/DiceService.java
|
<gh_stars>0
package fi.aalto.ekanban.services.dice;
@FunctionalInterface
public interface DiceService {
Integer castDie(Integer min, Integer max);
}
|
abzalhan/blablachat
|
app/controllers/APIDoc.java
|
<filename>app/controllers/APIDoc.java<gh_stars>1-10
package controllers;
import jobs.UpdateAPIDocJob;
import models.APIMethod;
import models.APIParam;
import models.User;
import play.db.jpa.JPA;
import play.libs.F;
import java.util.Arrays;
import java.util.List;
/**
* Created by bakhyt on 10/16/17.
*/
public class APIDoc extends Parent {
public static void update() {
User user = getCurrentUser();
if (user.isAdmin()) {
UpdateAPIDocJob job = new UpdateAPIDocJob();
F.Promise p = job.now();
await(p);
renderText("job executed");
} else {
error(401, "need to auth");
}
}
private static void injectNav() {
List<String> apis = (List<String>) JPA.em().createQuery("select distinct (o.apiName) from APIMethod o")
.getResultList();
// List<String> apis = Arrays.asList("BlaBlaChatApi");
renderArgs.put("injectNav", apis);
}
public static void api(String className) {
injectNav();
// List<APIMethod> methods = APIMethod.find("className=? and deleted=0 order by id desc", className).fetch();
List<APIMethod> methods = APIMethod.find("apiName=? and deleted=0 order by id desc", className).fetch();
render(methods,className);
}
public static void edit(Long id) {
injectNav();
APIMethod method = APIMethod.find("id=:id").setParameter("id", id).first();
render(method);
}
public static void save(APIMethod method, APIParam[] params) {
APIMethod m = APIMethod.find("id=:id").setParameter("id", method.getId()).first();
if(m!=null) {
m.setDescription(method.getDescription());
m.save();
}
if(params!=null){
for (APIParam param : params) {
APIParam p = APIParam.find("id=:id").setParameter("id", param.getId()).first();
p.setDescription(param.getDescription());
p.save();
}
}
index();
}
public static void index(){
injectNav();
render();
}
}
|
Sajaki/intellij-community
|
platform/platform-impl/src/com/intellij/ide/lightEdit/actions/LightEditGotoOpenedFileAction.java
|
<filename>platform/platform-impl/src/com/intellij/ide/lightEdit/actions/LightEditGotoOpenedFileAction.java
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.lightEdit.actions;
import com.intellij.ide.lightEdit.LightEdit;
import com.intellij.ide.lightEdit.LightEditCompatible;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.fileChooser.FileSystemTree;
import com.intellij.openapi.fileChooser.actions.FileChooserAction;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.ArrayUtil;
public final class LightEditGotoOpenedFileAction extends FileChooserAction implements LightEditCompatible {
@Override
protected void actionPerformed(FileSystemTree fileSystemTree, AnActionEvent e) {
Project project = e.getProject();
if (project != null) {
VirtualFile file = ArrayUtil.getFirstElement(FileEditorManager.getInstance(project).getSelectedFiles());
if (file != null) {
fileSystemTree.select(file, () -> fileSystemTree.expand(file, null));
}
}
}
@Override
protected void update(FileSystemTree fileChooser, AnActionEvent e) {
Project project = e.getProject();
if (!LightEdit.owns(project)) {
e.getPresentation().setEnabledAndVisible(false);
return;
}
e.getPresentation().setEnabled(FileEditorManager.getInstance(project).hasOpenFiles());
}
}
|
petrbouda/JoyREST
|
joyrest-core/src/main/java/org/joyrest/exception/configuration/ExceptionConfiguration.java
|
<filename>joyrest-core/src/main/java/org/joyrest/exception/configuration/ExceptionConfiguration.java<gh_stars>10-100
/*
* Copyright 2015 <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 org.joyrest.exception.configuration;
import java.util.Set;
import org.joyrest.exception.handler.InternalExceptionHandler;
/**
* Class is used as a holder for exception handlers.
*
* @see TypedExceptionConfiguration
* @author pbouda
*/
public interface ExceptionConfiguration {
/**
* Method closes and initializes exception handlers registered in this configurer.
*/
void initialize();
/**
* Returns all exception handlers registered in this configurer.
*
* @return set of exception handlers
*/
Set<InternalExceptionHandler> getExceptionHandlers();
}
|
ebVocab/ebVocabCore
|
src/main/java/de/ebuchner/sync/SyncListenerAdapter.java
|
package de.ebuchner.sync;
public class SyncListenerAdapter implements SyncListener {
@Override
public void onNodesCompare(SyncNode source, SyncNode target, SyncNodeComparator.ResultType resultType) {
}
@Override
public void onSourceOnly(SyncNode source) {
}
@Override
public void onTargetOnly(SyncNode target) {
}
@Override
public void onSyncStarted() {
}
@Override
public void onSyncFinished() {
}
@Override
public void onNodeContainersCompare(SyncNodeContainer source, SyncNodeContainer target) {
}
}
|
windcry1/My-ACM-ICPC
|
SWUST OJ/?.cpp
|
#include<iostream>
using namespace std;
const int MAXN = 21;
int map[MAXN][MAXN];
bool vis[MAXN];
int minlength = 20000;
int n = 0;
void dfs(int t,int tot,int count)
{
if (tot > minlength) return;
if (count == n)
{
if (map[t][1])
{
tot +=map[t][1];
if (tot <minlength)
{
minlength= tot;
}
}
return;
}
for (int i = 1; i <= n; i++)
if (!vis[i] &&map[t][i])
{
vis[i] =1;
dfs(i, tot +map[t][i], count+1);
vis[i] =0;
}
}
int main()
{
cin >> n;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= n;j++)
cin >>map[i][j];
vis[1] = 1;
dfs(1, 0, 1);
cout << minlength << endl;
return 0;
}
|
robmclarty/cred-auth-manager
|
tests/server/helpers/user_id_helper.js
|
'use strict'
// User IDs based on fixtures generated from /tests/server/fixters/users.json
module.exports = {
adminUserId: 1,
noPermsUserId: 2,
writeUserId: 3,
readUserId: 4,
inactiveUserId: 5,
emptyPermsUserId: 6,
otherPermsUserId: 7,
updateUserId: 8,
writeUserNoPermsId: 9,
invalidUserId: 9999999
}
|
JackToppen/deep-hipsc-tracking
|
deep_hipsc_tracking/plotting/styling.py
|
<filename>deep_hipsc_tracking/plotting/styling.py
""" Styling tools for plots
* :py:class:`~set_plot_style`: The plot style context manager
* :py:class:`~colorwheel`: Infinitely iterable color wheel
"""
# Imports
import itertools
import pathlib
from contextlib import ContextDecorator
from typing import Tuple, List, Optional, Dict
THISDIR = pathlib.Path(__file__).resolve().parent
# 3rd party imports
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as mplcolors
from matplotlib.axes import Axes
import seaborn as sns
# Our own imports
from .consts import (
RC_PARAMS_MINIMAL, RC_PARAMS_DARK, RC_PARAMS_LIGHT,
RC_PARAMS_POSTER, RC_PARAMS_DARK_POSTER, RC_PARAMS_FIGURE,
COLOR_PALETTE,
)
# Decorators
class set_plot_style(ContextDecorator):
""" Context manager for styling matplotlib plots
Basic usage as a context manager
.. code-block:: python
with set_plot_style('dark') as style:
# In here, plots are 'dark' styled
fig, ax = plt.subplots(1, 1)
ax.plot([1, 2, 3], [1, 2, 3])
# Save the plot with correct background colors
style.savefig('some_fig.png')
Can also be used as a decorator
.. code-block:: python
@set_plot_style('dark')
def plot_something():
# In here, plots are 'dark' styled
fig, ax = plt.subplots(1, 1)
ax.plot([1, 2, 3], [1, 2, 3])
plt.show()
For more complex use, see the
`Matplotlib rcParam <http://matplotlib.org/users/customizing.html>`_
docs which list all the parameters that can be tweaked.
:param str style:
One of 'dark', 'minimal', 'poster', 'dark_poster', 'default'
"""
_active_styles = []
def __init__(self, style: str = 'dark'):
style = style.lower().strip()
self.stylename = style
if style == 'dark':
self.params = RC_PARAMS_DARK
self.savefig_params = {'facecolor': 'k',
'edgecolor': 'k'}
elif style == 'dark_poster':
self.params = RC_PARAMS_DARK_POSTER
self.savefig_params = {'facecolor': 'k',
'edgecolor': 'k'}
elif style == 'poster':
self.params = RC_PARAMS_POSTER
self.savefig_params = {'facecolor': 'w',
'edgecolor': 'w'}
elif style == 'light':
self.params = RC_PARAMS_LIGHT
self.savefig_params = {'facecolor': 'w',
'edgecolor': 'w'}
elif style == 'figure':
self.params = RC_PARAMS_FIGURE
self.savefig_params = {'facecolor': 'w',
'edgecolor': 'w'}
elif style == 'minimal':
self.params = RC_PARAMS_MINIMAL
self.savefig_params = {}
elif style == 'default':
self.params = {}
self.savefig_params = {}
else:
raise KeyError(f'Unknown plot style: "{style}"')
@property
def axis_color(self) -> str:
""" Get the color for axis edges in the current theme
:returns:
The edge color or None
"""
if self.stylename.startswith('dark'):
default = 'white'
else:
default = 'black'
return self.params.get('axes.edgecolor', default)
@property
def edgecolor(self) -> str:
""" Get the color for edges in the current theme
:returns:
The edge color or None
"""
if self.stylename.startswith('dark'):
default = 'white'
else:
default = 'black'
return self.params.get('edgecolor', default)
@classmethod
def get_active_style(cls) -> Optional[str]:
""" Get the currently active style, or None if nothing is active
:returns:
The current style or None
"""
if cls._active_styles:
return cls._active_styles[-1]
return None
def twinx(self, ax: Optional[Axes] = None) -> Axes:
""" Create a second axis sharing the x axis
:param Axes ax:
The axis instance to set to off
:returns:
A second axis with a shared x coordinate
"""
if ax is None:
ax = plt.gca()
ax2 = ax.twinx()
# Fix up the defaults to make sense
ax2.spines['right'].set_visible(True)
ax2.tick_params(axis='y',
labelcolor=self.axis_color,
color=self.axis_color,
left=True)
return ax2
def set_axis_off(self, ax: Optional[Axes] = None):
""" Remove labels and ticks from the axis
:param Axes ax:
The axis instance to set to off
"""
if ax is None:
ax = plt.gca()
# Blank all the things
ax.set_xticks([])
ax.set_yticks([])
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
for side in ('top', 'bottom', 'left', 'right'):
if side in ax.spines:
ax.spines[side].set_visible(False)
ax.set_axis_off()
def set_image_axis_lims(self,
img: np.ndarray,
ax: Optional[Axes] = None,
axis_off: bool = True):
""" Set limits for the axis based on the images
:param ndarray img:
The image to use for the limits
:param Axes ax:
The axis to set limits on
"""
if ax is None:
ax = plt.gca()
rows, cols = img.shape[:2]
ax.set_xlim([0, cols])
ax.set_ylim([rows, 0])
if axis_off:
self.set_axis_off(ax)
def rotate_xticklabels(self,
ax: Axes,
rotation: float,
horizontalalignment: str = 'center',
verticalalignment: str = 'center',
rotation_mode: str = 'default'):
""" Rotate the x ticklabels
:param Axes ax:
The axis instance to rotate xticklabels on
:param float rotation:
Rotation of the text (in degrees)
:param str rotation_mode:
Either "default" or "anchor"
"""
for tick in ax.get_xticklabels():
plt.setp(tick,
rotation=rotation,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
rotation_mode=rotation_mode)
def rotate_yticklabels(self,
ax: Axes,
rotation: float,
horizontalalignment: str = 'center',
verticalalignment: str = 'center',
rotation_mode: str = 'default'):
""" Rotate the y ticklabels
:param Axes ax:
The axis instance to rotate xticklabels on
:param float rotation:
Rotation of the text (in degrees)
:param str rotation_mode:
Either "default" or "anchor"
"""
#FIXME: Not sure if this is right...
for tick in ax.get_yticklabels():
plt.setp(tick,
rotation=rotation,
horizontalalignment=horizontalalignment,
verticalalignment=verticalalignment,
rotation_mode=rotation_mode)
def show(self,
outfile: Optional[pathlib.Path] = None,
transparent: bool = True,
tight_layout: bool = True,
close: bool = True,
fig: Optional = None,
dpi: Optional[int] = None,
suffixes: Optional[List[str]] = None):
""" Act like matplotlib's show, but also save the file if passed
:param Path outfile:
If not None, save to this file instead of plotting
:param bool transparent:
If True, save with a transparent background if possible
:param bool tight_layout:
If True, try and squish the layout before saving
:param bool close:
If True, close the figure after saving it
:param Figure fig:
If not None, the figure to save
"""
# Save the plot with multiple suffixes
if suffixes is None:
suffixes = []
elif isinstance(suffixes, str):
suffixes = [suffixes]
suffixes = ['.' + str(s).lstrip('.') for s in suffixes
if s is not None and len(s) > 0]
# Apply a tight layout before showing the plot
if tight_layout:
plt.tight_layout()
if outfile is None:
plt.show()
else:
# Save the plot a bunch of different ways
if len(suffixes) == 0:
suffixes = [outfile.suffix]
for suffix in suffixes:
final_outfile = outfile.parent / f'{outfile.stem}{suffix}'
print(f'Writing {final_outfile}')
self.savefig(final_outfile, transparent=transparent, fig=fig, dpi=dpi)
# Close the figure unless it was specifically forced open
if close:
plt.close()
def update(self, params: Dict):
""" Update the matplotlib rc.params
:param dict params:
rcparams to fiddle with
"""
self.params.update(params)
def savefig(self,
savefile: pathlib.Path,
fig: Optional = None,
**kwargs):
""" Save the figure, with proper background colors
:param Path savefile:
The file to save
:param fig:
The figure or plt.gcf()
:param \\*\\*kwargs:
The keyword arguments to pass to fig.savefig
"""
if fig is None:
fig = plt.gcf()
savefile = pathlib.Path(savefile)
savefile.parent.mkdir(exist_ok=True, parents=True)
savefig_params = dict(self.savefig_params)
savefig_params.update(kwargs)
fig.savefig(str(savefile), **kwargs)
def load(self):
""" Load the style """
self._style = plt.rc_context(self.params)
self._style.__enter__()
self._active_styles.append(self.stylename)
def unload(self, *args, **kwargs):
""" Unload the active style """
self._style.__exit__(*args, **kwargs)
self._active_styles.pop()
def __enter__(self) -> 'set_plot_style':
self.load()
return self
def __exit__(self, *args, **kwargs):
self.unload(*args, **kwargs)
# Classes
class colorwheel(mplcolors.Colormap):
""" Generate colors like a matplotlib color cycle
.. code-block:: python
palette = colorwheel(palette='some seaborn palette', n_colors=5)
for item, color in zip(items, colors):
# In here, the colors will cycle over and over for each item
# Access by index
color = palette[10]
:param str palette:
A palette that can be recognized by seaborn
:param int n_colors:
The number of colors to generate
"""
def __init__(self,
palette: str = COLOR_PALETTE,
n_colors: int = 10):
if isinstance(palette, colorwheel):
palette = palette.palette
self.palette = palette
self.n_colors = n_colors
self.N = self.n_colors
self._idx = 0
self._color_table = None
@classmethod
def from_colors(cls,
colors: List[str],
n_colors: Optional[int] = None,
color_type: str = 'name') -> 'colorwheel':
""" Make a palette from a list of colors
:param str colors:
A list of matplotlib colors to use
:param int n_colors:
If not None, the number of colors in the cycle
:param str color_type:
Color type, one of ('name', '8bit', 'float')
:returns:
A colorwheel object with this palette
"""
if n_colors is None:
n_colors = len(colors)
palette = []
for _, color in zip(range(n_colors), itertools.cycle(colors)):
if color_type == 'name':
norm_color = mplcolors.to_rgba(color)
elif color_type == '8bit':
norm_color = tuple(float(c)/255.0 for c in color)
elif color_type == 'float':
norm_color = tuple(float(c) for c in color)
else:
raise KeyError(f'Unknown color_type "{color_type}"')
# Make the color RGBA and 0.0 <= c <= 1.0
if len(norm_color) == 3:
norm_color = norm_color + (1.0, )
if len(norm_color) != 4:
raise ValueError(f'Got invalid color spec {color}')
if min(norm_color) < 0.0 or max(norm_color) > 1.0:
raise ValueError(f'Got invalid color range {color}')
palette.append(norm_color)
return cls(palette, n_colors=n_colors)
@classmethod
def from_color_range(cls,
color_start: str,
color_end: str,
n_colors: int) -> 'colorwheel':
""" Make a color range
:param str color_start:
The start for the color range (i == 0)
:param str color_end:
The end for the color range (i == n_colors-1)
:param int n_colors:
The number of colors in the range
:returns:
A colorwheel object with this palette
"""
palette = []
color_start = mplcolors.to_rgba(color_start)
color_end = mplcolors.to_rgba(color_end)
red_color = np.linspace(color_start[0], color_end[0], n_colors)
green_color = np.linspace(color_start[1], color_end[1], n_colors)
blue_color = np.linspace(color_start[2], color_end[2], n_colors)
for r, g, b in zip(red_color, green_color, blue_color):
palette.append((r, g, b, 1.0))
return cls(palette, n_colors=n_colors)
@classmethod
def from_color_anchors(cls,
colors: List[str],
anchors: List[float],
n_colors: int) -> 'colorwheel':
""" Make a palette with linear ramps between the colors
:param list[str] colors:
The set points for the colors
:param list[float] anchors:
The points where those colors are mapped
:param int n_colors:
The number of colors in the range
:returns:
A colorwheel object with this palette
"""
colors = [mplcolors.to_rgba(c) for c in colors]
if len(colors) < 2:
return cls(palette=[colors[0]]*n_colors, n_colors=n_colors)
anchor_start = np.min(anchors)
anchor_end = np.max(anchors)
inds = np.argsort(anchors)
colors = np.array(colors)[inds, :]
anchors = np.array(anchors)[inds]
anchor_inds = np.arange(anchors.shape[0])
assert colors.shape[0] == anchors.shape[0]
assert colors.shape[1] == 4
ranges = np.linspace(anchor_start, anchor_end, n_colors)
palette = []
for anchor_pt in ranges:
left_idx = (anchor_inds[anchors <= anchor_pt])[-1]
right_idx = left_idx + 1
if right_idx >= len(anchors):
color = colors[-1, :]
else:
left_anchor = anchors[left_idx]
right_anchor = anchors[right_idx]
right_pct = (anchor_pt - left_anchor) / (right_anchor - left_anchor)
left_pct = 1.0 - right_pct
left_color = colors[left_idx, :]
right_color = colors[right_idx, :]
color = left_color*left_pct + right_color*right_pct
palette.append(tuple(color))
return cls(palette, n_colors=n_colors)
def __call__(self, X: float, alpha=None, bytes=False):
""" Pretend to be a colormap """
if isinstance(X, int):
return self.color_table[self._idx % self.n_colors]
elif isinstance(X, float):
n_color = X * self.n_colors
n_color_low = int(np.floor(n_color))
n_color_high = int(np.ceil(n_color))
frac = n_color - n_color_low
color_left = self.color_table[n_color_low % self.n_colors]
color_right = self.color_table[n_color_high % self.n_colors]
return color_left*frac + color_right*(1.0 - frac)
elif isinstance(X, np.ndarray):
max_color = self.n_colors
if X.dtype in (np.float, np.float32, np.float64):
X[X < 0.0] = 0.0
X[X > 1.0] = 1.0
n_color = X * (max_color - 1)
n_color_low = np.floor(n_color).astype(np.int)
n_color_high = np.ceil(n_color).astype(np.int)
n_color_low[n_color_low < 0] = 0
n_color_high[n_color_high < 0] = 0
n_color_low[n_color_low >= max_color] = max_color - 1
n_color_high[n_color_high >= max_color] = max_color - 1
frac = (n_color - n_color_low)[:, np.newaxis]
colors_left = np.array([self.color_table[i] for i in n_color_low])
colors_right = np.array([self.color_table[i] for i in n_color_high])
colors = (colors_left*frac + colors_right*(1.0 - frac))
alpha = np.ones((colors.shape[0], 1), dtype=np.float)
colors = np.concatenate([colors, alpha], axis=1)
return colors
else:
raise TypeError(f'Unknown array type {X.dtype}')
raise TypeError(f'Unknown type {type(X)}')
# Dynamic color palettes
# These aren't as good as the ones that come with matplotlib
# They are so todd can be happy
def wheel_grey(self):
return [
(141/255, 141/255, 141/255),
]
def wheel_bluegrey3(self):
return [
(0x04/255, 0x04/255, 0x07/255, 1.0),
(0xb0/255, 0xb0/255, 0xb3/255, 1.0),
(0x00/255, 0x00/255, 0xff/255, 1.0),
]
def wheel_bluegreywhite3(self):
return [
(0xaa/255, 0xaa/255, 0xaa/255, 1.0),
(0x00/255, 0xff/255, 0xff/255, 1.0),
(0x00/255, 0x00/255, 0xff/255, 1.0),
]
def wheel_bluegrey4(self):
return [
(0xa2/255, 0xa5/255, 0xa7/255, 1.0),
(0x5c/255, 0xca/255, 0xe7/255, 1.0),
(0x04/255, 0x07/255, 0x07/255, 1.0),
(0x3e/255, 0x5b/255, 0xa9/255, 1.0),
]
def wheel_blackwhite(self) -> List[Tuple]:
""" Colors from black to white in a linear ramp """
colors = np.linspace(0, 1, self.n_colors)
return [(c, c, c, 1.0) for c in colors]
def wheel_greys_light_dark(self) -> List[Tuple]:
""" Greys from light to dark in a linear ramp """
colors = np.linspace(0.75, 0.25, self.n_colors)
return [(c, c, c, 1.0) for c in colors]
def wheel_greyblack(self) -> List[Tuple]:
""" Colors from grey to black in a linear ramp """
colors = np.linspace(0.75, 0, self.n_colors)
return [(c, c, c, 1.0) for c in colors]
def wheel_greywhite(self) -> List[Tuple]:
""" Colors from grey to white in a linear ramp """
colors = np.linspace(0.25, 1, self.n_colors)
return [(c, c, c, 1.0) for c in colors]
def wheel_lightgreywhite(self) -> List[Tuple]:
""" Colors from grey to white in a linear ramp """
colors = np.linspace(0.608, 1, self.n_colors)
return [(c, c, c, 1.0) for c in colors]
def wheel_whitelightgrey(self) -> List[Tuple]:
""" Colors from grey to white in a linear ramp """
colors = np.linspace(1.0, 0.608, self.n_colors)
return [(c, c, c, 1.0) for c in colors]
def wheel_redgrey(self) -> List[Tuple]:
""" Grey to red color space """
red = np.linspace(155/255, 228/255, self.n_colors)
green = np.linspace(155/255, 26/255, self.n_colors)
blue = np.linspace(155/255, 28/255, self.n_colors)
return [(r, g, b, 1.0) for r, g, b in zip(red, green, blue)]
def wheel_bluegrey(self) -> List[Tuple]:
""" Grey to blue color space """
# red = np.linspace(155/255, 60/255, self.n_colors)
# green = np.linspace(155/255, 174/255, self.n_colors)
# blue = np.linspace(155/255, 238/255, self.n_colors)
red = np.linspace(155/255, 70/255, self.n_colors)
green = np.linspace(155/255, 130/255, self.n_colors)
blue = np.linspace(155/255, 180/255, self.n_colors)
return [(r, g, b, 1.0) for r, g, b in zip(red, green, blue)]
def wheel_illustrator_bwr(self) -> List[Tuple]:
""" Load the stupid illustrator BWR version """
red = []
green = []
blue = []
with (THISDIR / 'illustrator_bwr.txt').open('rt') as fp:
for line in fp:
rgb = line.strip()[1:]
assert len(rgb) == 6
r, g, b = rgb[:2], rgb[2:4], rgb[4:6]
red.append(int(r, 16)/256)
green.append(int(g, 16)/256)
blue.append(int(b, 16)/256)
x = np.linspace(0, 1, len(red))
xf = np.linspace(0, 1, self.n_colors)
red_f = np.interp(xf, x, red, left=red[0], right=red[-1])
green_f = np.interp(xf, x, green, left=green[0], right=green[-1])
blue_f = np.interp(xf, x, blue, left=blue[0], right=blue[-1])
return [(r, g, b, 1.0) for r, g, b in zip(red_f, green_f, blue_f)]
@property
def color_table(self):
if self._color_table is not None:
return self._color_table
# Magic color palettes
palette = self.palette
if isinstance(palette, str):
if palette.startswith('wheel_'):
palette = getattr(self, palette)()
elif palette.startswith('color_'):
color = palette.split('_', 1)[1]
color = mplcolors.to_rgba(color)
palette = [color for _ in range(self.n_colors)]
else:
palette = palette
else:
palette = self.palette
# Memorize the color table then output it
self._color_table = sns.color_palette(palette=palette, n_colors=self.n_colors)
return self._color_table
def __len__(self):
return len(self.color_table)
def __getitem__(self, idx):
return self.color_table[idx % len(self.color_table)]
def __iter__(self):
self._idx = 0
return self
def __next__(self):
color = self.color_table[self._idx]
self._idx = (self._idx + 1) % len(self.color_table)
return color
next = __next__
|
maroozm/AliPhysics
|
PWGCF/Correlations/JCORRAN/Pro/AliAnalysisTaskGenMCRidge.h
|
<reponame>maroozm/AliPhysics
#ifndef ALIANALYSISTASKGENMCRIDGE_H
#define ALIANALYSISTASKGENMCRIDGE_H
using namespace std;
class AliMultSelection;
class AliVMultiplicity;
class TClonesArray;
class AliJJetTask;
class AliDirList;
class AliJetContainer;
class AliParticleContainer;
class AliClusterContainer;
class AliEmcalTrackSelection;
class AliAnalysisUtils;
class AliCalorimeterUtils;
class AliMultSelection;
class TLorentzVector;
#include "TFile.h"
#include <TSystem.h>
#include <TGrid.h>
#include "THnSparse.h"
#include "AliAnalysisTaskSE.h"
#include "AliTriggerAnalysis.h"
#include "AliESDtrackCuts.h"
#include "AliESDEvent.h"
#include "AliAODEvent.h"
#include "AliPIDCombined.h"
#include "THistManager.h"
#include "AliAODMCParticle.h"
#include <deque>
#include <iostream>
#include <fstream>
#include "AliAnalysisUtils.h"
#include <vector>
#include <TVector.h>
#include <TRandom.h>
#include <TString.h>
#include <TLorentzVector.h>
#include "AliJJetTask.h"
#include "AliAnalysisTaskEmcalJet.h"
#include "AliJetContainer.h"
#include "AliInputEventHandler.h"
#include <TParticle.h>
#include "AliJFJTask.h"
class AliAnalysisTaskGenMCRidge : public AliAnalysisTaskEmcalJet {
public:
typedef std::vector<Bool_t> Bool_1d;
typedef std::vector<Double_t> Double1D;
typedef std::vector<int> Int1D;
typedef std::vector<Double1D> Double2D;
typedef std::vector<TLorentzVector> TLorentzVector1D;
AliAnalysisTaskGenMCRidge();
AliAnalysisTaskGenMCRidge
(
const char *name
, const char *option
);
AliAnalysisTaskGenMCRidge
(
const AliAnalysisTaskGenMCRidge& ap
);
AliAnalysisTaskGenMCRidge& operator =
(
const AliAnalysisTaskGenMCRidge& ap
);
~AliAnalysisTaskGenMCRidge();
virtual void UserCreateOutputObjects();
virtual void Exec(Option_t *);
virtual void FinishTaskOutput();
virtual void Terminate(Option_t *);
void RhoSparse(AliJetContainer *ktContainer, AliJetContainer *aktContainer, Int_t numberofexcludingjets);
Bool_t isOverlapping(AliEmcalJet* jet1, AliEmcalJet* jet2);
double GetMultiplicity( AliStack* stack );
bool GetProperTracks( AliStack* stack );
void GetCorrelations();
void SetPtHardMin( double pthardmin ){fPtHardMin = pthardmin; };
void SetPtHardMax( double pthardmax ){fPtHardMax = pthardmax; };
void SetJFJTaskName(TString name){ fJFJTaskName=name; }
void ESETagging(int iESE, double lpPT);
TAxis AxisFix( TString name, int nbin, Double_t xmin, Double_t xmax);
TAxis AxisVar( TString name, std::vector<Double_t> bin );
TAxis AxisLog( TString name, int nbin, Double_t xmin, Double_t xmax
, Double_t xmin0);
TAxis AxisStr( TString name, std::vector<TString> bin );
THnSparse * CreateTHnSparse(TString name, TString title
, Int_t ndim, std::vector<TAxis> bins, Option_t * opt="");
THnSparse * CreateTHnSparse(TString name, TString title
, TString templ, Option_t * opt="");
Long64_t FillTHnSparse( TString name, std::vector<Double_t> x, Double_t w=1.);
Long64_t FillTHnSparse( THnSparse *h, std::vector<Double_t> x, Double_t w=1.);
private:
typedef std::vector < TParticle* > tracklist;
typedef std::deque<tracklist> eventpool;
typedef std::vector<vector<eventpool> > mixingpool;
mixingpool fEMpool; //!
TAxis binCent; //!
TAxis binTPt; //!
TAxis binAPt; //!
TAxis binPhi; //!
TAxis binEta; //!
TAxis binLHPt; //!
TAxis binJetPt; //!
TAxis binNtrig; //!
TAxis binZ; //!
AliInputEventHandler* fMcHandler=nullptr; //!
AliMCEvent* fMcEvent=nullptr; //!
AliStack* fStack=nullptr; //!
AliDirList* fOutput=nullptr; //!
THistManager* fHistos=nullptr; //!
TString fOption;
std::vector < TParticle* > goodTracks; //!
std::vector < Double_t > NTracksPerPtBin; //!
Double_t RHO;
Double_t fMult;
Double_t fZ;
Double_t fLHPt;
Double_t fJetPt;
Int_t fbookingsize = 7;
double fPtHardMin;
double fPtHardMax;
Bool_t TagThisEvent[5];
AliJFJTask *fJFJTask;
TString fJFJTaskName;
ClassDef(AliAnalysisTaskGenMCRidge, 1);
};
#endif
|
cliffano/jenkins-api-clients-generator
|
clients/c/generated/model/github_repositorypermissions.h
|
/*
* github_repositorypermissions.h
*
*
*/
#ifndef _github_repositorypermissions_H_
#define _github_repositorypermissions_H_
#include <string.h>
#include "../external/cJSON.h"
#include "../include/list.h"
#include "../include/keyValuePair.h"
#include "../include/binary.h"
typedef struct github_repositorypermissions_t github_repositorypermissions_t;
typedef struct github_repositorypermissions_t {
int admin; //boolean
int push; //boolean
int pull; //boolean
char *_class; // string
} github_repositorypermissions_t;
github_repositorypermissions_t *github_repositorypermissions_create(
int admin,
int push,
int pull,
char *_class
);
void github_repositorypermissions_free(github_repositorypermissions_t *github_repositorypermissions);
github_repositorypermissions_t *github_repositorypermissions_parseFromJSON(cJSON *github_repositorypermissionsJSON);
cJSON *github_repositorypermissions_convertToJSON(github_repositorypermissions_t *github_repositorypermissions);
#endif /* _github_repositorypermissions_H_ */
|
FranicevicNikola/OOP
|
FER/Exams-master/2019_20/AutumnExam_2019_20-09-04-IR_3/solved/src/main/java/hr/fer/oop/task2/Main.java
|
<reponame>FranicevicNikola/OOP<filename>FER/Exams-master/2019_20/AutumnExam_2019_20-09-04-IR_3/solved/src/main/java/hr/fer/oop/task2/Main.java
package hr.fer.oop.task2;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class Main {
public static void main(String[] args) throws IOException {
CustomFileVisitor visitor1 = new CustomFileVisitor();
Files.walkFileTree(Paths.get("."), visitor1);
System.out.println(visitor1.toString());
Files.walkFileTree(Paths.get("."), new CustomFileVisitor2());
}
}
|
IamRaviTejaG/rubocop
|
lib/rubocop/cop/lint/duplicate_require.rb
|
<reponame>IamRaviTejaG/rubocop
# frozen_string_literal: true
module RuboCop
module Cop
module Lint
# This cop checks for duplicate `require`s and `require_relative`s.
#
# @example
# # bad
# require 'foo'
# require 'bar'
# require 'foo'
#
# # good
# require 'foo'
# require 'bar'
#
# # good
# require 'foo'
# require_relative 'foo'
#
class DuplicateRequire < Base
MSG = 'Duplicate `%<method>s` detected.'
REQUIRE_METHODS = Set.new(%i[require require_relative]).freeze
RESTRICT_ON_SEND = REQUIRE_METHODS
def_node_matcher :require_call?, <<~PATTERN
(send {nil? (const _ :Kernel)} %REQUIRE_METHODS _)
PATTERN
def on_new_investigation
# Holds the known required files for a given parent node (used as key)
@required = Hash.new { |h, k| h[k] = Set.new }.compare_by_identity
super
end
def on_send(node)
return unless require_call?(node)
return if @required[node.parent].add?("#{node.method_name}#{node.first_argument}")
add_offense(node, message: format(MSG, method: node.method_name))
end
end
end
end
end
|
beldenfox/LLGL
|
sources/Renderer/Direct3D12/D3D12ModuleInterface.cpp
|
/*
* D3D12ModuleInterface.h
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by <NAME>)
* See "LICENSE.txt" for license information.
*/
#include "../ModuleInterface.h"
#include "D3D12RenderSystem.h"
namespace LLGL
{
namespace ModuleDirect3D12
{
int GetRendererID()
{
return RendererID::Direct3D12;
}
const char* GetModuleName()
{
return "Direct3D12";
}
const char* GetRendererName()
{
return "Direct3D 12";
}
RenderSystem* AllocRenderSystem(const LLGL::RenderSystemDescriptor* /*renderSystemDesc*/)
{
return new D3D12RenderSystem();
}
} // /namespace ModuleDirect3D12
} // /namespace LLGL
#ifndef LLGL_BUILD_STATIC_LIB
extern "C"
{
LLGL_EXPORT int LLGL_RenderSystem_BuildID()
{
return LLGL_BUILD_ID;
}
LLGL_EXPORT int LLGL_RenderSystem_RendererID()
{
return LLGL::ModuleDirect3D12::GetRendererID();
}
LLGL_EXPORT const char* LLGL_RenderSystem_Name()
{
return LLGL::ModuleDirect3D12::GetRendererName();
}
LLGL_EXPORT void* LLGL_RenderSystem_Alloc(const void* /*renderSystemDesc*/)
{
return LLGL::ModuleDirect3D12::AllocRenderSystem(nullptr);
}
} // /extern "C"
#endif // /LLGL_BUILD_STATIC_LIB
// ================================================================================
|
lucgiffon/psm-nets
|
code/visualization/2020/09/5_6_compression_palm_act_objective_curves.py
|
<filename>code/visualization/2020/09/5_6_compression_palm_act_objective_curves.py
import pathlib
import random
import pandas as pd
from palmnet.visualization.utils import get_palminized_model_and_df, get_df
import matplotlib.pyplot as plt
import numpy as np
import logging
from collections import defaultdict
import plotly.graph_objects as go
import plotly.io as pio
mpl_logger = logging.getLogger('matplotlib')
mpl_logger.setLevel(logging.ERROR)
pio.templates.default = "plotly_white"
dataset = {
"Cifar10": "--cifar10",
"Cifar100": "--cifar100",
# "SVHN": "--svhn",
"MNIST": "--mnist"
}
models_data = {
"Cifar10": ["--cifar10-vgg19"],
# "Cifar100": ["--cifar100-resnet20", "--cifar100-resnet50"],
"Cifar100": ["--cifar100-vgg19", "--cifar100-resnet20", "--cifar100-resnet50"],
"SVHN": ["--svhn-vgg19"],
"MNIST":["--mnist-lenet"],
}
ylabel_task = {
"nb-param-compressed-total": "log(# non-zero value)",
"finetuned-score": "Accuracy",
"param-compression-rate-total": "Compression Rate"
}
scale_tasks = {
"nb-param-compressed-total": "log",
"finetuned-score": "linear",
"param-compression-rate-total": "linear"
}
def get_palm_results():
src_results_path = root_source_dir / results_path / "results.csv"
df = pd.read_csv(src_results_path, header=0)
df = df.fillna("None")
df = df.drop(columns=["Unnamed: 0", "idx-expe"]).drop_duplicates()
df = df.fillna("None")
df = df[df["nb-epochs"] == 1]
df = df[df["batch-size"] == 128]
return df
if __name__ == "__main__":
root_source_dir = pathlib.Path("/home/luc/PycharmProjects/palmnet/results/processed")
results_path = "2020/09/6_7_compression_palm_act"
root_output_dir = pathlib.Path("/home/luc/PycharmProjects/palmnet/reports/figures/")
output_dir = root_output_dir / results_path / "histo_compressions"
output_dir.mkdir(parents=True, exist_ok=True)
df = get_palm_results()
dct_config_color = {
"ACT K=3 Q=3": "navy",
"K=3 Q=3": "blue",
}
datasets = set(df["dataset"].values)
dct_table = dict()
for dataname in datasets:
df_data = df[df["dataset"] == dataname]
df_model_values = set(df_data["model"].values)
for modelname in df_model_values:
df_model = df_data[df_data["model"] == modelname]
dct_fig = defaultdict(lambda: go.Figure())
for idx_row, row in df_model.iterrows():
nb_iter_palm = row["nb-iteration-palm"]
objective_file_str = row["ouptut_file_objectives"]
train_percentage_size = f"{1 - float(row['train-val-split']):.2f}"
df_objectives = pd.read_csv(objective_file_str)
try:
layers = set(df_objectives["0"].values)
dct_objectives = {"2": "Batch objective",
# "3": "Val Objective"
}
except KeyError:
layers = set(df_objectives["layer_name"].values)
dct_objectives = {
"obj_batch": "Batch objective",
# "obj_val": "Val Objective"
}
for key_objective in dct_objectives.keys():
for layer in layers:
try:
df_objectives_layer = df_objectives[df_objectives["0"] == layer]
num_batches = df_objectives_layer["1"].values
except KeyError:
df_objectives_layer = df_objectives[df_objectives["layer_name"] == layer]
num_batches = df_objectives_layer["id_batch"].values
obj_values = df_objectives_layer[key_objective].values
name = f"{nb_iter_palm} PALM iterations {train_percentage_size}% train"
fig_name = "_".join(str(x) for x in [dataname, modelname, layer, dct_objectives[key_objective]])
fig = dct_fig[fig_name]
fig.add_trace(go.Scatter(name=name,
# x=num_batches, y=val_obj_values,
x=num_batches, y=obj_values,
# marker_color=dct_config_color[hover_text],
hovertext=name,
showlegend=True,
mode="lines"
))
replace_name_layer = lambda str_name: (str_name.replace("conv2d_", "Conv2D ").replace("dense_", "Dense ").replace("fc", "Dense ").replace("conv", "Conv2D"))
for fig_name, fig in dct_fig.items():
x_legend = 0
y_legend = -0.8
fig.update_layout(
barmode='group',
title=fig_name,
xaxis_title="Num batch",
yaxis_title="Valeur objectif",
# yaxis_type="log",
# xaxis_tickangle=-75,
# showlegend=True,
showlegend=True,
autosize=False,
margin=dict(l=20, r=20, t=20, b=20),
width=800,
height=400,
font=dict(
# family="Courier New, monospace",
size=12,
color="black"
),
legend_orientation="h",
legend=dict(
x=x_legend, y=y_legend,
traceorder="normal",
font=dict(
family="sans-serif",
size=18,
color="black"
),
# bgcolor="LightSteelBlue",
# bordercolor="Black",
borderwidth=1,
)
)
fig.update_xaxes(showline=True, ticks="outside", linewidth=2, linecolor='black', mirror=True)
fig.update_yaxes(showline=True, ticks="outside", linewidth=2, linecolor='black', mirror=True)
# fig.show()
fig.write_image(str((output_dir / fig_name).absolute()) + ".png")
|
linorallo/Product_Finder
|
backend/main_standalone.py
|
<filename>backend/main_standalone.py
import threading
from threading import *
try:
import Product_Finder.backend.amazon_v2 as amazon_v2
import Product_Finder.backend.newegg_scrapper as newegg_scrapper
import Product_Finder.backend.mercadolibre_scrapper as mercadolibre_scrapper
import Product_Finder.backend.sortResults as sortResults
import Product_Finder.backend.db as db
except:
import amazon_v2
import newegg_scrapper
import mercadolibre_scrapper
import sortResults
import db
import queue
class searchAmazon(Thread):
def __init__(self, threadID, name, counter, *args):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.args = args
def run(self) :
print('Amazon thread initiated...')
resultQueue = self.args[0][0]
searchParameters = self.args[0][1]
resultQueue.put(amazon_v2.searchInAmazon(searchParameters[0],searchParameters[1],searchParameters[2],searchParameters[3],searchParameters[4], ))
class searchNewegg(Thread):
def __init__(self, threadID, name, counter, *args):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.args = args
def run(self) :
print('Newegg thread initiated...')
resultQueue = self.args[0][0]
searchParameters = self.args[0][1]
resultQueue.put(newegg_scrapper.searchInNewegg(searchParameters[0],searchParameters[1],searchParameters[2],searchParameters[3],searchParameters[4], ))
class searchMercadoLibre(Thread):
def __init__(self, threadID, name, counter, *args):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.args = args
def run(self) :
print('Mercado_libre thread initiated...')
resultQueue = self.args[0][0]
searchParameters = self.args[0][1]
resultQueue.put(mercadolibre_scrapper.searchInMercadoLibre(searchParameters[0],searchParameters[1],searchParameters[2],searchParameters[3],searchParameters[4], ))
print('------------------------------')
searchList = []
blockWords = []
print('Enter to coninue')
while True :
searchString = str(input('SEARCH: '))
if searchString == '' :
break
else :
searchList.append(searchString)
continue
choiceBlockWords=searchChoice=''
while True :
choiceBlockWords = input('Want to block some not related results? y/n ')
if choiceBlockWords.capitalize() == ('Y') :
print('Press enter to continue')
while True :
blockWordInput = input('->')
if blockWordInput == '' :
break
else :
blockWords.append(blockWordInput)
if blockWordInput == '' :
break
elif choiceBlockWords.capitalize() == 'N' :
break
else :
continue
#MAKE SEARCH START IN DATABASE AND THEN ASK IF SHOULD EXTEND IT ONLINE
print('Choose 1 for DataBase search or 2 for new Online search: ')
while True :
searchChoice = int(input('Selection: '))
if searchChoice == 1 :
break
elif searchChoice == 2:
break
else :
continue
if searchChoice == 1 :
print('Search initiated... (implement animation)')
results = db.readFromDB(searchList, blockWords)
for result in results :
sortResults.sortIncreasing(results)
while True :
extendOnlineChoice = input('Would you like to exten the search online? y/n ')
if extendOnlineChoice.capitalize() == 'Y' :
searchChoice = 2
break
elif extendOnlineChoice.capitalize() == 'N' :
break
else :
continue
if searchChoice == 2 :
sortPreference = 'Increasing'
currency = 'USD'
searchString = ''
for searchWord in searchList :
searchString = searchString + searchWord + ' '
searchPageDepth = int(input('How many pages deep should i go? '))
choiceAmazon=choiceNewegg=choiceML=''
print('----- New Product Search -----')
results = []
searchParameters=[searchString,blockWords,searchPageDepth, sortPreference,currency]
outputQ = queue.Queue()
while True :
choiceAmazon = input('Search in Amazon? y/n ').capitalize()
if choiceAmazon == 'Y' :
amazonThread = searchAmazon(1,'amazonThread',1,([outputQ,searchParameters]))
amazonThread.start()
break
elif choiceAmazon == 'N' :
break
else :
continue
while True :
choiceNewegg = input('Search in Newegg? y/n ').capitalize()
if choiceNewegg == 'Y' :
neweggThread = searchNewegg(1,'neweggThread',1,([outputQ,searchParameters]))
neweggThread.start()
break
elif choiceNewegg == 'N' :
break
else :
continue
while True :
choiceML = input('Search in Mercado Libre? y/n ').capitalize()
if choiceML == 'Y' :
mercadolibreThread = searchMercadoLibre(1,'mercadolibreThread',1,([outputQ,searchParameters]))
mercadolibreThread.start()
break
elif choiceML == 'N' :
break
else :
continue
print('Search initiated... (implement animation)')
choiceAll =''
if choiceAll =='all':
while True:
if amazonThread.is_alive() == False :
amazonThreadStatus = False
else:
amazonThreadStatus = True
if neweggThread.is_alive() == False :
neweggThreadStatus = False
else:
neweggThreadStatus = True
if mercadolibreThread.is_alive() == False :
mercadolibreThreadStatus = False
else:
mercadolibreThreadStatus = True
if amazonThreadStatus == False :
if neweggThreadStatus == False :
if mercadolibreThreadStatus == False:
break
if choiceAmazon =='Y':
while True:
if amazonThread.is_alive() == False :
amazonThreadStatus = False
else:
amazonThreadStatus = True
if amazonThreadStatus ==False :
break
if choiceNewegg == 'Y':
while True:
if neweggThread.is_alive() == False :
neweggThreadStatus = False
else:
neweggThreadStatus = True
if neweggThreadStatus ==False:
break
if choiceML == 'Y':
while True:
if mercadolibreThread.is_alive() == False :
mercadolibreThreadStatus = False
else:
mercadolibreThreadStatus = True
if mercadolibreThreadStatus ==False:
break
print('All threads closed')
results = []
queue_length = outputQ.qsize()
for x in range(queue_length):
results = results + outputQ.get()
print('result"s lengt: ' + str(len(results)))
results = sortResults.sortIncreasing(results)
db.saveToDB(results)
quantityShow = int(input('How many items do you wish to see? '))
print('-------------RESULTS------------------')
orderItem = 0
for result in results :
orderItem+=1
print(str(orderItem)+'- $'+ str(result[1]) +' / -'+ result[4] +'% ' + result[2] + ' ; ' + result[3])
if quantityShow == orderItem :
print("***That's it***")
break
|
hydra3333/NVEnc
|
NVEncCore/rgy_timecode.cpp
|
// -----------------------------------------------------------------------------------------
// QSVEnc/NVEnc by rigaya
// -----------------------------------------------------------------------------------------
// The MIT License
//
// Copyright (c) 2019 rigaya
//
// 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.
//
// --------------------------------------------------------------------------------------------
#include "rgy_timecode.h"
RGY_ERR RGYTimecode::init(const tstring &filename) {
FILE *filep = nullptr;
if (_tfopen_s(&filep, filename.c_str(), _T("w")) != 0 || filep == nullptr) {
return RGY_ERR_FILE_OPEN;
}
fp.reset(filep);
fprintf(fp.get(), "# timecode format v2\n");
return RGY_ERR_NONE;
}
void RGYTimecode::write(int64_t timestamp, rgy_rational<int> timebase) {
fprintf(fp.get(), "%.6lf\n", (double)timestamp * timebase.qdouble() * 1000.0);
fflush(fp.get());
}
|
edkennard/diffa
|
kernel/src/test/scala/net/lshift/diffa/kernel/StoreReferenceContainer.scala
|
<reponame>edkennard/diffa<gh_stars>0
package net.lshift.diffa.kernel
import actors.IncrementingIdProvider
import config._
import config.Member
import config.system.JooqSystemConfigStore
import config.User
import differencing.JooqDomainDifferenceStore
import org.hibernate.dialect.Dialect
import org.slf4j.LoggerFactory
import preferences.JooqUserPreferencesStore
import scanning.JooqScanActivityStore
import util.cache.HazelcastCacheProvider
import util.MissingObjectException
import org.hibernate.SessionFactory
import net.lshift.diffa.schema.hibernate.SessionHelper.sessionFactoryToSessionHelper
import net.lshift.diffa.schema.cleaner.SchemaCleaner
import net.lshift.diffa.schema.environment.{DatabaseEnvironment, TestDatabaseEnvironments}
import net.lshift.diffa.schema.migrations.HibernateConfigStorePreparationStep
import collection.JavaConversions._
import com.jolbox.bonecp.BoneCPDataSource
import net.lshift.diffa.schema.jooq.DatabaseFacade
import scala.Some
import net.lshift.diffa.snowflake.IdProvider
import org.jooq.impl.Factory
object StoreReferenceContainer {
def withCleanDatabaseEnvironment(env: DatabaseEnvironment) = {
val stores = new LazyCleanStoreReferenceContainer(env)
stores.prepareEnvironmentForStores
stores
}
}
/**
* Maintains references to Store objects used in testing and provides an
* interface for simple initialisation of their configuration.
*/
trait StoreReferenceContainer {
private val logger = LoggerFactory.getLogger(getClass)
def sessionFactory: SessionFactory
def facade: DatabaseFacade
def dialect: Dialect
def systemConfigStore: JooqSystemConfigStore
def domainConfigStore: JooqDomainConfigStore
def domainDifferenceStore: JooqDomainDifferenceStore
def serviceLimitsStore: ServiceLimitsStore
def prepareEnvironmentForStores: Unit
def clearUserConfig {}
def clearConfiguration(space: Long) {
try {
serviceLimitsStore.deletePairLimitsByDomain(space)
domainDifferenceStore.removeDomain(space)
serviceLimitsStore.deleteDomainLimits(space)
systemConfigStore.deleteSpace(space)
} catch {
case e: MissingObjectException => {
logger.warn("Could not clear configuration for domain " + space)
}
}
}
def defaultDomain = "domain"
def defaultUser = "guest"
def tearDown: Unit
}
/**
* A Store reference container that also implements initialisation of the associated environment.
*/
class LazyCleanStoreReferenceContainer(val applicationEnvironment: DatabaseEnvironment) extends StoreReferenceContainer {
private val log = LoggerFactory.getLogger(getClass)
private val applicationConfig = applicationEnvironment.getHibernateConfigurationWithoutMappingResources.
setProperty("hibernate.generate_statistics", "true").
setProperty("hibernate.connection.autocommit", "true") // Turn this on to make the tests repeatable,
// otherwise the preparation step will not get committed
val dialect = Dialect.getDialect(applicationConfig.getProperties)
private var _sessionFactory: Option[SessionFactory] = None
private var _ds: Option[BoneCPDataSource] = None
private val membershipListener = new DomainMembershipAware {
def onMembershipCreated(member: Member) {}
def onMembershipRemoved(member: Member) {}
}
private def cacheProvider = new HazelcastCacheProvider
private val idProvider = IncrementingIdProvider
def sessionFactory = _sessionFactory.getOrElse {
throw new IllegalStateException("Failed to initialize environment before using SessionFactory")
}
def ds = _ds.getOrElse {
throw new IllegalStateException("Failed to initialize environment before using DataSource")
}
private def makeStore[T](consFn: SessionFactory => T, className: String): T = _sessionFactory match {
case Some(sf) =>
consFn(sf)
case None =>
throw new IllegalStateException("Failed to initialize environment before using " + className)
}
private lazy val _jooqDatabaseFacade = new DatabaseFacade(ds, applicationEnvironment.jooqDialect)
private lazy val _serviceLimitsStore =
makeStore[ServiceLimitsStore](sf => new JooqServiceLimitsStore(facade), "ServiceLimitsStore")
private lazy val _domainConfigStore =
makeStore(sf => new JooqDomainConfigStore(facade, cacheProvider, idProvider, membershipListener), "domainConfigStore")
private lazy val _systemConfigStore =
makeStore(sf => {
val store = new JooqSystemConfigStore(facade, cacheProvider, idProvider)
store.registerDomainEventListener(_domainConfigStore)
store
}, "SystemConfigStore")
private lazy val _domainCredentialsStore =
makeStore(sf => new JooqDomainCredentialsStore(facade), "domainCredentialsStore")
private lazy val _userPreferencesStore =
makeStore(sf => new JooqUserPreferencesStore(facade, cacheProvider), "userPreferencesStore")
private lazy val _domainDifferenceStore =
makeStore(sf => new JooqDomainDifferenceStore(facade, cacheProvider, idProvider), "DomainDifferenceStore")
private lazy val _scanActivityStore =
makeStore(sf => new JooqScanActivityStore(facade), "scanActivityStore")
def facade = _jooqDatabaseFacade
def serviceLimitsStore: ServiceLimitsStore = _serviceLimitsStore
def systemConfigStore: JooqSystemConfigStore = _systemConfigStore
def domainConfigStore: JooqDomainConfigStore = _domainConfigStore
def domainCredentialsStore: JooqDomainCredentialsStore = _domainCredentialsStore
def domainDifferenceStore: JooqDomainDifferenceStore = _domainDifferenceStore
def userPreferencesStore: JooqUserPreferencesStore = _userPreferencesStore
def scanActivityStore: JooqScanActivityStore = _scanActivityStore
def executeWithFactory[T](fn: Factory => T) = facade.execute(fn(_))
def prepareEnvironmentForStores {
performCleanerAction(cleaner => cleaner.clean)
_sessionFactory = Some(applicationConfig.buildSessionFactory)
_sessionFactory foreach { sf =>
(new HibernateConfigStorePreparationStep).prepare(sf, applicationConfig)
log.info("Schema created")
}
_ds = Some({
val ds = new BoneCPDataSource()
ds.setJdbcUrl(applicationEnvironment.url)
ds.setUsername(applicationEnvironment.username)
ds.setPassword(<PASSWORD>)
ds.setDriverClass(applicationEnvironment.driver)
ds
})
}
def tearDown {
log.debug("Dropping test schema")
// This is a bit of a hack, but basically what is happening is that we are connecting to the DB as a DBA and
// are nuking the user session on the server side, hence the client side data source (and Hibernate session factory)
// will be toast
try {
_ds.get.close()
} catch {
case x => {
log.warn("Could not close data source", x)
}
}
try {
_sessionFactory.get.close()
} catch {
case x => {
log.warn("Could not close sessionFactory", x)
}
}
_sessionFactory = None
_ds = None
try {
performCleanerAction(cleaner => cleaner.drop)
} catch {
case _ =>
}
}
private def performCleanerAction(action: SchemaCleaner => (DatabaseEnvironment, DatabaseEnvironment) => Unit) {
val sysEnv = TestDatabaseEnvironments.adminEnvironment
val dialect = Dialect.getDialect(sysEnv.getHibernateConfigurationWithoutMappingResources.getProperties)
val cleaner = SchemaCleaner.forDialect(dialect)
try {
action(cleaner)(sysEnv, applicationEnvironment)
} catch {
case ex: Exception =>
log.info("Failed to clean schema %s".format(applicationEnvironment.username))
throw ex
}
}
override def clearUserConfig {
_sessionFactory.get.withSession(s =>
s.createCriteria(classOf[User]).list.filterNot {
case u: User => u.name == "guest"
}.foreach(s.delete(_))
)
}
}
|
mingpz2010/PhysicsThinker
|
include/common/pairwise_sum.h
|
<reponame>mingpz2010/PhysicsThinker
// MIT License
//
// Copyright (c) 2021 PingzhouMing
//
// 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.
#ifndef _PAIRWISE_SUM_H_
#define _PAIRWISE_SUM_H_ 1
//
// 2D MOC neutron transport calculation
// Implement and modification base on the : https://github.com/mit-crpg/OpenMOC
//
#include <cmath>
/**
* @file pairwise_sum.h
* @brief Utility function for the accurate pairwise sum of a list of floating
* point numbers.
* @author <NAME> (<EMAIL>)
* @date June 13, 2013
*/
/**
* @brief Performs a pairwise sum of an array of numbers.
* @details This type of summation uses a divide-and-conquer algorithm which
* is necessary to bound the error for summations of large sequences
* of numbers.
* @param vector an array of numbers
* @param length the length of the array
* @return the sum of all numbers in the array
*/
template <typename T>
inline T pairwise_sum(T* vector, int length)
{
T sum = 0;
/* Base case: if length is less than 16, perform summation */
if (length < 16) {
#pragma simd reduction(+:sum)
for (int i=0; i < length; i++)
sum += vector[i];
}
else {
int offset = length % 2;
length = floor(length / 2);
sum = pairwise_sum<T>(&vector[0], length) +
pairwise_sum<T>(&vector[length], length+offset);
}
return sum;
}
#endif
|
chrisphe/fabric3-core
|
extension/core/fabric3-channel-impl/src/main/java/org/fabric3/channel/runtime/ChannelContextTargetAttacher.java
|
/*
* Fabric3
* Copyright (c) 2009-2015 Metaform 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
*
* 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.
* Portions originally based on Apache Tuscany 2007
* licensed under the Apache 2.0 license.
*/
package org.fabric3.channel.runtime;
import java.util.function.Supplier;
import org.fabric3.api.annotation.wire.Key;
import org.fabric3.api.host.Fabric3Exception;
import org.fabric3.channel.provision.ChannelContextWireTarget;
import org.fabric3.spi.container.builder.TargetWireAttacher;
import org.fabric3.spi.container.channel.ChannelResolver;
import org.oasisopen.sca.annotation.EagerInit;
import org.oasisopen.sca.annotation.Reference;
/**
*
*/
@EagerInit
@Key("org.fabric3.channel.provision.ChannelContextWireTarget")
public class ChannelContextTargetAttacher implements TargetWireAttacher<ChannelContextWireTarget> {
private ChannelResolver channelResolver;
public ChannelContextTargetAttacher(@Reference ChannelResolver channelResolver) {
this.channelResolver = channelResolver;
}
public Supplier<?> createSupplier(ChannelContextWireTarget target) throws Fabric3Exception {
return () -> new ChannelContextImpl(target.getChannelName(), channelResolver);
}
}
|
MiCHiLU/google_appengine_sdk
|
lib/PyAMF-0.7.2/pyamf/adapters/_django_utils_translation.py
|
<filename>lib/PyAMF-0.7.2/pyamf/adapters/_django_utils_translation.py<gh_stars>10-100
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
C{django.utils.translation} adapter module.
@see: U{Django Project<http://www.djangoproject.com>}
@since: 0.4.2
"""
from django.utils.translation import ugettext_lazy
import pyamf
def convert_lazy(l, encoder=None):
try:
if l.__class__._delegate_text:
return unicode(l)
except AttributeError:
if l.__class__._delegate_unicode:
return unicode(l)
if l.__class__._delegate_str:
return str(l)
raise ValueError('Don\'t know how to convert lazy value %s' % (repr(l),))
pyamf.add_type(type(ugettext_lazy('foo')), convert_lazy)
|
fugashy/fgs_opt
|
fgs_ceres_playground/include/fgs_ceres_playground/optimization_context.hpp
|
#ifndef FGS_CERES_PLAYGROUND_OPTIMIZATION_CONTEXT_HPP_
#define FGS_CERES_PLAYGROUND_OPTIMIZATION_CONTEXT_HPP_
#include <memory>
#include <ceres/ceres.h>
#include "fgs_ceres_playground/cv_viz.hpp"
#include "fgs_ceres_playground/data.hpp"
#include "fgs_ceres_playground/bundle_adjustment_in_the_large.hpp"
namespace fgs {
namespace ceres_playground {
class OptimizationContext {
public:
virtual ~OptimizationContext() {}
using Ptr = std::shared_ptr<OptimizationContext>;
virtual void Solve(ceres::Solver::Options& options) = 0;
};
template<class ResidualType>
class FittingContext : public OptimizationContext {
public:
FittingContext(const std::string& cv_storage_path) {
cv::FileStorage fs(cv_storage_path, cv::FileStorage::READ);
cv::Mat data;
fs["data"] >> data;
if (data.empty()) {
throw std::runtime_error("data is empty");
}
param_.Init(100.0);
typename ResidualType::DataArrayType data_array;
ResidualType::DataType::CvToDataArray(data, data_array);
for (auto it = data_array.begin(); it != data_array.end(); ++it) {
problem_.AddResidualBlock(ResidualType::Create(*it), NULL, ¶m_[0]);
}
}
virtual void Solve(ceres::Solver::Options& options) {
std::cout << "Before" << std::endl;
ResidualType::ShowParam(param_);
ceres::Solver::Summary summary;
ceres::Solve(options, &problem_, &summary);
std::cout << "After" << std::endl;
ResidualType::ShowParam(param_);
}
private:
typename ResidualType::ParameterType param_;
ceres::Problem problem_;
};
// opencv vizをインストールするまで封印
//template<class ResidualType>
//class BALContext : public OptimizationContext {
// public:
// BALContext(const std::string& cv_storage_path) :
// problem_source_(new BundleAdjustmentInTheLarge(cv_storage_path)) {
// for (int i = 0; i < problem_source_->observations_num(); ++i) {
// const cv::Mat data = problem_source_->observation_data(i);
// double* camera_parameter = problem_source_->param_associated_with_obs(
// i, BundleAdjustmentInTheLarge::Item::Camera);
// double* point = problem_source_->param_associated_with_obs(
// i, BundleAdjustmentInTheLarge::Item::Point);
// ceres::CostFunction* cf = ResidualType::Create(data);
// problem_.AddResidualBlock(cf, NULL, camera_parameter, point);
// }
// }
//
// virtual void Solve(ceres::Solver::Options& options) {
// CVBALVisualizer viz(problem_source_, "BAL");
// viz.AddNoise(0.0, 0.1);
// viz.Show();
//
// ceres::Solver::Summary summary;
// ceres::Solve(options, &problem_, &summary);
//
// viz.Show();
// }
//
// private:
// std::shared_ptr<BundleAdjustmentInTheLarge> problem_source_;
// ceres::Problem problem_;
//};
}
}
#endif
|
Faradey27/wix-style-react
|
src/MessageBox/MessageBoxFunctionalLayout.js
|
import React from 'react';
import PropTypes from 'prop-types';
import HeaderLayout from './HeaderLayout';
import FooterLayout from './FooterLayout';
import WixComponent from '../BaseComponents/WixComponent';
import classNames from 'classnames';
import styles from './MessageBoxFunctionalLayout.scss';
class MessageBoxFunctionalLayout extends WixComponent {
render() {
const {
title,
onCancel,
onOk,
onClose,
confirmText,
cancelText,
children,
buttonsHeight,
hideFooter,
footerBottomChildren,
theme,
closeButton,
disableConfirmation,
disableCancel,
width,
noBodyPadding
} = this.props;
return (
<div className={styles.content} style={{width}}>
<HeaderLayout title={title} onCancel={onClose ? onClose : onCancel} theme={theme} closeButton={closeButton}/>
<div className={classNames(styles.body, noBodyPadding ? styles.noPadding : styles.withPadding)} data-hook="message-box-body">
{children}
</div>
{
!hideFooter ?
<FooterLayout bottomChildren={footerBottomChildren} enableCancel={!disableCancel} enableOk={!disableConfirmation} buttonsHeight={buttonsHeight} confirmText={confirmText} cancelText={cancelText} onCancel={onCancel} onOk={onOk} theme={theme}/> : null
}
</div>
);
}
}
MessageBoxFunctionalLayout.propTypes = {
hideFooter: PropTypes.bool,
confirmText: PropTypes.node,
cancelText: PropTypes.node,
theme: PropTypes.string,
onOk: PropTypes.func,
onCancel: PropTypes.func,
onClose: PropTypes.func,
width: PropTypes.string,
title: PropTypes.node,
children: PropTypes.any,
buttonsHeight: PropTypes.string,
closeButton: PropTypes.bool,
disableCancel: PropTypes.bool,
disableConfirmation: PropTypes.bool,
noBodyPadding: PropTypes.bool,
footerBottomChildren: PropTypes.node
};
MessageBoxFunctionalLayout.defaultProps = {
buttonsHeight: 'small',
disableCancel: false,
disableConfirmation: false,
width: '600px',
noBodyPadding: false
};
export default MessageBoxFunctionalLayout;
|
Maximus5/git-bug-1
|
src/Setup/Setupper/VersionI.h
|
#define CONEMUVERN 15,4,20,0
#define CONEMUVERS "150420"
#define CONEMUVERL L"150420"
#define MSI86 "../ConEmu.150420.x86.msi"
#define MSI64 "../ConEmu.150420.x64.msi"
|
MotiejusJuodelis/intellij-scala
|
scala/scala-impl/test/org/jetbrains/plugins/scala/javaHighlighting/JavaHighlightingLiteralTypesTest.scala
|
<gh_stars>0
package org.jetbrains.plugins.scala.javaHighlighting
import org.jetbrains.plugins.scala.{ScalaVersion, Scala_2_13}
class JavaHighlightingLiteralTypesTest extends JavaHighlightingTestBase {
override protected def supportedIn(version: ScalaVersion) = version >= Scala_2_13
def testSCL15897(): Unit = {
val scala =
"""
|object Test {
| def a(): 123 = 123
|}
|""".stripMargin
val java =
"""
|public class JavaTest {
| public static void main(String[] args) {
| int a = Test.a();
| }
|}
|""".stripMargin
assertNothing(errorsFromJavaCode(scala, java, "JavaTest"))
}
}
|
AlexandrBasan/alex_basan_portfolio
|
app/models/blog.rb
|
class Blog < ActiveRecord::Base
default_scope -> { order('created_at DESC') }
validates :title, presence: true, length: {minimum: 6}
validates :content, presence: true, length: {minimum: 20}
end
|
barsgroup/m3-ext
|
src/m3_ext/static/m3/js/ext-extensions/LockingGridColumnWithHeaderGroup.js
|
Ext.ns('Ext.ux.grid');
Ext.ux.grid.LockingGridColumnWithHeaderGroup = Ext.extend(Ext.util.Observable, {
constructor: function (config) {
this.config = config;
},
init: function (grid) {
if (!grid instanceof Ext.grid.GridPanel) {
return;
}
if (!grid.getStore() instanceof Ext.data.GroupingStore) {
return;
}
Ext.applyIf(grid.colModel, this.columnModelConfig);
Ext.apply(grid.colModel, this.config.columnModelCfg);
Ext.apply(grid.colModel, this.columnModelFunctions);
Ext.applyIf(grid.getView(), this.viewConfig);
Ext.apply(grid.getView(), this.config.viewCfg);
Ext.apply(grid.getView(), this.viewFunctions);
grid.colModel.prepareHdRows.call(grid.colModel);
},
columnModelFunctions: {
/**
* Returns true if the given column index is currently locked
* @param {Number} colIndex The column index
* @return {Boolean} True if the column is locked
*/
isLocked: function (colIndex) {
return this.config[colIndex].locked === true;
},
isLockedHdGroup: function (rowIndex, groupIndex) {
return this.rows[rowIndex][groupIndex].locked === true;
},
/**
* Locks or unlocks a given column
* @param {Number} colIndex The column index
* @param {Boolean} value True to lock, false to unlock
* @param {Boolean} suppressEvent Pass false to cause the columnlockchange event not to fire
*/
setLocked: function (colIndex, value, suppressEvent) {
if (this.isLocked(colIndex) == value) {
return;
}
this.config[colIndex].locked = value;
if (!suppressEvent) {
this.fireEvent('columnlockchange', this, colIndex, value);
}
},
setLockedHdGroup: function (rowIndex, groupIndex, value) {
if (this.isLockedHdGroup(rowIndex, groupIndex) == value) {
return;
}
this.rows[rowIndex][groupIndex].locked = value;
},
/**
* Returns the total width of all locked columns
* @return {Number} The width of all locked columns
*/
getTotalLockedWidth: function () {
var totalWidth = 0;
for (var i = 0, len = this.config.length; i < len; i++) {
if (this.isLocked(i) && !this.isHidden(i)) {
totalWidth += this.getColumnWidth(i);
}
}
return totalWidth;
},
/**
* Returns the total number of locked columns
* @return {Number} The number of locked columns
*/
getLockedCount: function () {
var len = this.config.length;
for (var i = 0; i < len; i++) {
if (!this.isLocked(i)) {
return i;
}
}
//if we get to this point all of the columns are locked so we return the total
return len;
},
getLockedHdGroupCount: function (rowIndex) {
var row = this.rows[rowIndex],
len = row.length;
for (var i = 0; i < len; i++) {
if (!this.isLockedHdGroup(rowIndex, i)) {
return i;
}
}
return len;
},
/**
* Moves a column from one position to another
* @param {Number} oldIndex The current column index
* @param {Number} newIndex The destination column index
*/
moveColumn: function (oldIndex, newIndex) {
var oldLocked = this.isLocked(oldIndex),
newLocked = this.isLocked(newIndex);
if (oldIndex < newIndex && oldLocked && !newLocked) {
this.setLocked(oldIndex, false, true);
} else if (oldIndex > newIndex && !oldLocked && newLocked) {
this.setLocked(oldIndex, true, true);
}
Ext.grid.ColumnModel.prototype.moveColumn.apply(this, arguments);
},
processLockingHdGroups: function (colIndex) {
var rows = this.rows,
pos = [],
newColIndex,
lockedCount_0 = this.getLockedHdGroupCount(0);
if (lockedCount_0 > 0) {
this.getHdGroupsPositionsToMovie(colIndex, 0, 0, lockedCount_0 - 1, pos, false);
} else {
for (var j = 0; j < rows.length; j++) {
pos[j] = 0;
}
}
for (var i = 0; i < rows.length; i++) {
var lockingGroupIndex = this.findHdGroupIndex(colIndex, i),
lockedLen = this.getLockedHdGroupCount(i),
group = rows[i][lockingGroupIndex];
if (i == rows.length - 1) {
newColIndex = this.getBeforeHdGroupColCount(i, pos[i]);
}
this.setLockedHdGroup(i, lockingGroupIndex, true);
if (group.colspan == 1) {
//переносим полностью
this.moveHdGroup(i, lockingGroupIndex, pos[i]);
}
else {
//делим группу
var newgroup = {};
Ext.apply(newgroup, group);
newgroup.colspan = group.colspan - 1;
newgroup.locked = false;
group.colspan = 1;
this.moveHdGroup(i, lockingGroupIndex, pos[i], newgroup);
}
}
this.joinHdGroups();
return newColIndex;
},
processUnLockingHdGroups: function (colIndex) {
var rows = this.rows,
pos = [],
newColIndex,
lockedCount_0 = this.getLockedHdGroupCount(0);
if (lockedCount_0 < rows[0].length - 1) {
this.getHdGroupsPositionsToMovie(colIndex, 0, lockedCount_0, rows[0].length - 1, pos, true);
} else {
for (var j = 0; j < rows.length; j++) {
pos[j] = this.getLockedHdGroupCount(j);
}
}
for (var i = 0; i < rows.length; i++) {
var unLockingGrougIndex = this.findHdGroupIndex(colIndex, i),
lockedLen = this.getLockedHdGroupCount(i),
group = rows[i][unLockingGrougIndex];
this.setLockedHdGroup(i, unLockingGrougIndex, false);
if (group.colspan == 1) {
if (i == rows.length - 1) {
newColIndex = this.getBeforeHdGroupColCount(i, pos[i] - 1);
}
//переносим полностью
this.moveHdGroup(i, unLockingGrougIndex, pos[i] - 1);
}
else {
if (i == rows.length - 1) {
newColIndex = this.getBeforeHdGroupColCount(i, pos[i]);
}
//делим группу
var newgroup = {};
Ext.apply(newgroup, group);
newgroup.colspan = group.colspan - 1;
newgroup.locked = true;
group.colspan = 1;
this.moveHdGroup(i, unLockingGrougIndex, pos[i], newgroup);
}
}
this.joinHdGroups();
return newColIndex;
},
findHdGroupIndex: function (colIndex, rowIndex) {
var row = this.rows[rowIndex],
j = 0, colspan = 0;
while (j < row.length && colspan - 1 < colIndex) {
colspan += row[j].colspan;
j++;
}
return j - 1;
},
getHdGroupsPositionsToMovie: function (colIndex, rowIndex, leftIndex, rightIndex, resultArrayOfIndexes, paddingLeft) {
var currentGroupIndex = this.findHdGroupIndex(colIndex, rowIndex),
group = this.rows[rowIndex][currentGroupIndex],
newIndex;
for (var i = leftIndex; i <= rightIndex; i++) {
if (this.rows[rowIndex][i].id == group.id) {
//нашли группу с таким же идентификатором
if (paddingLeft) {
newIndex = i;
} else {
newIndex = i + 1;
}
resultArrayOfIndexes[resultArrayOfIndexes.length] = newIndex;
if (rowIndex + 1 < this.rows.length) {
var colCount = this.getBeforeHdGroupColCount(rowIndex, i),
leftIndex = this.findHdGroupIndex(colCount, rowIndex + 1),
rightIndex = this.findHdGroupIndex(colCount + this.rows[rowIndex][i].colspan - 1, rowIndex + 1);
this.getHdGroupsPositionsToMovie(colIndex, rowIndex + 1, leftIndex, rightIndex, resultArrayOfIndexes, paddingLeft);
}
return resultArrayOfIndexes;
}
}
if (paddingLeft) {
newIndex = leftIndex;
} else {
newIndex = rightIndex + 1;
}
resultArrayOfIndexes[resultArrayOfIndexes.length] = newIndex;
if (rowIndex + 1 < this.rows.length) {
var colCount = this.getBeforeHdGroupColCount(rowIndex, leftIndex),
colCount1 = this.getBeforeHdGroupColCount(rowIndex, rightIndex),
leftIndex = this.findHdGroupIndex(colCount, rowIndex + 1),
rightIndex = this.findHdGroupIndex(colCount1 + this.rows[rowIndex][rightIndex].colspan - 1, rowIndex + 1);
this.getHdGroupsPositionsToMovie(colIndex, rowIndex + 1, leftIndex, rightIndex, resultArrayOfIndexes, paddingLeft);
}
return resultArrayOfIndexes;
},
getBeforeHdGroupColCount: function (rowIndex, groupIndex) {
var colCount = 0;
for (var i = 0; i < groupIndex; i++) {
colCount += this.rows[rowIndex][i].colspan;
}
return colCount;
},
moveHdGroup: function (rowIndex, groupOldIndex, groupNewIndex, newGroup) {
var row = this.rows[rowIndex],
group = row[groupOldIndex];
if (groupOldIndex > groupNewIndex) {
var m = row.slice(0, groupNewIndex),
m1 = row.slice(groupNewIndex, groupOldIndex),
m2 = row.slice(groupOldIndex + 1, row.length);
if (newGroup) {
this.rows[rowIndex] = m.concat([group]).concat(m1).concat([newGroup]).concat(m2);
}
else {
this.rows[rowIndex] = m.concat([group]).concat(m1).concat(m2);
}
}
else if (groupOldIndex < groupNewIndex) {
if (newGroup) {
var m = row.slice(0, groupOldIndex),
m1 = row.slice(groupOldIndex + 1, groupNewIndex),
m2 = row.slice(groupNewIndex, row.length);
this.rows[rowIndex] = m.concat([newGroup]).concat(m1).concat([group]).concat(m2);
}
else {
var m = row.slice(0, groupOldIndex),
m1 = row.slice(groupOldIndex + 1, groupNewIndex + 1),
m2 = row.slice(groupNewIndex + 1, row.length);
this.rows[rowIndex] = m.concat(m1).concat([group]).concat(m2);
}
}
else if (newGroup) {
var m = row.slice(0, groupOldIndex),
m1 = row.slice(groupOldIndex + 1, row.length);
if (newGroup.locked) {
this.rows[rowIndex] = m.concat([newGroup]).concat([group]).concat(m1);
} else {
this.rows[rowIndex] = m.concat([group]).concat([newGroup]).concat(m1);
}
}
},
prepareHdRows: function () {
var columns = this.columns,
rows = this.rows,
lockedCount = this.lockedCount;
if (lockedCount) {
for (j = 0; j < lockedCount; j++) {
this.setLocked(j, true, true);
}
}
for (var i = 0; i < rows.length; i++) {
var row = rows[i],
colspan = 0,
j = 0;
//устанавливаем идентификаторы групп для дальнейшего объединения групп по этим идентификаторам
this.setHdGroupsId(i);
while (j < row.length && colspan < lockedCount) {
var group = row[j];
group.colspan = group.colspan || 1;
colspan += group.colspan;
var diff = colspan - lockedCount;
if (diff > 0) {
//делить группу
var m = row.slice(0, j + 1),
m1 = row.slice(j + 1, row.length),
newgroup = {};
Ext.apply(newgroup, group);
newgroup.colspan = diff;
group.colspan = group.colspan - diff;
this.setLockedHdGroup(i, j, true);
rows[i] = m.concat([newgroup]).concat(m1);
}
else {
//блокировать полностью
this.setLockedHdGroup(i, j, true);
}
j++;
}
}
},
setHdGroupsId: function (rowIndex) {
var row = this.rows[rowIndex];
for (var i = 0; i < row.length; i++) {
row[i].id = i;
}
},
joinHdGroups: function () {
var rows = this.rows;
for (var indexRow = rows.length - 1; indexRow >= 0; indexRow--) {
var row = rows[indexRow];
for (var indexCol = 0; indexCol < row.length - 1; indexCol++) {//- 1 берем парами
var groupCurent = row[indexCol];
var groupNext = row[indexCol + 1];
if ((groupCurent.header == groupNext.header)
&& (this.isLockedHdGroup(indexRow, indexCol) == this.isLockedHdGroup(indexRow, indexCol + 1))
&& (groupCurent.id == groupNext.id)) {
//Объединение
groupCurent.colspan += groupNext.colspan;
row.splice(indexCol + 1, 1);
}
}
}
}
},
columnModelConfig: {
/**
* lockedCount начальное количество блокированных столбцов
*/
lockedCount: 0,
/**
* rows строки с объединениями для построения многоуровневой шапки
*/
rows: [],
hierarchicalColMenu: true
},
viewConfig: {
//LockingView config****************************************************************
lockText: 'Lock',
unlockText: 'Unlock',
rowBorderWidth: 1,
lockedBorderWidth: 1,
/*
* This option ensures that height between the rows is synchronized
* between the locked and unlocked sides. This option only needs to be used
* when the row heights aren't predictable.
*/
syncHeights: false,
//GroupingView config*****************************************************************
/**
* @cfg {String} groupByText Text displayed in the grid header menu for grouping by a column
* (defaults to 'Group By This Field').
*/
groupByText: 'Group By This Field',
/**
* @cfg {String} showGroupsText Text displayed in the grid header for enabling/disabling grouping
* (defaults to 'Show in Groups').
*/
showGroupsText: 'Show in Groups',
/**
* @cfg {Boolean} hideGroupedColumn <tt>true</tt> to hide the column that is currently grouped (defaults to <tt>false</tt>)
*/
hideGroupedColumn: false,
/**
* @cfg {Boolean} showGroupName If <tt>true</tt> will display a prefix plus a ': ' before the group field value
* in the group header line. The prefix will consist of the <tt><b>{@link Ext.grid.Column#groupName groupName}</b></tt>
* (or the configured <tt><b>{@link Ext.grid.Column#header header}</b></tt> if not provided) configured in the
* {@link Ext.grid.Column} for each set of grouped rows (defaults to <tt>true</tt>).
*/
showGroupName: true,
/**
* @cfg {Boolean} startCollapsed <tt>true</tt> to start all groups collapsed (defaults to <tt>false</tt>)
*/
startCollapsed: false,
/**
* @cfg {Boolean} enableGrouping <tt>false</tt> to disable grouping functionality (defaults to <tt>true</tt>)
*/
enableGrouping: true,
/**
* @cfg {Boolean} enableGroupingMenu <tt>true</tt> to enable the grouping control in the column menu (defaults to <tt>true</tt>)
*/
enableGroupingMenu: true,
/**
* @cfg {Boolean} enableNoGroups <tt>true</tt> to allow the user to turn off grouping (defaults to <tt>true</tt>)
*/
enableNoGroups: true,
/**
* @cfg {String} emptyGroupText The text to display when there is an empty group value (defaults to <tt>'(None)'</tt>).
* May also be specified per column, see {@link Ext.grid.Column}.{@link Ext.grid.Column#emptyGroupText emptyGroupText}.
*/
emptyGroupText: '(None)',
/**
* @cfg {Boolean} ignoreAdd <tt>true</tt> to skip refreshing the view when new rows are added (defaults to <tt>false</tt>)
*/
ignoreAdd: false,
/**
* @cfg {String} groupTextTpl The template used to render the group header (defaults to <tt>'{text}'</tt>).
* This is used to format an object which contains the following properties:
* <div class="mdetail-params"><ul>
* <li><b>group</b> : String<p class="sub-desc">The <i>rendered</i> value of the group field.
* By default this is the unchanged value of the group field. If a <tt><b>{@link Ext.grid.Column#groupRenderer groupRenderer}</b></tt>
* is specified, it is the result of a call to that function.</p></li>
* <li><b>gvalue</b> : Object<p class="sub-desc">The <i>raw</i> value of the group field.</p></li>
* <li><b>text</b> : String<p class="sub-desc">The configured header (as described in <tt>{@link #showGroupName})</tt>
* if <tt>{@link #showGroupName}</tt> is <tt>true</tt>) plus the <i>rendered</i> group field value.</p></li>
* <li><b>groupId</b> : String<p class="sub-desc">A unique, generated ID which is applied to the
* View Element which contains the group.</p></li>
* <li><b>startRow</b> : Number<p class="sub-desc">The row index of the Record which caused group change.</p></li>
* <li><b>rs</b> : Array<p class="sub-desc">Contains a single element: The Record providing the data
* for the row which caused group change.</p></li>
* <li><b>cls</b> : String<p class="sub-desc">The generated class name string to apply to the group header Element.</p></li>
* <li><b>style</b> : String<p class="sub-desc">The inline style rules to apply to the group header Element.</p></li>
* </ul></div></p>
* See {@link Ext.XTemplate} for information on how to format data using a template. Possible usage:<pre><code>
var grid = new Ext.grid.GridPanel({
...
view: new Ext.grid.GroupingView({
groupTextTpl: '{text} ({[values.rs.length]} {[values.rs.length > 1 ? "Items" : "Item"]})'
}),
});
* </code></pre>
*/
groupTextTpl: '{text}',
/**
* @cfg {String} groupMode Indicates how to construct the group identifier. <tt>'value'</tt> constructs the id using
* raw value, <tt>'display'</tt> constructs the id using the rendered value. Defaults to <tt>'value'</tt>.
*/
groupMode: 'value',
/**
* @cfg {Function} groupRenderer This property must be configured in the {@link Ext.grid.Column} for
* each column.
*/
/**
* @cfg {Boolean} cancelEditOnToggle True to cancel any editing when the group header is toggled. Defaults to <tt>true</tt>.
*/
cancelEditOnToggle: true,
/**
* @cfg {Boolean} totalSummaryRowEnabled True to render total summary row. Defaults to <tt>true</tt>.
*/
totalSummaryEnabled: true
},
viewFunctions: {
initTemplates: function () {
Ext.grid.GridView.prototype.initTemplates.apply(this, arguments);
var ts = this.templates || {};
if (!ts.masterTpl) {
ts.masterTpl = new Ext.Template(
'<div class="x-grid3" hidefocus="true">',
'<div class="x-grid3-locked">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{lstyle}">{lockedHeader}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body" style="{lstyle}">{lockedBody}</div><div class="x-grid3-scroll-spacer"></div></div>',
'<div class="x-grid3-total-summary"><div class="x-grid3-total-summary-inner"><div class="x-grid3-total-summary-offset" style="{lstyle}">{lockedTotalSummary}</div></div><div class="x-clear"></div></div>',
'</div>',
'<div class="x-grid3-viewport x-grid3-unlocked">',
'<div class="x-grid3-header"><div class="x-grid3-header-inner"><div class="x-grid3-header-offset" style="{ostyle}">{header}</div></div><div class="x-clear"></div></div>',
'<div class="x-grid3-scroller"><div class="x-grid3-body" style="{bstyle}">{body}</div><a href="#" class="x-grid3-focus" tabIndex="-1"></a></div>',
'<div class="x-grid3-total-summary"><div class="x-grid3-total-summary-inner"><div class="x-grid3-total-summary-offset" style="{ostyle}">{totalSummary}</div></div><div class="x-clear"></div></div>',
'</div>',
'<div class="x-grid3-resize-marker"> </div>',
'<div class="x-grid3-resize-proxy"> </div>',
'</div>'
);
}
if (!ts.gcell) {
//ts.gcell = new Ext.XTemplate('<td class="x-grid3-hd x-grid3-gcell x-grid3-td-{id} ux-grid-hd-group-row-{row} {cls}" style="{style}">', '<div {tooltip} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a class="x-grid3-hd-btn" href="#"></a>' : '', '{value}</div></td>');
ts.gcell = new Ext.XTemplate('<td class="x-grid3-hd x-grid3-gcell x-grid3-td-{id} ux-grid-hd-group-row-{row} {cls}" style="{style}">', '<div {tooltip} class="x-grid3-hd-inner x-grid3-hd-{id}" unselectable="on" style="{istyle}">', this.grid.enableHdMenu ? '<a href="#"></a>' : '', '{value}</div></td>');
}
if (!ts.startGroup) {
ts.startGroup = new Ext.XTemplate(
'<div id="{groupId}" class="x-grid-group {cls}">',
'<div id="{groupId}-hd" class="x-grid-group-hd" style="{style}"><div class="x-grid-group-title">', this.groupTextTpl, '</div></div>',
'<div id="{groupId}-bd" class="x-grid-group-body">'
);
}
if (!ts.startLockedGroup) {
ts.startLockedGroup = new Ext.XTemplate(
'<div id="{groupId}-l" class="x-grid-group {cls}">',
'<div id="{groupId}-lhd" class="x-grid-group-hd" style="{style}"><div class="x-grid-group-title">', this.groupTextTpl, '</div></div>',
'<div id="{groupId}-lbd" class="x-grid-group-body">'
);
}
if (!ts.endGroup) {
ts.endGroup = '</div></div>';
}
if (!ts.summaryRow) {
ts.summaryRow = new Ext.Template(
'<div class="x-grid3-summary-row" style="{tstyle}">',
'<table class="x-grid3-summary-table" border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
'<tbody><tr>{cells}</tr></tbody>',
'</table></div>'
);
ts.summaryRow.disableFormats = true;
}
if (!ts.totalSummary) {
ts.totalSummary = new Ext.Template(
'<table border="0" cellspacing="0" cellpadding="0" style="{tstyle}">',
'<thead>',
'<tr class="x-grid3-total-summary-row x-grid3-hd-row">{cells}</tr>',
'</thead>',
'</table>'
);
}
if (!ts.totalSummaryCell) {
ts.totalSummaryCell = new Ext.XTemplate(
'<td class="x-grid3-hd x-grid3-total-td-{id} {css}" style="{style}">',
'<div {tooltip} class="x-grid3-cell-inner x-grid3-total-summary-cell-{id}" unselectable="on" style="{istyle}">',
'{value}</div></td>');
}
this.templates = ts;
this.hrowRe = new RegExp("ux-grid-hd-group-row-(\\d+)", "");
this.state = {};
var sm = this.grid.getSelectionModel();
sm.on(sm.selectRow ? 'beforerowselect' : 'beforecellselect',
this.onBeforeRowSelect, this);
},
initElements: function () {
var el = Ext.get(this.grid.getGridEl().dom.firstChild),
lockedWrap = el.child('div.x-grid3-locked'),
lockedHd = lockedWrap.child('div.x-grid3-header'),
lockedScroller = lockedWrap.child('div.x-grid3-scroller'),
lockedTotalSummary = lockedWrap.child('div.x-grid3-total-summary'),
mainWrap = el.child('div.x-grid3-viewport'),
mainHd = mainWrap.child('div.x-grid3-header'),
scroller = mainWrap.child('div.x-grid3-scroller'),
totalSummary = mainWrap.child('div.x-grid3-total-summary');
if (this.grid.hideHeaders) {
lockedHd.setDisplayed(false);
mainHd.setDisplayed(false);
}
if (this.totalSummaryEnabled !== true) {
lockedTotalSummary.setDisplayed(false);
totalSummary.setDisplayed(false);
}
if (this.forceFit) {
scroller.setStyle('overflow-x', 'hidden');
}
Ext.apply(this, {
el: el,
mainWrap: mainWrap,
mainHd: mainHd,
innerHd: mainHd.dom.firstChild,
scroller: scroller,
totalSummary: totalSummary,
totalSummaryInner: totalSummary.dom.firstChild,
mainBody: scroller.child('div.x-grid3-body'),
focusEl: scroller.child('a'),
resizeMarker: el.child('div.x-grid3-resize-marker'),
resizeProxy: el.child('div.x-grid3-resize-proxy'),
lockedWrap: lockedWrap,
lockedHd: lockedHd,
lockedScroller: lockedScroller,
lockedBody: lockedScroller.child('div.x-grid3-body'),
lockedInnerHd: lockedHd.child('div.x-grid3-header-inner', true),
lockedTotalSummary: lockedTotalSummary,
lockedTotalSummaryInner: lockedTotalSummary.dom.firstChild
});
this.focusEl.swallowEvent('click', true);
},
renderHeaders: function () {
var cm = this.cm,
rows = cm.rows,
ts = this.templates,
ct = ts.hcell,
headers = [],
lheaders = [],
clen = cm.getColumnCount(),
rlen = rows.length,
tstyle = 'width:' + this.getTotalWidth() + ';',
ltstyle = 'width:' + this.getLockedWidth() + ';';
for (var row = 0; row < rlen; row++) {
var r = rows[row], cells = [], lcells = [];
for (var i = 0, gcol = 0; i < r.length; i++) {
var group = r[i],
colIndex = group.dataIndex ? cm.findColumnIndex(group.dataIndex) : gcol;
group.colspan = group.colspan || 1;
if (cm.getColumnAt(colIndex) !== undefined) {
var id = this.getColumnId(colIndex),
gs = this.getGroupStyle(group, gcol);
gcol += group.colspan;
var htmlStr = ts.gcell.apply({
cls: 'ux-grid-hd-group-cell',
id: id,
row: row,
style: 'width:' + gs.width + ';' + (gs.hidden ? 'display:none;' : '') + (group.align ? 'text-align:' + group.align + ';' : ''),
tooltip: group.tooltip ? (Ext.QuickTips.isEnabled() ? 'ext:qtip' : 'title') + '="' + group.tooltip + '"' : '',
istyle: group.align == 'right' ? 'padding-right:16px' : '',
btn: this.grid.enableHdMenu && group.header,
value: group.header || ' '
});
if (cm.isLockedHdGroup(row, i)) {
lcells[lcells.length] = htmlStr;
}
else {
cells[cells.length] = htmlStr;
}
}
}
headers[row] = ts.header.apply({
tstyle: tstyle,
cells: cells.join('')
});
lheaders[row] = ts.header.apply({
tstyle: ltstyle,
cells: lcells.join('')
});
}
var cb = [], lcb = [];
for (var i = 0; i < clen; i++) {
if (cm.getColumnAt(i) === undefined) {
continue;
}
var p = {};
p.id = cm.getColumnId(i);
p.value = cm.getColumnHeader(i) || '';
p.style = this.getColumnStyle(i, true);
p.tooltip = this.getColumnTooltip(i);
p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == clen - 1 ? 'x-grid3-cell-last ' : '')) +
(cm.config[i].headerCls ? ' ' + cm.config[i].headerCls : '');
if (cm.config[i].align == 'right') {
p.istyle = 'padding-right:16px';
} else {
delete p.istyle;
}
if (cm.isLocked(i)) {
lcb[lcb.length] = ct.apply(p);
} else {
cb[cb.length] = ct.apply(p);
}
}
headers[rlen] = ts.header.apply({
tstyle: tstyle,
cells: cb.join('')
});
lheaders[rlen] = ts.header.apply({
tstyle: ltstyle,
cells: lcb.join('')
});
return [headers.join(''), lheaders.join('')];
},
renderTotalSummary: function () {
var columnModel = this.cm,
templates = this.templates,
cellTemplate = templates.totalSummaryCell,
rowTemplate = templates.totalSummary,
summaryCells = [],
lockedSummaryCells = [],
columnCount = columnModel.getColumnCount(),
tstyle = 'width:' + this.getTotalWidth() + ';',
ltstyle = 'width:' + this.getLockedWidth() + ';';
var columnData = this.getColumnData(),
dataSource = this.grid.store.allData ? this.grid.store.allData.items : this.grid.store.data.items,
summaryData = this.calculate(dataSource, columnData);
for (var i = 0; i < columnCount; i++) {
var column = columnModel.getColumnAt(i);
if (column === undefined) {
continue;
}
var p = {};
p.id = column.id;
p.style = this.getColumnStyle(i);
p.tooltip = '';
p.css = (i === 0 ? 'x-grid3-total-summary-cell-first ' : (i == columnCount - 1 ? 'x-grid3-total-summary-cell-last ' : '')) +
(column.headerCls ? ' ' + column.headerCls : '');
if (column.align == 'right') {
p.istyle = 'padding-right:16px';
}
/*
* не применяем рендерер столбца
*
if (column.summaryType || column.summaryRenderer) {
p.value = (column.summaryRenderer || column.renderer)(summaryData[column.dataIndex], p, summaryData, undefined, i, this.ds);
}
*/
if (column.summaryRenderer) {
p.value = column.summaryRenderer(summaryData[column.dataIndex], p, summaryData, undefined, i, this.ds);
} else {
p.value = summaryData[column.dataIndex];
}
if (p.value == undefined || p.value === "") p.value = " ";
if (columnModel.isLocked(i)) {
lockedSummaryCells[lockedSummaryCells.length] = cellTemplate.apply(p);
} else {
summaryCells[summaryCells.length] = cellTemplate.apply(p);
}
}
var summaryRow = rowTemplate.apply({
tstyle: tstyle,
cells: summaryCells.join('')
});
var lockedSummaryRow = rowTemplate.apply({
tstyle: ltstyle,
cells: lockedSummaryCells.join('')
});
return [summaryRow, lockedSummaryRow];
},
onColumnWidthUpdated: function () {
Ext.grid.GridView.prototype.onColumnWidthUpdated.apply(this, arguments);
this.updateHdGroupStyles();
this.updateGroupWidths();
},
onAllColumnWidthsUpdated: function () {
Ext.grid.GridView.prototype.onAllColumnWidthsUpdated.apply(this, arguments);
this.updateHdGroupStyles();
this.updateGroupWidths();
},
onColumnHiddenUpdated: function () {
Ext.grid.GridView.prototype.onColumnHiddenUpdated.apply(this, arguments);
this.updateHdGroupStyles();
this.updateGroupWidths();
},
getHeaderCell: function (index) {
var lockedLen = this.cm.getLockedCount();
if (index < lockedLen) {
var lockedElements = this.lockedHd.dom.getElementsByTagName('td');
for (var i = 0, lcellIdx = 0; i < lockedElements.length; i++) {
if (lockedElements[i].className.indexOf('ux-grid-hd-group-cell') < 0) {
if (lcellIdx == index) {
return lockedElements[i];
}
lcellIdx++;
}
}
} else {
var elements = this.mainHd.dom.getElementsByTagName('td');
for (var j = 0, cellIdx = 0; j < elements.length; j++) {
if (elements[j].className.indexOf('ux-grid-hd-group-cell') < 0) {
if (cellIdx + lockedLen == index) {
return elements[j];
}
cellIdx++;
}
}
}
},
findHeaderCell: function (el) {
return el ? this.fly(el).findParent('td.x-grid3-hd', this.cellSelectorDepth) : false;
},
findHeaderIndex: function (el) {
var cell = this.findHeaderCell(el);
return cell ? this.getCellIndex(cell) : false;
},
updateSortIcon: function (col, dir) {
var sortClasses = this.sortClasses,
lockedHeaders = this.lockedHd.select(this.cellSelector).removeClass(sortClasses),
headers = this.mainHd.select(this.cellSelector).removeClass(sortClasses),
lockedLen = this.cm.getLockedCount(),
cls = sortClasses[dir == 'DESC' ? 1 : 0];
if (col < lockedLen) {
lockedHeaders.item(col).addClass(cls);
} else {
headers.item(col - lockedLen).addClass(cls);
}
},
handleHdDown: function (e, t) {
Ext.grid.GridView.prototype.handleHdDown.call(this, e, t);
var el = Ext.get(t);
if (el.hasClass('x-grid3-hd-btn')) {
e.stopEvent();
var hd = this.findHeaderCell(t);
Ext.fly(hd).addClass('x-grid3-hd-menu-open');
var index = this.getCellIndex(hd);
this.hdCtxIndex = index;
var ms = this.hmenu.items, cm = this.cm;
ms.get('asc').setDisabled(!cm.isSortable(index));
ms.get('desc').setDisabled(!cm.isSortable(index));
ms.get('lock').setDisabled(cm.isLocked(index));
ms.get('unlock').setDisabled(!cm.isLocked(index));
this.hmenu.on('hide', function () {
Ext.fly(hd).removeClass('x-grid3-hd-menu-open');
}, this, {
single: true
});
this.hmenu.show(t, 'tl-bl?');
} else if (el.hasClass('ux-grid-hd-group-cell') || Ext.fly(t).up('.ux-grid-hd-group-cell')) {
e.stopEvent();
}
},
handleHdMenuClick: function (item) {
var index = this.hdCtxIndex,
cm = this.cm,
ds = this.ds,
id = item.getItemId(),
llen = cm.getLockedCount();
switch (id) {
case 'asc':
ds.sort(cm.getDataIndex(index), 'ASC');
break;
case 'desc':
ds.sort(cm.getDataIndex(index), 'DESC');
break;
case 'lock':
if (cm.getColumnCount(true) <= llen + 1) {
this.onDenyColumnLock();
return undefined;
}
var newColIndex = cm.processLockingHdGroups(index);
if (!newColIndex) {
newColIndex = llen;
}
cm.setLocked(index, true, newColIndex != index);
if (newColIndex != index) {
cm.moveColumn(index, newColIndex);
this.grid.fireEvent('columnmove', index, newColIndex);
}
break;
case 'unlock':
var newColIndex = cm.processUnLockingHdGroups(index);
if (!newColIndex) {
newColIndex = llen - 1;
}
if (newColIndex != index) {
cm.setLocked(index, false, true);
cm.moveColumn(index, newColIndex);
this.grid.fireEvent('columnmove', index, newColIndex);
} else {
cm.setLocked(index, false);
}
break;
default:
return this.handleHdMenuClickDefault(item);
}
return true;
},
handleHdMenuClickDefault: function (item) {
var cm = this.cm, id = item.getItemId();
if (id.substr(0, 6) == 'group-') {
var i = id.split('-'), row = parseInt(i[1], 10), col = parseInt(i[2], 10), r = this.cm.rows[row], group, gcol = 0;
for (var i = 0, len = r.length; i < len; i++) {
group = r[i];
if (col >= gcol && col < gcol + group.colspan) {
break;
}
gcol += group.colspan;
}
if (item.checked) {
var max = cm.getColumnsBy(this.isHideableColumn, this).length;
for (var i = gcol, len = gcol + group.colspan; i < len; i++) {
if (!cm.isHidden(i)) {
max--;
}
}
if (max < 1) {
this.onDenyColumnHide();
return false;
}
}
for (var i = gcol, len = gcol + group.colspan; i < len; i++) {
if (cm.config[i].fixed !== true && cm.config[i].hideable !== false) {
cm.setHidden(i, item.checked);
}
}
} else if (id.substr(0, 4) == 'col-') {
var index = cm.getIndexById(id.substr(4));
if (index != -1) {
if (item.checked && cm.getColumnsBy(this.isHideableColumn, this).length <= 1) {
this.onDenyColumnHide();
return false;
}
cm.setHidden(index, item.checked);
}
}
if (id.substr(0, 6) == 'group-' || id.substr(0, 4) == 'col-') {
item.checked = !item.checked;
if (item.menu) {
var updateChildren = function (menu) {
menu.items.each(function (childItem) {
if (!childItem.disabled) {
childItem.setChecked(item.checked, false);
if (childItem.menu) {
updateChildren(childItem.menu);
}
}
});
};
updateChildren(item.menu);
}
var parentMenu = item, parentItem;
while (parentMenu = parentMenu.parentMenu) {
if (!parentMenu.parentMenu || !(parentItem = parentMenu.parentMenu.items.get(parentMenu.getItemId())) || !parentItem.setChecked) {
break;
}
var checked = parentMenu.items.findIndexBy(function (m) {
return m.checked;
}) >= 0;
parentItem.setChecked(checked, true);
}
item.checked = !item.checked;
}
},
handleHdMove: function (e, t) {
var hd = this.findHeaderCell(this.activeHdRef);
if (hd && !this.headersDisabled && !Ext.fly(hd).hasClass('ux-grid-hd-group-cell')) {
var hw = this.splitHandleWidth || 5, r = this.activeHdRegion, x = e.getPageX(), ss = hd.style, cur = '';
if (this.grid.enableColumnResize !== false) {
if (x - r.left <= hw && this.cm.isResizable(this.activeHdIndex - 1)) {
cur = Ext.isAir ? 'move' : Ext.isWebKit ? 'e-resize' : 'col-resize'; // col-resize
// not
// always
// supported
} else if (r.right - x <= (!this.activeHdBtn ? hw : 2) && this.cm.isResizable(this.activeHdIndex)) {
cur = Ext.isAir ? 'move' : Ext.isWebKit ? 'w-resize' : 'col-resize';
}
}
ss.cursor = cur;
}
},
handleHdOver: function (e, t) {
var hd = this.findHeaderCell(t);
if (hd && !this.headersDisabled) {
this.activeHdRef = t;
this.activeHdIndex = this.getCellIndex(hd);
var fly = this.fly(hd);
this.activeHdRegion = fly.getRegion();
if (!(this.cm.isMenuDisabled(this.activeHdIndex) || fly.hasClass('ux-grid-hd-group-cell'))) {
fly.addClass('x-grid3-hd-over');
this.activeHdBtn = fly.child('.x-grid3-hd-btn');
if (this.activeHdBtn) {
this.activeHdBtn.dom.style.height = (hd.firstChild.offsetHeight - 1) + 'px';
}
}
}
},
handleHdOut: function (e, t) {
var hd = this.findHeaderCell(t);
if (hd && (!Ext.isIE || !e.within(hd, true))) {
this.activeHdRef = null;
this.fly(hd).removeClass('x-grid3-hd-over');
hd.style.cursor = '';
}
},
beforeColMenuShow: function () {
var cm = this.cm, rows = this.cm.rows;
this.colMenu.removeAll();
for (var col = 0, clen = cm.getColumnCount(); col < clen; col++) {
var menu = this.colMenu, title = cm.getColumnHeader(col), text = [];
if (cm.config[col].fixed !== true && cm.config[col].hideable !== false) {
for (var row = 0, rlen = rows.length; row < rlen; row++) {
var r = rows[row], group, gcol = 0;
for (var i = 0, len = r.length; i < len; i++) {
group = r[i];
if (col >= gcol && col < gcol + group.colspan) {
break;
}
gcol += group.colspan;
}
if (group && group.header) {
if (cm.hierarchicalColMenu) {
var gid = 'group-' + row + '-' + gcol,
item = menu.items ? menu.getComponent(gid) : null,
submenu = item ? item.menu : null;
if (!submenu) {
submenu = new Ext.menu.Menu({
itemId: gid
});
submenu.on("itemclick", this.handleHdMenuClick, this);
var checked = false, disabled = true;
for (var c = gcol, lc = gcol + group.colspan; c < lc; c++) {
if (!cm.isHidden(c)) {
checked = true;
}
if (cm.config[c].hideable !== false) {
disabled = false;
}
}
menu.add({
itemId: gid,
text: group.header,
menu: submenu,
hideOnClick: false,
checked: checked,
disabled: disabled
});
}
menu = submenu;
} else {
text.push(group.header);
}
}
}
text.push(title);
menu.add(new Ext.menu.CheckItem({
itemId: "col-" + cm.getColumnId(col),
text: text.join(' '),
checked: !cm.isHidden(col),
hideOnClick: false,
disabled: cm.config[col].hideable === false
}));
}
}
},
getEditorParent: function (ed) {
return this.el.dom;
},
getLockedRows: function () {
if (!this.canGroup()) {
return this.hasRows() ? this.lockedBody.dom.childNodes : [];
}
var r = [],
gs = this.getGroups(true),
g,
i = 0,
len = gs.length,
j,
jlen;
for (; i < len; ++i) {
g = gs[i].childNodes[1];
if (g) {
g = g.childNodes;
for (j = 0, jlen = g.length; j < jlen; ++j) {
r[r.length] = g[j];
}
}
}
return r;
},
getLockedRow: function (row) {
return this.getLockedRows()[row];
},
getTotalSummaryRow: function(locked){
if (locked === true){
return this.lockedTotalSummaryInner.firstChild.firstChild.firstChild.firstChild;
} else {
return this.totalSummaryInner.firstChild.firstChild.firstChild.firstChild;
}
},
getCell: function (row, col) {
var lockedLen = this.cm.getLockedCount();
if (col < lockedLen) {
return Ext.fly(this.getLockedRow(row)).query(this.cellSelector)[col];
}
return Ext.grid.GridView.prototype.getCell.call(this, row, col - lockedLen);
},
addRowClass: function (row, cls) {
var lockedRow = this.getLockedRow(row);
if (lockedRow) {
this.fly(lockedRow).addClass(cls);
}
Ext.grid.GridView.prototype.addRowClass.call(this, row, cls);
},
removeRowClass: function (row, cls) {
var lockedRow = this.getLockedRow(row);
if (lockedRow) {
this.fly(lockedRow).removeClass(cls);
}
Ext.grid.GridView.prototype.removeRowClass.call(this, row, cls);
},
removeRow: function (row) {
Ext.removeNode(this.getLockedRow(row));
Ext.grid.GridView.prototype.removeRow.call(this, row);
},
removeRows: function (firstRow, lastRow) {
var lockedBody = this.lockedBody.dom,
rowIndex = firstRow;
for (; rowIndex <= lastRow; rowIndex++) {
Ext.removeNode(lockedBody.childNodes[firstRow]);
}
Ext.grid.GridView.prototype.removeRows.call(this, firstRow, lastRow);
},
syncScroll: function (e) {
this.lockedScroller.dom.scrollTop = this.scroller.dom.scrollTop;
this.totalSummaryInner.scrollLeft = this.scroller.dom.scrollLeft;
this.totalSummaryInner.scrollLeft = this.scroller.dom.scrollLeft; // second time for IE (1/2 time first fails, other browsers ignore)
Ext.grid.GridView.prototype.syncScroll.call(this, e);
},
updateAllColumnWidths: function () {
var tw = this.getTotalWidth(),
clen = this.cm.getColumnCount(),
lw = this.getLockedWidth(),
llen = this.cm.getLockedCount(),
ws = [], len, i;
this.updateLockedWidth();
for (i = 0; i < clen; i++) {
ws[i] = this.getColumnWidth(i);
var hd = this.getHeaderCell(i);
hd.style.width = ws[i];
}
var lns = this.getLockedRows(), ns = this.getRows(), row, trow, j;
for (i = 0, len = ns.length; i < len; i++) {
row = lns[i];
row.style.width = lw;
if (row.firstChild) {
row.firstChild.style.width = lw;
trow = row.firstChild.rows[0];
for (j = 0; j < llen; j++) {
trow.childNodes[j].style.width = ws[j];
}
}
row = ns[i];
row.style.width = tw;
if (row.firstChild) {
row.firstChild.style.width = tw;
trow = row.firstChild.rows[0];
for (j = llen; j < clen; j++) {
trow.childNodes[j - llen].style.width = ws[j];
}
}
}
this.onAllColumnWidthsUpdated(ws, tw);
this.syncHeaderHeight();
},
updateColumnWidth: function (col, width) {
var w = this.getColumnWidth(col),
llen = this.cm.getLockedCount(),
totalSummaryRow,
ns, rw, c, row;
this.updateLockedWidth();
if (col < llen) {
ns = this.getLockedRows();
rw = this.getLockedWidth();
totalSummaryRow = this.getTotalSummaryRow(true);
c = col;
} else {
ns = this.getRows();
rw = this.getTotalWidth();
c = col - llen;
totalSummaryRow = this.getTotalSummaryRow(false);
}
var hd = this.getHeaderCell(col);
hd.style.width = w;
for (var i = 0, len = ns.length; i < len; i++) {
row = ns[i];
row.style.width = rw;
if (row.firstChild) {
row.firstChild.style.width = rw;
row.firstChild.rows[0].childNodes[c].style.width = w;
}
}
totalSummaryRow.childNodes[c].style.width = w;
this.onColumnWidthUpdated(col, w, this.getTotalWidth());
this.syncHeaderHeight();
},
updateColumnHidden: function (col, hidden) {
var llen = this.cm.getLockedCount(),
ns, rw, c, row,
totalSummaryRow,
display = hidden ? 'none' : '';
this.updateLockedWidth();
if (col < llen) {
ns = this.getLockedRows();
rw = this.getLockedWidth();
totalSummaryRow = this.getTotalSummaryRow(true);
c = col;
} else {
ns = this.getRows();
rw = this.getTotalWidth();
totalSummaryRow = this.getTotalSummaryRow(false);
c = col - llen;
}
var hd = this.getHeaderCell(col);
hd.style.display = display;
for (var i = 0, len = ns.length; i < len; i++) {
row = ns[i];
row.style.width = rw;
if (row.firstChild) {
row.firstChild.style.width = rw;
row.firstChild.rows[0].childNodes[c].style.display = display;
}
}
totalSummaryRow.childNodes[c].style.display = display;
this.onColumnHiddenUpdated(col, hidden, this.getTotalWidth());
delete this.lastViewWidth;
this.layout();
},
doRender: function (cs, rs, ds, startRow, colCount, stripe) {
if (rs.length < 1) {
return '';
}
if (!this.canGroup() || this.isUpdating) {
return this.doRenderRows(cs, rs, ds, startRow, colCount, stripe);
}
var groupField = this.getGroupField(),
colIndex = this.cm.findColumnIndex(groupField),
g,
gstyle = 'width:' + this.getTotalWidth() + ';',
lgstyle = 'width:' + this.getLockedWidth() + ';',
cfg = this.cm.config[colIndex],
groupRenderer = cfg.groupRenderer || cfg.renderer,
prefix = this.showGroupName ? (cfg.groupName || cfg.header) + ': ' : '',
groups = [],
curGroup, i, len, gid;
for (i = 0, len = rs.length; i < len; i++) {
var rowIndex = startRow + i,
r = rs[i],
gvalue = r.data[groupField];
g = this.getGroup(gvalue, r, groupRenderer, rowIndex, colIndex, ds);
if (!curGroup || curGroup.group != g) {
gid = this.constructId(gvalue, groupField, colIndex);
// if state is defined use it, however state is in terms of expanded
// so negate it, otherwise use the default.
this.state[gid] = !(Ext.isDefined(this.state[gid]) ? !this.state[gid] : this.startCollapsed);
curGroup = {
group: g,
gvalue: gvalue,
text: prefix + g,
groupId: gid,
startRow: rowIndex,
rs: [r],
cls: this.state[gid] ? '' : 'x-grid-group-collapsed'
};
groups.push(curGroup);
} else {
curGroup.rs.push(r);
}
r._groupId = gid;
}
var buf = [], lbuf = [];
for (i = 0, len = groups.length; i < len; i++) {
g = groups[i];
g.style = gstyle;
this.doGroupStart(buf, g, cs, ds, colCount, false);
g.style = lgstyle;
this.doGroupStart(lbuf, g, cs, ds, colCount, true);
var rowBuf = this.doRenderRows(cs, g.rs, ds, g.startRow, colCount, stripe);
buf[buf.length] = rowBuf[0];
lbuf[lbuf.length] = rowBuf[1];
this.doGroupEnd(buf, g, cs, ds, colCount, false);
this.doGroupEnd(lbuf, g, cs, ds, colCount, true);
}
return [buf.join(''), lbuf.join('')];
},
doRenderRows: function (cs, rs, ds, startRow, colCount, stripe) {
var ts = this.templates, ct = ts.cell, rt = ts.row, last = colCount - 1,
tstyle = 'width:' + this.getTotalWidth() + ';',
lstyle = 'width:' + this.getLockedWidth() + ';',
buf = [], lbuf = [], cb, lcb, c, p = {}, rp = {}, r;
for (var j = 0, len = rs.length; j < len; j++) {
r = rs[j];
cb = [];
lcb = [];
var rowIndex = (j + startRow);
for (var i = 0; i < colCount; i++) {
c = cs[i];
p.id = c.id;
p.css = (i === 0 ? 'x-grid3-cell-first ' : (i == last ? 'x-grid3-cell-last ' : '')) +
(this.cm.config[i].cellCls ? ' ' + this.cm.config[i].cellCls : '');
p.attr = p.cellAttr = '';
p.value = c.renderer.call(c.scope, r.data[c.name], p, r, rowIndex, i, ds);
p.style = c.style;
if (Ext.isEmpty(p.value)) {
p.value = ' ';
}
if (this.markDirty && r.dirty && Ext.isDefined(r.modified[c.name])) {
p.css += ' x-grid3-dirty-cell';
}
if (!Ext.isEmpty(r.error) && Ext.isDefined(r.data[c.name])) {
var matchedCols = r.error.filter(function (item) {
return item.errorText && item.column == c.name;
});
if (!Ext.isEmpty(matchedCols)) {
p.css += ' x-grid3-row-invalid';
p.css += ' x-form-invalid';
}
}
if (c.locked) {
lcb[lcb.length] = ct.apply(p);
} else {
cb[cb.length] = ct.apply(p);
}
}
var alt = [];
if (stripe && ((rowIndex + 1) % 2 === 0)) {
alt[0] = 'x-grid3-row-alt';
}
if (r.dirty) {
alt[1] = ' x-grid3-dirty-row';
}
rp.cols = colCount;
if (this.getRowClass) {
alt[2] = this.getRowClass(r, rowIndex, rp, ds);
}
rp.alt = alt.join(' ');
rp.cells = cb.join('');
rp.tstyle = tstyle;
buf[buf.length] = rt.apply(rp);
rp.cells = lcb.join('');
rp.tstyle = lstyle;
lbuf[lbuf.length] = rt.apply(rp);
}
return [buf.join(''), lbuf.join('')];
},
processRows: function (startRow, skipStripe) {
if (!this.ds || this.ds.getCount() < 1) {
return;
}
var rows = this.getRows(),
lrows = this.getLockedRows(),
row, lrow;
skipStripe = skipStripe || !this.grid.stripeRows;
startRow = startRow || 0;
for (var i = 0, len = rows.length; i < len; ++i) {
row = rows[i];
lrow = lrows[i];
row.rowIndex = i;
lrow.rowIndex = i;
if (!skipStripe) {
row.className = row.className.replace(this.rowClsRe, ' ');
lrow.className = lrow.className.replace(this.rowClsRe, ' ');
if ((i + 1) % 2 === 0) {
row.className += ' x-grid3-row-alt';
lrow.className += ' x-grid3-row-alt';
}
}
this.syncRowHeights(row, lrow);
}
if (startRow === 0) {
Ext.fly(rows[0]).addClass(this.firstRowCls);
Ext.fly(lrows[0]).addClass(this.firstRowCls);
}
Ext.fly(rows[rows.length - 1]).addClass(this.lastRowCls);
Ext.fly(lrows[lrows.length - 1]).addClass(this.lastRowCls);
},
syncRowHeights: function (row1, row2) {
if (this.syncHeights) {
var el1 = Ext.get(row1),
el2 = Ext.get(row2);
// сбрасываем текущие высоты строк
el1.dom.style.height = '';
el2.dom.style.height = '';
var h1 = el1.getHeight(),
h2 = el2.getHeight();
if (h1 > h2) {
el2.setHeight(h1);
} else if (h2 > h1) {
el1.setHeight(h2);
}
}
},
afterRender: function () {
if (!this.ds || !this.cm) {
return;
}
var bd = this.renderRows() || [' ', ' '];
this.mainBody.dom.innerHTML = bd[0];
this.lockedBody.dom.innerHTML = bd[1];
this.processRows(0, true);
if (this.deferEmptyText !== true) {
this.applyEmptyText();
}
this.grid.fireEvent('viewready', this.grid);
if (this.grid.deferRowRender) {
this.updateGroupWidths();
}
},
layout: function () {
if (!this.mainBody) {
return;
}
var g = this.grid;
var c = g.getGridEl();
var csize = c.getSize(true);
var vw = csize.width;
if (!g.hideHeaders && (vw < 20 || csize.height < 20)) {
return;
}
this.syncHeaderHeight();
if (g.autoHeight) {
this.scroller.dom.style.overflow = 'visible';
this.lockedScroller.dom.style.overflow = 'visible';
if (Ext.isWebKit) {
this.scroller.dom.style.position = 'static';
this.lockedScroller.dom.style.position = 'static';
}
} else {
this.el.setSize(csize.width, csize.height);
var hdHeight = this.mainHd.getHeight();
var totalSummaryHeight = this.totalSummary.getHeight();
var vh = csize.height - (hdHeight) - (totalSummaryHeight);
}
this.updateLockedWidth();
if (this.forceFit) {
if (this.lastViewWidth != vw) {
this.fitColumns(false, false);
this.lastViewWidth = vw;
}
} else {
this.autoExpand();
this.syncHeaderScroll();
}
this.onLayout(vw, vh);
},
getOffsetWidth: function () {
return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth() + this.getScrollOffset()) + 'px';
},
updateHeaders: function () {
var hd = this.renderHeaders();
this.innerHd.firstChild.innerHTML = hd[0];
this.innerHd.firstChild.style.width = this.getOffsetWidth();
this.innerHd.firstChild.firstChild.style.width = this.getTotalWidth();
this.lockedInnerHd.firstChild.innerHTML = hd[1];
var lw = this.getLockedWidth();
this.lockedInnerHd.firstChild.style.width = lw;
this.lockedInnerHd.firstChild.firstChild.style.width = lw;
},
updateTotalSummary: function () {
var totalsummary = this.renderTotalSummary();
this.totalSummaryInner.firstChild.innerHTML = totalsummary[0];
this.totalSummaryInner.firstChild.style.width = this.getOffsetWidth();
this.totalSummaryInner.firstChild.firstChild.style.width = this.getTotalWidth();
this.lockedTotalSummaryInner.firstChild.innerHTML = totalsummary[1];
var lw = this.getLockedWidth();
this.lockedTotalSummaryInner.firstChild.style.width = lw;
this.lockedTotalSummaryInner.firstChild.firstChild.style.width = lw;
},
getResolvedXY: function (resolved) {
if (!resolved) {
return null;
}
var c = resolved.cell, r = resolved.row;
return c ? Ext.fly(c).getXY() : [this.scroller.getX(), Ext.fly(r).getY()];
},
syncFocusEl: function (row, col, hscroll) {
Ext.grid.GridView.prototype.syncFocusEl.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
},
ensureVisible: function (row, col, hscroll) {
return Ext.grid.GridView.prototype.ensureVisible.call(this, row, col, col < this.cm.getLockedCount() ? false : hscroll);
},
insertRows: function (dm, firstRow, lastRow, isUpdate) {
var last = dm.getCount() - 1;
if (!isUpdate && firstRow === 0 && lastRow >= last) {
this.refresh();
} else {
if (!isUpdate) {
this.fireEvent('beforerowsinserted', this, firstRow, lastRow);
}
var html = this.renderRows(firstRow, lastRow),
before = this.getRow(firstRow);
if (before) {
if (firstRow === 0) {
this.removeRowClass(0, this.firstRowCls);
}
Ext.DomHelper.insertHtml('beforeBegin', before, html[0]);
before = this.getLockedRow(firstRow);
Ext.DomHelper.insertHtml('beforeBegin', before, html[1]);
} else {
this.removeRowClass(last - 1, this.lastRowCls);
Ext.DomHelper.insertHtml('beforeEnd', this.mainBody.dom, html[0]);
Ext.DomHelper.insertHtml('beforeEnd', this.lockedBody.dom, html[1]);
}
if (!isUpdate) {
this.fireEvent('rowsinserted', this, firstRow, lastRow);
this.processRows(firstRow);
} else if (firstRow === 0 || firstRow >= last) {
this.addRowClass(firstRow, firstRow === 0 ? this.firstRowCls : this.lastRowCls);
}
}
this.syncFocusEl(firstRow);
},
getColumnStyle: function (col, isHeader) {
var style = !isHeader ? this.cm.config[col].cellStyle || this.cm.config[col].css || '' : this.cm.config[col].headerStyle || '';
style += 'width:' + this.getColumnWidth(col) + ';';
if (this.cm.isHidden(col)) {
style += 'display:none;';
}
var align = this.cm.config[col].align;
if (align) {
style += 'text-align:' + align + ';';
}
return style;
},
getColumnWidth: function (column) {
var columnWidth = this.cm.getColumnWidth(column),
borderWidth = this.borderWidth;
if (Ext.isNumber(columnWidth)) {
if (Ext.isBorderBox || (Ext.isWebKit && !Ext.isSafari2 && !Ext.isChrome)) {
return columnWidth + "px";
} else {
return Math.max(columnWidth - borderWidth, 0) + "px";
}
} else {
return columnWidth;
}
},
getLockedWidth: function () {
return this.cm.getTotalLockedWidth() + 'px';
},
getTotalWidth: function () {
return (this.cm.getTotalWidth() - this.cm.getTotalLockedWidth()) + 'px';
},
getColumnData: function () {
var cs = [], cm = this.cm, colCount = cm.getColumnCount();
for (var i = 0; i < colCount; i++) {
var name = cm.getDataIndex(i);
cs[i] = {
name: (!Ext.isDefined(name) ? this.ds.fields.get(i).name : name),
renderer: cm.getRenderer(i),
scope: cm.getRendererScope(i),
id: cm.getColumnId(i),
style: this.getColumnStyle(i),
locked: cm.isLocked(i)
};
}
return cs;
},
renderBody: function () {
var markup = this.renderRows() || [' ', ' '];
return [this.templates.body.apply({rows: markup[0]}), this.templates.body.apply({rows: markup[1]})];
},
refreshRow: function (record) {
var store = this.ds,
colCount = this.cm.getColumnCount(),
columns = this.getColumnData(),
last = colCount - 1,
cls = ['x-grid3-row'],
rowParams = {
tstyle: String.format("width: {0};", this.getTotalWidth())
},
lockedRowParams = {
tstyle: String.format("width: {0};", this.getLockedWidth())
},
colBuffer = [],
lockedColBuffer = [],
cellTpl = this.templates.cell,
rowIndex,
row,
lockedRow,
column,
meta,
css,
i;
this.isUpdating = true;
if (Ext.isNumber(record)) {
rowIndex = record;
record = store.getAt(rowIndex);
} else {
rowIndex = store.indexOf(record);
}
if (!record || rowIndex < 0) {
return;
}
for (i = 0; i < colCount; i++) {
column = columns[i];
if (i == 0) {
css = 'x-grid3-cell-first';
} else {
css = (i == last) ? 'x-grid3-cell-last ' : '';
}
meta = {
id: column.id,
style: column.style,
css: css,
attr: "",
cellAttr: ""
};
meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store);
if (Ext.isEmpty(meta.value)) {
meta.value = ' ';
}
if (this.markDirty && record.dirty && Ext.isDefined(record.modified[column.name])) {
meta.css += ' x-grid3-dirty-cell';
}
if (!Ext.isEmpty(record.error) && Ext.isDefined(record.data[column.name])) {
var matchedCols = record.error.filter(function (item) {
return item.errorText && item.column == column.name;
});
if (!Ext.isEmpty(matchedCols)) {
meta.css += ' x-grid3-row-invalid';
meta.css += ' x-form-invalid';
}
}
if (column.locked) {
lockedColBuffer[i] = cellTpl.apply(meta);
} else {
colBuffer[i] = cellTpl.apply(meta);
}
}
row = this.getRow(rowIndex);
row.className = '';
lockedRow = this.getLockedRow(rowIndex);
lockedRow.className = '';
if (this.grid.stripeRows && ((rowIndex + 1) % 2 === 0)) {
cls.push('x-grid3-row-alt');
}
if (this.getRowClass) {
rowParams.cols = colCount;
cls.push(this.getRowClass(record, rowIndex, rowParams, store));
}
// Unlocked rows
this.fly(row).addClass(cls).setStyle(rowParams.tstyle);
rowParams.cells = colBuffer.join("");
row.innerHTML = this.templates.rowInner.apply(rowParams);
// Locked rows
this.fly(lockedRow).addClass(cls).setStyle(lockedRowParams.tstyle);
lockedRowParams.cells = lockedColBuffer.join("");
lockedRow.innerHTML = this.templates.rowInner.apply(lockedRowParams);
lockedRow.rowIndex = rowIndex;
this.syncRowHeights(row, lockedRow);
this.fireEvent('rowupdated', this, rowIndex, record);
this.isUpdating = false;
},
refresh: function (headersToo) {
this.fireEvent('beforerefresh', this);
this.grid.stopEditing(true);
var result = this.renderBody();
this.mainBody.update(result[0]).setWidth(this.getTotalWidth());
this.lockedBody.update(result[1]).setWidth(this.getLockedWidth());
if (headersToo === true) {
this.updateHeaders();
this.updateHeaderSortState();
}
this.processRows(0, true);
this.updateTotalSummary();
this.layout();
this.applyEmptyText();
this.fireEvent('refresh', this);
},
onDenyColumnLock: function () {
},
initData: function (ds, cm) {
if (this.cm) {
this.cm.un('columnlockchange', this.onColumnLock, this);
}
Ext.grid.GridView.prototype.initData.call(this, ds, cm);
if (this.cm) {
this.cm.on('columnlockchange', this.onColumnLock, this);
}
},
onColumnLock: function () {
this.refresh(true);
},
syncHeaderHeight: function () {
var hrows = this.mainHd.dom.getElementsByTagName('tr'),
lhrows = this.lockedHd.dom.getElementsByTagName('tr');
if (lhrows.length != hrows.length) {
return;
}
for (var i = 0; i < hrows.length; i++) {
var hrow = hrows[i],
lhrow = lhrows[i];
hrow.style.height = 'auto';
lhrow.style.height = 'auto';
var hd = hrow.offsetHeight,
lhd = lhrow.offsetHeight,
height = Math.max(lhd, hd) + 'px';
hrow.style.height = height;
lhrow.style.height = height;
}
},
updateLockedWidth: function () {
var lw = this.cm.getTotalLockedWidth(),
tw = this.cm.getTotalWidth() - lw,
csize = this.grid.getGridEl().getSize(true),
lp = Ext.isBorderBox ? 0 : this.lockedBorderWidth,
rp = Ext.isBorderBox ? 0 : this.rowBorderWidth,
vw = Math.max(csize.width - lw - lp - rp, 0) + 'px',
so = this.getScrollOffset();
if (!this.grid.autoHeight) {
var vh = Math.max(csize.height - this.mainHd.getHeight() - this.totalSummary.getHeight(), 0) + 'px';
this.lockedScroller.dom.style.height = vh;
this.scroller.dom.style.height = vh;
}
this.lockedWrap.dom.style.width = (lw + rp) + 'px';
this.scroller.dom.style.width = vw;
this.mainWrap.dom.style.left = (lw + lp + rp) + 'px';
if (this.lockedInnerHd) {
this.lockedInnerHd.firstChild.style.width = lw + 'px';
this.lockedInnerHd.firstChild.firstChild.style.width = lw + 'px';
}
if (this.innerHd) {
this.innerHd.style.width = vw;
this.innerHd.firstChild.style.width = (tw + rp + so) + 'px';
this.innerHd.firstChild.firstChild.style.width = tw + 'px';
}
if (this.lockedBody) {
this.lockedBody.dom.style.width = (lw + rp) + 'px';
}
if (this.mainBody) {
this.mainBody.dom.style.width = (tw + rp) + 'px';
}
if (this.totalSummaryInner){
this.totalSummaryInner.style.width = vw;
this.totalSummaryInner.firstChild.style.width = (tw + rp + so) + 'px';
this.totalSummaryInner.firstChild.firstChild.style.width = tw + 'px';
}
if (this.lockedTotalSummaryInner) {
this.lockedTotalSummaryInner.firstChild.style.width = lw + 'px';
this.lockedTotalSummaryInner.firstChild.firstChild.style.width = lw + 'px';
}
},
getGroupStyle: function (group, gcol) {
var width = 0, hidden = true;
for (var i = gcol, len = gcol + group.colspan; i < len; i++) {
if (this.cm.getColumnAt(i) !== undefined && !this.cm.isHidden(i)) {
var cw = this.cm.getColumnWidth(i);
if (typeof cw == 'number') {
width += cw;
}
hidden = false;
}
}
return {
width: (Ext.isBorderBox || (Ext.isWebKit && !Ext.isSafari2 && !Ext.isChrome) ? width : Math.max(width - this.borderWidth, 0)) + 'px',
hidden: hidden
};
},
updateHdGroupStyles: function (col) {
var tables = this.mainHd.query('.x-grid3-header-offset > table'),
ltables = this.lockedHd.query('.x-grid3-header-offset > table'),
ltw = this.getLockedWidth(),
tw = this.getTotalWidth(),
rows = this.cm.rows,
lockedColumnCount = this.cm.getLockedCount();
for (var row = 0; row < tables.length; row++) {
tables[row].style.width = tw;
if (row < rows.length) {
var lockedGroupCount = this.cm.getLockedHdGroupCount(row);
var cells = tables[row].firstChild.firstChild.childNodes;
for (var i = 0, gcol = lockedColumnCount; i < cells.length; i++) {
var group = rows[row][i + lockedGroupCount];
if ((typeof col != 'number') || (col >= gcol && col < gcol + group.colspan)) {
var gs = this.getGroupStyle(group, gcol);
cells[i].style.width = gs.width;
cells[i].style.display = gs.hidden ? 'none' : '';
}
gcol += group.colspan;
}
}
}
for (var row = 0; row < ltables.length; row++) {
ltables[row].style.width = ltw;
if (row < rows.length) {
var cells = ltables[row].firstChild.firstChild.childNodes;
for (var i = 0, gcol = 0; i < cells.length; i++) {
var group = rows[row][i];
if ((typeof col != 'number') || (col >= gcol && col < gcol + group.colspan)) {
var gs = this.getGroupStyle(group, gcol);
cells[i].style.width = gs.width;
cells[i].style.display = gs.hidden ? 'none' : '';
}
gcol += group.colspan;
}
}
}
},
renderUI: function () {
var templates = this.templates,
header = this.renderHeaders(),
body = templates.body.apply({rows: ' '}),
totalSummary = this.renderTotalSummary();
return templates.masterTpl.apply({
body: body,
header: header[0],
totalSummary: totalSummary[0],
ostyle: 'width:' + this.getOffsetWidth() + ';',
bstyle: 'width:' + this.getTotalWidth() + ';',
lockedBody: body,
lockedHeader: header[1],
lockedTotalSummary: totalSummary[1],
lstyle: 'width:' + this.getLockedWidth() + ';'
});
},
afterRenderUI: function () {
var g = this.grid;
this.initElements();
Ext.fly(this.innerHd).on('click', this.handleHdDown, this);
Ext.fly(this.lockedInnerHd).on('click', this.handleHdDown, this);
this.mainHd.on({
scope: this,
mouseover: this.handleHdOver,
mouseout: this.handleHdOut,
mousemove: this.handleHdMove
});
this.lockedHd.on({
scope: this,
mouseover: this.handleHdOver,
mouseout: this.handleHdOut,
mousemove: this.handleHdMove
});
this.scroller.on('scroll', this.syncScroll, this);
if (g.enableColumnResize !== false) {
this.splitZone = new Ext.grid.GridView.SplitDragZone(g, this.mainHd.dom);
this.splitZone.setOuterHandleElId(Ext.id(this.lockedHd.dom));
this.splitZone.setOuterHandleElId(Ext.id(this.mainHd.dom));
Ext.apply(this.splitZone, Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.splitZoneConfig);
}
if (g.enableColumnMove) {
this.columnDrag = new Ext.grid.GridView.ColumnDragZone(g, this.innerHd);
this.columnDrag.setOuterHandleElId(Ext.id(this.lockedInnerHd));
this.columnDrag.setOuterHandleElId(Ext.id(this.innerHd));
this.columnDrop = new Ext.grid.HeaderDropZone(g, this.mainHd.dom);
Ext.apply(this.columnDrop, Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.columnDropConfig);
}
if (g.enableHdMenu !== false) {
this.hmenu = new Ext.menu.Menu({id: g.id + '-hctx'});
this.hmenu.add(
{itemId: 'asc', text: this.sortAscText, cls: 'xg-hmenu-sort-asc'},
{itemId: 'desc', text: this.sortDescText, cls: 'xg-hmenu-sort-desc'}
);
if (g.enableColLock !== false) {
this.hmenu.add('-',
{itemId: 'lock', text: this.lockText, cls: 'xg-hmenu-lock'},
{itemId: 'unlock', text: this.unlockText, cls: 'xg-hmenu-unlock'}
);
}
if (g.enableColumnHide !== false) {
this.colMenu = new Ext.menu.Menu({id: g.id + '-hcols-menu'});
this.colMenu.on({
scope: this,
beforeshow: this.beforeColMenuShow,
itemclick: this.handleHdMenuClick
});
this.hmenu.add('-', {
itemId: 'columns',
hideOnClick: false,
text: this.columnsText,
menu: this.colMenu,
iconCls: 'x-cols-icon'
});
}
if (this.enableGroupingMenu) {
this.hmenu.add('-', {
itemId: 'groupBy',
text: this.groupByText,
handler: this.onGroupByClick,
scope: this,
iconCls: 'x-group-by-icon'
});
if (this.enableNoGroups) {
this.hmenu.add({
itemId: 'showGroups',
text: this.showGroupsText,
checked: true,
checkHandler: this.onShowGroupsClick,
scope: this
});
}
this.hmenu.on('beforeshow', this.beforeMenuShow, this);
}
this.hmenu.on('itemclick', this.handleHdMenuClick, this);
}
if (g.trackMouseOver) {
this.mainBody.on({
scope: this,
mouseover: this.onRowOver,
mouseout: this.onRowOut
});
this.lockedBody.on({
scope: this,
mouseover: this.onRowOver,
mouseout: this.onRowOut
});
}
if (g.enableDragDrop || g.enableDrag) {
this.dragZone = new Ext.grid.GridDragZone(g, {
ddGroup: g.ddGroup || 'GridDD'
});
}
this.updateHeaderSortState();
},
//GroupingView methods **************************************
syncGroupHeaderHeights: function () {
if (!this.canGroup() || !this.hasRows()) {
return;
}
var gs = this.getGroups(false),
lgs = this.getGroups(true);
if (gs.length != lgs.length) {
return;
}
for (var i = 0, len = gs.length; i < len; i++) {
var el1 = gs[i].childNodes[0],
el2 = lgs[i].childNodes[0];
el1.style.height = 'auto';
el2.style.height = 'auto';
var h1 = el1.offsetHeight,
h2 = el2.offsetHeight,
height = Math.max(h1, h2) + 'px';
el1.style.height = height;
el2.style.height = height;
}
},
findGroup: function (el) {
return Ext.fly(el).up('.x-grid-group', this.mainBody.dom);
},
getGroups: function (lockedArea) {
if (!this.hasRows()) {
return [];
}
if (lockedArea) {
return this.lockedBody.dom.childNodes;
} else {
return this.mainBody.dom.childNodes;
}
},
onAdd: function (ds, records, index) {
if (this.canGroup() && !this.ignoreAdd) {
var ss = this.getScrollState();
this.fireEvent('beforerowsinserted', ds, index, index + (records.length - 1));
this.refresh();
this.restoreScroll(ss);
this.fireEvent('rowsinserted', ds, index, index + (records.length - 1));
} else if (!this.canGroup()) {
Ext.grid.GridView.prototype.onAdd.apply(this, arguments);
}
},
onRemove: function (ds, record, index, isUpdate) {
Ext.grid.GridView.prototype.onRemove.apply(this, arguments);
var grNodes = this.findGroupNodes(record._groupId),
gel = grNodes[0],
lgel = grNodes[1],
toUpdateSummary = false;
if (gel && gel.childNodes[1].childNodes.length < 1) {
Ext.removeNode(gel);
} else {
toUpdateSummary = true;
}
if (lgel && lgel.childNodes[1].childNodes.length < 1) {
Ext.removeNode(lgel);
} else {
toUpdateSummary = true;
}
if ((!isUpdate) && toUpdateSummary) {
this.refreshSummaryById(record._groupId);
this.updateTotalSummary();
}
this.applyEmptyText();
},
beforeMenuShow: function () {
var item, items = this.hmenu.items, disabled = this.cm.config[this.hdCtxIndex].groupable === false;
if ((item = items.get('groupBy'))) {
item.setDisabled(disabled);
}
if ((item = items.get('showGroups'))) {
item.setDisabled(disabled);
item.setChecked(this.canGroup(), true);
}
},
processEvent: function (name, e) {
Ext.grid.GridView.prototype.processEvent.call(this, name, e);
var hd = e.getTarget('.x-grid-group-hd', this.mainBody);
if (hd) {
// group value is at the end of the string
var field = this.getGroupField(),
prefix = this.getPrefix(field),
groupValue = hd.id.substring(prefix.length),
emptyRe = new RegExp('gp-' + Ext.escapeRe(field) + '--hd');
// remove trailing '-hd'
groupValue = groupValue.substr(0, groupValue.length - 3);
// also need to check for empty groups
if (groupValue || emptyRe.test(hd.id)) {
this.grid.fireEvent('group' + name, this.grid, field, groupValue, e);
}
if (name == 'mousedown' && e.button == 0) {
this.toggleGroup(hd.parentNode);
}
}
},
onGroupByClick: function () {
var grid = this.grid;
this.enableGrouping = true;
grid.store.groupBy(this.cm.getDataIndex(this.hdCtxIndex));
grid.fireEvent('groupchange', grid, grid.store.getGroupState());
this.beforeMenuShow(); // Make sure the checkboxes get properly set when changing groups
this.refresh();
},
onShowGroupsClick: function (mi, checked) {
this.enableGrouping = checked;
if (checked) {
this.onGroupByClick();
} else {
this.grid.store.clearGrouping();
this.grid.fireEvent('groupchange', this, null);
}
},
/**
* Toggle the group that contains the specific row.
* @param {Number} rowIndex The row inside the group
* @param {Boolean} expanded (optional)
*/
toggleRowIndex: function (rowIndex, expanded) {
if (!this.canGroup()) {
return;
}
var row = this.getRow(rowIndex);
if (row) {
this.toggleGroup(this.findGroup(row), expanded);
}
},
findGroupNodes: function (groupNodeId) {
var gel, lgel;
var els = this.mainBody.dom.childNodes,
lels = this.lockedBody.dom.childNodes;
var isSameGroup = function (g1, g2) {
// Приводим к одному виду xxxx-l
if (g1 && g1.substr(g1.length - 2) !== '-l') {
g1 += '-l';
}
if (g2 && g2.substr(g1.length - 2) !== '-l') {
g2 += '-l';
}
return g1 === g2;
};
if (els && lels) {
for (var i = 0; i < els.length; i++) {
if (isSameGroup(els[i].id, groupNodeId)) {
gel = els[i];
break;
}
}
for (var j = 0; j < lels.length; j++) {
if (isSameGroup(lels[j].id, groupNodeId)) {
lgel = lels[j];
break;
}
}
}
return [gel , lgel];
},
/**
* Toggles the specified group if no value is passed, otherwise sets the expanded state of the group to the value passed.
* @param {String} groupId The groupId assigned to the group (see getGroupId)
* @param {Boolean} expanded (optional)
*/
toggleGroup: function (group, expanded) {
var grNodes = this.findGroupNodes(group.id),
gel = grNodes[0],
lgel = grNodes[1];
if ((!gel) || (!lgel)) {
return;
}
expanded = Ext.isDefined(expanded) ? expanded : group.className.indexOf('x-grid-group-collapsed') > -1;
if (this.state[group.id] !== expanded) {
if (this.cancelEditOnToggle !== false) {
this.grid.stopEditing(true);
}
this.state[group.id] = expanded;
if (expanded) {
var idx = gel.className.indexOf('x-grid-group-collapsed');
if (idx > -1) {
gel.className = gel.className.replace('x-grid-group-collapsed', '');
}
var lidx = lgel.className.indexOf('x-grid-group-collapsed');
if (lidx > -1) {
lgel.className = lgel.className.replace('x-grid-group-collapsed', '');
}
} else {
var idx = gel.className.indexOf('x-grid-group-collapsed');
if (idx < 0) {
gel.className = gel.className.concat(' x-grid-group-collapsed');
}
var lidx = lgel.className.indexOf('x-grid-group-collapsed');
if (lidx < 0) {
lgel.className = lgel.className.concat(' x-grid-group-collapsed');
}
}
}
},
/**
* Toggles all groups if no value is passed, otherwise sets the expanded state of all groups to the value passed.
* @param {Boolean} expanded (optional)
*/
toggleAllGroups: function (expanded) {
var groups = this.getGroups();
for (var i = 0, len = groups.length; i < len; i++) {
this.toggleGroup(groups[i], expanded);
}
},
/**
* Expands all grouped rows.
*/
expandAllGroups: function () {
this.toggleAllGroups(true);
},
/**
* Collapses all grouped rows.
*/
collapseAllGroups: function () {
this.toggleAllGroups(false);
},
getGroup: function (v, r, groupRenderer, rowIndex, colIndex, ds) {
var column = this.cm.config[colIndex],
g = groupRenderer ? groupRenderer.call(column.scope, v, {}, r, rowIndex, colIndex, ds) : String(v);
if (g === '' || g === ' ') {
g = column.emptyGroupText || this.emptyGroupText;
}
return g;
},
getGroupField: function () {
return this.grid.store.getGroupState();
},
renderRows: function () {
var groupField = this.getGroupField();
var eg = !!groupField;
// if they turned off grouping and the last grouped field is hidden
if (this.hideGroupedColumn) {
var colIndex = this.cm.findColumnIndex(groupField),
hasLastGroupField = Ext.isDefined(this.lastGroupField);
if (!eg && hasLastGroupField) {
this.mainBody.update('');
this.lockedBody.update('');
this.cm.setHidden(this.cm.findColumnIndex(this.lastGroupField), false);
delete this.lastGroupField;
} else if (eg && !hasLastGroupField) {
this.lastGroupField = groupField;
this.cm.setHidden(colIndex, true);
} else if (eg && hasLastGroupField && groupField !== this.lastGroupField) {
this.mainBody.update('');
this.lockedBody.update('');
var oldIndex = this.cm.findColumnIndex(this.lastGroupField);
this.cm.setHidden(oldIndex, false);
this.lastGroupField = groupField;
this.cm.setHidden(colIndex, true);
}
}
return Ext.grid.GridView.prototype.renderRows.apply(
this, arguments);
},
/**
* Dynamically tries to determine the groupId of a specific value
* @param {String} value
* @return {String} The group id
*/
getGroupId: function (value) {
var field = this.getGroupField();
return this.constructId(value, field, this.cm.findColumnIndex(field));
},
constructId: function (value, field, idx) {
var cfg = this.cm.config[idx],
groupRenderer = cfg.groupRenderer || cfg.renderer,
val = (this.groupMode == 'value') ? value : this.getGroup(value, {data: {}}, groupRenderer, 0, idx, this.ds);
return this.getPrefix(field) + Ext.util.Format.htmlEncode(val);
},
canGroup: function () {
return this.enableGrouping && !!this.getGroupField();
},
getPrefix: function (field) {
return this.grid.getGridEl().id + '-gp-' + field + '-';
},
doGroupStart: function (buf, g, cs, ds, colCount, locked) {
if (locked) {
buf[buf.length] = this.templates.startGroup.apply(g);
} else {
buf[buf.length] = this.templates.startLockedGroup.apply(g);
}
},
doGroupEnd: function (buf, g, cs, ds, colCount, lockedArea) {
var data = this.calculate(g.rs, cs);
buf.push('</div>', this.renderSummary({data: data}, cs, lockedArea), '</div>');
},
getRows: function () {
if (!this.canGroup()) {
return Ext.grid.GridView.prototype.getRows.call(this);
}
var r = [],
gs = this.getGroups(),
g,
i = 0,
len = gs.length,
j,
jlen;
for (; i < len; ++i) {
g = gs[i].childNodes[1];
if (g) {
g = g.childNodes;
for (j = 0, jlen = g.length; j < jlen; ++j) {
r[r.length] = g[j];
}
}
}
return r;
},
updateGroupWidths: function () {
if (!this.canGroup() || !this.hasRows()) {
return;
}
var tw = this.getTotalWidth(),
ltw = this.getLockedWidth(),
gs = this.getGroups(false),
lgs = this.getGroups(true),
lcount = this.cm.getLockedCount();
for (var i = 0, len = gs.length; i < len; i++) {
gs[i].firstChild.style.width = tw;
var s = gs[i].childNodes[2];
if (s) {
s.style.width = tw;
s.firstChild.style.width = tw;
var cells = s.firstChild.rows[0].childNodes;
for (var j = 0; j < cells.length; j++) {
cells[j].style.width = this.getColumnWidth(j + lcount);
cells[j].style.display = this.cm.isHidden(j + lcount) ? 'none' : '';
}
}
}
for (var k = 0, len = lgs.length; k < len; k++) {
lgs[k].firstChild.style.width = ltw;
var s = lgs[k].childNodes[2];
if (s) {
s.style.width = ltw;
s.firstChild.style.width = ltw;
var cells = s.firstChild.rows[0].childNodes;
for (var j = 0; j < cells.length; j++) {
cells[j].style.width = this.getColumnWidth(j);
cells[j].style.display = this.cm.isHidden(j) ? 'none' : '';
}
}
}
this.syncGroupHeaderHeights();
},
onLayout: function () {
this.updateGroupWidths();
},
onBeforeRowSelect: function (sm, rowIndex) {
this.toggleRowIndex(rowIndex, true);
},
//GroupSummary methods
calculate: function (rs, cs) {
var data = {}, r, c, cfg = this.cm.config, cf;
for (var j = 0, jlen = rs.length; j < jlen; j++) {
r = rs[j];
for (var i = 0, len = cs.length; i < len; i++) {
c = cs[i];
cf = cfg[i];
if (cf.summaryType) {
data[c.name] = Ext.ux.grid.GroupSummary.Calculations[cf.summaryType](data[c.name] || 0, r, c.name, data);
}
}
}
return data;
},
renderSummary: function (o, cs, lockedArea) {
cs = cs || this.getColumnData();
var cfg = this.cm.config,
buf = [],
first = lockedArea ? 0 : this.cm.getLockedCount(),
last = lockedArea ? this.cm.getLockedCount() - 1 : cs.length - 1;
for (var i = first; i <= last; i++) {
var c = cs[i],
cf = cfg[i],
p = {};
p.id = c.id;
p.style = c.style;
p.css = i == 0 ? 'x-grid3-cell-first ' : (i == cs.length - 1 ? 'x-grid3-cell-last ' : '');
/*
* не применяем рендерер столбца
*
if (cf.summaryType || cf.summaryRenderer) {
p.value = (cf.summaryRenderer || c.renderer)(o.data[c.name], p, o, undefined, i, this.ds);
} */
if (cf.summaryRenderer) {
p.value = cf.summaryRenderer(o.data[c.name], p, o, undefined, i, this.ds);
} else {
p.value = o.data[c.name];
}
if (p.value == undefined || p.value === "") p.value = " ";
buf[buf.length] = this.templates.cell.apply(p);
}
return this.templates.summaryRow.apply({
tstyle: 'width:' + (lockedArea ? this.getLockedWidth() : this.getTotalWidth()) + ';',
cells: buf.join('')
});
},
refreshSummaryById: function (gid) {
var groupNodes = this.findGroupNodes(gid),
lockedGrNode = groupNodes[1],
unlockedGrNode = groupNodes[0],
rs = [];
if ((!lockedGrNode) || (!unlockedGrNode)) {
return false;
}
this.grid.getStore().each(function (r) {
if (r._groupId == gid) {
rs[rs.length] = r;
}
});
var cs = this.getColumnData(),
data = this.calculate(rs, cs),
markup = this.renderSummary({data: data}, cs, false),
lmarkup = this.renderSummary({data: data}, cs, true),
existing = unlockedGrNode.childNodes[2],
lexisting = lockedGrNode.childNodes[2];
if (existing) {
unlockedGrNode.removeChild(existing);
}
Ext.DomHelper.append(unlockedGrNode, markup);
if (lexisting) {
lockedGrNode.removeChild(lexisting);
}
Ext.DomHelper.append(lockedGrNode, lmarkup);
return true;
},
onUpdate: function (ds, record) {
Ext.grid.GridView.prototype.onUpdate.apply(this, arguments);
this.refreshSummaryById(record._groupId);
this.updateTotalSummary();
}
},
splitZoneConfig: {
allowHeaderDrag: function (e) {
return !e.getTarget(null, null, true).hasClass('ux-grid-hd-group-cell');
}
},
columnDropConfig: {
getTargetFromEvent: function (e) {
var t = Ext.lib.Event.getTarget(e);
return this.view.findHeaderCell(t);
},
positionIndicator: function (h, n, e) {
var data = Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.getDragDropData.call(this, h, n, e);
if (data === false) {
return false;
}
var px = data.px + this.proxyOffsets[0];
this.proxyTop.setLeftTop(px, data.r.top + this.proxyOffsets[1]);
this.proxyTop.show();
this.proxyBottom.setLeftTop(px, data.r.bottom);
this.proxyBottom.show();
return data.pt;
},
onNodeDrop: function (n, dd, e, data) {
var h = data.header;
if (h != n) {
var d = Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.getDragDropData.call(this, h, n, e);
if (d === false) {
return false;
}
var cm = this.grid.colModel, right = d.oldIndex < d.newIndex, rows = cm.rows;
for (var row = d.row, rlen = rows.length; row < rlen; row++) {
var r = rows[row], len = r.length, fromIx = 0, span = 1, toIx = len;
for (var i = 0, gcol = 0; i < len; i++) {
var group = r[i];
if (d.oldIndex >= gcol && d.oldIndex < gcol + group.colspan) {
fromIx = i;
}
if (d.oldIndex + d.colspan - 1 >= gcol && d.oldIndex + d.colspan - 1 < gcol + group.colspan) {
span = i - fromIx + 1;
}
if (d.newIndex >= gcol && d.newIndex < gcol + group.colspan) {
toIx = i;
}
gcol += group.colspan;
}
var groups = r.splice(fromIx, span);
rows[row] = r.splice(0, toIx - (right ? span : 0)).concat(groups).concat(r);
}
for (var c = 0; c < d.colspan; c++) {
var oldIx = d.oldIndex + (right ? 0 : c), newIx = d.newIndex + (right ? -1 : c);
cm.moveColumn(oldIx, newIx);
this.grid.fireEvent("columnmove", oldIx, newIx);
}
return true;
}
return false;
}
},
getGroupRowIndex: function (el) {
if (el) {
var m = el.className.match(this.hrowRe);
if (m && m[1]) {
return parseInt(m[1], 10);
}
}
return this.cm.rows.length;
},
getGroupSpan: function (row, col) {
if (row < 0) {
return {
col: 0,
colspan: this.cm.getColumnCount()
};
}
var r = this.cm.rows[row];
if (r) {
for (var i = 0, gcol = 0, len = r.length; i < len; i++) {
var group = r[i];
if (col >= gcol && col < gcol + group.colspan) {
return {
col: gcol,
colspan: group.colspan
};
}
gcol += group.colspan;
}
return {
col: gcol,
colspan: 0
};
}
return {
col: col,
colspan: 1
};
},
getDragDropData: function (h, n, e) {
if (h.parentNode != n.parentNode) {
return false;
}
var cm = this.grid.colModel, x = Ext.lib.Event.getPageX(e), r = Ext.lib.Dom.getRegion(n.firstChild), px, pt;
if ((r.right - x) <= (r.right - r.left) / 2) {
px = r.right + this.view.borderWidth;
pt = "after";
} else {
px = r.left;
pt = "before";
}
var oldIndex = this.view.getCellIndex(h), newIndex = this.view.getCellIndex(n);
if (cm.isFixed(newIndex)) {
return false;
}
var row = Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.getGroupRowIndex.call(this.view, h),
oldGroup = Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.getGroupSpan.call(this.view, row, oldIndex),
newGroup = Ext.ux.grid.LockingGridColumnWithHeaderGroup.prototype.getGroupSpan.call(this.view, row, newIndex),
oldIndex = oldGroup.col;
newIndex = newGroup.col + (pt == "after" ? newGroup.colspan : 0);
if (newIndex >= oldGroup.col && newIndex <= oldGroup.col + oldGroup.colspan) {
return false;
}
var parentGroup = Ext.ux.grid.ColumnHeaderGroup.prototype.getGroupSpan.call(this.view, row - 1, oldIndex);
if (newIndex < parentGroup.col || newIndex > parentGroup.col + parentGroup.colspan) {
return false;
}
return {
r: r,
px: px,
pt: pt,
row: row,
oldIndex: oldIndex,
newIndex: newIndex,
colspan: oldGroup.colspan
};
}
});
|
jattySu/hrms
|
src/main/java/com/hrms/dao/impl/EmployeeRedeployDaoImpl.java
|
package com.hrms.dao.impl;
import org.springframework.stereotype.Repository;
import com.hrms.dao.IEmployeeRedeployDao;
import com.hrms.model.EmployeeRedeploy;
@Repository("employeeRedeployDao")
public class EmployeeRedeployDaoImpl extends GenericDaoImpl<EmployeeRedeploy, Integer>
implements IEmployeeRedeployDao{
}
|
zhawan/maro
|
maro/simulator/scenarios/helpers.py
|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.s
import sys
import warnings
from datetime import datetime
from dateutil.tz import UTC
from dateutil.relativedelta import relativedelta
from maro.backends.frame import node, NodeBase, NodeAttribute
timestamp_start = datetime(1970, 1, 1, 0, 0, 0, tzinfo=UTC)
def utc_timestamp_to_timezone(timestamp: int, timezone):
"""Convert utc timestamp into specified tiemzone datetime
Args:
timestamp(int): UTC timestamp to convert
timezone: target timezone
"""
if sys.platform == "win32":
# windows do not support negative timestamp, use this to support it
return (timestamp_start + relativedelta(seconds=timestamp)).astimezone(timezone)
else:
return datetime.utcfromtimestamp(timestamp).replace(tzinfo=UTC).astimezone(timezone)
class DocableDict:
"""A thin wrapper that provide a read-only dictionary with customized doc
Args:
doc (str): customized doc of the dict
kwargs (dict): dictionary items to store
"""
def __init__(self, doc: str, **kwargs):
self._original_dict = kwargs
DocableDict.__doc__ = doc
def __getattr__(self, name):
return getattr(self._original_dict, name, None)
def __getitem__(self, k):
return self._original_dict[k]
def __setitem__(self, k, v):
warnings.warn("Do not support add new key")
def __getstate__(self):
return self.__dict__
def __setstate__(self, state):
self.__dict__.update(state)
def __repr__(self):
return self._original_dict.__repr__()
def __str__(self):
return self.__repr__()
def __len__(self):
return len(self._original_dict)
class MatrixAttributeAccessor:
"""Wrapper for each attribute with matrix like interface
Args:
node(NodeBase): node instance the attribute belongs to
attribute(str): attribute name to wrap
row_num(int): result matrix row number
col_num(int): result matrix column number
"""
def __init__(self, node: NodeBase, attribute: str, row_num: int, col_num: int):
self._node = node
self._attr = None
self._attr_name = attribute
self._row_num = row_num
self._col_num = col_num
@property
def columns(self):
"""Get column number"""
return self._col_num
@property
def rows(self):
"""Get row number"""
return self._row_num
def _ensure_attr(self):
"""Ensure that the attribute instance correct"""
if self._attr is None:
self._attr = getattr(self._node, self._attr_name, None)
assert self._attr is not None
def __getitem__(self, item: tuple):
key_type = type(item)
self._ensure_attr()
if key_type == tuple:
row_idx = item[0]
column_idx = item[1]
return self._attr[self._col_num * row_idx + column_idx]
elif key_type == slice:
return self._attr[:]
def __setitem__(self, key: tuple, value:int):
key_type = type(key)
self._ensure_attr()
if key_type == tuple:
row_idx = key[0]
column_idx = key[1]
self._attr[self._col_num * row_idx + column_idx] = value
elif key_type == slice:
# slice will ignore all parameters, and set values for all slots
self._attr[:] = value
def get_row(self, row_idx: int):
"""Get values of a row"""
self._ensure_attr()
start = self._col_num * row_idx
return self._attr[start: start + self._col_num]
def get_column(self, column_idx: int):
"""Get values of a column"""
self._ensure_attr()
rows = [r * self._col_num + column_idx for r in range(self._row_num)]
return self._attr[rows]
|
EricPW/custom-gatsby-contentful-build
|
src/components/insights/insightsList.js
|
<gh_stars>0
import React from 'react'
import { graphql, useStaticQuery, Link } from 'gatsby'
import Img from 'gatsby-image'
import styled from 'styled-components'
import Insight from './insight'
const List = styled.ul`
list-style: none;
`
const ListItem = styled.li`
&:last-child {
article {
margin-bottom: 0;
}
}
`
const InsightsList = (props) => {
return (
<List className={props.className}>
{props.posts.map((post, index) => {
post = post.node || post
return (
<ListItem key={post.index} style={{ marginBottom: `1.925rem` }}>
<Insight {...post} />
</ListItem>
)
})}
</List>
)
}
export default InsightsList
|
4dams/ArdentGirl
|
index.js
|
<reponame>4dams/ArdentGirl<gh_stars>1-10
var tmi = require("tmi.js")
var moment = require("moment")
var fs = require("fs")
var jsonfile = require("jsonfile")
var request = require("request")
var winston = require("winston")
var config = require("./config.json")
var client = new tmi.client({
"options": {
"debug": false
},
"connection": {
"reconnect": true
},
"identity": {
"username": config.twitch.username,
"password": <PASSWORD>
},
"channels": config.twitch.channels
})
var startTime = moment()
var version = config.bot.version
var totalCommands = 0
var messagePrefix = config.bot.messagePrefix
var developers = config.bot.developers
var apiKey = config.league.apiKey
var apiEndpoint = config.league.apiEndpoint
var lolVersion = config.league.gameVersion
var champList
var logger = new(winston.Logger)({
transports: [
new(winston.transports.Console)({
'timestamp': true
}),
new(winston.transports.File)({
filename: 'process.log'
})
]
})
function getChampionList() {
request('http://ddragon.leagueoflegends.com/cdn/' + lolVersion + '/data/de_DE/champion.json', (error, response, body) => {
var list = JSON.parse(body)
champList = list.data
logger.log(`info`, ` Global | Champion List Loaded`)
})
}
getChampionList()
client.on("chat", (channel, userstate, message, self) => {
if (self) return
if (message.indexOf(config.bot.prefix) !== 0) return
let args = message.slice(config.bot.prefix.length).trim().split(/ +/g)
let command = args.shift().toLowerCase()
try {
let commandFile = require(`./commands/${channel.split('#')[1]}/${command}.js`)
logger.log(`info`, ` ${channel.split('#')[1]} | Command Used | ${config.bot.prefix}${command}`)
commandFile.run(client, channel, userstate, message, messagePrefix, startTime, version, totalCommands, developers, apiKey, apiEndpoint, args, champList)
totalCommands++
} catch (err) {
logger.log(`info`, `${err}`)
}
})
client.on("cheer", (channel, userstate, message) => {
try {
let eventFile = require(`./events/${channel.split('#')[1]}/cheer.js`)
logger.log(`info`, ` ${channel.split('#')[1]} | Cheer Event`)
eventFile.run(client, channel, userstate, message)
} catch (err) {
logger.log(`info`, `${err}`)
}
})
client.on("hosted", (channel, username, viewers, autohost) => {
try {
let eventFile = require(`./events/${channel.split('#')[1]}/hosted.js`)
logger.log(`info`, ` ${channel.split('#')[1]} | Host Event`)
eventFile.run(client, channel, username, viewers, autohost)
} catch (err) {
logger.log(`info`, `${err}`)
}
})
client.on("resub", (channel, username, months, message, userstate, methods) => {
try {
let eventFile = require(`./events/${channel.split('#')[1]}/resub.js`)
logger.log(`info`, ` ${channel.split('#')[1]} | Resub Event`)
eventFile.run(client, channel, username, months, message, userstate, methods)
} catch (err) {
logger.log(`info`, `${err}`)
}
})
client.on("subscription", (channel, username, method, message, userstate) => {
try {
let eventFile = require(`./events/${channel.split('#')[1]}/subscription.js`)
logger.log(`info`, ` ${channel.split('#')[1]} | Subscription Event`)
eventFile.run(client, channel, username, method, message, userstate)
} catch (err) {
logger.log(`info`, `${err}`)
}
})
client.connect()
|
josemonsalve2/SCM
|
SCMUlate/src/machines/scm_machine.cpp
|
#include "scm_machine.hpp"
#include <iostream>
scm::scm_machine::scm_machine(char * in_filename, l2_memory_t const memory, ILP_MODES ilp_mode):
alive(false),
init_correct(true),
filename(in_filename),
reg_file_m(),
inst_mem_m(filename, ®_file_m),
control_store_m(NUM_CUS),
fetch_decode_m(&inst_mem_m, &control_store_m, &alive, ilp_mode) {
SCMULATE_INFOMSG(0, "Initializing SCM machine")
// Configuration parameters
// We check the register configuration is valid
if(!reg_file_m.checkRegisterConfig()) {
SCMULATE_ERROR(0, "Error when checking the register");
init_correct = false;
return;
}
if(!inst_mem_m.isValid()) {
SCMULATE_ERROR(0, "Error when loading file");
init_correct = false;
return;
}
TIMERS_COUNTERS_GUARD(
this->fetch_decode_m.setTimerCounter(&this->time_cnt_m);
this->time_cnt_m.addTimer("SCM_MACHINE",scm::SYS_TIMER);
)
// Creating execution Units
int exec_units_threads[] = {CUS};
int * cur_exec = exec_units_threads;
for (int i = 0; i < NUM_CUS; i++, cur_exec++) {
SCMULATE_INFOMSG(4, "Creating executor (CUMEM) %d out of %d for thread %d", i, NUM_CUS, *cur_exec);
cu_executor_module* newExec = new cu_executor_module(*cur_exec, &control_store_m, i, &alive, memory);
TIMERS_COUNTERS_GUARD(
newExec->setTimerCnt(&this->time_cnt_m);
)
executors_m.push_back(newExec);
}
init_correct = true;
ITT_RESUME;
}
scm::run_status
scm::scm_machine::run() {
if (!this->init_correct) return SCM_RUN_FAILURE;
TIMERS_COUNTERS_GUARD(
this->time_cnt_m.resetTimer();
this->time_cnt_m.addEvent("SCM_MACHINE",SYS_START);
);
this->alive = true;
int run_result = 0;
std::chrono::time_point<std::chrono::high_resolution_clock> timer = std::chrono::high_resolution_clock::now();
#pragma omp parallel reduction(+: run_result) shared(alive) num_threads(NUM_CUS+1)
{
#pragma omp master
{
SCMULATE_INFOMSG(1, "Running with %d threads ", omp_get_num_threads());
}
switch (omp_get_thread_num()) {
case SU_THREAD:
fetch_decode_m.behavior();
break;
case CU_THREADS:
// Find my executor
for (auto it = executors_m.begin(); it < executors_m.end(); ++it) {
if ((*it)->get_executor_id() == omp_get_thread_num()) {
(*it)->behavior();
break; // exit for loop
}
}
break;
default:
{
// Initialization barrier
#pragma omp barrier
SCMULATE_WARNING(0, "Thread created with no purpose. What's my purpose? You pass the butter");
}
}
#pragma omp barrier
}
std::chrono::time_point<std::chrono::high_resolution_clock> timer2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = timer2 - timer;
std::cout << "Exec Time = " << diff.count() << std::endl;
TIMERS_COUNTERS_GUARD(
this->time_cnt_m.addEvent("SCM_MACHINE",SYS_END);
);
if (run_result != 0 ) return SCM_RUN_FAILURE;
return SCM_RUN_SUCCESS;
}
scm::scm_machine::~scm_machine() {
ITT_PAUSE;
for (auto it = executors_m.begin(); it < executors_m.end(); ++it)
delete (*it);
TIMERS_COUNTERS_GUARD(
this->time_cnt_m.dumpTimers();
);
}
|
bandaloo/proc-cave-game
|
static/test/run.js
|
<reponame>bandaloo/proc-cave-game<filename>static/test/run.js
import "./vector.test.js";
import "./collision.test.js";
mocha.checkLeaks();
mocha.run();
|
hdowalil/software-design
|
training-clean/clean-inheritance/src/main/java/lab01/excercise/solution/your/package-info.java
|
<gh_stars>1-10
/**
* implement the requested functionality without violation of liskovs substition principle, think about the contracts!
*/
package lab01.excercise.solution.your;
|
codepoet80/webos-forums
|
app/javascripts/formatting.js
|
<filename>app/javascripts/formatting.js<gh_stars>0
var Formatting = Class.create({
formatForumImage: function(value, model) {
var composedImage;
if (value) {
composedImage = value;
//TODO: check debug setting
if (value.length > 0) {
Mojo.Log.info("formatForumImage(), value:" + value);
}
} else {
composedImage = 'images/default-forum-blue.png';
}
return composedImage;
},
formatCanReply: function(value, model) {
//Mojo.Log.info(value)
if(value == true) {
return "momentary";
} else {
return "none";
}
},
formatIsOnline: function(value, model) {
var returnText = "";
if (value) {
returnText = "connected";
} else {
returnText = "";
}
return returnText;
},
formatTopicImage: function(value, model) {
// Mojo.Log.info("formatTopicImage: " + value);
if(!value) {
//model.show_user_image = "hidden";
model.icon_url = "images/list-avatar-default.png";
value = model.icon_url;
}
else if (value.indexOf("http") != 0) {
if (value.indexOf("//") != 0) {
value = "http://" + value;
} else {
value = "http:" + value;
}
model.icon_url = value;
}
var composedImage = "<img src='" + value + "'/>";
// Mojo.Log.info("formatTopicImage, returning: " + composedImage);
return composedImage;
//return value;
},
formatTopicTitle: function(value, model) {
//this only escapes topic titles.
return escape(value);
},
getNiceDate: function(value, model){
if (false && appSettings.debug.dumpPosts && appSettings.debug.detailedLogging) {
Mojo.Log.warn("getNiceDate called with value: " + value);
//model is the whole object the value is attached to -- the list item generally.
//Mojo.Log.info("getNiceDate, model: " + JSON.stringify(model));
}
var d = new Date();
if (value !== undefined) {
d.setTime(value);
}
else {
//mw I think I added this as defensive code while debugging recent post problem.
//Mojo.Log.warn("getNiceDate - date was undefined.. using current date.");
}
var getLocalDate = function (originalDate){
var offSet = d.getTimezoneOffset();
offSet = offSet*60000;
var cleanDate = new Date();
cleanDate.setTime(originalDate.getTime()+offSet);
return cleanDate;
};
d = getLocalDate(d);
model.niceDate = BucketDateFormatter.getDateBucket(d, false, false);
var midnight = new Date();
midnight.setHours(0,0,0,1);
//Mojo.Log.warn("getNiceDate - ORIGINAL: ",d);
if (d > midnight) {
model.dividerStyle = "display:none;"
//Mojo.Log.warn("getNiceDate - formatted: " + Mojo.Format.formatDate(d, {time:'short'}));
return Mojo.Format.formatDate(d, {time:'short'});
} else {
//Mojo.Log.warn("getNiceDate - formatted: " + Mojo.Format.formatDate(d, {time:'short'}));
return Mojo.Format.formatDate(d, {date:'short'});
}
},
formatPostContent: function(value, model) {
if (appSettings.Tapatalk.config.disable_html) {
model.textFormat = "";
} else {
model.textFormat = "html";
}
if (!!value) {
try {
var emotifiedText = appSettings.Formatting.getEmoticons(value);
//var emotifiedText = Mojo.Format.runTextIndexer(value);
//var listedText = emotificedText; //appSettings.Formatting.getLists(emotifiedText);
var myHTML = myParser.toHTML(emotifiedText);
//myHTML = appSettings.Formatting.getEmoticons(myHTML);
return myHTML;
} catch(e) {
Mojo.Log.error("ERROR PARSING BBCODE", e);
return value;
}
}
},
formatIfNewPosts: function(value, model) {
if (!!value) {
var strStyle = "";
if (value) {
strStyle = "hasNewPosts";
return strStyle
} else {
strStyle = "";
return strStyle
}
}
},
formatIfUrlPlaceholder: function(value, model) {
if (!value) {
return "hidden";
}
else {
return "";
}
},
formatForumSubscribed: function(value, model) {
if(!value) {
value = "hidden";
} else {
value = "";
}
if (!model.is_closed) {
model.is_closed = false;
}
return value;
},
formatForumClosed: function(value, model) {
if(!value) {
value = "hidden";
} else {
value = "";
}
return value;
},
/**
* Formatting message status
*/
formatMessageStatus: function(value, model) {
var returnValue = "";
if (value == 1) {
returnValue = "<img src='images/list-unread.png' width='18' height='18' style='position:absolute;top:28px;left:5px;'/>";
model.read = "unread";
}
else
if (value == 2) {
returnValue = "";
}
else
if (value == 3) {
returnValue = "<img src='images/list-reply.png' width='18' height='18' style='position:absolute;top:28px;left:5px;'/>";
}
else
if (value == 4) {
returnValue = "<img src='images/list-forward.png' width='18' height='18' style='position:absolute;top:28px;left:5px;'/>";
}
return returnValue;
},
formatMessageDate: function(value, model) {
var d = new Date();
d.setTime(value);
var getLocalDate = function (originalDate){
var offSet = d.getTimezoneOffset();
offSet = offSet*60000;
var cleanDate = new Date();
cleanDate.setTime(originalDate.getTime()+offSet);
return cleanDate;
};
d = getLocalDate(d);
model.niceDate = BucketDateFormatter.getDateBucket(d, false, false);
var midnight = new Date();
midnight.setHours(0,0,0,1);
//Mojo.Log.warn("ORIGINAL: ",d);
if (d > midnight) {
//Mojo.Log.warn(Mojo.Format.formatDate(d, {time:'short'}));
return Mojo.Format.formatDate(d, {time:'short'});
} else {
//Mojo.Log.warn(Mojo.Format.formatDate(d, {time:'short'}));
return Mojo.Format.formatDate(d, {date:'short'});
}
},
formatMessageRecipients: function (value, model) {
var formattedNames = "";
if (value) {
for (var i = 0; i < value.length; i++) {
if (formattedNames) {
formattedNames = formattedNames + ";";
}
if (value[i].display_name) {
formattedNames = formattedNames + value[i].display_name;
}
else {
formattedNames = formattedNames + value[i].username;
}
}
return formattedNames;
} else {
return value;
}
},
chooseThumbnailOrUrl: function(value, model) {
if (value == "") {
//Mojo.Log.info("chooseThumbnailOrUrl returning " + model.url);
//Full size image URL
//return model.url;
//Nice blue paperclip
//return "http://b.dryicons.com/images/icon_sets/coquette_part_2_icons_set/png/64x64/attachment.png";
//Attempt to use cmd menu attach icon
//return Mojo.appPath + "./images/attach-64.png";
return Mojo.Config.IMAGES_HOME + "/menu-icon-attach.png";
//return Mojo.Config.IMAGES_HOME + "/corrupt-image.png";
//return Mojo.Config.IMAGES_HOME + "/details-image-generic.png";
} else {
//Mojo.Log.info("chooseThumbnailOrUrl returning " + value);
return value;
}
},
getEmoticons: function(text) {
/*
text = text.replace(/(\W|^):confused:/g,'<img src="images/emoticons/emoticon-confused.png" />');
text = text.replace(/(\W|^):laugh:/gi,'<img src="images/emoticons/emoticon-laugh.png"/>');
text = text.replace(/(\W|^):lol:/gi,'<img src="images/emoticons/emoticon-laugh.png"/>');
text = text.replace(/(\W|^):neutral:/gi,'<img src="images/emoticons/emoticon-neutral.png"/>');
text = text.replace(/(\W|^):meh:/gi,'<img src="images/emoticons/emoticon-neutral.png"/>');
text = text.replace(/(\W|^):sick:/gi,'<img src="images/emoticons/emoticon-sick.png"/>');
text = text.replace(/(\W|^):smile:/gi,'<img src="images/emoticons/emoticon-smile.png"/>');
text = text.replace(/(\W|^):doh:/gi,'<img src="images/emoticons/emoticon-undecided.png"/>');
text = text.replace(/(\W|^):wink:/gi,'<img src="images/emoticons/emoticon-wink.png"/>');
text = text.replace(/(\W|^):yuck:/gi,'<img src="images/emoticons/emoticon-yuck.png"/>');
text = text.replace(/(\W|^):razz:/gi,'<img src="images/emoticons/emoticon-yuck.png"/>');
text = text.replace(/(\W|^):angry:/gi,'<img src="images/emoticons/emoticon-angry.png"/>');
text = text.replace(/(\W|^):mad:/gi,'<img src="images/emoticons/emoticon-angry.png"/>');
text = text.replace(/(\W|^):heart:/gi,'<img src="images/emoticons/emoticon-heart.png"/>');
text = text.replace(/(\W|^):evil:/gi,'<img src="images/emoticons/emoticon-naughty.png"/>');
text = text.replace(/(\W|^):twisted:/gi,'<img src="images/emoticons/emoticon-naughty.png"/>');
*/
// :thumbsup
text = text.replace(/(\W|^):thumbsup:/gi,'<img src="images/emoticons/emoticon-thumbsup.png"/>');
// :thumbsdown
text = text.replace(/(\W|^)(:thumbsdown:|:thumbsdwn:)/gi,'<img src="images/emoticons/emoticon-thumbsdown.png"/>');
//text = text.replace(/(\W|^):thumbsdwn:/gi,'<img src="images/emoticons/emoticon-thumbsdown.png"/>');
// :censored
text = text.replace(/(\W|^):censored:/gi,'<img src="images/emoticons/emoticon-censored.png"/>');
//o_O :confused
text = text.replace(/(\W|^)o_O/g,'<img src="images/emoticons/emoticon-confused.png" />');
text = text.replace(/(\W|^):confused:/gi,'<img src="images/emoticons/emoticon-confused.png" />');
// :Shake
text = text.replace(/(\W|^):shake:/gi,'<img src="images/emoticons/shake.gif"/>');
text = text.replace(/(\W|^):rolleyes:/gi,'<img src="images/emoticons/rolleyes.gif"/>');
text = text.replace(/(\W|^):brick:/gi,'<img src="images/emoticons/brick.gif"/>');
//8) 8-) B) B-) :cool
text = text.replace(/(\W|^)(8\)|8-\)|B\)|B-\)|:cool:)/g,'<img src="images/emoticons/emoticon-cool.png" />');
// :’( =’( :cry
text = text.replace(/(\W|^)(:´\(|\=´\(|:'\(|\='\(|:cry:)/g,'<img src="images/emoticons/emoticon-cry.png" />');
// :{ :-[ =[ =-[ :redface
text = text.replace(/(\W|^)(:\{|:-\[|\=\[|\=-\[|:redface:)/g,'<img src="images/emoticons/emoticon-embarrassed.png" />');
// :S :-S :s :-s %-( %( X-( X( :eww :gross
text = text.replace(/(\W|^)(:S\W|:-S|:eww:|:gross:)/gi,'<img src="images/emoticons/emoticon-eww.png"/>');
text = text.replace(/(\W|^)(\%-\(|\%\(|X-\(|X\()/g,'<img src="images/emoticons/emoticon-eww.png"/>');
// :! :_! :eek
text = text.replace(/(\W|^)(:\!|:\_\!|:eek:)/gi,'<img src="images/emoticons/emoticon-footinmouth.png"/>');
// :( :-( =( =-( :sad
text = text.replace(/(\W|^)(:\(|:-\(|\=\(|\=-\(|:sad:)/gi,'<img src="images/emoticons/emoticon-frown.png"/>');
// :O :-O :o :-o =O =-O =o =-o :surprised :shock :omg
text = text.replace(/(\W|^)(:O\W|:-O|\=O|\=-O|:surprised:|:shock:|:omg:)/gi,'<img src="images/emoticons/emoticon-gasp.png"/>');
// ^^ ^_^ ^-^ :grin :biggrin
text = text.replace(/(\W|^)(\^\^|\^\-\^|\^\_\^|:grin:|:biggrin:)/gi,'<img src="images/emoticons/emoticon-grin.png"/>');
// O:) O:-) o:) o:-) :innocent :angel
text = text.replace(/(\W|^)(o:\)|o:-\)|:innocent:|:angel:)/gi,'<img src="images/emoticons/emoticon-innocent.png"/>');
// :-* :* =* =-* :kiss
text = text.replace(/(\W|^)(:-\*|:\*|\=\*|\=-\*|:kiss:)/gi,'<img src="images/emoticons/emoticon-kiss.png"/>');
// :-D :D =D =-D :laugh :lol
text = text.replace(/(\W|^)(:-D|:D|=-D|=D|:laugh:|:lol:)/g,'<img src="images/emoticons/emoticon-laugh.png"/>');
// :| :-| :neutral :meh
text = text.replace(/(\W|^)(:\||:-\||:neutral:|:meh:)/gi,'<img src="images/emoticons/emoticon-neutral.png"/>');
// :-& :& =& =-& :-@ :@ =@ =-@ :sick
text = text.replace(/(\W|^)(:-&\W|:&\W|\=-&\W|\=&\W|:-&|:&|\=-&|\=&|:-\@|:\@|\=-\@|\=\@|:sick:)/gi,'<img src="images/emoticons/emoticon-sick.png"/>');
// :) :-) =) =-) :smile
text = text.replace(/(\W|^)(:\)|:-\)|=\)|=-\)|:smile:)/gi,' <img src="images/emoticons/emoticon-smile.png"/>');
// :/ :-/ :\ :-\ =/ =-/ =\ =-\ :doh
text = text.replace(/(\W|^)(:\/|:-\/|:\\|:-\\|\=\/|\=-\/|\=\\|\=-\\|:doh:)/g,'<img src="images/emoticons/emoticon-undecided.png"/>');
// ;) ;-) :wink
text = text.replace(/(\W|^)(;\)|;-\)|:wink:)/gi,'<img src="images/emoticons/emoticon-wink.png"/>');
// :P :-P :p :-p :b :-b =p =P =b =-b =-p =-P :yuck :razz
text = text.replace(/(\W|^)(:p|:-p|\=p|=-p|:yuck:|:razz:)/gi,'<img src="images/emoticons/emoticon-yuck.png"/>');
text = text.replace(/(\W|^)(:b|:-b|\=-b|\=b)/g,'<img src="images/emoticons/emoticon-yuck.png"/>');
// >:o >:-o >:O >:-O >:( >:-( :angry :mad
text = text.replace(/(\W|^)(>:-o|>:o|>:-\(|>:\(|:angry:|:mad:)/gi,'<img src="images/emoticons/emoticon-angry.png"/>');
// <3 :heart
text = text.replace(/(\W|^)(<3|:heart:)/gi,'<img src="images/emoticons/emoticon-heart.png"/>');
// >:-) >:) >:-> >:> :evil :twisted
text = text.replace(/(\W|^)(>:-\)|>:\)|>:->|>:>|:evil:|:twisted:)/gi,'<img src="images/emoticons/emoticon-naughty.png"/>');
/**
* REEMPLAZAMOS COMIENZO DE POSTS
*/
return text;
}
});
|
zealoussnow/chromium
|
components/language/content/browser/language_code_locator.h
|
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_LANGUAGE_CONTENT_BROWSER_LANGUAGE_CODE_LOCATOR_H_
#define COMPONENTS_LANGUAGE_CONTENT_BROWSER_LANGUAGE_CODE_LOCATOR_H_
#include <string>
#include <vector>
namespace language {
class LanguageCodeLocator {
public:
virtual ~LanguageCodeLocator() {}
// Get suitable language codes given a coordinate.
// If the latitude, longitude pair is not found, will return an empty vector.
virtual std::vector<std::string> GetLanguageCodes(double latitude,
double longitude) const = 0;
};
} // namespace language
#endif // COMPONENTS_LANGUAGE_CONTENT_BROWSER_LANGUAGE_CODE_LOCATOR_H_
|
venkaeswarak/nimbus-exercise
|
nimbus-test/src/main/java/com/antheminc/oss/nimbus/test/scenarios/s3/core/ServiceLine.java
|
<reponame>venkaeswarak/nimbus-exercise
/**
* Copyright 2016-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.antheminc.oss.nimbus.test.scenarios.s3.core;
import java.util.Date;
import java.util.List;
import com.antheminc.oss.nimbus.domain.defn.ConfigNature.Ignore;
import com.antheminc.oss.nimbus.domain.defn.Model;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* @author <NAME>
*/
@Model
@Getter @Setter @EqualsAndHashCode(of={"service", "something", "discharge", "elemId"})
public class ServiceLine {
@Ignore
private static final long serialVersionUID = 1L;
@Model
@Getter @Setter @EqualsAndHashCode(of={"by", "why", "when"})
public static class AuditInfo {
private String by;
private String why;
private Date when;
}
@Model
@Getter @Setter @EqualsAndHashCode(of={"yesNo", "audits"})
public static class Discharge {
private boolean yesNo;
private List<AuditInfo> audits;
}
private String service;
private String something;
private Discharge discharge;
private String elemId;
}
|
andriidem308/java_practice
|
src/university/classworks/classwork_2/task_4_6.java
|
package classwork_2;
import java.beans.Expression;
import java.util.Scanner;
public class task_4_6 {
public static int factorial(int number){
int r = 1;
for (int i = 1; i <= number; i++){
r *= i;
}
return r;
}
public static double function(double x, int y){
return (Math.pow(x, 2*y)) / (2 * factorial(y));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
double x, eps;
x = scanner.nextDouble();
eps = scanner.nextDouble();
double prev_sum_a = 1000;
double sum = 0;
int i = 0;
while (Math.abs(prev_sum_a - sum) > eps){
prev_sum_a = sum;
sum += function(x, i);
i+=1;
}
System.out.println("Sum: " + sum + "\nTerms amount: " + (i+1));
}
}
|
Magenic/JMAQS
|
jmaqs-appium/src/test/java/com/magenic/jmaqs/appium/MobileDriverManagerUnitTest.java
|
/*
* Copyright 2021 (C) Magenic, All rights Reserved
*/
package com.magenic.jmaqs.appium;
import com.magenic.jmaqs.base.BaseGenericTest;
import io.appium.java_client.AppiumDriver;
import java.util.function.Supplier;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.Test;
/**
* The type Mobile driver manager unit test.
*/
public class MobileDriverManagerUnitTest extends BaseGenericTest {
/**
* Test get mobile driver.
*/
@Test
public void testGetMobileDriver() {
Supplier<AppiumDriver<WebElement>> supplier = AppiumDriverFactory::getDefaultMobileDriver;
AppiumTestObject appiumTestObject = new AppiumTestObject(supplier, this.getLogger(),
this.getTestObject().getFullyQualifiedTestName());
try (MobileDriverManager mobileDriverManager = new MobileDriverManager(supplier, appiumTestObject)) {
Assert.assertNotNull(mobileDriverManager.getMobileDriver(), "Expected Mobile Driver to not be null.");
}
}
/**
* Test close.
*/
@Test
public void testClose() {
Supplier<AppiumDriver<WebElement>> supplier = AppiumDriverFactory::getDefaultMobileDriver;
MobileDriverManager mobileDriverManager = new MobileDriverManager(supplier, this.getTestObject());
mobileDriverManager.close();
Assert.assertNull(mobileDriverManager.getBaseDriver(), "Expected Mobile Driver to be null.");
}
/**
* Test close with instantiated driver.
*/
@Test
public void testCloseWithInstantiatedDriver() {
MobileDriverManager mobileDriverManager = new MobileDriverManager(AppiumDriverFactory.getDefaultMobileDriver(), this.getTestObject());
mobileDriverManager.close();
Assert.assertNull(mobileDriverManager.getBaseDriver(), "Expected Mobile Driver to be null.");
}
/**
* Test close null base driver.
*/
@Test
public void testCloseNullBaseDriver() {
Supplier<AppiumDriver<WebElement>> supplier = AppiumDriverFactory::getDefaultMobileDriver;
MobileDriverManager mobileDriverManager = new MobileDriverManager(supplier, this.getTestObject());
// Close once to make Base Driver null
mobileDriverManager.close();
// Close again with driver not initialized
mobileDriverManager.close();
Assert.assertNull(mobileDriverManager.getBaseDriver(), "Expected Base Driver to be null.");
}
}
|
patrickbjohnson/wtbr-tv
|
src/components/navigation.js
|
<filename>src/components/navigation.js
import React from 'react'
import { StaticQuery, graphql } from 'gatsby'
import Desktop from './nav-desktop'
import Mobile from './nav-mobile'
import MediaQuery from 'react-responsive'
export default () => (
<StaticQuery
query={graphql`
query {
allContentfulNavigation {
edges {
node {
navItem {
id
slug
pageName
pageHeadline
}
}
}
}
}
`}
render={data => {
const { navItem } = data.allContentfulNavigation.edges[0].node
return (
<div>
<MediaQuery minWidth={1024}>
<Desktop nav={navItem}/>
</MediaQuery>
<MediaQuery maxWidth={1024}>
<Mobile nav={navItem}/>
</MediaQuery>
</div>
)
}}
/>
)
|
narke/Aragveli
|
src/kernel/process/sched_rr.c
|
<filename>src/kernel/process/sched_rr.c
/*
* Copyright (c) 2017 <NAME>.
* All rights reserved.
* Use of this source code is governed by a MIT license that can be
* found in the LICENSE file.
*/
#include <lib/types.h>
#include <lib/c/string.h>
#include <lib/c/assert.h>
#include <lib/c/stdbool.h>
#include "scheduler.h"
TAILQ_HEAD(, thread) ready_threads;
void
scheduler_setup(void)
{
TAILQ_INIT(&ready_threads);
}
void
scheduler_insert_thread(thread_t *t)
{
/* Don't do anything for already ready threads */
if (t->state == THREAD_READY)
return;
/* Schedule it for the present turn */
assert((t->state == THREAD_CREATED)
|| (t->state == THREAD_RUNNING)
|| (t->state == THREAD_BLOCKED));
t->state = THREAD_READY;
thread_t *thread;
TAILQ_FOREACH(thread, &ready_threads, next)
{
if (t->priority > thread->priority)
break;
}
TAILQ_INSERT_TAIL(&ready_threads, t, next);
}
void
scheduler_remove_thread(thread_t *t)
{
TAILQ_REMOVE(&ready_threads, t, next);
}
thread_t *
scheduler_elect_new_current_thread(void)
{
return TAILQ_FIRST(&ready_threads);
}
void
schedule(void)
{
thread_t *current_thread = thread_get_current();
assert(TAILQ_EMPTY(&ready_threads) == false);
thread_t *next_thread = TAILQ_FIRST(&ready_threads);
TAILQ_REMOVE(&ready_threads, next_thread, next);
TAILQ_INSERT_TAIL(&ready_threads, next_thread, next);
next_thread->state = THREAD_READY;
thread_set_current(next_thread);
// Avoid context switch if the context does not change
if (current_thread != next_thread)
{
cpu_context_switch(¤t_thread->cpu_state,
next_thread->cpu_state);
assert(current_thread == thread_get_current());
assert(current_thread->state == THREAD_RUNNING);
}
}
|
cmbasnett/fake-bpy-module
|
modules/2.79/bpy/types/GPUSSAOSettings.py
|
class GPUSSAOSettings:
attenuation = None
color = None
distance_max = None
factor = None
samples = None
|
Simon-aikuier/inclavare-containers
|
enclave-tls/src/tls_wrappers/wolfssl/main.c
|
/* Copyright (c) 2020-2021 Alibaba Cloud and Intel Corporation
*
* SPDX-License-Identifier: Apache-2.0
*/
#include <enclave-tls/tls_wrapper.h>
#include <enclave-tls/log.h>
#include <enclave-tls/cert.h>
extern tls_wrapper_err_t wolfssl_pre_init(void);
extern tls_wrapper_err_t wolfssl_init(tls_wrapper_ctx_t *);
extern tls_wrapper_err_t wolfssl_use_privkey(tls_wrapper_ctx_t *ctx, void *privkey_buf,
size_t privkey_len);
extern tls_wrapper_err_t wolfssl_use_cert(tls_wrapper_ctx_t *ctx,
enclave_tls_cert_info_t *cert_info);
extern tls_wrapper_err_t wolfssl_negotiate(tls_wrapper_ctx_t *, int fd);
extern tls_wrapper_err_t wolfssl_transmit(tls_wrapper_ctx_t *, void *, size_t *);
extern tls_wrapper_err_t wolfssl_receive(tls_wrapper_ctx_t *, void *, size_t *);
extern tls_wrapper_err_t wolfssl_cleanup(tls_wrapper_ctx_t *);
static tls_wrapper_opts_t wolfssl_opts = {
.api_version = TLS_WRAPPER_API_VERSION_DEFAULT,
.name = "wolfssl",
.priority = 20,
.pre_init = wolfssl_pre_init,
.init = wolfssl_init,
.use_privkey = wolfssl_use_privkey,
.use_cert = wolfssl_use_cert,
.negotiate = wolfssl_negotiate,
.transmit = wolfssl_transmit,
.receive = wolfssl_receive,
.cleanup = wolfssl_cleanup,
};
void __attribute__((constructor)) libtls_wrapper_wolfssl_init(void)
{
ETLS_DEBUG("called\n");
tls_wrapper_err_t err = tls_wrapper_register(&wolfssl_opts);
if (err != TLS_WRAPPER_ERR_NONE)
ETLS_ERR("failed to register the tls wrapper 'wolfssl' %#x\n", err);
}
|
kkcookies99/UAST
|
Dataset/Leetcode/train/22/716.py
|
<reponame>kkcookies99/UAST
class Solution:
def XXX(self, n: int) -> List[str]:
tmp = ["()"]
for j in range(n - 1):
cur = set()
for i in range(len(tmp)):
for x in range(len(tmp[i]) + 1):
cur.add(tmp[i][:x] + "()" + tmp[i][x:])
tmp = list(cur)
return tmp
|
matthenning/etl-monitor-frontend
|
src/store/models/Sla/DeliverableSlaModel.js
|
import SlaModel from "./SlaModel";
import DeliverableSlaDefinitionModel from "@/store/models/Sla/DeliverableSlaDefinitionModel";
import DeliverableSlaStatisticModel from "@/store/models/Sla/DeliverableSlaStatisticModel";
import moment from "moment";
export default class DeliverableSlaModel extends SlaModel {
static name = 'DeliverableSla'
static entity = 'deliverable_slas'
static package = 'sla'
static menu = false
static route = {
title: 'SLA'
}
static fields () {
return {
...super.fields(),
achieved_at: this.attr(null),
definition: this.belongsTo(DeliverableSlaDefinitionModel, 'sla_definition_id'),
statistic: this.hasOne(DeliverableSlaStatisticModel, 'sla_id')
}
}
get sla_history () {
return this.statistic?.achievement_history.map((h) => {
return {
sla_id: h.sla_id,
status: h.status,
start: moment(h.start),
end: moment(h.end),
achieved_at: h.achieved_at ? moment(h.achieved_at) : null,
achieved_percent: h.achieved_percent,
error_margin_minutes: h.error_margin_minutes
}
})
}
get sla_landing () {
return {
start: moment(this.range_start),
end: moment(this.range_end),
average: this.statistic ? {
lower: this.statistic.average_lower,
upper: this.statistic.average_upper
} : null,
achieved_at: this.achieved_at ? moment(this.achieved_at) : null,
error_margin_minutes: this.error_margin_minutes
}
}
}
|
gameley-tc/bi-go
|
bimodels/guild_level.go
|
<reponame>gameley-tc/bi-go
// Copyright 2018 The Gameley-TC Authors. All rights reserved.
package bimodels
import (
"strconv"
"github.com/gameley-tc/bi-go"
)
type LogGuildLevel struct {
*LogGuildBase
// 公会原来的等级
GuildOldLevel int
// 公会新的等级
GuildNewLevel int
// 本次变动的等级
GuildLevel int
}
func (l *LogGuildLevel) ToString() string {
return bigo.BiJoin("log_guild_level", l.LogGuildBase.ToString(), strconv.Itoa(l.GuildOldLevel), strconv.Itoa(l.GuildNewLevel), strconv.Itoa(l.GuildLevel))
}
func NewLogGuildLevel(channelId, guildId, guildOldLevel, guildNewLevel int) *LogGuildLevel {
return &LogGuildLevel{LogGuildBase: NewLogGuildBase(channelId, guildId), GuildOldLevel: guildOldLevel, GuildNewLevel: guildNewLevel, GuildLevel: bigo.BiAbs(guildNewLevel - guildOldLevel)}
}
|
fuldaros/paperplane_kernel_wileyfox-spark
|
sources/include/trustzone/tz_cross/ta_securetime.h
|
#ifndef __TRUSTZONE_TA_SECURE_TIMER__
#define __TRUSTZONE_TA_SECURE_TIMER__
#define TZ_TA_SECURETIME_UUID "b25bf100-d276-11e2-9c9c-9c9c9c9c9c9c"
#define uint64 unsigned long long
#define TZ_SECURETIME_BIRTHDATE 1392967151
/* used for getting encrypted prtime struct to save file when shutdown and
suspend or after THREAD_SAVEFILE_VALUE second */
#define TZCMD_SECURETIME_GET_CURRENT_COUNTER 0x00000000
/* used for set new playready time using the current rtc counter and
encrypted saved prtime struct when resume and bootup */
#define TZCMD_SECURETIME_SET_CURRENT_COUNTER 0x00000001
/* used for increase current counter at least PR_TIME_INC_COUNTER secs and
no more than PR_TIME_MAX_COUNTER_OFFSET secs */
#define TZCMD_SECURETIME_INC_CURRENT_COUNTER 0x00000002
/* used for network time-sync module to sync pr_time */
#define TZCMD_SECURETIME_SET_CURRENT_PRTIME 0x00000003
#define GB_TIME_INC_COUNTER 5
#define GB_TIME_MAX_COUNTER_OFFSET 8
#define GB_TIME_FILE_BASE 50000
#define GB_TIME_FILE_ERROR_SIGN (GB_TIME_FILE_BASE + 1)
#define GB_TIME_FILE_OK_SIGN (GB_TIME_FILE_BASE + 2)
#define GB_NO_SECURETD_FILE (GB_TIME_FILE_BASE + 3)
#define GB_TIME_ERROR_SETPRTIME (GB_TIME_FILE_BASE + 4)
#define DRM_UINT64 unsigned long long
typedef struct TZ_GB_SECURETIME_INFO {
volatile unsigned long long hwcounter;
volatile unsigned long long gb_time;
char signature[8];
} TZ_GB_SECURETIME_INFO;
struct TM_GB {
int tm_sec; /* seconds */
int tm_min; /* minutes */
int tm_hour; /* hours */
int tm_mday; /* day of the month */
int tm_mon; /* month */
int tm_year; /* year */
int tm_wday; /* day of the week */
int tm_yday; /* day in the year */
int tm_isdst; /* daylight saving time */
long int tm_gmtoff; /* Seconds east of UTC. */
const char *tm_zone; /* Timezone abbreviation. */
};
/* end of SUPPORT_GB_SECURE_CLOCK */
typedef struct SECURETIME_IVDATA {
unsigned long long qwInitializationVector;
unsigned long long qwBlockOffset;
unsigned long bByteOffset;
} SECURETIME_IVDATA;
typedef struct TZ_SECURETIME_ENCINFO {
char role[100];
unsigned int dataSize; /* total enc buffer size */
unsigned int segNum; /* trunk number */
SECURETIME_IVDATA iv[10]; /* IV data for each trunk */
unsigned int offset[10]; /* pointer to an integer array,
each element describes clear data size */
unsigned int length[10]; /* pointer to an integer array,
each element describe enc data size */
unsigned int dstHandle; /* true : dstData is a handle;
false : dstData is a buffer; */
} TZ_SECURETIME_ENCINFO;
/* only be userd in tee, in user or kernel, should call the tee_service call */
/* unsigned long long GetTee_SecureTime(); */
#endif /* __TRUSTZONE_TA_SECURE_TIMER__ */
|
guflores/conference-application
|
src/test/java/de/codecentric/controller/EditSessionControllerTest.java
|
<filename>src/test/java/de/codecentric/controller/EditSessionControllerTest.java
package de.codecentric.controller;
import static org.junit.Assert.assertEquals;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import de.codecentric.controller.EditSessionController;
import de.codecentric.dao.SessionDao;
public class EditSessionControllerTest {
@Mock
private SessionDao sessionDao;
private EditSessionController controller;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
controller = new EditSessionController(sessionDao, new StaticTimeslotDao());
}
@Test
public void shouldGetTimeslotListFromDay() {
Map<String, String> timeslots = controller.getTimeslotForDay("Wed");
assertEquals(3, timeslots.size());
}
}
|
Einlar/free_recall
|
web/src/pages/ThankYouPage/ThankYouPage.js
|
<filename>web/src/pages/ThankYouPage/ThankYouPage.js
import { MetaTags } from '@redwoodjs/web'
const ThankYouPage = () => {
return (
<>
<MetaTags
title="ThankYou"
// description="ThankYou description"
/* you should un-comment description and add a unique description, 155 characters or less
You can look at this documentation for best practices : https://developers.google.com/search/docs/advanced/appearance/good-titles-snippets */
/>
<div
style={{
fontSize: '18px',
textAlign: 'center',
}}
>
<p>L'esperimento è andato a buon fine!</p>
<p> Grazie per avere partecipato!</p>
<p>
Puoi ora <b>chiudere</b> questa pagina.
</p>
</div>
</>
)
}
export default ThankYouPage
|
MilanKral/atalk-android
|
aTalk/src/main/java/org/atalk/impl/neomedia/transform/dtls/DtlsTransformEngine.java
|
<reponame>MilanKral/atalk-android
/*
* Jitsi, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license. See terms of license at gnu.org.
*/
package org.atalk.impl.neomedia.transform.dtls;
import org.atalk.impl.neomedia.transform.PacketTransformer;
import org.atalk.impl.neomedia.transform.TransformEngine;
import org.atalk.service.neomedia.SrtpControl;
/**
* Implements {@link SrtpControl.TransformEngine} (and, respectively,
* {@link TransformEngine}) for DTLS-SRTP.
*
* @author <NAME>
*/
public class DtlsTransformEngine implements SrtpControl.TransformEngine
{
/**
* The index of the RTP component.
*/
static final int COMPONENT_RTP = 0;
/**
* The index of the RTCP component.
*/
static final int COMPONENT_RTCP = 1;
/**
* The indicator which determines whether {@link SrtpControl.TransformEngine#cleanup()} has been
* invoked on this instance to prepare it for garbage collection.
*/
private boolean disposed = false;
/**
* The <tt>DtlsControl</tt> which has initialized this instance.
*/
private final DtlsControlImpl dtlsControl;
/**
* The <tt>PacketTransformer</tt>s of this <tt>TransformEngine</tt> for data/RTP and
* control/RTCP packets.
*/
private final DtlsPacketTransformer[] packetTransformers = new DtlsPacketTransformer[2];
/**
* Initializes a new <tt>DtlsTransformEngine</tt> instance.
*/
public DtlsTransformEngine(DtlsControlImpl dtlsControl)
{
this.dtlsControl = dtlsControl;
}
/**
* {@inheritDoc}
*/
@Override
public void cleanup()
{
disposed = true;
for (int i = 0; i < packetTransformers.length; i++) {
DtlsPacketTransformer packetTransformer = packetTransformers[i];
if (packetTransformer != null) {
packetTransformer.close();
packetTransformers[i] = null;
}
}
}
/**
* Initializes a new <tt>DtlsPacketTransformer</tt> instance which is to work on control/RTCP or
* data/RTP packets.
*
* @param componentID the ID of the component for which the new instance is to work
* @return a new <tt>DtlsPacketTransformer</tt> instance which is to work on control/RTCP or
* data/RTP packets (in accord with <tt>data</tt>)
*/
protected DtlsPacketTransformer createPacketTransformer(int componentID)
{
return new DtlsPacketTransformer(this, componentID);
}
/**
* Gets the <tt>DtlsControl</tt> which has initialized this instance.
*
* @return the <tt>DtlsControl</tt> which has initialized this instance
*/
DtlsControlImpl getDtlsControl()
{
return dtlsControl;
}
/**
* Gets the <tt>PacketTransformer</tt> of this <tt>TransformEngine</tt> which is to work or
* works for the component with a specific ID.
*
* @param componentID the ID of the component for which the returned <tt>PacketTransformer</tt> is to work or works
* @return the <tt>PacketTransformer</tt>, if any, which is to work or works for the component
* with the specified <tt>componentID</tt>
*/
private DtlsPacketTransformer getPacketTransformer(int componentID)
{
DtlsPacketTransformer packetTransformer = packetTransformers[componentID];
if ((packetTransformer == null) && !disposed) {
packetTransformer = createPacketTransformer(componentID);
if (packetTransformer != null)
packetTransformers[componentID] = packetTransformer;
}
return packetTransformer;
}
/**
* Gets the properties of {@code DtlsControlImpl} and their values which
* {@link #dtlsControl} shares with this instance and
* {@link DtlsPacketTransformer}.
*
* @return the properties of {@code DtlsControlImpl} and their values which
* {@code dtlsControl} shares with this instance and
* {@code DtlsPacketTransformer}
*/
Properties getProperties()
{
return getDtlsControl().getProperties();
}
/**
* {@inheritDoc}
*/
public PacketTransformer getRTCPTransformer()
{
return getPacketTransformer(COMPONENT_RTCP);
}
/**
* {@inheritDoc}
*/
public PacketTransformer getRTPTransformer()
{
return getPacketTransformer(COMPONENT_RTP);
}
}
|
mdhillmancmcl/TheWorldAvatar-CMCL-Fork
|
JPS_CITY_CHEM/citychem-1.3/preproc/bconcc2.2/ioapi3.2/ioapi/wratt3c.c
|
<filename>JPS_CITY_CHEM/citychem-1.3/preproc/bconcc2.2/ioapi3.2/ioapi/wratt3c.c<gh_stars>10-100
/**************************************************************************
VERSION "$Id: wratt3c.c 1 2017-06-10 18:05:20Z coats $"
EDSS/Models-3 I/O API.
COPYRIGHT
(C) 1992-2002 MCNC and <NAME>, Jr., and
(C) 2003-2010 Baron Advanced Meteorological Systems.
Distributed under the GNU LESSER GENERAL PUBLIC LICENSE version 2.1
See file "LGPL.txt" for conditions of use.
PURPOSE:
Writes the attribute named ANAME for the variable VNAME to the
file FNAME. If VNAME == ALLVAR3, writes global attribute ANAME.
Wrapper around I/O API Fortran-binding routines WRATT3()
for numeric attributes, and WRATTC() for character string
attributes)
PRECONDITIONS:
FNAME already opened by OPEN3() or open3c()
VNAME a valid variable in FNAME, or else is ALLVAR3=='ALL'
CALLS:
I/O API's Fortran WRATT3(), WRATTC()
REVISION HISTORY:
Prototype 1/2002 by C
Modified 2/2003 by CJC, BAMS: bug-fix for Cray case;
bug discovered by David Wong, US EPA.
Modified 10/2003 by CJC for I/O APIv3: cross-language FINT/FSTR_L
type resolution modifications
Modified 11/2005 by CJC: extra name-mangling for Absoft Pro Fortran:
upper-case Fortran symbols, prepend _C to common blocks.
**************************************************************************/
#include <string.h>
#include "iodecl3.h"
/** HACKS FOR FELDMAN-DESCENDED FC'S FOLLOW: **/
#if FLDMN
#define WRATT3 wratt3_
#define WRATTC wrattc_
#elif defined(__hpux) || defined(_AIX)
#define WRATT3 wratt3
#define WRATTC wrattc
#endif
#if defined(WRATT3) || defined(ABSFT)
extern FINT WRATT3( const char * fname ,
const char * vname ,
const char * aname ,
const FINT * atype,
const FINT * amax,
void * aval ,
FSTR_L fnamelen,
FSTR_L vnamelen,
FSTR_L anamelen ) ;
extern FINT WRATTC( const char * fname ,
const char * vname ,
const char * aname ,
char * aval ,
FSTR_L fnamelen,
FSTR_L vnamelen,
FSTR_L anamelen,
FSTR_L avallen ) ;
int wratt3c( const char * fname ,
const char * vname ,
const char * aname ,
int atyp ,
int amax ,
int * asiz ,
void * att )
{ /* begin body of wratt3c() */
FINT atype, amax1 ;
FSTR_L amaxc ;
if ( atyp == M3CHAR )
{
amaxc = (FSTR_L) amax ;
return( (FINT) WRATTC( fname ,
vname ,
aname ,
att ,
STRLEN( fname ) ,
STRLEN( vname ) ,
STRLEN( aname ) ,
amaxc ) ) ;
}
else
{
atype = (FINT) atyp ;
amax1 = (FINT) amax ;
return( (FINT) WRATT3( fname ,
vname ,
aname ,
& atype ,
& amax1 ,
att ,
STRLEN( fname ) ,
STRLEN( vname ) ,
STRLEN( aname ) ) ) ;
}
} /* end body of wratt3c() */
/** END CASE OF FELDMAN-DESCENDED F77 TARGETS **/
/** NEXT CASE: Win32 wratt3c(): **/
#elif defined(_WIN32)
#include <stdio.h> /* for sprintf */
extern FINT WRATT3( const char * fname , FSTR_L fnamelen ,
const char * vname , FSTR_L vnamelen ,
const char * aname , FSTR_L anamelen ,
const FINT * atype,
const FINT * amax,
void * aval ) ;
extern FINT WRATTC( const char * fname , FSTR_L fnamelen ,
const char * vname , FSTR_L vnamelen ,
const char * aname , FSTR_L anamelen ,
char * aval , FSTR_L avallen ) ;
int wratt3c( const char * fname ,
const char * vname ,
const char * aname ,
int atyp ,
int amax ,
void * att )
{ /* begin body of wratt3c() */
FINT atype, amax1 ;
FSTR_L amaxc ;
if ( atyp == M3CHAR )
{
amaxc = (FSTR_L) amax ;
return( (FINT) WRATTC( fname , STRLEN( fname ) ,
vname , STRLEN( vname ) ,
aname , STRLEN( aname ) ,
att , amaxc ) ) ;
}
else{
atype = (FINT) atyp ;
amax1 = (FINT) amax ;
return( (FINT) WRATT3( fname , STRLEN( fname ) ,
vname , STRLEN( vname ) ,
aname , STRLEN( aname ) ,
& atype ,
& amax1 ,
att ) ) ;
}
} /* end body of wratt3c() */
/** END CASE OF Win32 **/
/** NEXT CASE: CRAY-TARGETED wratt3c(): **/
#elif defined(_CRAY) /** treatment: CRAY arryas of strings?? **/
#include <fortran.h>
extern FINT WRATT3( const _fcd fname ,
const _fcd vname ,
const _fcd aname ,
const FINT * atype ,
const FINT * amax ,
void * aval ) ;
extern FINT WRATTC( const _fcd fname ,
const _fcd vname ,
const _fcd aname ,
_fcd aval ) ;
int wratt3c( const char * fname ,
const char * vname ,
const char * aname ,
int atyp ,
int amax ,
void * att )
{ /* begin body of wratt3c() */
FINT atype, amax1 ;
FSTR_L amaxc ;
_fcd file ;
_fcd vble ;
_fcd atnm ;
_fcd aval ;
file = _cptofcd( (char *)fname, STRLEN( fname ) ) ;
vble = _cptofcd( (char *)vname, STRLEN( vname ) ) ;
atnm = _cptofcd( (char *)aname, STRLEN( aname ) ) ;
if ( atyp == M3CHAR )
{
amaxc = (FSTR_L) amax ;
aval = _cptofcd( (char *)att, amaxc ) ;
return( _btol( WRATTC( file ,
vble ,
atnm ,
aval ) ) ) ;
}
else{
atype = (FINT) atyp ;
amax1 = (FINT) amax ;
return( _btol( WRATT3( file ,
vble ,
atnm ,
& atype ,
& amax1 ,
att ) ) ) ;
}
} /* end body of wratt3c() */
#else
#error "Error compiling wratt3c(): unsupported architecture"
#endif /** IF FELDMAN-DESCENDED "FC" TARGETED,
OR IF Win32, OR IF CRAY **/
|
jjb/coverband_demo
|
node_modules/material-design-kit/src/carousel/carousel.js
|
<reponame>jjb/coverband_demo<filename>node_modules/material-design-kit/src/carousel/carousel.js
import { handler, util } from 'dom-factory'
const isTouch = () => ('ontouchstart' in window)
const matrixValues = (matrix) => {
if (matrix === 'none') {
matrix = 'matrix(0,0,0,0,0)'
}
var obj = {}
var values = matrix.match(/([-+]?[\d\.]+)/g)
obj.translate = {
x: parseInt(values[4], 10) || 0,
y: parseInt(values[5], 10) || 0
}
return obj
}
const transformMatrix = (el) => {
var st = window.getComputedStyle(el, null)
var matrix = st.getPropertyValue('-webkit-transform') ||
st.getPropertyValue('-moz-transform') ||
st.getPropertyValue('-ms-transform') ||
st.getPropertyValue('-o-transform') ||
st.getPropertyValue('transform')
return matrixValues(matrix)
}
/**
* Compute the pointer coordinates from multiple event types.
* @param {TouchEvent|MouseEvent} event
*/
const pointer = (event) => {
event = event.originalEvent || event || window.event
event = event.touches && event.touches.length
? event.touches[0]
: event.changedTouches && event.changedTouches.length
? event.changedTouches[0]
: event
return {
x: event.pageX ? event.pageX : event.clientX,
y: event.pageY ? event.pageY : event.clientY
}
}
/**
* Compute the difference between the properties of two objects.
* @param {Object} a
* @param {Object} b
* @return {Object}
*/
const difference = (a, b) => {
return {
x: a.x - b.x,
y: a.y - b.y
}
}
/**
* A Carousel component for cycling through elements.
* @param {HTMLELement} element
* @return {Object}
*/
export const carouselComponent = () => ({
/**
* Event listeners.
* @type {Array}
*/
listeners: [
'_onEnter(mouseenter)',
'_onLeave(mouseleave)',
'_onTransitionend(transitionend)',
'_onDragStart(mousedown, touchstart)',
'_onMouseDrag(dragstart, selectstart)',
'document._onDragMove(mousemove, touchmove)',
'document._onDragEnd(mouseup, touchend)',
'window._debounceResize(resize)'
],
// The carousel items
_items: [],
// The carousel moving state
_isMoving: false,
// A reference to the carousel content container
_content: null,
// A reference to the active item
_current: null,
// Drag and touch state
_drag: {},
/**
* Set the initial state.
* Gets called automatically on `window.load`.
*/
_reset () {
this._content = this.element.querySelector('.mdk-carousel__content')
this._items = [...this._content.children]
this._content.style.width = ''
this._items.forEach(function (item) {
item.style.width = ''
})
var width = this.element.offsetWidth
var itemWidth = this._items[0].offsetWidth
var visible = width / itemWidth
this._itemWidth = itemWidth
this._visible = Math.round(visible)
this._max = this._items.length - this._visible
this.element.style.overflow = 'hidden'
this._content.style.width = (itemWidth * this._items.length) + 'px'
this._items.forEach(function (item) {
item.classList.add('mdk-carousel__item')
item.style.width = itemWidth + 'px'
})
if (!this._current) {
this._current = this._items[0]
}
if (this._items.length < 2) {
return
}
var currentIndex = this._items.indexOf(this._current)
this._transform(currentIndex * itemWidth * -1, 0)
this.start()
},
/**
* Start sliding the carousel on a time interval.
*/
start () {
this.stop()
if (this._items.length < 2 || this._items.length <= this._visible) {
return
}
this._setContentTransitionDuration('')
this._interval = setInterval(this.next.bind(this), 2000)
},
/**
* Stop sliding the carousel on a time interval.
*/
stop () {
clearInterval(this._interval)
this._interval = null
},
/**
* Move the carousel forward by one item.
*/
next () {
if (this._items.length < 2 || this._isMoving || document.hidden || !this._isOnScreen()) {
return
}
var currentIndex = this._items.indexOf(this._current)
var nextIndex = this._items[currentIndex + 1] !== undefined
? currentIndex + 1 : 0
var remaining = this._items.length - currentIndex
if (remaining === this._visible) {
nextIndex = 0
}
this._to(nextIndex)
},
/**
* Move the carousel backward by one item.
*/
prev () {
if (this._items.length < 2 || this._isMoving) {
return
}
var currentIndex = this._items.indexOf(this._current)
var prevIndex = this._items[currentIndex - 1] !== undefined
? currentIndex - 1 : this._items.length
this._to(prevIndex)
},
_transform (translate, duration, callback) {
if (duration !== undefined) {
this._setContentTransitionDuration(duration + 'ms')
}
var matrix = transformMatrix(this._content)
if (matrix.translate.x === translate) {
if (typeof callback === 'function') {
callback.call(this)
}
}
else {
requestAnimationFrame(function () {
if (duration !== 0) {
this._isMoving = true
}
util.transform('translate3d(' + translate + 'px, 0, 0)', this._content)
if (typeof callback === 'function') {
callback.call(this)
}
}.bind(this))
}
},
/**
* Slide to a specific item by index.
* @param {Number} index
*/
_to (index) {
if (this._items.length < 2 || this._isMoving) {
return
}
if (index > this._max) {
index = this._max
}
if (index < 0) {
index = 0
}
var translate = index * this._itemWidth * -1
this._transform(translate, false, function () {
this._current = this._items[index]
})
},
/**
* `window.resize` debounce handler.
*/
_debounceResize () {
clearTimeout(this._resizeTimer)
if (this._resizeWidth !== window.innerWidth) {
this._resizeTimer = setTimeout(function () {
this._resizeWidth = window.innerWidth
this.stop()
this._reset()
}.bind(this), 50)
}
},
_setContentTransitionDuration (duration) {
this._content.style.transitionDuration = duration
},
/**
* Stop the carousel auto sliding on `mouseenter`.
*/
_onEnter () {
this.stop()
},
/**
* (Re)start the carousel auto sliding on `mouseleave`.
*/
_onLeave () {
if (!this._drag.wasDragging) {
this.start()
}
},
/**
* Handle `transitionend` events
* @param {TransitionEvent} event
*/
_onTransitionend () {
this._isMoving = false
},
/**
* Handle `mousedown` and `touchstart` events
* @param {MouseEvent|TouchEvent} event
*/
_onDragStart (event) {
if (this._drag.isDragging || this._isMoving || event.which === 3) {
return
}
this.stop()
var stage = transformMatrix(this._content).translate
this._drag.isDragging = true
this._drag.isScrolling = false
this._drag.time = new Date().getTime()
this._drag.start = stage
this._drag.current = stage
this._drag.delta = {
x: 0,
y: 0
}
this._drag.pointer = pointer(event)
this._drag.target = event.target
},
/**
* Handle `mousemove` and `touchmove` events
* @param {MouseEvent|TouchEvent} event
*/
_onDragMove (event) {
if (!this._drag.isDragging) {
return
}
var delta = difference(this._drag.pointer, pointer(event))
var stage = difference(this._drag.start, delta)
var isScrolling = isTouch() && Math.abs(delta.x) < Math.abs(delta.y)
if (!isScrolling) {
event.preventDefault()
this._transform(stage.x, 0)
}
this._drag.delta = delta
this._drag.current = stage
this._drag.isScrolling = isScrolling
this._drag.target = event.target
},
/**
* Handle `mouseup` and `touchend` events
* @param {MouseEvent|TouchEvent} event
*/
_onDragEnd (event) {
if (!this._drag.isDragging) {
return
}
this._setContentTransitionDuration('')
this._drag.duration = new Date().getTime() - this._drag.time
var dx = Math.abs(this._drag.delta.x)
var change = dx > 20 || dx > this._itemWidth / 3
var factor = Math.max(Math.round(dx / this._itemWidth), 1)
var next = this._drag.delta.x > 0
if (change) {
var currentIndex = this._items.indexOf(this._current)
var index = next ? currentIndex + factor : currentIndex - factor
this._to(index)
}
else {
this._transform(this._drag.start.x)
}
this._drag.isDragging = false
this._drag.wasDragging = true
},
/**
* Prevent and stop the default actions on text selection and dragging elements
* @param {Event|DragEvent} event
*/
_onMouseDrag (event) {
event.preventDefault()
event.stopPropagation()
},
/**
* Determine if the carousel is currently in the visibile viewport.
* @return {Boolean}
*/
_isOnScreen () {
var rect = this.element.getBoundingClientRect()
return rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= window.innerHeight &&
rect.right <= window.innerWidth
},
/**
* Initialize the carousel.
*/
init () {
this._resizeWidth = window.innerWidth
this._reset()
},
/**
* Destroy the carousel.
*/
destroy () {
this.stop()
clearTimeout(this._resizeTimer)
}
})
handler.register('mdk-carousel', carouselComponent)
|
kripken/intensityengine
|
packages/models/areatrigger/obj.js
|
<reponame>kripken/intensityengine
// An inivisible model that can be used to fill space and detect when something passes through that space,
// i.e., as a trigger area
//
//mdlbb 10 5 0
Model.shadow(0);
Model.collide(1);
Model.collisionsOnlyForTriggering(1);
Model.perEntityCollisionBoxes(1);
|
Wenzhao299/SAMS
|
src/main/java/com/tiantian/sams/controller/RepairController.java
|
package com.tiantian.sams.controller;
import com.tiantian.sams.dao.DepartmentDao;
import com.tiantian.sams.dao.DormitoryDao;
import com.tiantian.sams.model.*;
import com.tiantian.sams.service.RepairService;
import com.tiantian.sams.service.impl.RepairServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.Date;
import java.util.List;
/**
* RepairController
* @author tiantian152
*/
@Controller
@RequestMapping("/repair")
public class RepairController {
@Autowired
private final RepairService repairService = new RepairServiceImpl();
@Autowired
private DepartmentDao departmentDao;
@Autowired
private DormitoryDao dormitoryDao;
/**
* 添加维修
* @author tiantian152
*/
@RequestMapping("/addRepair")
public String addRepair(Repair repair,
Model model) {
// 从界面获得的数据有:公寓Id,寝室Id,维修内容,备注
repair.setStatus("等待维修");
repair.setRecordTime(new Date());
repair.setStartTime(new Date(0));
repair.setEndTime(new Date(0));
int result = repairService.insertRepair(repair);
if (result == 1)
System.out.println("插入成功");
return "redirect:loadRepair";
}
/**
* 添加维修开始时间
* @author tiantian152
*/
@RequestMapping("/updateRepairStartTime")
public String updateRepairStartTime(Repair repair,
Model model) {
// 如果状态为:等待维修,即可进行这一步,否则不行
if (repairService.judgeStatusForStart(repair.getRepairId())) {
repair.setStatus("维修中");
repair.setRecordTime(new Date());
int result = repairService.updateStartTime(repair);
if (result == 1)
System.out.println("插入成功");
} else {
model.addAttribute("msg", "状态不正确");
}
return "redirect:loadRepair";
}
/**
* 添加维修结束时间
* @author tiantian152
*/
@RequestMapping("/updateRepairEndTime")
public String updateRepairEndTime(Repair repair,
Model model) {
if (repairService.judgeStatusForEnd(repair.getRepairId())) {
repair.setStatus("维修结束");
repair.setRecordTime(new Date());
int result = repairService.updateEndTime(repair);
if (result == 1)
System.out.println("插入成功");
} else {
model.addAttribute("msg", "状态不正确");
}
return "redirect:loadRepair";
}
@RequestMapping("/loadAddRepairPage")
public String loadAddRepairPage(Model model) {
System.out.println("==================读取添加维修所需信息开始==================");
// 查询公寓表
List<DepartmentInformation> departmentInformationList = departmentDao.selectDepartmentInformation();
System.out.println("departmentInformationList="+departmentInformationList);
model.addAttribute("departmentInformationList",departmentInformationList);
// 查询宿舍表
List<DormitoryInformation> dormitoryInformationList = dormitoryDao.selectDormitoryInformation();
System.out.println("dormitoryInformationList="+dormitoryInformationList);
model.addAttribute("dormitoryInformationList",dormitoryInformationList);
System.out.println("==================读取添加日常登记所需信息结束==================");
return "addRepair";
}
/**
* 加载 维修查询 页面
* @author tiantian152
*/
@RequestMapping("/loadRepair")
public String loadRepair(Model model) {
List<RepairView> repairs = repairService.selectRepairView();
model.addAttribute("repairs", repairs);
System.out.println(repairs);
return "quireRepair";
}
}
|
HeyLey/catboost
|
contrib/libs/musl-1.1.20/include/sys/epoll.h
|
#ifndef _SYS_EPOLL_H
#define _SYS_EPOLL_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <sys/types.h>
#include <fcntl.h>
#define __NEED_sigset_t
#include <bits/alltypes.h>
#define EPOLL_CLOEXEC O_CLOEXEC
#define EPOLL_NONBLOCK O_NONBLOCK
enum EPOLL_EVENTS { __EPOLL_DUMMY };
#define EPOLLIN 0x001
#define EPOLLPRI 0x002
#define EPOLLOUT 0x004
#define EPOLLRDNORM 0x040
#define EPOLLNVAL 0x020
#define EPOLLRDBAND 0x080
#define EPOLLWRNORM 0x100
#define EPOLLWRBAND 0x200
#define EPOLLMSG 0x400
#define EPOLLERR 0x008
#define EPOLLHUP 0x010
#define EPOLLRDHUP 0x2000
#define EPOLLEXCLUSIVE (1U<<28)
#define EPOLLWAKEUP (1U<<29)
#define EPOLLONESHOT (1U<<30)
#define EPOLLET (1U<<31)
#define EPOLL_CTL_ADD 1
#define EPOLL_CTL_DEL 2
#define EPOLL_CTL_MOD 3
typedef union epoll_data {
void *ptr;
int fd;
uint32_t u32;
uint64_t u64;
} epoll_data_t;
struct epoll_event {
uint32_t events;
epoll_data_t data;
}
#ifdef __x86_64__
__attribute__ ((__packed__))
#endif
;
int epoll_create(int);
int epoll_create1(int);
int epoll_ctl(int, int, int, struct epoll_event *);
int epoll_wait(int, struct epoll_event *, int, int);
int epoll_pwait(int, struct epoll_event *, int, int, const sigset_t *);
#ifdef __cplusplus
}
#endif
#endif /* sys/epoll.h */
|
ahmed-basyouni/Capstone-Project
|
ArkWallpaper/app/src/main/java/com/ark/android/arkwallpaper/ui/fragment/AlbumsFragment.java
|
<reponame>ahmed-basyouni/Capstone-Project<gh_stars>0
package com.ark.android.arkwallpaper.ui.fragment;
import android.accounts.Account;
import android.app.Activity;
import android.app.Dialog;
import android.content.ContentResolver;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.ark.android.arkanalytics.GATrackerManager;
import com.ark.android.arkwallpaper.R;
import com.ark.android.arkwallpaper.data.model.AlbumObject;
import com.ark.android.arkwallpaper.presenter.contract.AlbumFragmentContract;
import com.ark.android.arkwallpaper.presenter.presenterImp.AlbumsPresenter;
import com.ark.android.gallerylib.data.GallaryDataBaseContract;
import com.ark.android.onlinesourcelib.syncadapter.FiveHundredSyncAdapter;
import com.ark.android.onlinesourcelib.Account.FivePxGenericAccountService;
import com.ark.android.onlinesourcelib.syncUtils.FivePxSyncUtils;
import com.ark.android.onlinesourcelib.Account.TumblrGenericAccountService;
import com.ark.android.onlinesourcelib.manager.TumblrManager;
import com.ark.android.onlinesourcelib.syncadapter.TumblrSyncAdapter;
import com.ark.android.onlinesourcelib.syncUtils.TumblrSyncUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import rx.functions.Action1;
/**
*
* Created by ahmed-basyouni on 4/22/17.
*/
public class AlbumsFragment extends BaseFragment implements
AlbumFragmentContract.IAlbumsView
, LoaderManager.LoaderCallbacks<Cursor>, View.OnClickListener {
@BindView(R.id.albumsList)
RecyclerView albumList;
@BindView(R.id.addAlbum)
FloatingActionButton addAlbum;
@BindView(R.id.floatingMenu)
FloatingActionButton floatingMenu;
@BindView(R.id.addTumblr)
FloatingActionButton addtumblr;
@BindView(R.id.addFive)
FloatingActionButton add500px;
@BindView(R.id.addFiveContainer)
LinearLayout addFiveContainer;
@BindView(R.id.addTumblrContainer)
LinearLayout addTumblrContainer;
@BindView(R.id.addAlbumContainer)
LinearLayout addAlbumContainer;
@BindView(R.id.addtumblrText)
TextView addTumblrText;
@BindView(R.id.addFiveText)
TextView addFiveText;
@BindView(R.id.addAlbumText)
TextView addAlbumText;
private AlbumsPresenter albumsPresenter;
int count = 0;
private static final int LOADER_ID = 214;
private Animation fabOpen;
private Animation fabClose;
private Animation rotateForward;
private Animation rotateBackward;
private boolean isFabOpen;
private Dialog albumNameDialog;
private Dialog fivePxDialog;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.albums_fragment, container, false);
ButterKnife.bind(this, rootView);
albumsPresenter = new AlbumsPresenter(this);
getActivity().getSupportLoaderManager().initLoader(LOADER_ID, null, this);
fabOpen = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_open);
fabClose = AnimationUtils.loadAnimation(getActivity(), R.anim.fab_close);
rotateForward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_forward);
rotateBackward = AnimationUtils.loadAnimation(getActivity(), R.anim.rotate_backward);
floatingMenu.setOnClickListener(this);
addAlbum.setOnClickListener(this);
addtumblr.setOnClickListener(this);
add500px.setOnClickListener(this);
return rootView;
}
@Override
public void showAddAlbumDialog(final boolean isTumblr, String editFieldText, final Action1<String> action1) {
albumNameDialog = new Dialog(getActivity());
albumNameDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
albumNameDialog.setContentView(R.layout.add_album_dialog);
final EditText albumNameField = (EditText) albumNameDialog.findViewById(R.id.albumNameField);
if (isTumblr)
albumNameField.setHint(getString(R.string.blogName));
else
albumNameField.setHint(getString(R.string.albumName));
if (editFieldText != null)
albumNameField.setText(editFieldText);
Button okButton = (Button) albumNameDialog.findViewById(R.id.addAlbum);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!albumNameField.getText().toString().isEmpty()) {
final String albumName = albumNameField.getText().toString();
if (isTumblr) {
TumblrManager.getInstance().checkBlogInfo(albumNameField.getText().toString(), action1);
albumNameDialog.dismiss();
} else {
albumsPresenter.addAlbum(albumNameField.getText().toString(), GallaryDataBaseContract.AlbumsTable.ALBUM_TYPE_GALLERY, null, albumName);
albumNameDialog.dismiss();
}
} else {
Toast.makeText(getActivity(), getString(R.string.no_name_provided), Toast.LENGTH_SHORT).show();
}
}
});
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(albumNameDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
albumNameDialog.getWindow().setAttributes(lp);
albumNameDialog.show();
}
@Override
public void showAdd500PxDialog(int index, final Action1<String> action1) {
fivePxDialog = new Dialog(getActivity());
fivePxDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
fivePxDialog.setContentView(R.layout.add_fivepx_dialog);
final Spinner spinner = (Spinner) fivePxDialog.findViewById(R.id.catSpinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.fivePx_Cat, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
spinner.setSelection(index);
Button okButton = (Button) fivePxDialog.findViewById(R.id.addAlbum);
okButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(action1 == null)
add500PxAlbum(spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
else
action1.call(spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
fivePxDialog.dismiss();
}
});
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.copyFrom(fivePxDialog.getWindow().getAttributes());
lp.width = WindowManager.LayoutParams.MATCH_PARENT;
lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
fivePxDialog.getWindow().setAttributes(lp);
fivePxDialog.show();
}
@Override
public RecyclerView getAlbumList() {
return albumList;
}
@Override
public Activity getActivityContext() {
return getActivity();
}
@Override
public void showSnackWithMsg(String msg) {
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(getActivity(), GallaryDataBaseContract.AlbumsTable.CONTENT_URI, new String[]{BaseColumns._ID, GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_NAME,
GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_IMAGE_URI
, GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_ENABLED, GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_TYPE, GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_COUNT
, GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_TUMBLR_BLOG_NAME, GallaryDataBaseContract.AlbumsTable.COLUMN_ALBUM_Five_PX_CATEGORY}, null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (data != null && data.getCount() > 0) {
albumList.setVisibility(View.VISIBLE);
albumsPresenter.onAlbumsLoaded(data);
} else {
albumList.setVisibility(View.GONE);
albumsPresenter.clearAlbums();
if (albumsPresenter.getAlbums() != null)
checkFloatingAlbumState();
}
}
@Override
public void checkFloatingAlbumState() {
boolean tumblrExist = false;
boolean fivePxExist = false;
for (AlbumObject albumObject : albumsPresenter.getAlbums()) {
if (albumObject.getAlbumName().equals(TumblrSyncAdapter.ALBUM_NAME)) {
addtumblr.setEnabled(false);
addTumblrText.setText(getString(R.string.tumblrAlreadyExist));
tumblrExist = true;
}
if (albumObject.getAlbumName().equals(FiveHundredSyncAdapter.ALBUM_NAME)) {
add500px.setEnabled(false);
addFiveText.setText(getString(R.string.fivePxAlreadyExist));
fivePxExist = true;
}
}
if (!fivePxExist) {
add500px.setEnabled(true);
addFiveText.setText(getString(R.string.addfivePxAlbum));
}
if (!tumblrExist) {
addtumblr.setEnabled(true);
addTumblrText.setText(getString(R.string.addTumblrAlbum));
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
@Override
public void onClick(View v) {
int id = v.getId();
switch (id) {
case R.id.floatingMenu:
animateFAB();
break;
case R.id.addAlbum:
showAddAlbumDialog(false, null, null);
GATrackerManager.getInstance().trackEvent(getString(R.string.albums)
, getString(R.string.addNewAlbum),
getString(R.string.fromGallery));
animateFAB();
break;
case R.id.addTumblr:
showAddAlbumDialog(true, null, getTumblrAction());
GATrackerManager.getInstance().trackEvent(getString(R.string.albums)
, getString(R.string.addNewAlbum),
getString(R.string.fromTumblr));
animateFAB();
break;
case R.id.addFive:
showAdd500PxDialog(0, null);
GATrackerManager.getInstance().trackEvent(getString(R.string.albums)
, getString(R.string.addNewAlbum),
getString(R.string.from500Px));
animateFAB();
break;
}
}
Action1<String> getTumblrAction() {
return new Action1<String>() {
@Override
public void call(String albumName) {
if (albumName != null) {
Bundle bundle = new Bundle();
bundle.putString("albumName", albumName);
bundle.putBoolean("isPer", true);
albumsPresenter.addAlbum(TumblrSyncAdapter.ALBUM_NAME, GallaryDataBaseContract.AlbumsTable.ALBUM_TYPE_TUMBLR, null, albumName);
if (!TumblrSyncUtils.getInstance().CreateSyncAccount(getActivity(), bundle)) {
TumblrSyncUtils.getInstance().addPeriodicSync(bundle);
TumblrSyncUtils.getInstance().TriggerRefresh(bundle);
}
} else {
Toast.makeText(getActivity(), getString(R.string.blogNotFound), Toast.LENGTH_SHORT).show();
}
}
};
}
private void add500PxAlbum(String s) {
Bundle bundle = new Bundle();
bundle.putString(FiveHundredSyncAdapter.CAT_KEY, s);
bundle.putBoolean("isPer", true);
albumsPresenter.addAlbum(FiveHundredSyncAdapter.ALBUM_NAME, GallaryDataBaseContract.AlbumsTable.ALBUM_TYPE_PX, s, null);
if (!FivePxSyncUtils.getInstance().CreateSyncAccount(getActivity(), bundle)) {
FivePxSyncUtils.getInstance().addPeriodicSync(bundle);
FivePxSyncUtils.getInstance().TriggerRefresh(bundle);
}
}
private void animateFAB() {
if (isFabOpen) {
floatingMenu.startAnimation(rotateBackward);
addFiveText.animate().setDuration(300).alpha(0);
addTumblrText.animate().setDuration(300).alpha(0);
addAlbumText.animate().setDuration(300).alpha(0);
add500px.startAnimation(fabClose);
addAlbum.startAnimation(fabClose);
addtumblr.startAnimation(fabClose);
addAlbum.setClickable(false);
addtumblr.setClickable(false);
add500px.setClickable(false);
isFabOpen = false;
} else {
floatingMenu.startAnimation(rotateForward);
addFiveText.animate().setDuration(300).alpha(1);
addTumblrText.animate().setDuration(300).alpha(1);
addAlbumText.animate().setDuration(300).alpha(1);
add500px.startAnimation(fabOpen);
addAlbum.startAnimation(fabOpen);
addtumblr.startAnimation(fabOpen);
addAlbum.setClickable(true);
addtumblr.setClickable(true);
add500px.setClickable(true);
isFabOpen = true;
}
}
@Override
public void onEmptyAlbums() {
}
@Override
public void registerObservers(boolean shouldAdd500PxObserver, boolean shouldAddTumblrObserver) {
if (shouldAdd500PxObserver) {
Account account = FivePxGenericAccountService.GetAccount(FivePxSyncUtils.ACCOUNT_TYPE);
boolean syncActive = ContentResolver.isSyncActive(
account, GallaryDataBaseContract.GALLERY_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, GallaryDataBaseContract.GALLERY_AUTHORITY);
if (!syncActive && !syncPending && albumsPresenter.get500PxAlbum().getCount() == 0) {
Bundle bundle = new Bundle();
bundle.putString(FiveHundredSyncAdapter.CAT_KEY, albumsPresenter.get500PxAlbum().getFivePxCategoryName());
bundle.putBoolean("isPer", true);
FivePxSyncUtils.getInstance().TriggerRefresh(bundle);
}
}
if (shouldAddTumblrObserver) {
Account account = TumblrGenericAccountService.GetAccount(TumblrSyncUtils.ACCOUNT_TYPE);
boolean syncActive = ContentResolver.isSyncActive(
account, GallaryDataBaseContract.GALLERY_AUTHORITY);
boolean syncPending = ContentResolver.isSyncPending(
account, GallaryDataBaseContract.GALLERY_AUTHORITY);
if (!syncActive && !syncPending && albumsPresenter.getTumblrAlbum().getCount() == 0) {
Bundle bundle = new Bundle();
bundle.putString("albumName", albumsPresenter.getTumblrAlbum().getTumblrBlogName());
bundle.putBoolean("isPer", true);
TumblrSyncUtils.getInstance().TriggerRefresh(bundle);
}
}
}
@Override
protected String getFragmentTitle() {
return getString(R.string.albumsFragment);
}
}
|
johnh865/election_sim
|
archive/examples/election3way/run.py
|
# -*- coding: utf-8 -*-
"""
Honest election simulations comparing IRV, plurality, and score voting.
Pickle output.
"""
import itertools
import votesim
from votesim.models import spatial
from votesim.utilities.write import StringTable
import matplotlib.pyplot as plt
#import seaborn as sns
import numpy as np
import pandas as pd
#votesim.logconfig.setInfo()
#votesim.logconfig.setDebug()
votesim.logconfig.setWarning()
outputfile = 'election3way.pkl'
types = ['irv', 'score', 'star', 'plurality', 'smith_minimax', 'approval50', 'approval75']
metric_name = 'stats.regret.vsp'
v = spatial.SimpleVoters(0)
v.add_random(500, ndim=1)
c = spatial.Candidates(v, 0)
e = spatial.Election(v, None, seed=0, scoremax=5)
### Develop parametric study variables
distances = np.linspace(0, 3, 20)[1:]
skew = np.linspace(0,1, 10)[1:-1]
offset = np.linspace(0, 0.5, 10 )
### Loop through parameters
loop_product = itertools.product(distances, skew, offset)
data = []
for ii, (d, s, o) in enumerate(loop_product):
print(ii, end=',')
c.reset()
a = np.array([0, s, 1]) - 0.5
a = a * d + o
a = np.atleast_2d(a).T
c.add(a)
e.set_data(v, c)
args = {'distance':d, 'skew':s, 'offset':o}
e.user_data(**args)
data.append(a)
for t in types:
e.run(etype=t)
data = np.array(data)
e.save(outputfile)
|
ssyyzs/JavaMesh
|
javamesh-samples/javamesh-route/route-server/src/main/java/com/huawei/route/server/entity/ServiceRegistrarMessage.java
|
<reponame>ssyyzs/JavaMesh
/*
* Copyright (c) Huawei Technologies Co., Ltd. 2021-2022. All rights reserved.
*/
package com.huawei.route.server.entity;
import com.alibaba.fastjson.JSONArray;
import lombok.Data;
import lombok.EqualsAndHashCode;
/**
* 上报数据
*
* @author zhouss
* @since 2021-10-13
*/
@EqualsAndHashCode(callSuper = true)
@Data
public class ServiceRegistrarMessage extends BaseRegistrarMessage{
/**
* 下游服务名称
*/
private String downServiceName;
/**
* Zookeeper中代表根路径;nacos中代表分组;serviceComb中代表所属应用
*/
private String root;
/**
* 命名空间 nacos专属
*/
private String namespaceId;
/**
* 注册中心的名称,有ZOOKEEPER、NACOS和SERVICECOMB三种
*/
private String registry;
/**
* 协议,有dubbo和springcloud两种
*/
private String protocol;
/**
* Ldc的businesses信息
*/
private JSONArray businesses;
/**
* 注册中心中服务的名称,serviceComb独有,其余为null
*/
private String registrarServiceName;
/**
* 集群名称,nacos独有,其他为nul
*
*/
private String clusterName;
@Override
public String getShareKey() {
return namespaceId;
}
}
|
Masoudkh/pancake-backend
|
app/models/batch.rb
|
# frozen_string_literal: true
class Batch < ApplicationRecord
has_many :rebate_forms, dependent: :nullify
belongs_to :council, required: true
end
|
DanDeMicco/box-ui-elements
|
src/elements/content-sidebar/activity-feed/activity-feed/__tests__/ActiveState-test.js
|
import * as React from 'react';
import { shallow } from 'enzyme';
import ActiveState from '../ActiveState';
import Task from '../../task/Task';
const items = [
{
type: 'comment',
id: 123,
created_at: '2018-07-03T14:43:52-07:00',
tagged_message: 'test @[123:Jeezy] @[10:Kanye West]',
created_by: { name: 'Akon', id: 11 },
},
{
type: 'task',
id: 234,
created_at: '2018-07-03T14:43:52-07:00',
created_by: { name: 'Akon', id: 11 },
modified_at: '2018-07-03T14:43:52-07:00',
tagged_message: 'test',
modified_by: { name: 'Jay-Z', id: 10 },
dueAt: '2018-07-03T14:43:52-07:00',
task_assignment_collection: {
entries: [
{
assigned_to: { name: 'Akon', id: 11 },
status: 'incomplete',
},
],
total_count: 1,
},
},
{
type: 'file_version',
id: 345,
created_at: '2018-07-03T14:43:52-07:00',
trashed_at: '2018-07-03T14:43:52-07:00',
modified_at: '2018-07-03T14:43:52-07:00',
modified_by: { name: 'Akon', id: 11 },
},
{
type: 'task',
id: 234,
created_at: '2018-07-03T14:43:52-07:00',
created_by: { name: 'Akon', id: 11 },
modified_at: '2018-07-03T14:43:52-07:00',
tagged_message: 'test',
modified_by: { name: 'Jay-Z', id: 10 },
dueAt: '2018-07-03T14:43:52-07:00',
task_assignment_collection: {
entries: [],
total_count: 0,
},
},
];
const activityFeedError = { title: 't', content: 'm' };
describe('elements/content-sidebar/ActiveState/activity-feed/ActiveState', () => {
test('should correctly render empty state', () => {
const wrapper = shallow(<ActiveState items={[]} />);
expect(wrapper).toMatchSnapshot();
});
test('should correctly render with comments, tasks, versions', () => {
const wrapper = shallow(<ActiveState items={items} />).dive();
expect(wrapper).toMatchSnapshot();
expect(wrapper.find(Task)).toHaveLength(1);
});
test('should correctly render with an inline error if some feed items fail to fetch', () => {
const wrapper = shallow(<ActiveState inlineError={activityFeedError} items={[]} />);
expect(wrapper).toMatchSnapshot();
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.