text stringlengths 2 1.04M | meta dict |
|---|---|
package com.example.hp.exercise10_sharepreference;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.hp.exercise10_sharepreference", appContext.getPackageName());
}
}
| {
"content_hash": "b8633e77828361fd9c7cd09d53ba3ebd",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 95,
"avg_line_length": 30.23076923076923,
"alnum_prop": 0.7557251908396947,
"repo_name": "mahdiheravi/Exercise10_sharepreference",
"id": "aaece2af60e718d202f6cb479b7ea8b09ae76b7a",
"size": "786",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/src/androidTest/java/com/example/hp/exercise10_sharepreference/ExampleInstrumentedTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "9374"
}
],
"symlink_target": ""
} |
using System;
using System.ComponentModel;
using OSharp.Core.Packs;
using OSharp.Entity;
using OSharp.Entity.MySql;
namespace Liuliu.Demo.Web.Startups
{
/// <summary>
/// MySql-DefaultDbContext迁移模块
/// </summary>
[DependsOnPacks(typeof(MySqlEntityFrameworkCorePack))]
[Description("MySql-DefaultDbContext迁移模块")]
public class MySqlDefaultDbContextMigrationPack : MigrationPackBase<DefaultDbContext>
{
/// <summary>
/// 获取 模块启动顺序,模块启动的顺序先按级别启动,同一级别内部再按此顺序启动,
/// 级别默认为0,表示无依赖,需要在同级别有依赖顺序的时候,再重写为>0的顺序值
/// </summary>
public override int Order => 2;
/// <summary>
/// 获取 数据库类型
/// </summary>
protected override DatabaseType DatabaseType => DatabaseType.MySql;
/// <summary>
/// 重写实现获取数据上下文实例
/// </summary>
/// <param name="scopedProvider">服务提供者</param>
/// <returns></returns>
protected override DefaultDbContext CreateDbContext(IServiceProvider scopedProvider)
{
return new DesignTimeDefaultDbContextFactory(scopedProvider).CreateDbContext(new string[0]);
}
}
}
| {
"content_hash": "2d5a7b029f3763eed31576bf3c67aa9f",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 104,
"avg_line_length": 29.384615384615383,
"alnum_prop": 0.6483420593368238,
"repo_name": "i66soft/osharp-ns20",
"id": "9527779b1343f8fdc1db63c94a7331c0db21d4df",
"size": "1799",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "samples/web/Liuliu.Demo.Web/Startups/MySqlDefaultDbContextMigrationPack.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "432"
},
{
"name": "C#",
"bytes": "2083952"
},
{
"name": "CSS",
"bytes": "1165534"
},
{
"name": "Dockerfile",
"bytes": "208"
},
{
"name": "HTML",
"bytes": "253152"
},
{
"name": "JavaScript",
"bytes": "81056"
},
{
"name": "Smalltalk",
"bytes": "3"
},
{
"name": "TypeScript",
"bytes": "451111"
},
{
"name": "Vue",
"bytes": "13702"
}
],
"symlink_target": ""
} |
package checksum
import (
"encoding/base64"
"fmt"
"strconv"
"testing"
"github.com/Azure/azure-sdk-for-go/services/resources/mgmt/2019-05-01/resources"
"github.com/Azure/go-autorest/autorest/to"
"github.com/giantswarm/azure-operator/v6/pkg/helpers/vmss"
"github.com/giantswarm/azure-operator/v6/service/controller/key"
"github.com/giantswarm/azure-operator/v6/service/controller/templates"
)
func Test_getDeploymentTemplateChecksum(t *testing.T) {
testCases := []struct {
name string
template map[string]interface{}
expectedChecksum string
errorMatcher func(err error) bool
}{
{
name: "case 0: Successful checksum calculation",
template: map[string]interface{}{"bob": "5"},
expectedChecksum: "8f3f86c9bc89affcd4eb86effad32055c6b9f575b53d44373e87cbff547b6e51",
},
}
for i, tc := range testCases {
t.Run(strconv.Itoa(i), func(t *testing.T) {
t.Log(tc.name)
properties := resources.DeploymentProperties{
Template: tc.template,
}
deployment := resources.Deployment{
Properties: &properties,
}
chk, err := GetDeploymentTemplateChecksum(deployment)
switch {
case err == nil && tc.errorMatcher == nil:
// fall through
case err != nil && tc.errorMatcher == nil:
t.Fatalf("expected %#v got %#v", nil, err)
case err == nil && tc.errorMatcher != nil:
t.Fatalf("expected %#v got %#v", "error", nil)
case !tc.errorMatcher(err):
t.Fatalf("expected %#v got %#v", true, false)
}
if chk != tc.expectedChecksum {
t.Fatalf("Wrong checksum: expected %s got %s", tc.expectedChecksum, chk)
}
})
}
}
func Test_getDeploymentParametersChecksum(t *testing.T) {
testCases := map[string]testData{
"case 0: Default test data": defaultTestData(),
"case 1: Changed OS Image Offer": defaultTestData().WithosImageOffer("Ubuntu"),
"case 2: Changed OS Image Publisher": defaultTestData().WithosImagePublisher("Canonical"),
"case 3: Changed OS Image SKU": defaultTestData().WithosImageSKU("LTS"),
"case 4: Changed OS Image Version": defaultTestData().WithosImageVersion("18.04"),
"case 5: Changed VM Size": defaultTestData().WithvmSize("very_sml"),
"case 6: Changed Docker Volume Size": defaultTestData().WithdockerVolumeSizeGB(100),
"case 7: Changed Master Blob Url": defaultTestData().WithmasterBlobUrl("http://www.giantwarm.io"),
"case 8: Changed Master Encryption Key": defaultTestData().WithmasterEncryptionKey("0123456789abcdef"),
"case 9: Changed Master Initial Vector": defaultTestData().WithmasterInitialVector("fedcba9876543210"),
"case 10: Changed Worker Blob Url": defaultTestData().WithworkerBlobUrl("http://www.giantwarm.io"),
"case 11: Changed Worker Encryption Key": defaultTestData().WithworkerEncryptionKey("0123456789abcdef"),
"case 12: Changed Worker Initial Vector": defaultTestData().WithworkerInitialVector("fedcba9876543210"),
"case 13: Changed MasterLB Backend Pool": defaultTestData().WithmasterLBBackendPoolID("/just/a/test"),
"case 14: Changed Cluster ID": defaultTestData().WithclusterID("abcde"),
"case 15: Changed Master Subnet ID": defaultTestData().WithmasterSubnetID("/and/another/one"),
"case 16: Change VMSS MSIE enabled": defaultTestData().WithvmssMSIEnabled(false),
"case 17: Changed Worker Subnet ID": defaultTestData().WithworkerSubnetID("/and/the/last/one"),
"case 18: Added a new field": defaultTestData().WithadditionalFields(map[string]string{"additional": "field"}),
"case 19: Removed a field": defaultTestData().WithremovedFields([]string{"masterSubnetID"}),
"case 20: Changed the cloud config tmpl": defaultTestData().WithcloudConfigSmallTemplates([]string{"{}"}),
}
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
deployment, err := getDeployment(tc)
if err != nil {
t.Fatalf("Unable to construct a deployment: %v", err)
}
chk, err := GetDeploymentParametersChecksum(*deployment)
if err != nil {
t.Fatalf("Unexpected error")
}
if tc.checksumIs != nil && chk != *tc.checksumIs {
t.Fatalf("Checksum calculation invalid (expected %s, got %s)", *tc.checksumIs, chk)
}
if tc.checksumIsNot != nil && chk == *tc.checksumIsNot {
t.Fatalf("Expected checksum to change but it didn't")
}
})
}
}
type testData struct {
osImageOffer string
osImagePublisher string
osImageSKU string
osImageVersion string
vmSize string
dockerVolumeSizeGB int
masterBlobUrl string
masterEncryptionKey string
masterInitialVector string
masterInstanceRole string
workerBlobUrl string
workerEncryptionKey string
workerInitialVector string
workerInstanceRole string
masterLBBackendPoolID string
clusterID string
masterSubnetID string
vmssMSIEnabled bool
workerSubnetID string
additionalFields map[string]string
removedFields []string
cloudConfigSmallTemplates []string
checksumIs *string
checksumIsNot *string
}
func defaultTestData() testData {
return testData{
osImageOffer: "CoreOS",
osImagePublisher: "CoreOS",
osImageSKU: "Stable",
osImageVersion: "2191.5.0",
vmSize: "Standard_D4s_v3",
dockerVolumeSizeGB: 50,
masterBlobUrl: "https://gssatjb62.blob.core.windows.net/ignition/2.8.0-v4.7.0-worker?se=2020-05-18T13%3A60%3A03Z&sig=9tXJCWxsZb6MxBQZDDbVykB3VMs0CxxoIDHJtpKs10g%3D&sp=r&spr=https&sr=b&sv=2018-03-28",
masterEncryptionKey: "00112233445566778899aabbccddeeff00112233445566778899aabbccddee",
masterInitialVector: "0011223344556677889900aabbccddee",
masterInstanceRole: "master",
workerBlobUrl: "https://gssatjb62.blob.core.windows.net/ignition/2.8.0-v4.7.0-worker?se=2020-05-18T13%3A61%3A03Z&sig=9tXJCWxsZb6MxBQZDDbVykB3VMs0CxxoIDHJtpKs10g%3D&sp=r&spr=https&sr=b&sv=2018-03-28",
workerEncryptionKey: "eeddccbbaa99887766554433221100ffeeddccbbaa99887766554433221100",
workerInitialVector: "eeddccbbaa0099887766554433221100",
workerInstanceRole: "worker",
masterLBBackendPoolID: "/subscriptions/746379f9-ad35-1d92-1829-cba8579d71e6/resourceGroups/tjb62/providers/Microsoft.Network/loadBalancers/tjb62-API-PublicLoadBalancer/backendAddressPools/tjb62-API-PublicLoadBalancer-BackendPool",
clusterID: "tjb62",
masterSubnetID: "/subscriptions/746379f9-ad35-1d92-1829-cba8579d71e6/resourceGroups/tjb62/providers/Microsoft.Network/virtualNetworks/tjb62-VirtualNetwork/subnets/tjb62-VirtualNetwork-MasterSubnet",
vmssMSIEnabled: true,
workerSubnetID: "/subscriptions/746379f9-ad35-1d92-1829-cba8579d71e6/resourceGroups/tjb62/providers/Microsoft.Network/virtualNetworks/tjb62-VirtualNetwork/subnets/tjb62-VirtualNetwork-WorkerSubnet",
additionalFields: nil,
removedFields: nil,
cloudConfigSmallTemplates: key.CloudConfigSmallTemplates(),
checksumIs: to.StringPtr("c951fe3f40c07e081f17098989a1a9ecc1e16e8074505eb897afb0436bec45e3"),
checksumIsNot: nil,
}
}
func (td testData) WithosImageOffer(data string) testData {
td.osImageOffer = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithosImagePublisher(data string) testData {
td.osImagePublisher = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithosImageSKU(data string) testData {
td.osImageSKU = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithosImageVersion(data string) testData {
td.osImageVersion = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithvmSize(data string) testData {
td.vmSize = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithdockerVolumeSizeGB(data int) testData {
td.dockerVolumeSizeGB = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithmasterBlobUrl(data string) testData {
td.masterBlobUrl = data
// checksum isn't expected to change
return td
}
func (td testData) WithmasterEncryptionKey(data string) testData {
td.masterEncryptionKey = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithmasterInitialVector(data string) testData {
td.masterInitialVector = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithworkerBlobUrl(data string) testData {
td.workerBlobUrl = data
// checksum isn't expected to change
return td
}
func (td testData) WithworkerEncryptionKey(data string) testData {
td.workerEncryptionKey = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithworkerInitialVector(data string) testData {
td.workerInitialVector = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithmasterLBBackendPoolID(data string) testData {
td.masterLBBackendPoolID = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithclusterID(data string) testData {
td.clusterID = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithmasterSubnetID(data string) testData {
td.masterSubnetID = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithvmssMSIEnabled(data bool) testData {
td.vmssMSIEnabled = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithworkerSubnetID(data string) testData {
td.workerSubnetID = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithadditionalFields(data map[string]string) testData {
td.additionalFields = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithremovedFields(data []string) testData {
td.removedFields = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func (td testData) WithcloudConfigSmallTemplates(data []string) testData {
td.cloudConfigSmallTemplates = data
td.checksumIsNot = td.checksumIs
td.checksumIs = nil
return td
}
func getDeployment(data testData) (*resources.Deployment, error) {
nodes := []vmss.Node{
{
OSImage: vmss.NodeOSImage{
Offer: data.osImageOffer,
Publisher: data.osImagePublisher,
SKU: data.osImageSKU,
Version: data.osImageVersion,
},
VMSize: data.vmSize,
DockerVolumeSizeGB: data.dockerVolumeSizeGB,
},
}
_ = struct {
}{}
c := vmss.SmallCloudconfigConfig{
BlobURL: data.masterBlobUrl,
EncryptionKey: data.masterEncryptionKey,
InitialVector: data.masterInitialVector,
InstanceRole: data.masterInstanceRole,
}
masterCloudConfig, err := templates.Render(data.cloudConfigSmallTemplates, c)
if err != nil {
return nil, err
}
encodedMasterCloudConfig := base64.StdEncoding.EncodeToString([]byte(masterCloudConfig))
c = vmss.SmallCloudconfigConfig{
BlobURL: data.workerBlobUrl,
EncryptionKey: data.workerEncryptionKey,
InitialVector: data.workerInitialVector,
InstanceRole: data.workerInstanceRole,
}
workerCloudConfig, err := templates.Render(data.cloudConfigSmallTemplates, c)
if err != nil {
return nil, err
}
encodedWorkerCloudConfig := base64.StdEncoding.EncodeToString([]byte(workerCloudConfig))
parameters := map[string]interface{}{
"masterLBBackendPoolID": data.masterLBBackendPoolID,
"clusterID": data.clusterID,
"masterCloudConfigData": struct{ Value interface{} }{Value: encodedMasterCloudConfig},
"masterNodes": nodes,
"masterSubnetID": data.masterSubnetID,
"vmssMSIEnabled": data.vmssMSIEnabled,
"workerCloudConfigData": struct{ Value interface{} }{Value: encodedWorkerCloudConfig},
"workerNodes": nodes,
"workerSubnetID": data.workerSubnetID,
}
if data.additionalFields != nil {
for k, v := range data.additionalFields {
parameters[k] = v
}
}
if data.removedFields != nil {
for _, v := range data.removedFields {
_, ok := parameters[v]
if !ok {
panic(fmt.Sprintf("Field '%s' was not found for removal", v))
}
delete(parameters, v)
}
}
properties := resources.DeploymentProperties{
Parameters: parameters,
}
return &resources.Deployment{Properties: &properties}, nil
}
| {
"content_hash": "c0557bb6e501cd765bcc978fbe6b2411",
"timestamp": "",
"source": "github",
"line_count": 400,
"max_line_length": 236,
"avg_line_length": 31.815,
"alnum_prop": 0.7132641835612132,
"repo_name": "giantswarm/azure-operator",
"id": "fccb59a4b4f152cc35214beb8e849fb226a2b78d",
"size": "12726",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "pkg/checksum/checksum_test.go",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "605"
},
{
"name": "Go",
"bytes": "1166258"
},
{
"name": "HTML",
"bytes": "285"
},
{
"name": "Makefile",
"bytes": "5128"
},
{
"name": "Mustache",
"bytes": "1707"
},
{
"name": "Shell",
"bytes": "13425"
}
],
"symlink_target": ""
} |
class Solution {
public:
int maxDepth(TreeNode* root) {
if (root == NULL) {
return 0;
}
int left = maxDepth(root->left);
int right = maxDepth(root->right);
return (left > right) ? left + 1 : right + 1;
}
}; | {
"content_hash": "d2c35de44632809a2bfb76c7941bed40",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 53,
"avg_line_length": 24.181818181818183,
"alnum_prop": 0.5,
"repo_name": "andy-sheng/leetcode",
"id": "79264469736bdc5b8879f8d5fca8a8023fa18e49",
"size": "266",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "104-Maximum-Depth-of-Binary-Tree.cpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "22195"
},
{
"name": "C++",
"bytes": "315781"
},
{
"name": "Java",
"bytes": "37348"
},
{
"name": "Objective-C",
"bytes": "2621"
},
{
"name": "Python",
"bytes": "12592"
}
],
"symlink_target": ""
} |
'''
.. _motionevent:
Motion Event
============
The :class:`MotionEvent` is the base class used for every touch and non-touch
event. This class defines all the properties and methods needed to handle 2D and
3D movements but has many more capabilities.
.. note::
You never create the :class:`MotionEvent` yourself: this is the role of the
:mod:`~kivy.input.providers`.
Motion Event and Touch
----------------------
We differentiate between a Motion Event and Touch event. A Touch event is a
:class:`MotionEvent` with the `pos` profile. Only theses events are dispatched
throughout the widget tree.
1. The :class:`MotionEvent` 's are gathered from input providers.
2. All the :class:`MotionEvent` 's are dispatched from
:py:func:`~kivy.core.window.WindowBase.on_motion`.
3. If a :class:`MotionEvent` has a `pos` profile, we dispatch it through
:py:func:`~kivy.core.window.WindowBase.on_touch_down`,
:py:func:`~kivy.core.window.WindowBase.on_touch_move` and
:py:func:`~kivy.core.window.WindowBase.on_touch_up`.
Listening to a Motion Event
---------------------------
If you want to receive all MotionEvents, Touch or not, you can bind the
MotionEvent from the :class:`~kivy.core.window.Window` to your own callback::
def on_motion(self, etype, motionevent):
# will receive all motion events.
pass
Window.bind(on_motion=on_motion)
Profiles
--------
A capability is the ability of a :class:`MotionEvent` to store new
information or a way to indicate what is supported by the MotionEvent. For
example, you can receive a MotionEvent that has an angle, a fiducial ID, or
even a shape. You can check the :attr:`~MotionEvent.profile` attribute to check
what is currently supported by the MotionEvent and how to access it.
This is a tiny list of the supported profiles by default. Check other input
providers to see if there are other profiles available.
============== ================================================================
Profile name Description
-------------- ----------------------------------------------------------------
angle 2D angle. Use property `a`
button Mouse button (left, right, middle, scrollup, scrolldown)
Use property `button`
markerid Marker or Fiducial ID. Use property `fid`
pos 2D position. Use properties `x`, `y` or `pos``
pos3d 3D position. Use properties `x`, `y`, `z`
pressure Pressure of the contact. Use property `pressure`
shape Contact shape. Use property `shape`
============== ================================================================
If you want to know whether the current :class:`MotionEvent` has an angle::
def on_touch_move(self, touch):
if 'angle' in touch.profile:
print('The touch angle is', touch.a)
If you want to select only the fiducials::
def on_touch_move(self, touch):
if 'markerid' not in touch.profile:
return
'''
__all__ = ('MotionEvent', )
import weakref
from inspect import isroutine
from copy import copy
from time import time
from kivy.vector import Vector
class EnhancedDictionnary(dict):
def __getattr__(self, attr):
try:
return self.__getitem__(attr)
except KeyError:
return super(EnhancedDictionnary, self).__getattr__(attr)
def __setattr__(self, attr, value):
self.__setitem__(attr, value)
class MotionEventMetaclass(type):
def __new__(mcs, name, bases, attrs):
__attrs__ = []
for base in bases:
if hasattr(base, '__attrs__'):
__attrs__.extend(base.__attrs__)
if '__attrs__' in attrs:
__attrs__.extend(attrs['__attrs__'])
attrs['__attrs__'] = tuple(__attrs__)
return super(MotionEventMetaclass, mcs).__new__(mcs, name, bases, attrs)
MotionEventBase = MotionEventMetaclass('MotionEvent', (object, ), {})
class MotionEvent(MotionEventBase):
'''Abstract class to represent a touch and non-touch object.
:Parameters:
`id` : str
unique ID of the MotionEvent
`args` : list
list of parameters, passed to the depack() function
'''
__uniq_id = 0
__attrs__ = \
('device', 'push_attrs', 'push_attrs_stack',
'is_touch', 'id', 'shape', 'profile',
# current position, in 0-1 range
'sx', 'sy', 'sz',
# first position set, in 0-1 range
'osx', 'osy', 'osz',
# last position set, in 0-1 range
'psx', 'psy', 'psz',
# delta from the last position and current one, in 0-1 range
'dsx', 'dsy', 'dsz',
# current position, in screen range
'x', 'y', 'z',
# first position set, in screen range
'ox', 'oy', 'oz',
# last position set, in 0-1 range
'px', 'py', 'pz',
# delta from the last position and current one, in screen range
'dx', 'dy', 'dz',
'time_start',
'is_double_tap', 'double_tap_time',
'is_triple_tap', 'triple_tap_time',
'ud')
def __init__(self, device, id, args):
if self.__class__ == MotionEvent:
raise NotImplementedError('class MotionEvent is abstract')
MotionEvent.__uniq_id += 1
#: True if the Motion Event is a Touch. Can be also verified is `pos` is
#: :attr:`profile`.
self.is_touch = False
#: Attributes to push by default, when we use :func:`push` : x, y, z,
#: dx, dy, dz, ox, oy, oz, px, py, pz.
self.push_attrs_stack = []
self.push_attrs = ('x', 'y', 'z', 'dx', 'dy', 'dz', 'ox', 'oy', 'oz',
'px', 'py', 'pz', 'pos')
#: Uniq ID of the touch. You can safely use this property, it will be
#: never the same accross all existing touches.
self.uid = MotionEvent.__uniq_id
#: Device used for creating this touch
self.device = device
# For grab
self.grab_list = []
self.grab_exclusive_class = None
self.grab_state = False
#: Used to determine which widget the touch is being dispatched to.
#: Check the :func:`grab` function for more information.
self.grab_current = None
#: Profiles currently used in the touch
self.profile = []
#: Id of the touch, not uniq. This is generally the Id set by the input
#: provider, like ID in TUIO. If you have multiple TUIO source, the same
#: id can be used. Prefer to use :attr:`uid` attribute instead.
self.id = id
#: Shape of the touch, subclass of
#: :class:`~kivy.input.shape.Shape`.
#: By default, the property is set to None
self.shape = None
#: X position, in 0-1 range
self.sx = 0.0
#: Y position, in 0-1 range
self.sy = 0.0
#: Z position, in 0-1 range
self.sz = 0.0
#: Origin X position, in 0-1 range.
self.osx = None
#: Origin Y position, in 0-1 range.
self.osy = None
#: Origin Z position, in 0-1 range.
self.osz = None
#: Previous X position, in 0-1 range.
self.psx = None
#: Previous Y position, in 0-1 range.
self.psy = None
#: Previous Z position, in 0-1 range.
self.psz = None
#: Delta between self.sx and self.psx, in 0-1 range.
self.dsx = None
#: Delta between self.sy and self.psy, in 0-1 range.
self.dsy = None
#: Delta between self.sz and self.psz, in 0-1 range.
self.dsz = None
#: X position, in window range
self.x = 0.0
#: Y position, in window range
self.y = 0.0
#: Z position, in window range
self.z = 0.0
#: Origin X position, in window range
self.ox = None
#: Origin Y position, in window range
self.oy = None
#: Origin Z position, in window range
self.oz = None
#: Previous X position, in window range
self.px = None
#: Previous Y position, in window range
self.py = None
#: Previous Z position, in window range
self.pz = None
#: Delta between self.x and self.px, in window range
self.dx = None
#: Delta between self.y and self.py, in window range
self.dy = None
#: Delta between self.z and self.pz, in window range
self.dz = None
#: Position (X, Y), in window range
self.pos = (0.0, 0.0)
#: Initial time of the touch creation
self.time_start = time()
#: Time of the last update
self.time_update = self.time_start
#: Time of the end event (last touch usage)
self.time_end = -1
#: Indicate if the touch is a double tap or not
self.is_double_tap = False
#: Indicate if the touch is a triple tap or not
#:
#: .. versionadded:: 1.7.0
self.is_triple_tap = False
#: If the touch is a :attr:`is_double_tap`, this is the time between the
#: previous tap and the current touch.
self.double_tap_time = 0
#: If the touch is a :attr:`is_triple_tap`, this is the time between the
#: first tap and the current touch.
#: .. versionadded:: 1.7.0
self.triple_tap_time = 0
#: User data dictionnary. Use this dictionnary to save your own data on
#: the touch.
self.ud = EnhancedDictionnary()
self.depack(args)
def depack(self, args):
'''Depack `args` into attributes of the class'''
# set initial position and last position
if self.osx is None:
self.psx = self.osx = self.sx
self.psy = self.osy = self.sy
self.psz = self.osz = self.sz
# update the delta
self.dsx = self.sx - self.psx
self.dsy = self.sy - self.psy
self.dsz = self.sz - self.psz
def grab(self, class_instance, exclusive=False):
'''Grab this motion event. You can grab a touch if you absolutly want to
receive on_touch_move() and on_touch_up(), even if the touch is not
dispatched by your parent::
def on_touch_down(self, touch):
touch.grab(self)
def on_touch_move(self, touch):
if touch.grab_current is self:
# I received my grabbed touch
else:
# it's a normal touch
def on_touch_up(self, touch):
if touch.grab_current is self:
# I receive my grabbed touch, I must ungrab it!
touch.ungrab(self)
else:
# it's a normal touch
pass
'''
if not self.is_touch:
raise Exception('Grab works only for Touch MotionEvents.')
if self.grab_exclusive_class is not None:
raise Exception('Cannot grab the touch, touch is exclusive')
class_instance = weakref.ref(class_instance)
if exclusive:
self.grab_exclusive_class = class_instance
self.grab_list.append(class_instance)
def ungrab(self, class_instance):
'''Ungrab a previously grabbed touch
'''
class_instance = weakref.ref(class_instance)
if self.grab_exclusive_class == class_instance:
self.grab_exclusive_class = None
if class_instance in self.grab_list:
self.grab_list.remove(class_instance)
def move(self, args):
'''Move the touch to another position
'''
self.px = self.x
self.py = self.y
self.pz = self.z
self.psx = self.sx
self.psy = self.sy
self.psz = self.sz
self.time_update = time()
self.depack(args)
def scale_for_screen(self, w, h, p=None, rotation=0):
'''Scale position for the screen
'''
sx, sy = self.sx, self.sy
if rotation == 0:
self.x = sx * float(w)
self.y = sy * float(h)
elif rotation == 90:
sx, sy = sy, 1 - sx
self.x = sx * float(h)
self.y = sy * float(w)
elif rotation == 180:
sx, sy = 1 - sx, 1 - sy
self.x = sx * float(w)
self.y = sy * float(h)
elif rotation == 270:
sx, sy = 1 - sy, sx
self.x = sx * float(h)
self.y = sy * float(w)
if p:
self.z = self.sz * float(p)
if self.ox is None:
self.px = self.ox = self.x
self.py = self.oy = self.y
self.pz = self.oz = self.z
self.dx = self.x - self.px
self.dy = self.y - self.py
self.dz = self.z - self.pz
# cache position
self.pos = self.x, self.y
def push(self, attrs=None):
'''Push attribute values in `attrs` onto the stack
'''
if attrs is None:
attrs = self.push_attrs
values = [getattr(self, x) for x in attrs]
self.push_attrs_stack.append((attrs, values))
def pop(self):
'''Pop attributes values from the stack
'''
attrs, values = self.push_attrs_stack.pop()
for i in range(len(attrs)):
setattr(self, attrs[i], values[i])
def apply_transform_2d(self, transform):
'''Apply a transformation on x, y, z, px, py, pz,
ox, oy, oz, dx, dy, dz
'''
self.x, self.y = self.pos = transform(self.x, self.y)
self.px, self.py = transform(self.px, self.py)
self.ox, self.oy = transform(self.ox, self.oy)
self.dx = self.x - self.px
self.dy = self.y - self.py
def copy_to(self, to):
'''Copy some attribute to another touch object.'''
for attr in self.__attrs__:
to.__setattr__(attr, copy(self.__getattribute__(attr)))
def distance(self, other_touch):
'''Return the distance between the current touch and another touch.
'''
return Vector(self.pos).distance(other_touch.pos)
def update_time_end(self):
self.time_end = time()
# facilities
@property
def dpos(self):
'''Return delta between last position and current position, in the
screen coordinate system (self.dx, self.dy)'''
return self.dx, self.dy
@property
def opos(self):
'''Return the initial position of the touch in the screen
coordinate system (self.ox, self.oy)'''
return self.ox, self.oy
@property
def ppos(self):
'''Return the previous position of the touch in the screen
coordinate system (self.px, self.py)'''
return self.px, self.py
@property
def spos(self):
'''Return the position in the 0-1 coordinate system
(self.sx, self.sy)'''
return self.sx, self.sy
def __str__(self):
basename = str(self.__class__)
classname = basename.split('.')[-1].replace('>', '').replace('\'', '')
return '<%s spos=%s pos=%s>' % (classname, self.spos, self.pos)
def __repr__(self):
out = []
for x in dir(self):
v = getattr(self, x)
if x[0] == '_':
continue
if isroutine(v):
continue
out.append('%s="%s"' % (x, v))
return '<%s %s>' % (
self.__class__.__name__,
' '.join(out))
@property
def is_mouse_scrolling(self, *args):
'''Returns True if the touch is a mousewheel scrolling
.. versionadded:: 1.6.0
'''
return 'button' in self.profile and 'scroll' in self.button
| {
"content_hash": "72c54b4a6c5b746e3b4fddb51cd153ec",
"timestamp": "",
"source": "github",
"line_count": 467,
"max_line_length": 80,
"avg_line_length": 33.5524625267666,
"alnum_prop": 0.5563852192226689,
"repo_name": "kivatu/kivy_old",
"id": "3554160e2cc37199be7070b49a21c390a2122357",
"size": "15669",
"binary": false,
"copies": "4",
"ref": "refs/heads/master",
"path": "kivy/input/motionevent.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "154026"
},
{
"name": "CSS",
"bytes": "6729"
},
{
"name": "Emacs Lisp",
"bytes": "9603"
},
{
"name": "F#",
"bytes": "289"
},
{
"name": "JavaScript",
"bytes": "11300"
},
{
"name": "Python",
"bytes": "2887512"
},
{
"name": "Shell",
"bytes": "6010"
},
{
"name": "TeX",
"bytes": "4271"
},
{
"name": "VimL",
"bytes": "1123"
}
],
"symlink_target": ""
} |
<?php
class Tribe__Events__Pro__Recurrence__Meta_Builder {
/**
* @var array
*/
protected $data;
/**
* @var int An event type post ID
*/
protected $event_id;
/**
* @var Tribe__Events__Pro__Recurrence__Utils
*/
protected $utils;
/**
* Tribe__Events__Pro__Recurrence__Meta_Builder constructor.
*
* @param array $data
*/
public function __construct( $event_id, array $data = array(), Tribe__Events__Pro__Recurrence__Utils $utils = null ) {
$this->event_id = $event_id;
$this->data = $data;
$this->utils = $utils ? $utils : new Tribe__Events__Pro__Recurrence__Utils();
}
public function build_meta() {
if ( empty( $this->data ) || empty( $this->data['recurrence'] ) || ! is_array( $this->data['recurrence'] ) ) {
return $this->get_zero_array();
}
$recurrence_meta = $this->get_zero_array();
$custom_types = array(
Tribe__Events__Pro__Recurrence__Custom_Types::DAILY_CUSTOM_TYPE,
Tribe__Events__Pro__Recurrence__Custom_Types::WEEKLY_CUSTOM_TYPE,
Tribe__Events__Pro__Recurrence__Custom_Types::MONTHLY_CUSTOM_TYPE,
Tribe__Events__Pro__Recurrence__Custom_Types::YEARLY_CUSTOM_TYPE,
Tribe__Events__Pro__Recurrence__Custom_Types::DATE_CUSTOM_TYPE,
);
if ( isset( $this->data['recurrence']['recurrence-description'] ) ) {
unset( $this->data['recurrence']['recurrence-description'] );
}
foreach ( array( 'rules', 'exclusions' ) as $rule_type ) {
if ( ! isset( $this->data['recurrence'][ $rule_type ] ) ) {
continue;
}
foreach ( $this->data['recurrence'][ $rule_type ] as $key => &$recurrence ) {
if ( ! $recurrence ) {
continue;
}
// Ignore the rule if the type isn't set OR the type is set to 'None'
// (we're not interested in exclusions here)
if ( empty( $recurrence['type'] ) || 'None' === $recurrence['type'] ) {
continue;
}
if ( in_array( $recurrence['type'], $custom_types ) ) {
// we now consider all non-blank types to be custom types
$recurrence['custom']['type'] = $recurrence['type'];
$recurrence['type'] = 'Custom';
}
$has_no_type = empty( $recurrence['type'] ) && empty( $recurrence['custom']['type'] );
$is_custom_none_recurrence = 'exclusions' == $rule_type && ! empty( $recurrence['custom']['type'] ) && 'None' === $recurrence['custom']['type'];
if ( $has_no_type || $is_custom_none_recurrence ) {
unset( $this->data['recurrence'][ $rule_type ][ $key ] );
continue;
}
if ( isset( $recurrence['custom'] ) && isset( $recurrence['custom']['type-text'] ) ) {
unset( $recurrence['custom']['type-text'] );
}
unset( $recurrence['occurrence-count-text'] );
$datepicker_format = $this->utils->datepicker_formats( tribe_get_option( 'datepickerFormat' ) );
if ( ! empty( $recurrence['end'] ) ) {
$recurrence['end'] = $this->utils->datetime_from_format( $datepicker_format, $recurrence['end'] );
}
// if the month should use the same day of the month as the main event, then unset irrelevant fields if they exist
if (
isset( $recurrence['custom']['month']['same-day'] )
&& 'yes' === $recurrence['custom']['month']['same-day']
) {
$remove = array( 'number', 'day' );
$recurrence['custom']['month'] = array_intersect_key( $recurrence['custom']['month'], array_flip( $remove ) );
}
if (
isset( $recurrence['custom']['type'] )
&& Tribe__Events__Pro__Recurrence__Custom_Types::DATE_CUSTOM_TYPE === $recurrence['custom']['type']
&& isset( $recurrence['custom']['date']['date'] )
) {
$recurrence['custom']['date']['date'] = $this->utils->datetime_from_format( $datepicker_format, $recurrence['custom']['date']['date'] );
}
// if this isn't an exclusion and it isn't a Custom rule, then we don't need the custom array index
if ( 'rules' === $rule_type && 'Custom' !== $recurrence['type'] ) {
if ( isset( $recurrence['custom'] ) ) {
unset( $recurrence['custom'] );
}
} else {
$type = $recurrence['custom']['type'];
$type_slug = Tribe__Events__Pro__Recurrence__Custom_Types::to_key( $type );
$slugs_to_remove = array(
'date',
'day',
'week',
'month',
'year',
);
$slugs_to_remove = array_diff( $slugs_to_remove, array( $type_slug ) );
// clean up extraneous array elements
$recurrence['custom'] = array_diff_key( $recurrence['custom'], array_flip( $slugs_to_remove ) );
}
if ( empty( $recurrence['custom']['same-time'] ) ) {
$recurrence['custom']['same-time'] = 'yes';
}
if ( empty( $recurrence['custom']['interval'] ) ) {
$recurrence['custom']['interval'] = 1;
}
$recurrence['EventStartDate'] = $this->data['EventStartDate'];
$recurrence['EventEndDate'] = $this->data['EventEndDate'];
if ( $this->utils->is_valid( $this->event_id, $recurrence ) ) {
$recurrence_meta[ $rule_type ][] = $recurrence;
}
}
}
return $recurrence_meta;
}
private function get_zero_array() {
$data_recurrence = null;
if ( ! empty( $this->data['recurrence'] ) ) {
$data_recurrence = (array) $this->data['recurrence'];
}
return array(
'rules' => array(),
'exclusions' => array(),
'description' => empty( $data_recurrence['description'] ) ? null : sanitize_text_field( $data_recurrence['description'] ),
);
}
}
| {
"content_hash": "470744df049164e959c41dffdfdd03dd",
"timestamp": "",
"source": "github",
"line_count": 160,
"max_line_length": 148,
"avg_line_length": 33.6,
"alnum_prop": 0.5900297619047619,
"repo_name": "mandino/hotelmilosantabarbara.com",
"id": "f29237009f29113fb947deaa02edb9e2c007e3eb",
"size": "5376",
"binary": false,
"copies": "8",
"ref": "refs/heads/master",
"path": "wp-content/plugins/events-calendar-pro/src/Tribe/Recurrence/Meta_Builder.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "4421076"
},
{
"name": "HTML",
"bytes": "377475"
},
{
"name": "JavaScript",
"bytes": "6259360"
},
{
"name": "PHP",
"bytes": "30321979"
},
{
"name": "Ruby",
"bytes": "2879"
},
{
"name": "Shell",
"bytes": "1145"
},
{
"name": "Smarty",
"bytes": "200578"
},
{
"name": "XSLT",
"bytes": "9376"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>unicoq: Not compatible 👼</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.7.2 / unicoq - 1.3+8.6</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
unicoq
<small>
1.3+8.6
<span class="label label-info">Not compatible 👼</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-11-20 04:58:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-11-20 04:58:01 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.7.2 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "matthieu.sozeau@inria.fr"
authors: [ "Matthieu Sozeau <matthieu.sozeau@inria.fr>" "Beta Ziliani <bziliani@famaf.unc.edu.ar>" ]
dev-repo: "git+https://github.com/unicoq/unicoq.git"
homepage: "https://github.com/unicoq/unicoq"
bug-reports: "https://github.com/unicoq/unicoq/issues"
license: "MIT"
build: [
["coq_makefile" "-f" "Make" "-o" "Makefile"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/Unicoq"]
depends: [
"ocaml"
"coq" {>= "8.6.0" & < "8.7~"}
]
synopsis: "An enhanced unification algorithm for Coq"
flags: light-uninstall
url {
src: "https://github.com/unicoq/unicoq/archive/v1.3-8.6.tar.gz"
checksum: "md5=954ccceb6e470d2b276f6487d995641c"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-unicoq.1.3+8.6 coq.8.7.2</code></dd>
<dt>Return code</dt>
<dd>5120</dd>
<dt>Output</dt>
<dd><pre>[NOTE] Package coq is already installed (current version is 8.7.2).
The following dependencies couldn't be met:
- coq-unicoq -> coq < 8.7~ -> ocaml < 4.03.0
base of this switch (use `--unlock-base' to force)
Your request can't be satisfied:
- No available version of coq satisfies the constraints
No solution found, exiting
</pre></dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq; opam install -y --show-action --unlock-base coq-unicoq.1.3+8.6</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>0 s</dd>
</dl>
<h2>Installation size</h2>
<p>No files were installed.</p>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "a1e204089af1e6c6742f4a43d8837649",
"timestamp": "",
"source": "github",
"line_count": 168,
"max_line_length": 159,
"avg_line_length": 40.75595238095238,
"alnum_prop": 0.5332262304658975,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "8bdb55f38fd000cbc4b1ce804b996718b7051342",
"size": "6872",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.7.2/unicoq/1.3+8.6.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
<!--?xml version="1.0" encoding="utf-8"?-->
<request method="invoice.lines.add">
<invoice_id>111</invoice_id>
<lines>
<line>
<amount>40</amount>
<name>Yak Shaving</name>
<description>Shaved the yak</description>
<unit_cost>10</unit_cost>
<quantity>4</quantity>
<type>Item</type>
</line>
<line>
<amount>23</amount>
<name>Telephone Sanitizing</name>
<description>Sanitized the telephone</description>
<unit_cost>10</unit_cost>
<quantity>2.30</quantity>
<type>Item</type>
</line>
</lines>
</request> | {
"content_hash": "bcff06132abcaa6d1e118a22c28d4a54",
"timestamp": "",
"source": "github",
"line_count": 22,
"max_line_length": 56,
"avg_line_length": 26.818181818181817,
"alnum_prop": 0.5966101694915255,
"repo_name": "mattjcowan/FreshBooks.Api",
"id": "353096bc68d90cdc629bda818c15ee8b251f1900",
"size": "590",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xml/invoice.lines.add.request.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "750626"
}
],
"symlink_target": ""
} |
@interface ViewController (Swizzling)
@end
| {
"content_hash": "8dca672cf448e15d3d5269560995a120",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 37,
"avg_line_length": 14.666666666666666,
"alnum_prop": 0.7954545454545454,
"repo_name": "wangyanlong/MyCode",
"id": "89e09381b8f84bb12d6e1f1a7ed5466692dc965a",
"size": "216",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Runtime/Swizzling/Swizzling/ViewController+Swizzling.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "892885"
},
{
"name": "Ruby",
"bytes": "298"
},
{
"name": "Shell",
"bytes": "8385"
}
],
"symlink_target": ""
} |
function playerButtons(){
console.log("butts");
}
| {
"content_hash": "6c08e8335a0e461a8c8b72b2ec926384",
"timestamp": "",
"source": "github",
"line_count": 3,
"max_line_length": 25,
"avg_line_length": 17,
"alnum_prop": 0.7058823529411765,
"repo_name": "rcxking/pierce_logic_reloaded",
"id": "17e428af0f8f8bad8e9ad004f3151fcc28ddbf6a",
"size": "51",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "appengine/js/gui/player.js",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "CSS",
"bytes": "19160"
},
{
"name": "JavaScript",
"bytes": "158253"
},
{
"name": "Python",
"bytes": "2832"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "64e76014344c8b96540fafebfbe73229",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "acddc39d917ccee463bd4aae70abb4b6f6506aef",
"size": "172",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Pteridophyta/Polypodiopsida/Polypodiales/Pteridaceae/Adiantum/Adiantum patens/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
#ifndef GAME_H
#define GAME_H
/*Game*/
#define ROTSPEED 0.1
#define STEP_SIZE 0.2
#define SHOOT_BUTTON 12
#define SHOOT_BUTTON2 9
#define RIGHT 0
#define LEFT 1
#define NBR_OF_ENEMIES 6
typedef struct Player {
double x;
double y;
double dirX;
double dirY;
double planeX;
double planeY;
uint8_t shooting;
uint8_t points;
} Player;
typedef struct enemy {
int16_t xPos;
int16_t yPos;
uint8_t visible;
uint8_t destroyed;
} Enemy;
void rotatePlayer(Player *player, uint8_t right);
void movePlayer(Player *player);
void disp_player_posistion (Player *player);
void drawSprite(Player *player, Enemy *enemy);
void playerShoot(Player *player);
void theEnd();
#endif /* GAME_H */ | {
"content_hash": "c5bb2083ee717d9dadb9231ca9b07f91",
"timestamp": "",
"source": "github",
"line_count": 38,
"max_line_length": 49,
"avg_line_length": 18.36842105263158,
"alnum_prop": 0.7177650429799427,
"repo_name": "mrskoog/ray-gfx",
"id": "83e2a2b303fb6f629848c836e501805ab314207e",
"size": "698",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "game.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Arduino",
"bytes": "14407"
},
{
"name": "C",
"bytes": "1083"
}
],
"symlink_target": ""
} |
.class Lcom/android/server/am/ServiceRecord$1;
.super Ljava/lang/Object;
.source "ServiceRecord.java"
# interfaces
.implements Ljava/lang/Runnable;
# annotations
.annotation system Ldalvik/annotation/EnclosingMethod;
value = Lcom/android/server/am/ServiceRecord;->postNotification()V
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/android/server/am/ServiceRecord;
.field final synthetic val$appPid:I
.field final synthetic val$appUid:I
.field final synthetic val$localForegroundId:I
.field final synthetic val$localForegroundNoti:Landroid/app/Notification;
.field final synthetic val$localPackageName:Ljava/lang/String;
# direct methods
.method constructor <init>(Lcom/android/server/am/ServiceRecord;Ljava/lang/String;IIILandroid/app/Notification;)V
.locals 0
.parameter
.parameter
.parameter
.parameter
.parameter
.parameter
.prologue
.line 351
iput-object p1, p0, Lcom/android/server/am/ServiceRecord$1;->this$0:Lcom/android/server/am/ServiceRecord;
iput-object p2, p0, Lcom/android/server/am/ServiceRecord$1;->val$localPackageName:Ljava/lang/String;
iput p3, p0, Lcom/android/server/am/ServiceRecord$1;->val$appUid:I
iput p4, p0, Lcom/android/server/am/ServiceRecord$1;->val$appPid:I
iput p5, p0, Lcom/android/server/am/ServiceRecord$1;->val$localForegroundId:I
iput-object p6, p0, Lcom/android/server/am/ServiceRecord$1;->val$localForegroundNoti:Landroid/app/Notification;
invoke-direct/range {p0 .. p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
# virtual methods
.method public run()V
.locals 11
.prologue
const/4 v10, 0x0
const/4 v9, 0x1
.line 353
invoke-static {}, Landroid/app/NotificationManager;->getService()Landroid/app/INotificationManager;
move-result-object v0
check-cast v0, Lcom/android/server/NotificationManagerService;
.line 355
.local v0, nm:Lcom/android/server/NotificationManagerService;
if-nez v0, :cond_0
.line 372
:goto_0
return-void
.line 359
:cond_0
const/4 v1, 0x1
:try_start_0
new-array v7, v1, [I
.line 360
.local v7, outId:[I
iget-object v1, p0, Lcom/android/server/am/ServiceRecord$1;->val$localPackageName:Ljava/lang/String;
iget v2, p0, Lcom/android/server/am/ServiceRecord$1;->val$appUid:I
iget v3, p0, Lcom/android/server/am/ServiceRecord$1;->val$appPid:I
const/4 v4, 0x0
iget v5, p0, Lcom/android/server/am/ServiceRecord$1;->val$localForegroundId:I
iget-object v6, p0, Lcom/android/server/am/ServiceRecord$1;->val$localForegroundNoti:Landroid/app/Notification;
invoke-virtual/range {v0 .. v7}, Lcom/android/server/NotificationManagerService;->enqueueNotificationInternal(Ljava/lang/String;IILjava/lang/String;ILandroid/app/Notification;[I)V
:try_end_0
.catch Ljava/lang/RuntimeException; {:try_start_0 .. :try_end_0} :catch_0
goto :goto_0
.line 362
.end local v7 #outId:[I
:catch_0
move-exception v8
.line 363
.local v8, e:Ljava/lang/RuntimeException;
const-string v1, "ActivityManager"
const-string v2, "Error showing notification for service"
invoke-static {v1, v2, v8}, Landroid/util/Slog;->w(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I
.line 367
iget-object v1, p0, Lcom/android/server/am/ServiceRecord$1;->this$0:Lcom/android/server/am/ServiceRecord;
iget-object v1, v1, Lcom/android/server/am/ServiceRecord;->ams:Lcom/android/server/am/ActivityManagerService;
iget-object v2, p0, Lcom/android/server/am/ServiceRecord$1;->this$0:Lcom/android/server/am/ServiceRecord;
iget-object v2, v2, Lcom/android/server/am/ServiceRecord;->name:Landroid/content/ComponentName;
iget-object v3, p0, Lcom/android/server/am/ServiceRecord$1;->this$0:Lcom/android/server/am/ServiceRecord;
const/4 v4, 0x0
move-object v5, v10
move v6, v9
invoke-virtual/range {v1 .. v6}, Lcom/android/server/am/ActivityManagerService;->setServiceForeground(Landroid/content/ComponentName;Landroid/os/IBinder;ILandroid/app/Notification;Z)V
.line 369
iget-object v1, p0, Lcom/android/server/am/ServiceRecord$1;->this$0:Lcom/android/server/am/ServiceRecord;
iget-object v1, v1, Lcom/android/server/am/ServiceRecord;->ams:Lcom/android/server/am/ActivityManagerService;
iget v2, p0, Lcom/android/server/am/ServiceRecord$1;->val$appUid:I
iget v3, p0, Lcom/android/server/am/ServiceRecord$1;->val$appPid:I
iget-object v4, p0, Lcom/android/server/am/ServiceRecord$1;->val$localPackageName:Ljava/lang/String;
new-instance v5, Ljava/lang/StringBuilder;
invoke-direct {v5}, Ljava/lang/StringBuilder;-><init>()V
const-string v6, "Bad notification for startForeground: "
invoke-virtual {v5, v6}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v5
invoke-virtual {v5, v8}, Ljava/lang/StringBuilder;->append(Ljava/lang/Object;)Ljava/lang/StringBuilder;
move-result-object v5
invoke-virtual {v5}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v5
invoke-virtual {v1, v2, v3, v4, v5}, Lcom/android/server/am/ActivityManagerService;->crashApplication(IILjava/lang/String;Ljava/lang/String;)V
goto :goto_0
.end method
| {
"content_hash": "cf48a8a6391cec45719c256b052df4e9",
"timestamp": "",
"source": "github",
"line_count": 179,
"max_line_length": 187,
"avg_line_length": 30.48603351955307,
"alnum_prop": 0.7293384643577057,
"repo_name": "baidurom/devices-onex",
"id": "4c5a3a82749bdd1f27dd40519dbffbf2223092cc",
"size": "5457",
"binary": false,
"copies": "2",
"ref": "refs/heads/coron-4.0",
"path": "services.jar.out/smali/com/android/server/am/ServiceRecord$1.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
export {AotCompilerHost, AotCompilerHost as StaticReflectorHost, StaticReflector, StaticSymbol} from '@angular/compiler';
export {CodeGenerator} from './src/codegen';
export {CompilerHost, CompilerHostContext, ModuleResolutionHostAdapter, NodeCompilerHostContext} from './src/compiler_host';
export {Extractor} from './src/extractor';
export * from '@angular/tsc-wrapped';
import {Version} from '@angular/core';
/**
* @stable
*/
export const VERSION = new Version('0.0.0-PLACEHOLDER'); | {
"content_hash": "a5407388fee81318bcfd3bb9f58e34ed",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 124,
"avg_line_length": 40.75,
"alnum_prop": 0.7689161554192229,
"repo_name": "xcaliber-tech/angular",
"id": "b9cd406d968c2d262afd9b3134f766d851e281c3",
"size": "691",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "modules/@angular/compiler-cli/index.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "17278"
},
{
"name": "HTML",
"bytes": "32127"
},
{
"name": "JavaScript",
"bytes": "200409"
},
{
"name": "Python",
"bytes": "3535"
},
{
"name": "Shell",
"bytes": "45637"
},
{
"name": "TypeScript",
"bytes": "5427865"
}
],
"symlink_target": ""
} |
#import "AppDelegate.h"
#import "RCTRootView.h"
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
NSURL *jsCodeLocation;
/**
* Loading JavaScript code - uncomment the one you want.
*
* OPTION 1
* Load from development server. Start the server from the repository root:
*
* $ npm start
*
* To run on device, change `localhost` to the IP address of your computer
* (you can get this by typing `ifconfig` into the terminal and selecting the
* `inet` value under `en0:`) and make sure your computer and iOS device are
* on the same Wi-Fi network.
*/
jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.ios.bundle?platform=ios&dev=true"];
/**
* OPTION 2
* Load from pre-bundled file on disk. The static bundle is automatically
* generated by "Bundle React Native code and images" build step.
*/
// jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
moduleName:@"example"
initialProperties:nil
launchOptions:launchOptions];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
UIViewController *rootViewController = [[UIViewController alloc] init];
rootViewController.view = rootView;
self.window.rootViewController = rootViewController;
[self.window makeKeyAndVisible];
return YES;
// return [[FBSDKApplicationDelegate sharedInstance] application:application
// didFinishLaunchingWithOptions:launchOptions];
}
// Facebook SDK
//- (void)applicationDidBecomeActive:(UIApplication *)application {
// [FBSDKAppEvents activateApp];
//}
//- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
// return [[FBSDKApplicationDelegate sharedInstance] application:application
// openURL:url
// sourceApplication:sourceApplication
// annotation:annotation];
//}
@end
| {
"content_hash": "061b8b1f473473ac79cc059fd5e77c28",
"timestamp": "",
"source": "github",
"line_count": 66,
"max_line_length": 147,
"avg_line_length": 36.666666666666664,
"alnum_prop": 0.6433884297520661,
"repo_name": "lrettig/react-native-stripe",
"id": "29c12c075f540aadac858d560171f2cc738705c2",
"size": "2728",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "example/ios/example/AppDelegate.m",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "JavaScript",
"bytes": "7786"
},
{
"name": "Objective-C",
"bytes": "25125"
},
{
"name": "Shell",
"bytes": "308"
}
],
"symlink_target": ""
} |
package org.apache.druid.query.aggregation;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Ordering;
import java.util.List;
public class TimestampMinAggregatorFactory extends TimestampAggregatorFactory
{
@JsonCreator
public TimestampMinAggregatorFactory(
@JsonProperty("name") String name,
@JsonProperty("fieldName") String fieldName,
@JsonProperty("timeFormat") String timeFormat
)
{
super(name, fieldName, timeFormat, Ordering.natural().reverse(), Long.MAX_VALUE);
Preconditions.checkNotNull(name, "Must have a valid, non-null aggregator name");
}
@Override
public AggregatorFactory getCombiningFactory()
{
return new TimestampMinAggregatorFactory(name, name, timeFormat);
}
@Override
public List<AggregatorFactory> getRequiredColumns()
{
return ImmutableList.of(
new TimestampMinAggregatorFactory(name, fieldName, timeFormat)
);
}
@Override
public String toString()
{
return "TimestampMinAggregatorFactory{" +
"name='" + name + '\'' +
", fieldName='" + fieldName + '\'' +
", timeFormat='" + timeFormat + '\'' +
'}';
}
}
| {
"content_hash": "4fc8e7452937a7113f6cb094510b7bb3",
"timestamp": "",
"source": "github",
"line_count": 49,
"max_line_length": 85,
"avg_line_length": 27.448979591836736,
"alnum_prop": 0.7078066914498141,
"repo_name": "mghosh4/druid",
"id": "79cb1cadfae348fe125066bb9ab874e3dbf0ed05",
"size": "2152",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "extensions-contrib/time-min-max/src/main/java/org/apache/druid/query/aggregation/TimestampMinAggregatorFactory.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "5360"
},
{
"name": "CSS",
"bytes": "3878"
},
{
"name": "Dockerfile",
"bytes": "8766"
},
{
"name": "HTML",
"bytes": "2536"
},
{
"name": "Java",
"bytes": "34944606"
},
{
"name": "JavaScript",
"bytes": "59220"
},
{
"name": "Makefile",
"bytes": "659"
},
{
"name": "PostScript",
"bytes": "5"
},
{
"name": "Python",
"bytes": "66994"
},
{
"name": "R",
"bytes": "17002"
},
{
"name": "Roff",
"bytes": "3617"
},
{
"name": "SCSS",
"bytes": "109536"
},
{
"name": "Shell",
"bytes": "81730"
},
{
"name": "Smarty",
"bytes": "3517"
},
{
"name": "Stylus",
"bytes": "7682"
},
{
"name": "TeX",
"bytes": "399468"
},
{
"name": "Thrift",
"bytes": "1003"
},
{
"name": "TypeScript",
"bytes": "1224966"
}
],
"symlink_target": ""
} |
<?php
namespace AppBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class RespuestaType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('correcta')
->add('expresion', TextareaType::class,
array(
'label_attr' => array('class' => 'control-label'),
'attr'=> array('class' => 'form-control', 'ck-editor' => ''),
'required' => true,
)
)
->add('tema', EntityType::class,
array(
'class' => 'AppBundle:Tema',
'choice_label' => 'nombre',
'label_attr' => array('class' => 'control-label'),
'attr'=> array('class' => 'form-control select2', 'data-placeholder'=>'Seleccione un tema'),
'required' => false,
)
)
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\Respuesta',
'cascade_validation' => true
));
}
}
| {
"content_hash": "a5de89b8182631d6a2c5724b97835c90",
"timestamp": "",
"source": "github",
"line_count": 50,
"max_line_length": 112,
"avg_line_length": 31.68,
"alnum_prop": 0.5366161616161617,
"repo_name": "1211agarcia/sistemaPrediccion",
"id": "730e48c943d1f7c702e30d2cd8152f8d32f2dd39",
"size": "1584",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/AppBundle/Form/RespuestaType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "3606"
},
{
"name": "Batchfile",
"bytes": "406"
},
{
"name": "CSS",
"bytes": "659083"
},
{
"name": "HTML",
"bytes": "2083259"
},
{
"name": "JavaScript",
"bytes": "2965636"
},
{
"name": "PHP",
"bytes": "202506"
},
{
"name": "R",
"bytes": "50654"
},
{
"name": "Shell",
"bytes": "602"
}
],
"symlink_target": ""
} |
<?xml version="1.0" standalone="no"?>
<!DOCTYPE caldavtest SYSTEM "caldavtest.dtd">
<!--
Copyright (c) 2006-2015 Apple Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<caldavtest>
<description>Test timezone cache</description>
<require-feature>
<feature>caldav</feature>
</require-feature>
<start/>
<test-suite name='Timezone cache'>
<test name='1'>
<description>PUT event with truncated timezone in April</description>
<request end-delete='yes'>
<method>PUT</method>
<ruri>$calendarpath1:/1.ics</ruri>
<data>
<content-type>text/calendar; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/1.ics</filepath>
</data>
<verify>
<callback>statusCode</callback>
</verify>
</request>
</test>
<test name='2'>
<description>query for free busy with time range</description>
<request>
<method>REPORT</method>
<ruri>$calendarpath1:/</ruri>
<data>
<content-type>text/xml; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/2.xml</filepath>
</data>
<verify>
<callback>freeBusy</callback>
<arg>
<name>busy</name>
<value>$now.year.0:0401T143000Z/$now.year.0:0401T153000Z</value>
</arg>
</verify>
</request>
</test>
<test name='3'>
<description>PUT event with truncated timezone in December</description>
<request end-delete='yes'>
<method>PUT</method>
<ruri>$calendarpath1:/3.ics</ruri>
<data>
<content-type>text/calendar; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/3.ics</filepath>
</data>
<verify>
<callback>statusCode</callback>
</verify>
</request>
</test>
<test name='4'>
<description>query for free busy with time range</description>
<request>
<method>REPORT</method>
<ruri>$calendarpath1:/</ruri>
<data>
<content-type>text/xml; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/2.xml</filepath>
</data>
<verify>
<callback>freeBusy</callback>
<arg>
<name>busy</name>
<value>$now.year.0:0401T143000Z/$now.year.0:0401T153000Z</value>
<value>$now.year.0:1210T153000Z/$now.year.0:1210T163000Z</value>
</arg>
</verify>
</request>
</test>
</test-suite>
<test-suite name='Timezone cache - aliases'>
<test name='1'>
<description>PUT event with truncated timezone in April</description>
<request end-delete='yes'>
<method>PUT</method>
<ruri>$calendarpath1:/4.ics</ruri>
<data>
<content-type>text/calendar; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/4.ics</filepath>
</data>
<verify>
<callback>statusCode</callback>
</verify>
</request>
</test>
<test name='2'>
<description>query for free busy with time range</description>
<request>
<method>REPORT</method>
<ruri>$calendarpath1:/</ruri>
<data>
<content-type>text/xml; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/2.xml</filepath>
</data>
<verify>
<callback>freeBusy</callback>
<arg>
<name>busy</name>
<value>$now.year.0:0401T143000Z/$now.year.0:0401T153000Z</value>
<value>$now.year.0:1210T153000Z/$now.year.0:1210T163000Z</value>
<value>$now.year.0:0402T150000Z/$now.year.0:0402T160000Z</value>
</arg>
</verify>
</request>
</test>
<test name='3'>
<description>PUT event with truncated timezone in December</description>
<request end-delete='yes'>
<method>PUT</method>
<ruri>$calendarpath1:/5.ics</ruri>
<data>
<content-type>text/calendar; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/5.ics</filepath>
</data>
<verify>
<callback>statusCode</callback>
</verify>
</request>
</test>
<test name='4'>
<description>query for free busy with time range</description>
<request>
<method>REPORT</method>
<ruri>$calendarpath1:/</ruri>
<data>
<content-type>text/xml; charset=utf-8</content-type>
<filepath>Resource/CalDAV/timezones/2.xml</filepath>
</data>
<verify>
<callback>freeBusy</callback>
<arg>
<name>busy</name>
<value>$now.year.0:0401T143000Z/$now.year.0:0401T153000Z</value>
<value>$now.year.0:1210T153000Z/$now.year.0:1210T163000Z</value>
<value>$now.year.0:0402T150000Z/$now.year.0:0402T160000Z</value>
<value>$now.year.0:1211T140000Z/$now.year.0:1211T150000Z</value>
</arg>
</verify>
</request>
</test>
</test-suite>
<end/>
</caldavtest>
| {
"content_hash": "c744a39b0b3410a71f36be1d4f6c8e88",
"timestamp": "",
"source": "github",
"line_count": 172,
"max_line_length": 75,
"avg_line_length": 29.50581395348837,
"alnum_prop": 0.6599014778325123,
"repo_name": "fpiotrow/caldav-tester-packaging",
"id": "fe4cfd53ae9fbb6e38e4dfc4b49f3642f308e904",
"size": "5075",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "scripts/tests/CalDAV/timezones.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Python",
"bytes": "249685"
},
{
"name": "Shell",
"bytes": "6275"
}
],
"symlink_target": ""
} |
<?php
session_start();
$thispage = 'index';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>VOICE ☑</title>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="theme-color" content="#ffffff">
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel=stylesheet href="css/mystyles.css"/>
<link href="https://fonts.googleapis.com/css?family=Lora|Raleway|Source+Code+Pro" rel="stylesheet">
<link rel="apple-touch-icon" sizes="180x180" href="apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="favicon-32x32.png">
<link rel="icon" type="image/png" sizes="194x194" href="favicon-194x194.png">
<link rel="icon" type="image/png" sizes="192x192" href="android-chrome-192x192.png">
<link rel="icon" type="image/png" sizes="16x16" href="favicon-16x16.png">
<link rel="manifest" href="manifest.json">
<link rel="mask-icon" href="safari-pinned-tab.svg" color="#5bbad5">
<meta name="theme-color" content="#ffffff">
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<header>
<nav class="navbar navbar-inverse">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#navbarCollapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="/voice">VOICE</a>
</div>
<div class="collapse navbar-collapse" id="navbarCollapse">
<?php
include 'menu_left.php';
include 'menu_right.php';
?>
</div>
</div>
</nav>
<h1 class="sr-only">Home</h1>
</header>
<div class="container">
<section>
<div class="jumbotron">
<h1>Welcome to VOICE.</h1>
<p>Hi! New here? VOICE is where you can register to vote and participate in online voting. VOICE: making it easy to exercise your enfranchisement, and your civic duty.</p>
</div>
<div class="alert alert-info alert-dismissible" role="alert" id="logoutdiv" hidden>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span class="sr-only">Message:</span>You have been logged out.
</div>
<div class="alert alert-info alert-dismissible" role="alert" id="noaccess" hidden>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<span class="glyphicon glyphicon-exclamation-sign" aria-hidden="true"></span>
<span>You do not have access to that area.</span>
</div>
<div class="row">
<div class="col-md-4"><div class="well"><a href="vote.php"><h1 class="text-center"><span class="glyphicon glyphicon-ok"></span> Vote</h1></a></div></div>
<div class="col-md-4"><div class="well"><a href="register.php"><h1 class="text-center"><span class="glyphicon glyphicon-user"></span> Register</h1></a></div></div>
<div class="col-md-4"><div class="well"><a href="account.php"><h1 class="text-center"><span class="glyphicon glyphicon-wrench"></span> My Account</h1></a></div></div>
</div>
<div class="well well-sm">
<p class="text-center text-muted">What is VOICE? It is <strong>V</strong>ote-<strong>O</strong>nline <strong>I</strong>nteractive <strong>C</strong>ivic <strong>E</strong>nablement. It's <em>your</em> voice being heard!</p>
</div>
</section>
</div>
<nav id="pagefooter" class="navbar navbar-default navbar-fixed-bottom navbar-inverse">
<div class="container">
<div class="col-xs-12 text-center navbar-text">
<p class="text-muted">Copyright © 2017 <a href="mailto:little_charles1@columbusstate.edu">Charles Little</a>, All rights reserved.</p>
</div>
</div>
</nav>
<script src="js/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/purl.min.js"></script>
<script>
$(document).ready(function($) {
if ($.url().param('x')=='logout'){
$('#logoutdiv').show();
}
if ($.url().param('x')=='403'){
$('#noaccess').show();
}
});
</script>
</body>
</html>
| {
"content_hash": "72ccf10c490c1527f398af548748fc8f",
"timestamp": "",
"source": "github",
"line_count": 104,
"max_line_length": 224,
"avg_line_length": 46.57692307692308,
"alnum_prop": 0.6073492981007432,
"repo_name": "calittle/voice",
"id": "32bf255e068ddf58fa8d89dd9632a3798a75eecf",
"size": "4844",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "index.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3488"
},
{
"name": "JavaScript",
"bytes": "31028"
},
{
"name": "PHP",
"bytes": "220433"
},
{
"name": "PLpgSQL",
"bytes": "348470"
},
{
"name": "SQLPL",
"bytes": "44608"
}
],
"symlink_target": ""
} |
<?php
/**
* @see Zend_Gdata_Extension
*/
require_once 'Zend/Gdata/Extension.php';
/**
* @see Zend_Gdata_Geo
*/
require_once 'Zend/Gdata/Geo.php';
/**
* @see Zend_Gdata_Geo_Extension_GmlPos
*/
require_once 'Zend/Gdata/Geo/Extension/GmlPos.php';
/**
* Represents the gml:point element used by the Gdata Geo extensions.
*
* @category Zend
* @package Zend_Gdata
* @subpackage Geo
* @copyright Copyright (c) 2005-2014 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
*/
class Zend_Gdata_Geo_Extension_GmlPoint extends Zend_Gdata_Extension
{
protected $_rootNamespace = 'gml';
protected $_rootElement = 'Point';
/**
* The position represented by this GmlPoint
*
* @var Zend_Gdata_Geo_Extension_GmlPos
*/
protected $_pos = null;
/**
* Create a new instance.
*
* @param Zend_Gdata_Geo_Extension_GmlPos $pos (optional) Pos to which this
* object should be initialized.
*/
public function __construct($pos = null)
{
$this->registerAllNamespaces(Zend_Gdata_Geo::$namespaces);
parent::__construct();
$this->setPos($pos);
}
/**
* Retrieves a DOMElement which corresponds to this element and all
* child properties. This is used to build an entry back into a DOM
* and eventually XML text for application storage/persistence.
*
* @param DOMDocument $doc The DOMDocument used to construct DOMElements
* @return DOMElement The DOMElement representing this element and all
* child properties.
*/
public function getDOM($doc = null, $majorVersion = 1, $minorVersion = null)
{
$element = parent::getDOM($doc, $majorVersion, $minorVersion);
if ($this->_pos !== null) {
$element->appendChild($this->_pos->getDOM($element->ownerDocument));
}
return $element;
}
/**
* Creates individual Entry objects of the appropriate type and
* stores them as members of this entry based upon DOM data.
*
* @param DOMNode $child The DOMNode to process
*/
protected function takeChildFromDOM($child)
{
$absoluteNodeName = $child->namespaceURI . ':' . $child->localName;
switch ($absoluteNodeName) {
case $this->lookupNamespace('gml') . ':' . 'pos';
$pos = new Zend_Gdata_Geo_Extension_GmlPos();
$pos->transferFromDOM($child);
$this->_pos = $pos;
break;
}
}
/**
* Get the value for this element's pos attribute.
*
* @see setPos
* @return Zend_Gdata_Geo_Extension_GmlPos The requested attribute.
*/
public function getPos()
{
return $this->_pos;
}
/**
* Set the value for this element's distance attribute.
*
* @param Zend_Gdata_Geo_Extension_GmlPos $value The desired value for this attribute
* @return Zend_Gdata_Geo_Extension_GmlPoint Provides a fluent interface
*/
public function setPos($value)
{
$this->_pos = $value;
return $this;
}
}
| {
"content_hash": "7488f94f4e620a0d501427b8303453ea",
"timestamp": "",
"source": "github",
"line_count": 117,
"max_line_length": 89,
"avg_line_length": 28.196581196581196,
"alnum_prop": 0.5871476204910578,
"repo_name": "Harshad-Makwana/NEW-Facebook-Photos-Challenges",
"id": "f826b2986b7f2cf0620e588019cb4f41efc472c1",
"size": "4028",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libs/Zend/Gdata/Geo/Extension/GmlPoint.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "JavaScript",
"bytes": "94799"
},
{
"name": "PHP",
"bytes": "2803285"
}
],
"symlink_target": ""
} |
import json
import pandas as pd
import numpy as np
import glob
import os
from pyaxiom.netcdf.sensors import TimeSeries
# In[27]:
var = 'pwrsys'
buoys = {'ce02shsm':{'lon':-124.31, 'lat':44.64, 'depth':0.0},
'ce04ossm':{'lon':-124.31, 'lat':44.64, 'depth':0.0},
'ce07shsm':{'lon':-124.31, 'lat':44.64, 'depth':0.0},
'ce09ossm':{'lon':-124.31, 'lat':44.64, 'depth':0.0}
}
# pick the last deployment
deployment_index = -1
# In[28]:
global_attributes = {
'institution':'Oregon State University',
'title':'OOI CE02SHSM Pwrsys Data',
'summary':'OOI data from Coastal Endurance',
'creator_name':'Chris Wingard',
'creator_email':'cwingard@coas.oregonstate.edu',
'creator_url':'http://ceoas.oregonstate.edu/ooi'
}
# In[29]:
def json2df(infile):
with open(infile) as jf:
df = pd.DataFrame(json.load(jf))
return df
# In[31]:
ipath = '/sand/usgs/users/rsignell/data/ooi/endurance/cg_proc/'
odir = '/usgs/data2/notebook/data/nc'
for buoy in buoys.keys():
deployment_path = glob.glob(os.path.join(ipath,buoy,'D*'))[deployment_index]
deployment = deployment_path.split('/')[-1]
path = os.path.join(deployment_path,'buoy',var,'*.{}.json'.format(var))
ofile = '{}_{}_{}.nc'.format(buoy,var,deployment)
print(path)
df = pd.concat([json2df(file) for file in glob.glob(path)])
df['time'] = pd.to_datetime(df.time, unit='s')
df.index = df['time']
df['depth'] = buoys[buoy]['depth']
global_attributes['title']='OOI {} {} Data'.format(buoy,var)
ts = TimeSeries(output_directory=odir,
latitude=buoys[buoy]['lat'],
longitude=buoys[buoy]['lon'],
station_name=buoy,
global_attributes=global_attributes,
times=df.time.values.astype(np.int64) // 10**9,
verticals=df.depth.values,
output_filename=ofile,
vertical_positive='down'
)
df.columns.tolist();
# In[22]:
# In[2]:
ce02shsm/D00004/buoy/pwrsys/*.pwrsys.json'
# In[7]:
path, filename = os.path.split(path)
print(path,filename)
# In[4]:
# In[5]:
# ### Define the NetCDF global attributes
# In[7]:
global_attributes = {
'institution':'Oregon State University',
'title':'OOI CE02SHSM Pwrsys Data',
'summary':'OOI Pwrsys data from Coastal Endurance Oregon Shelf Surface Mooring',
'creator_name':'Chris Wingard',
'creator_email':'cwingard@coas.oregonstate.edu',
'creator_url':'http://ceoas.oregonstate.edu/ooi'
}
# ### Create initial file
# In[8]:
# ### Add data variables
# In[9]:
df.columns.tolist()
# In[10]:
for c in df.columns:
if c in ts._nc.variables:
print("Skipping '{}' (already in file)".format(c))
continue
if c in ['time', 'lat', 'lon', 'depth', 'cpm_date_time_string']:
print("Skipping axis '{}' (already in file)".format(c))
continue
print("Adding {}".format(c))
try:
ts.add_variable(c, df[c].values)
except:
print('skipping, hit object')
# In[ ]:
| {
"content_hash": "2fe6dbd118b3ee77fd720215817280ad",
"timestamp": "",
"source": "github",
"line_count": 148,
"max_line_length": 84,
"avg_line_length": 20.472972972972972,
"alnum_prop": 0.6102310231023103,
"repo_name": "rsignell-usgs/notebook",
"id": "429e8c5fdfe1742c9a418aff2fe65382c1f1a742",
"size": "3229",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "OOI/from_ooi_json-pwrsys-deployment-Copy1.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "13956"
},
{
"name": "Jupyter Notebook",
"bytes": "202646883"
},
{
"name": "Python",
"bytes": "1476735"
}
],
"symlink_target": ""
} |
package org.openkilda.wfm.topology.switchmanager.model.v2;
import org.openkilda.messaging.info.switches.v2.MisconfiguredInfo;
import org.openkilda.messaging.info.switches.v2.RuleInfoEntryV2;
import lombok.Value;
import java.util.List;
@Value
public class ValidateRulesResultV2 {
boolean asExpected;
List<RuleInfoEntryV2> missingRules;
List<RuleInfoEntryV2> properRules;
List<RuleInfoEntryV2> excessRules;
List<MisconfiguredInfo<RuleInfoEntryV2>> misconfiguredRules;
}
| {
"content_hash": "6343ddb1143ffaab619c44b087b51e06",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 66,
"avg_line_length": 26,
"alnum_prop": 0.805668016194332,
"repo_name": "telstra/open-kilda",
"id": "eb855b6377ba58307e4772dd611eadd07119e824",
"size": "1111",
"binary": false,
"copies": "1",
"ref": "refs/heads/develop",
"path": "src-java/swmanager-topology/swmanager-storm-topology/src/main/java/org/openkilda/wfm/topology/switchmanager/model/v2/ValidateRulesResultV2.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C++",
"bytes": "89798"
},
{
"name": "CMake",
"bytes": "4314"
},
{
"name": "CSS",
"bytes": "233390"
},
{
"name": "Dockerfile",
"bytes": "30541"
},
{
"name": "Groovy",
"bytes": "2234079"
},
{
"name": "HTML",
"bytes": "362166"
},
{
"name": "Java",
"bytes": "14631453"
},
{
"name": "JavaScript",
"bytes": "369015"
},
{
"name": "Jinja",
"bytes": "937"
},
{
"name": "Makefile",
"bytes": "20500"
},
{
"name": "Python",
"bytes": "367364"
},
{
"name": "Shell",
"bytes": "62664"
},
{
"name": "TypeScript",
"bytes": "867537"
}
],
"symlink_target": ""
} |
"""For checking health with the kubernetes API."""
from __future__ import division
from __future__ import unicode_literals
import os
from datetime import datetime
import requests
# standard location for gke containers
CACRT = str("/var/run/secrets/kubernetes.io/serviceaccount/ca.crt")
class KubeAPI(object):
"""Stores the automatically injected kube API token."""
def __init__(self):
self.base_url = KubeAPI._api_version()
@staticmethod
def _api_version():
"""Determines the available api version(s)."""
if not hasattr(KubeAPI, "base_url"):
port = int(os.environ.get("KUBERNETES_SERVICE_PORT", "443"))
url = "http{}://kubernetes:{}/api/".format(
"s" * int(port == 443),
port,
)
res = requests.get(url, headers=KubeAPI.headers(), verify=CACRT)
res.raise_for_status()
KubeAPI.base_url = url + res.json()["versions"][0]
return KubeAPI.base_url
@staticmethod
def headers():
"""Returns the default token content in a headers dict."""
token_file = "/var/run/secrets/kubernetes.io/serviceaccount/token"
if not hasattr(KubeAPI, "_token"):
with open(token_file, "r") as opentoken:
KubeAPI._token = opentoken.read().strip()
return {
"Authorization": "Bearer {}".format(KubeAPI._token)
}
def get(self, url=""):
"""Request a URL from the kube API, returns JSON loaded response."""
res = requests.get(
"{}/{}".format(self.base_url, url),
headers=KubeAPI.headers(),
verify=CACRT,
)
res.raise_for_status()
return res.json()
def all_services():
"""Returns a list of all services (unique pod names) in our cluster."""
services = []
if not os.path.isfile(CACRT):
return services # not running inside kube, no kube services
api = KubeAPI()
for pod in api.get("pods")["items"]:
if pod["metadata"]["namespace"] == "kube-system":
continue
try:
services.append(pod["metadata"]["generateName"][:-1])
except KeyError:
pass
return sorted(set(services))
def check_kube_health(service):
"""Checks the health of a service with the Kube API.
Args:
service: string service name to check
Returns:
dictionary with keys: ready, total, restarts, color
"""
api = KubeAPI()
ready = 0
total = 0
restarts = 0
color = "green"
for pod in api.get("pods")["items"]:
try:
pod_name = pod["metadata"]["generateName"][:-1]
except KeyError:
continue
if pod_name == service:
for container in pod["status"].get("containerStatuses", []):
restarts += container["restartCount"]
total += 1
ready += int(container["ready"])
pod_created = datetime.strptime(
pod["metadata"]["creationTimestamp"],
"%Y-%m-%dT%H:%M:%SZ",
)
days = max((datetime.utcnow() - pod_created).days, 1)
if ready != total:
color = "red"
elif restarts / days > ((days / 2) / days):
if color != "red": # red takes priority
color = "yellow"
return {
"ready": ready,
"total": total,
"restarts": restarts,
"color": color,
}
def kube_health(service):
"""Checks the kube health of the service, returns a result dict."""
res = check_kube_health(service)
return {
"label": "health",
"status": "{}/{} ({} restart{})".format(
res["ready"],
res["total"],
res["restarts"],
"s" * int(res["restarts"] != 1),
),
"color": res["color"] or ("green" if res["ready"] else "red"),
}
| {
"content_hash": "582c66b87707ee1771243c45efcd6a36",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 76,
"avg_line_length": 27.93661971830986,
"alnum_prop": 0.5384421477186792,
"repo_name": "ccpgames/kube-shields",
"id": "88a05e283e59b59dc9977303cb829fd79332c623",
"size": "3967",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "kube_shields/kubernetes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "1218"
},
{
"name": "Python",
"bytes": "22170"
}
],
"symlink_target": ""
} |
<?php
// SOAP_CLIENT_BASEDIR - folder that contains the PHP Toolkit and your WSDL
// $USERNAME - variable that contains your Salesforce.com username (must be in the form of an email)
// $PASSWORD - variable that contains your Salesforce.ocm password
define("SOAP_CLIENT_BASEDIR", "../soapclient");
$USERNAME = 'mrusso@salesforce.com';
$PASSWORD = "sa13sf0rc3";
require_once (SOAP_CLIENT_BASEDIR . '/SforcePartnerClient.php');
require_once (SOAP_CLIENT_BASEDIR . '/SforceHeaderOptions.php');
try {
$mySforceConnection = new SforcePartnerClient();
$mySoapClient = $mySforceConnection->createConnection(SOAP_CLIENT_BASEDIR . '/enterprise.wsdl.xml');
$mylogin = $mySforceConnection->login($USERNAME, $PASSWORD);
echo "***** Get Server Timestamp *****\n";
$response = $mySforceConnection->getServerTimestamp();
print_r($response);
} catch (Exception $e) {
print_r($e);
}
?>
| {
"content_hash": "c4f90edb82e78fb8550c9883c2bb8005",
"timestamp": "",
"source": "github",
"line_count": 25,
"max_line_length": 104,
"avg_line_length": 36.08,
"alnum_prop": 0.7117516629711752,
"repo_name": "miradnan/Force.com-PHP-Toolkit",
"id": "f26e08340d23a5fb542d29084951d6ee52d67a84",
"size": "902",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "tests/enterprise.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Batchfile",
"bytes": "6"
},
{
"name": "CSS",
"bytes": "19273"
},
{
"name": "HTML",
"bytes": "611524"
},
{
"name": "PHP",
"bytes": "302208"
}
],
"symlink_target": ""
} |
<?php
namespace Base\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Activity
*
* @ORM\Table(name="bonus")
* @ORM\Entity
*/
class Bonus extends Base\BaseEntity
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var \Base\Entity\Users
*
* @ORM\ManyToOne(targetEntity="Base\Entity\Users")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="user_id", referencedColumnName="id")
* })
*/
private $userId;
/**
* @var integer
*
* @ORM\Column(name="amount", type="integer", nullable=true)
*/
protected $amount;
/**
* @var integer
*
* @ORM\Column(name="type", type="integer", nullable=true)
*/
protected $type;
/**
* @var integer
*
* @ORM\Column(name="status", type="integer", nullable=true)
*/
protected $status;
/**
* @var \DateTime
*
* @ORM\Column(name="created", type="datetime", nullable=true)
*/
protected $created;
/**
* @var \DateTime
*
* @ORM\Column(name="updated", type="datetime", nullable=true)
*/
protected $updated;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set userId
*
* @param integer $userId
* @return Activity
*/
public function setUserId($userId) {
$this->userId = $userId;
return $this;
}
/**
* Get userId
*
* @return integer
*/
public function getUserId() {
return $this->userId;
}
/**
* Set amount
*
* @param integer $amount
* @return Activity
*/
public function setAmount($amount) {
$this->amount = $amount;
return $this;
}
/**
* Get amount
*
* @return integer
*/
public function getAmount() {
return $this->amount;
}
/**
* Set type
*
* @param integer $type
* @return Activity
*/
public function setType($type) {
$this->type = $type;
return $this;
}
/**
* Get type
*
* @return integer
*/
public function getType() {
return $this->type;
}
/**
* Set status
*
* @param integer $status
* @return Activity
*/
public function setStatus($status) {
$this->status = $status;
return $this;
}
/**
* Get status
*
* @return integer
*/
public function getStatus() {
return $this->status;
}
/**
* Set created
*
* @param \DateTime $created
* @return Activity
*/
public function setCreated($created) {
$this->created = $created;
return $this;
}
/**
* Get created
*
* @return \DateTime
*/
public function getCreated() {
return $this->created;
}
/**
* Set updated
*
* @param \DateTime $updated
* @return Activity
*/
public function setUpdated($updated) {
$this->updated = $updated;
return $this;
}
/**
* Get updated
*
* @return \DateTime
*/
public function getUpdated() {
return $this->updated;
}
} | {
"content_hash": "bb060224c51ef2e209424ae0176c8c8e",
"timestamp": "",
"source": "github",
"line_count": 203,
"max_line_length": 67,
"avg_line_length": 16.960591133004925,
"alnum_prop": 0.48620389195469066,
"repo_name": "Jhonnorton/vivekvtc",
"id": "887f47c3563df48b82d1c6d349251506ac8bdbb2",
"size": "3443",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/Base/src/Base/Entity/Bonus.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ActionScript",
"bytes": "70896"
},
{
"name": "CSS",
"bytes": "408725"
},
{
"name": "JavaScript",
"bytes": "990385"
},
{
"name": "PHP",
"bytes": "15771341"
},
{
"name": "Shell",
"bytes": "404"
}
],
"symlink_target": ""
} |
'use strict';
import 'vs/css!./media/runtimeExtensionsEditor';
import * as nls from 'vs/nls';
import * as os from 'os';
import product from 'vs/platform/node/product';
import URI from 'vs/base/common/uri';
import { EditorInput } from 'vs/workbench/common/editor';
import pkg from 'vs/platform/node/package';
import { TPromise } from 'vs/base/common/winjs.base';
import { Action, IAction } from 'vs/base/common/actions';
import { Builder, Dimension } from 'vs/base/browser/builder';
import { BaseEditor } from 'vs/workbench/browser/parts/editor/baseEditor';
import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry';
import { IInstantiationService, createDecorator } from 'vs/platform/instantiation/common/instantiation';
import { IExtensionsWorkbenchService, IExtension } from 'vs/workbench/parts/extensions/common/extensions';
import { IThemeService } from 'vs/platform/theme/common/themeService';
import { IWorkbenchEditorService } from 'vs/workbench/services/editor/common/editorService';
import { IExtensionService, IExtensionDescription, IExtensionsStatus, IExtensionHostProfile } from 'vs/platform/extensions/common/extensions';
import { IDelegate, IRenderer } from 'vs/base/browser/ui/list/list';
import { WorkbenchList } from 'vs/platform/list/browser/listService';
import { append, $, addClass, toggleClass } from 'vs/base/browser/dom';
import { ActionBar, Separator } from 'vs/base/browser/ui/actionbar/actionbar';
import { IMessageService, Severity } from 'vs/platform/message/common/message';
import { dispose, IDisposable } from 'vs/base/common/lifecycle';
import { RunOnceScheduler } from 'vs/base/common/async';
import { clipboard } from 'electron';
import { LocalExtensionType } from 'vs/platform/extensionManagement/common/extensionManagement';
import { IContextMenuService } from 'vs/platform/contextview/browser/contextView';
import { IWindowService } from 'vs/platform/windows/common/windows';
import { writeFile } from 'vs/base/node/pfs';
import { IEnvironmentService } from 'vs/platform/environment/common/environment';
import { memoize } from 'vs/base/common/decorators';
import { isFalsyOrEmpty } from 'vs/base/common/arrays';
import Event from 'vs/base/common/event';
import { DisableForWorkspaceAction, DisableGloballyAction } from 'vs/workbench/parts/extensions/browser/extensionsActions';
export const IExtensionHostProfileService = createDecorator<IExtensionHostProfileService>('extensionHostProfileService');
export const enum ProfileSessionState {
None = 0,
Starting = 1,
Running = 2,
Stopping = 3
}
export interface IExtensionHostProfileService {
_serviceBrand: any;
readonly onDidChangeState: Event<void>;
readonly onDidChangeLastProfile: Event<void>;
readonly state: ProfileSessionState;
readonly lastProfile: IExtensionHostProfile;
startProfiling(): void;
stopProfiling(): void;
clearLastProfile(): void;
}
interface IExtensionProfileInformation {
/**
* segment when the extension was running.
* 2*i = segment start time
* 2*i+1 = segment end time
*/
segments: number[];
/**
* total time when the extension was running.
* (sum of all segment lengths).
*/
totalTime: number;
}
interface IRuntimeExtension {
originalIndex: number;
description: IExtensionDescription;
marketplaceInfo: IExtension;
status: IExtensionsStatus;
profileInfo: IExtensionProfileInformation;
}
export class RuntimeExtensionsEditor extends BaseEditor {
static ID: string = 'workbench.editor.runtimeExtensions';
private _list: WorkbenchList<IRuntimeExtension>;
private _profileInfo: IExtensionHostProfile;
private _elements: IRuntimeExtension[];
private _extensionsDescriptions: IExtensionDescription[];
private _updateSoon: RunOnceScheduler;
constructor(
@ITelemetryService telemetryService: ITelemetryService,
@IThemeService themeService: IThemeService,
@IExtensionsWorkbenchService private readonly _extensionsWorkbenchService: IExtensionsWorkbenchService,
@IExtensionService private readonly _extensionService: IExtensionService,
@IMessageService private readonly _messageService: IMessageService,
@IContextMenuService private readonly _contextMenuService: IContextMenuService,
@IInstantiationService private readonly _instantiationService: IInstantiationService,
@IExtensionHostProfileService private readonly _extensionHostProfileService: IExtensionHostProfileService,
) {
super(RuntimeExtensionsEditor.ID, telemetryService, themeService);
this._list = null;
this._profileInfo = this._extensionHostProfileService.lastProfile;
this._register(this._extensionHostProfileService.onDidChangeLastProfile(() => {
this._profileInfo = this._extensionHostProfileService.lastProfile;
this._updateExtensions();
}));
this._elements = null;
this._extensionsDescriptions = [];
this._updateExtensions();
this._updateSoon = this._register(new RunOnceScheduler(() => this._updateExtensions(), 200));
this._extensionService.getExtensions().then((extensions) => {
// We only deal with extensions with source code!
this._extensionsDescriptions = extensions.filter((extension) => {
return !!extension.main;
});
this._updateExtensions();
});
this._register(this._extensionService.onDidChangeExtensionsStatus(() => this._updateSoon.schedule()));
}
private _updateExtensions(): void {
this._elements = this._resolveExtensions();
if (this._list) {
this._list.splice(0, this._list.length, this._elements);
}
}
private _resolveExtensions(): IRuntimeExtension[] {
let marketplaceMap: { [id: string]: IExtension; } = Object.create(null);
for (let extension of this._extensionsWorkbenchService.local) {
marketplaceMap[extension.id] = extension;
}
let statusMap = this._extensionService.getExtensionsStatus();
// group profile segments by extension
let segments: { [id: string]: number[]; } = Object.create(null);
if (this._profileInfo) {
let currentStartTime = this._profileInfo.startTime;
for (let i = 0, len = this._profileInfo.deltas.length; i < len; i++) {
const id = this._profileInfo.ids[i];
const delta = this._profileInfo.deltas[i];
let extensionSegments = segments[id];
if (!extensionSegments) {
extensionSegments = [];
segments[id] = extensionSegments;
}
extensionSegments.push(currentStartTime);
currentStartTime = currentStartTime + delta;
extensionSegments.push(currentStartTime);
}
}
let result: IRuntimeExtension[] = [];
for (let i = 0, len = this._extensionsDescriptions.length; i < len; i++) {
const extensionDescription = this._extensionsDescriptions[i];
let profileInfo: IExtensionProfileInformation = null;
if (this._profileInfo) {
let extensionSegments = segments[extensionDescription.id] || [];
let extensionTotalTime = 0;
for (let j = 0, lenJ = extensionSegments.length / 2; j < lenJ; j++) {
const startTime = extensionSegments[2 * j];
const endTime = extensionSegments[2 * j + 1];
extensionTotalTime += (endTime - startTime);
}
profileInfo = {
segments: extensionSegments,
totalTime: extensionTotalTime
};
}
result[i] = {
originalIndex: i,
description: extensionDescription,
marketplaceInfo: marketplaceMap[extensionDescription.id],
status: statusMap[extensionDescription.id],
profileInfo: profileInfo
};
}
result = result.filter((element) => element.status.activationTimes);
if (this._profileInfo) {
// sort descending by time spent in the profiler
result = result.sort((a, b) => {
if (a.profileInfo.totalTime === b.profileInfo.totalTime) {
return a.originalIndex - b.originalIndex;
}
return b.profileInfo.totalTime - a.profileInfo.totalTime;
});
}
return result;
}
protected createEditor(parent: Builder): void {
const container = parent.getHTMLElement();
addClass(container, 'runtime-extensions-editor');
const TEMPLATE_ID = 'runtimeExtensionElementTemplate';
const delegate = new class implements IDelegate<IRuntimeExtension>{
getHeight(element: IRuntimeExtension): number {
return 62;
}
getTemplateId(element: IRuntimeExtension): string {
return TEMPLATE_ID;
}
};
interface IRuntimeExtensionTemplateData {
root: HTMLElement;
element: HTMLElement;
name: HTMLElement;
activationTime: HTMLElement;
profileTime: HTMLElement;
profileTimeline: HTMLElement;
msgIcon: HTMLElement;
msgLabel: HTMLElement;
actionbar: ActionBar;
disposables: IDisposable[];
elementDisposables: IDisposable[];
}
const renderer: IRenderer<IRuntimeExtension, IRuntimeExtensionTemplateData> = {
templateId: TEMPLATE_ID,
renderTemplate: (root: HTMLElement): IRuntimeExtensionTemplateData => {
const element = append(root, $('.extension'));
const desc = append(element, $('div.desc'));
const name = append(desc, $('div.name'));
const msgContainer = append(desc, $('div.msg'));
const msgIcon = append(msgContainer, $('.'));
const msgLabel = append(msgContainer, $('span.msg-label'));
const timeContainer = append(element, $('.time'));
const activationTime = append(timeContainer, $('div.activation-time'));
const profileTime = append(timeContainer, $('div.profile-time'));
const profileTimeline = append(element, $('div.profile-timeline'));
const actionbar = new ActionBar(element, {
animated: false
});
actionbar.onDidRun(({ error }) => error && this._messageService.show(Severity.Error, error));
actionbar.push(new ReportExtensionIssueAction(), { icon: true, label: true });
const disposables = [actionbar];
return {
root,
element,
name,
actionbar,
activationTime,
profileTime,
profileTimeline,
msgIcon,
msgLabel,
disposables,
elementDisposables: []
};
},
renderElement: (element: IRuntimeExtension, index: number, data: IRuntimeExtensionTemplateData): void => {
data.elementDisposables = dispose(data.elementDisposables);
toggleClass(data.root, 'odd', index % 2 === 1);
data.name.textContent = element.marketplaceInfo ? element.marketplaceInfo.displayName : element.description.displayName;
const activationTimes = element.status.activationTimes;
let syncTime = activationTimes.codeLoadingTime + activationTimes.activateCallTime;
data.activationTime.textContent = activationTimes.startup ? `Startup Activation: ${syncTime}ms` : `Activation: ${syncTime}ms`;
data.actionbar.context = element;
toggleClass(data.actionbar.getContainer().getHTMLElement(), 'hidden', element.marketplaceInfo && element.marketplaceInfo.type === LocalExtensionType.User && (!element.description.repository || !element.description.repository.url));
let title: string;
if (activationTimes.activationEvent === '*') {
title = nls.localize('starActivation', "Activated on start-up");
} else if (/^workspaceContains:/.test(activationTimes.activationEvent)) {
let fileNameOrGlob = activationTimes.activationEvent.substr('workspaceContains:'.length);
if (fileNameOrGlob.indexOf('*') >= 0 || fileNameOrGlob.indexOf('?') >= 0) {
title = nls.localize('workspaceContainsGlobActivation', "Activated because a file matching {0} exists in your workspace", fileNameOrGlob);
} else {
title = nls.localize('workspaceContainsFileActivation', "Activated because file {0} exists in your workspace", fileNameOrGlob);
}
} else if (/^onLanguage:/.test(activationTimes.activationEvent)) {
let language = activationTimes.activationEvent.substr('onLanguage:'.length);
title = nls.localize('languageActivation', "Activated because you opened a {0} file", language);
} else {
title = nls.localize('workspaceGenericActivation', "Activated on {0}", activationTimes.activationEvent);
}
data.activationTime.title = title;
if (!isFalsyOrEmpty(element.status.runtimeErrors)) {
data.msgIcon.className = 'octicon octicon-bug';
data.msgLabel.textContent = nls.localize('errors', "{0} uncaught errors", element.status.runtimeErrors.length);
} else if (element.status.messages && element.status.messages.length > 0) {
data.msgIcon.className = 'octicon octicon-alert';
data.msgLabel.textContent = element.status.messages[0].message;
} else {
data.msgIcon.className = '';
data.msgLabel.textContent = '';
}
if (this._profileInfo) {
data.profileTime.textContent = `Profile: ${(element.profileInfo.totalTime / 1000).toFixed(2)}ms`;
const elementSegments = element.profileInfo.segments;
let inner = '<rect x="0" y="99" width="100" height="1" />';
for (let i = 0, len = elementSegments.length / 2; i < len; i++) {
const absoluteStart = elementSegments[2 * i];
const absoluteEnd = elementSegments[2 * i + 1];
const start = absoluteStart - this._profileInfo.startTime;
const end = absoluteEnd - this._profileInfo.startTime;
const absoluteDuration = this._profileInfo.endTime - this._profileInfo.startTime;
const xStart = start / absoluteDuration * 100;
const xEnd = end / absoluteDuration * 100;
inner += `<rect x="${xStart}" y="0" width="${xEnd - xStart}" height="100" />`;
}
let svg = `<svg class="profile-timeline-svg" preserveAspectRatio="none" height="16" viewBox="0 0 100 100">${inner}</svg>`;
data.profileTimeline.innerHTML = svg;
data.profileTimeline.style.display = 'inherit';
} else {
data.profileTime.textContent = '';
data.profileTimeline.innerHTML = '';
}
},
disposeTemplate: (data: IRuntimeExtensionTemplateData): void => {
data.disposables = dispose(data.disposables);
}
};
this._list = this._instantiationService.createInstance(WorkbenchList, container, delegate, [renderer], {
multipleSelectionSupport: false
}) as WorkbenchList<IRuntimeExtension>;
this._list.splice(0, this._list.length, this._elements);
this._list.onContextMenu((e) => {
const actions: IAction[] = [];
if (e.element.marketplaceInfo.type === LocalExtensionType.User) {
actions.push(this._instantiationService.createInstance(DisableForWorkspaceAction, DisableForWorkspaceAction.LABEL));
actions.push(this._instantiationService.createInstance(DisableGloballyAction, DisableGloballyAction.LABEL));
actions.forEach((a: DisableForWorkspaceAction | DisableGloballyAction) => a.extension = e.element.marketplaceInfo);
actions.push(new Separator());
}
actions.push(this.extensionHostProfileAction, this.saveExtensionHostProfileAction);
this._contextMenuService.showContextMenu({
getAnchor: () => e.anchor,
getActions: () => TPromise.as(actions)
});
});
}
public getActions(): IAction[] {
return [
this.saveExtensionHostProfileAction,
this.extensionHostProfileAction
];
}
@memoize
private get extensionHostProfileAction(): IAction {
return this._instantiationService.createInstance(ExtensionHostProfileAction, ExtensionHostProfileAction.ID, ExtensionHostProfileAction.LABEL_START);
}
@memoize
private get saveExtensionHostProfileAction(): IAction {
return this._instantiationService.createInstance(SaveExtensionHostProfileAction, SaveExtensionHostProfileAction.ID, SaveExtensionHostProfileAction.LABEL);
}
public layout(dimension: Dimension): void {
this._list.layout(dimension.height);
}
}
export class RuntimeExtensionsInput extends EditorInput {
static readonly ID = 'workbench.runtimeExtensions.input';
constructor() {
super();
}
getTypeId(): string {
return RuntimeExtensionsInput.ID;
}
getName(): string {
return nls.localize('extensionsInputName', "Running Extensions");
}
matches(other: any): boolean {
if (!(other instanceof RuntimeExtensionsInput)) {
return false;
}
return true;
}
resolve(refresh?: boolean): TPromise<any> {
return TPromise.as(null);
}
supportsSplitEditor(): boolean {
return false;
}
getResource(): URI {
return URI.from({
scheme: 'runtime-extensions',
path: 'default'
});
}
}
export class ShowRuntimeExtensionsAction extends Action {
static readonly ID = 'workbench.action.showRuntimeExtensions';
static LABEL = nls.localize('showRuntimeExtensions', "Show Running Extensions");
constructor(
id: string, label: string,
@IWorkbenchEditorService private readonly _editorService: IWorkbenchEditorService,
@IInstantiationService private readonly _instantiationService: IInstantiationService
) {
super(id, label);
}
public run(e?: any): TPromise<any> {
return this._editorService.openEditor(this._instantiationService.createInstance(RuntimeExtensionsInput), { revealIfOpened: true });
}
}
class ReportExtensionIssueAction extends Action {
static readonly ID = 'workbench.extensions.action.reportExtensionIssue';
static LABEL = nls.localize('reportExtensionIssue', "Report Issue");
constructor(
id: string = ReportExtensionIssueAction.ID, label: string = ReportExtensionIssueAction.LABEL
) {
super(id, label, 'extension-action report-issue');
}
run(extension: IRuntimeExtension): TPromise<any> {
clipboard.writeText('```json \n' + JSON.stringify(extension.status, null, '\t') + '\n```');
window.open(this.generateNewIssueUrl(extension));
return TPromise.as(null);
}
private generateNewIssueUrl(extension: IRuntimeExtension): string {
let baseUrl = extension.marketplaceInfo && extension.marketplaceInfo.type === LocalExtensionType.User && extension.description.repository ? extension.description.repository.url : undefined;
if (!!baseUrl) {
baseUrl = `${baseUrl.indexOf('.git') !== -1 ? baseUrl.substr(0, baseUrl.length - 4) : baseUrl}/issues/new/`;
} else {
baseUrl = product.reportIssueUrl;
}
const osVersion = `${os.type()} ${os.arch()} ${os.release()}`;
const queryStringPrefix = baseUrl.indexOf('?') === -1 ? '?' : '&';
const body = encodeURIComponent(
`- Extension Name: ${extension.description.name}
- Extension Version: ${extension.description.version}
- OS Version: ${osVersion}
- VSCode version: ${pkg.version}` + '\n\n We have written the needed data into your clipboard. Please paste:'
);
return `${baseUrl}${queryStringPrefix}body=${body}`;
}
}
class ExtensionHostProfileAction extends Action {
static readonly ID = 'workbench.extensions.action.extensionHostProfile';
static LABEL_START = nls.localize('extensionHostProfileStart', "Start Extension Host Profile");
static LABEL_STOP = nls.localize('extensionHostProfileStop', "Stop Extension Host Profile");
static STOP_CSS_CLASS = 'extension-host-profile-stop';
static START_CSS_CLASS = 'extension-host-profile-start';
constructor(
id: string = ExtensionHostProfileAction.ID, label: string = ExtensionHostProfileAction.LABEL_START,
@IExtensionHostProfileService private readonly _extensionHostProfileService: IExtensionHostProfileService,
) {
super(id, label, ExtensionHostProfileAction.START_CSS_CLASS);
this._extensionHostProfileService.onDidChangeState(() => this._update());
}
private _update(): void {
const state = this._extensionHostProfileService.state;
if (state === ProfileSessionState.Running) {
this.class = ExtensionHostProfileAction.STOP_CSS_CLASS;
this.label = ExtensionHostProfileAction.LABEL_STOP;
} else {
this.class = ExtensionHostProfileAction.START_CSS_CLASS;
this.label = ExtensionHostProfileAction.LABEL_START;
}
}
run(): TPromise<any> {
const state = this._extensionHostProfileService.state;
if (state === ProfileSessionState.Running) {
this._extensionHostProfileService.stopProfiling();
} else if (state === ProfileSessionState.None) {
this._extensionHostProfileService.startProfiling();
}
return TPromise.as(null);
}
}
class SaveExtensionHostProfileAction extends Action {
static LABEL = nls.localize('saveExtensionHostProfile', "Save Extension Host Profile");
static readonly ID = 'workbench.extensions.action.saveExtensionHostProfile';
constructor(
id: string = SaveExtensionHostProfileAction.ID, label: string = SaveExtensionHostProfileAction.LABEL,
@IWindowService private readonly _windowService: IWindowService,
@IEnvironmentService private readonly _environmentService: IEnvironmentService,
@IExtensionHostProfileService private readonly _extensionHostProfileService: IExtensionHostProfileService,
) {
super(id, label, 'save-extension-host-profile', false);
this.enabled = (this._extensionHostProfileService.lastProfile !== null);
this._extensionHostProfileService.onDidChangeLastProfile(() => {
this.enabled = (this._extensionHostProfileService.lastProfile !== null);
});
}
async run(): TPromise<any> {
let picked = await this._windowService.showSaveDialog({
title: 'Save Extension Host Profile',
buttonLabel: 'Save',
defaultPath: `CPU-${new Date().toISOString().replace(/[\-:]/g, '')}.cpuprofile`,
filters: [{
name: 'CPU Profiles',
extensions: ['cpuprofile', 'txt']
}]
});
if (!picked) {
return;
}
const profileInfo = this._extensionHostProfileService.lastProfile;
let dataToWrite: object = profileInfo.data;
if (this._environmentService.isBuilt) {
const profiler = await import('v8-inspect-profiler');
// when running from a not-development-build we remove
// absolute filenames because we don't want to reveal anything
// about users. We also append the `.txt` suffix to make it
// easier to attach these files to GH issues
let tmp = profiler.rewriteAbsolutePaths({ profile: dataToWrite }, 'piiRemoved');
dataToWrite = tmp.profile;
picked = picked + '.txt';
}
return writeFile(picked, JSON.stringify(profileInfo.data, null, '\t'));
}
}
| {
"content_hash": "ec7988f8b22294bcc36dbf51bc2a4de2",
"timestamp": "",
"source": "github",
"line_count": 594,
"max_line_length": 235,
"avg_line_length": 36.387205387205384,
"alnum_prop": 0.7314703432960118,
"repo_name": "cra0zy/VSCode",
"id": "e6256d7aeaea8d751ee3cc5f221f804774146ff5",
"size": "21965",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "src/vs/workbench/parts/extensions/electron-browser/runtimeExtensionsEditor.ts",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "25581"
}
],
"symlink_target": ""
} |
CREATE SCHEMA USER_REALM_DB;
USE USER_REALM_DB;
-- Tables
CREATE TABLE Users
(
username VARCHAR(255) PRIMARY KEY,
passwd VARCHAR(255)
);
CREATE TABLE UserRoles
(
username VARCHAR(255),
role VARCHAR(32)
);
-- Default data
INSERT INTO Users (`username`, `passwd`) VALUES ('admin', 'jGl25bVBBBW96Qi9Te4V37Fnqchz/Eu4qB9vKrRIqRg=');
INSERT INTO UserRoles (`username`, `role`) VALUES ('admin', 'admin');
INSERT INTO UserRoles (`username`, `role`) VALUES ('admin', 'customer');
select *
from Users u
inner join UserRoles ur on u.username = ur.username; | {
"content_hash": "173d8589a8a8be5b509b3c81af62027a",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 106,
"avg_line_length": 21.346153846153847,
"alnum_prop": 0.7225225225225225,
"repo_name": "wesleyegberto/java-webservices",
"id": "98f74abfb9b18d2e9fc26294960952189d72fa07",
"size": "555",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rest-ws-basic-security/Script.sql",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "44907"
}
],
"symlink_target": ""
} |
<?php // phpcs:disable Generic.PHP.DiscourageGoto.Found
declare(strict_types=1);
namespace Mwop\Contact\Handler;
use Mezzio\Helper\UrlHelper;
use Mezzio\Template\TemplateRendererInterface;
use Psr\Container\ContainerInterface;
use Psr\EventDispatcher\EventDispatcherInterface;
class ProcessContactFormHandlerFactory
{
public function __invoke(ContainerInterface $container): ProcessContactFormHandler
{
return new ProcessContactFormHandler(
dispatcher: $container->get(EventDispatcherInterface::class),
template: $container->get(TemplateRendererInterface::class),
urlHelper: $container->get(UrlHelper::class),
config: $container->get('config-contact'),
);
}
}
| {
"content_hash": "0edadcbb91417682924cdd6a4939b383",
"timestamp": "",
"source": "github",
"line_count": 24,
"max_line_length": 86,
"avg_line_length": 30.875,
"alnum_prop": 0.7341430499325237,
"repo_name": "weierophinney/mwop.net",
"id": "f8ef59f5511ae2ac8e93bd766c2bc61906c1e6aa",
"size": "741",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/Contact/Handler/ProcessContactFormHandlerFactory.php",
"mode": "33188",
"license": "bsd-2-clause",
"language": [
{
"name": "CSS",
"bytes": "2756"
},
{
"name": "Dockerfile",
"bytes": "3296"
},
{
"name": "HTML",
"bytes": "134026"
},
{
"name": "JavaScript",
"bytes": "2783"
},
{
"name": "Makefile",
"bytes": "3293"
},
{
"name": "PHP",
"bytes": "401163"
},
{
"name": "Shell",
"bytes": "5059"
}
],
"symlink_target": ""
} |
package org.elasticsearch.painless.node;
import org.elasticsearch.painless.ClassWriter;
import org.elasticsearch.painless.CompilerSettings;
import org.elasticsearch.painless.Globals;
import org.elasticsearch.painless.Locals;
import org.elasticsearch.painless.Locals.Variable;
import org.elasticsearch.painless.Location;
import org.elasticsearch.painless.MethodWriter;
import org.elasticsearch.painless.ScriptRoot;
import org.objectweb.asm.Label;
import org.objectweb.asm.Opcodes;
import java.util.Objects;
import java.util.Set;
/**
* Represents a catch block as part of a try-catch block.
*/
public final class SCatch extends AStatement {
private final String type;
private final String name;
private final SBlock block;
private Variable variable = null;
Label begin = null;
Label end = null;
Label exception = null;
public SCatch(Location location, String type, String name, SBlock block) {
super(location);
this.type = Objects.requireNonNull(type);
this.name = Objects.requireNonNull(name);
this.block = block;
}
@Override
void storeSettings(CompilerSettings settings) {
if (block != null) {
block.storeSettings(settings);
}
}
@Override
void extractVariables(Set<String> variables) {
variables.add(name);
if (block != null) {
block.extractVariables(variables);
}
}
@Override
void analyze(ScriptRoot scriptRoot, Locals locals) {
Class<?> clazz = scriptRoot.getPainlessLookup().canonicalTypeNameToType(this.type);
if (clazz == null) {
throw createError(new IllegalArgumentException("Not a type [" + this.type + "]."));
}
if (!Exception.class.isAssignableFrom(clazz)) {
throw createError(new ClassCastException("Not an exception type [" + this.type + "]."));
}
variable = locals.addVariable(location, clazz, name, true);
if (block != null) {
block.lastSource = lastSource;
block.inLoop = inLoop;
block.lastLoop = lastLoop;
block.analyze(scriptRoot, locals);
methodEscape = block.methodEscape;
loopEscape = block.loopEscape;
allEscape = block.allEscape;
anyContinue = block.anyContinue;
anyBreak = block.anyBreak;
statementCount = block.statementCount;
}
}
@Override
void write(ClassWriter classWriter, MethodWriter methodWriter, Globals globals) {
methodWriter.writeStatementOffset(location);
Label jump = new Label();
methodWriter.mark(jump);
methodWriter.visitVarInsn(MethodWriter.getType(variable.clazz).getOpcode(Opcodes.ISTORE), variable.getSlot());
if (block != null) {
block.continu = continu;
block.brake = brake;
block.write(classWriter, methodWriter, globals);
}
methodWriter.visitTryCatchBlock(begin, end, jump, MethodWriter.getType(variable.clazz).getInternalName());
if (exception != null && (block == null || !block.allEscape)) {
methodWriter.goTo(exception);
}
}
@Override
public String toString() {
return singleLineToString(type, name, block);
}
}
| {
"content_hash": "8162cdf3021b0be133c939451be10364",
"timestamp": "",
"source": "github",
"line_count": 113,
"max_line_length": 118,
"avg_line_length": 29.38053097345133,
"alnum_prop": 0.6493975903614457,
"repo_name": "coding0011/elasticsearch",
"id": "04842110e55ed060e14423edefadbfa64b3ffe27",
"size": "4108",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/lang-painless/src/main/java/org/elasticsearch/painless/node/SCatch.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ANTLR",
"bytes": "11081"
},
{
"name": "Batchfile",
"bytes": "18064"
},
{
"name": "Emacs Lisp",
"bytes": "3341"
},
{
"name": "FreeMarker",
"bytes": "45"
},
{
"name": "Groovy",
"bytes": "312193"
},
{
"name": "HTML",
"bytes": "5519"
},
{
"name": "Java",
"bytes": "41505710"
},
{
"name": "Perl",
"bytes": "7271"
},
{
"name": "Python",
"bytes": "55163"
},
{
"name": "Shell",
"bytes": "119286"
}
],
"symlink_target": ""
} |
<?php
namespace App\Modules\Nucleo\Models\Protheus;
use App\Shared\Models\ModelBase;
class ProdutosGrupos extends ModelBase {
public $sbmGrupo;
public $sbmDesc;
public $sbmxFlag;
public $sbmSdel;
public function initialize() {
parent::initialize();
$this->setSchema('PRODUCAO_9ZGXI5');
$this->setConnectionService('protheusDb');
$this->setReadConnectionService('protheusDb');
$this->hasMany('sbmGrupo', __NAMESPACE__ . '\ProdutosDescricao', 'sb1Grupo', ['alias' => 'ProdutosDescricao',]);
}
public function getSource() {
return 'SBM010';
}
public static function columnMap() {
return [
'BM_GRUPO' => 'sbmGrupo',
'BM_DESC' => 'sbmDesc',
'BM_XFLAG' => 'sbmxFlag',
'D_E_L_E_T_' => 'sbmSdel',
];
}
}
| {
"content_hash": "a66874313ab60cdf35a0f90edd17e9f3",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 120,
"avg_line_length": 21.525,
"alnum_prop": 0.5772357723577236,
"repo_name": "denners777/API-Phalcon",
"id": "2e03a5db90a53d07563c32ee1dd58e4d961bbfc9",
"size": "1062",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/modules/nucleo/models/Protheus/ProdutosGrupos.php",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "24713"
},
{
"name": "CSS",
"bytes": "779260"
},
{
"name": "HTML",
"bytes": "123"
},
{
"name": "JavaScript",
"bytes": "47002"
},
{
"name": "PHP",
"bytes": "1227700"
},
{
"name": "Volt",
"bytes": "170583"
}
],
"symlink_target": ""
} |
<header>
<ul class="nodot">
<li class="allcaps bolded"><a href="//zro617.github.io">Home</a></li>
<li class="allcaps"><a href="//zro617.github.io/aboutme.html">About Me</a></li>
<li class="allcaps"><a href="//zro617.github.io/index.html">Placeholder1</a></li>
<li class="allcaps"><a href="//zro617.github.io/index.html">Placeholder2</a></li>
<li class="allcaps"><a href="//zro617.github.io/index.html">Placeholder3</a></li>
<li class="allcaps"><a href="//zro617.github.io/index.html">Placeholder4</a></li>
</ul>
</header>
| {
"content_hash": "26000ee095af666f95ef64a14937856a",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 81,
"avg_line_length": 52.2,
"alnum_prop": 0.6781609195402298,
"repo_name": "Zro617/zro617.github.io",
"id": "f10a8b59fa4b5589c722c2466605ed504975639c",
"size": "522",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "templates/header.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "8909"
},
{
"name": "HTML",
"bytes": "69348"
},
{
"name": "JavaScript",
"bytes": "97892"
}
],
"symlink_target": ""
} |
package ciris
import com.comcast.ip4s.Host
import com.comcast.ip4s.Port
import org.http4s.Uri
package object http4s {
implicit final val hostConfigDecoder: ConfigDecoder[String, Host] =
ConfigDecoder[String].mapOption("Host")(Host.fromString)
implicit final val portConfigDecoder: ConfigDecoder[String, Port] =
ConfigDecoder[String].mapOption("Port")(Port.fromString)
implicit final val uriConfigDecoder: ConfigDecoder[String, Uri] =
ConfigDecoder[String].mapOption("Uri")(Uri.fromString(_).toOption)
}
| {
"content_hash": "8ebfe9e92999ac553054c6887c0e1748",
"timestamp": "",
"source": "github",
"line_count": 18,
"max_line_length": 70,
"avg_line_length": 29.27777777777778,
"alnum_prop": 0.7722960151802657,
"repo_name": "vlovgr/ciris",
"id": "ab863eeb8e28a3ab1b5450a83136c0f0fcb1ffcd",
"size": "607",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "modules/http4s/shared/src/main/scala/ciris/http4s/http4s.scala",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "923"
},
{
"name": "JavaScript",
"bytes": "6232"
},
{
"name": "Scala",
"bytes": "189888"
}
],
"symlink_target": ""
} |
class PatternsWindow : public Skeleton, public Palette {
public:
PatternsWindow(EditorGUI *screen, nanogui::Theme *theme);
void setVisible(bool which) { window->setVisible(which); }
private:
EditorGUI *gui;
};
#endif
| {
"content_hash": "0feb5e5cb3734f4285bcd45b7f90cd53",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 59,
"avg_line_length": 22.2,
"alnum_prop": 0.7477477477477478,
"repo_name": "latproc/humid",
"id": "d8f3d6614665c586d2dbf304da2485fc8fbcf496",
"size": "679",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/patternswindow.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C",
"bytes": "247"
},
{
"name": "C++",
"bytes": "607337"
},
{
"name": "CMake",
"bytes": "39993"
},
{
"name": "Makefile",
"bytes": "854"
}
],
"symlink_target": ""
} |
package org.camunda.bpm.engine.cdi.test.impl.beans;
import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import org.camunda.bpm.engine.cdi.annotation.CompleteTask;
import org.camunda.bpm.engine.cdi.annotation.ProcessVariable;
import org.camunda.bpm.engine.cdi.annotation.ProcessVariableLocalTyped;
import org.camunda.bpm.engine.cdi.annotation.ProcessVariableTyped;
import org.camunda.bpm.engine.cdi.annotation.StartProcess;
import org.camunda.bpm.engine.variable.Variables;
import org.camunda.bpm.engine.variable.value.StringValue;
import org.camunda.bpm.engine.variable.value.TypedValue;
/**
*
* @author Daniel Meyer
*/
@Dependent
public class DeclarativeProcessController {
@ProcessVariable
String name; // this is going to be set as a process variable
@ProcessVariableTyped
String untypedName;
@ProcessVariableTyped
StringValue typedName;
@Inject
@ProcessVariableTyped
TypedValue injectedValue;
@Inject
@ProcessVariableLocalTyped
TypedValue injectedLocalValue;
@StartProcess("keyOfTheProcess")
public void startProcessByKey() {
name = "camunda";
untypedName = "untypedName";
typedName = Variables.stringValue("typedName");
}
@CompleteTask(endConversation = false)
public void completeTask() {
}
@CompleteTask(endConversation = true)
public void completeTaskEndConversation() {
}
public TypedValue getInjectedValue() {
return injectedValue;
}
public TypedValue getInjectedLocalValue() {
return injectedLocalValue;
}
}
| {
"content_hash": "1c9f7cbe54b370434496bf45f24cd2cf",
"timestamp": "",
"source": "github",
"line_count": 63,
"max_line_length": 71,
"avg_line_length": 24.22222222222222,
"alnum_prop": 0.7765399737876802,
"repo_name": "langfr/camunda-bpm-platform",
"id": "f65b5872f6167aa3a9c8af5fd1c6fd646e9deff1",
"size": "2333",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "engine-cdi/core/src/test/java/org/camunda/bpm/engine/cdi/test/impl/beans/DeclarativeProcessController.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "8608"
},
{
"name": "CSS",
"bytes": "5486"
},
{
"name": "Fluent",
"bytes": "3111"
},
{
"name": "FreeMarker",
"bytes": "1439225"
},
{
"name": "Groovy",
"bytes": "1904"
},
{
"name": "HTML",
"bytes": "961289"
},
{
"name": "Java",
"bytes": "44041849"
},
{
"name": "JavaScript",
"bytes": "3063544"
},
{
"name": "Less",
"bytes": "154956"
},
{
"name": "Python",
"bytes": "192"
},
{
"name": "Ruby",
"bytes": "60"
},
{
"name": "SQLPL",
"bytes": "44180"
},
{
"name": "Shell",
"bytes": "11634"
}
],
"symlink_target": ""
} |
package za.org.grassroot.services.group;
import com.google.common.base.Stopwatch;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.thymeleaf.util.StringUtils;
import za.org.grassroot.core.domain.ActionLog;
import za.org.grassroot.core.domain.GroupRole;
import za.org.grassroot.core.domain.Permission;
import za.org.grassroot.core.domain.User;
import za.org.grassroot.core.domain.campaign.CampaignLog;
import za.org.grassroot.core.domain.group.Group;
import za.org.grassroot.core.domain.group.GroupJoinMethod;
import za.org.grassroot.core.domain.group.GroupLog;
import za.org.grassroot.core.domain.group.JoinDateCondition;
import za.org.grassroot.core.domain.group.Membership;
import za.org.grassroot.core.dto.group.GroupFullDTO;
import za.org.grassroot.core.dto.group.GroupLogDTO;
import za.org.grassroot.core.dto.group.GroupMembersDTO;
import za.org.grassroot.core.dto.group.GroupMinimalDTO;
import za.org.grassroot.core.dto.group.GroupRefDTO;
import za.org.grassroot.core.dto.group.GroupTimeChangedDTO;
import za.org.grassroot.core.dto.group.GroupWebDTO;
import za.org.grassroot.core.dto.group.MembershipRecordDTO;
import za.org.grassroot.core.dto.membership.MembershipDTO;
import za.org.grassroot.core.dto.membership.MembershipFullDTO;
import za.org.grassroot.core.enums.CampaignLogType;
import za.org.grassroot.core.enums.Province;
import za.org.grassroot.core.repository.CampaignLogRepository;
import za.org.grassroot.core.repository.GroupLogRepository;
import za.org.grassroot.core.repository.GroupRepository;
import za.org.grassroot.core.repository.MembershipRepository;
import za.org.grassroot.core.repository.UserRepository;
import za.org.grassroot.core.specifications.GroupLogSpecifications;
import za.org.grassroot.core.specifications.GroupSpecifications;
import za.org.grassroot.core.specifications.MembershipSpecifications;
import za.org.grassroot.services.PermissionBroker;
import za.org.grassroot.services.exception.MemberLacksPermissionException;
import za.org.grassroot.services.util.FullTextSearchUtils;
import za.org.grassroot.services.util.LogsAndNotificationsBroker;
import java.time.Instant;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;
import static za.org.grassroot.core.specifications.GroupSpecifications.hasParent;
import static za.org.grassroot.core.specifications.GroupSpecifications.isActive;
/**
* Primary class for new style group feching, watch performance very closely (e.g., on size of memberships)
*/
@Service @Slf4j
public class GroupFetchBrokerImpl implements GroupFetchBroker {
// todo: make configurable
private static final int MAX_DTO_MEMBERS = 100;
private final UserRepository userRepository;
private final GroupRepository groupRepository;
private final GroupLogRepository groupLogRepository;
private final MembershipRepository membershipRepository;
private final CampaignLogRepository campaignLogRepository;
private final PermissionBroker permissionBroker;
private final LogsAndNotificationsBroker logsBroker;
@Autowired
public GroupFetchBrokerImpl(UserRepository userRepository, GroupRepository groupRepository,
GroupLogRepository groupLogRepository, MembershipRepository membershipRepository,
CampaignLogRepository campaignLogRepository, LogsAndNotificationsBroker logsBroker,
PermissionBroker permissionBroker) {
this.userRepository = userRepository;
this.groupRepository = groupRepository;
this.groupLogRepository = groupLogRepository;
this.membershipRepository = membershipRepository;
this.campaignLogRepository = campaignLogRepository;
this.permissionBroker = permissionBroker;
this.logsBroker = logsBroker;
}
@Override
@Transactional(readOnly = true)
public Set<GroupTimeChangedDTO> findNewlyChangedGroups(String userUid, Map<String, Long> excludedGroupsByTimeChanged) {
Objects.requireNonNull(excludedGroupsByTimeChanged);
User user = userRepository.findOneByUid(userUid);
Specification<Group> specifications = Specification
.where(GroupSpecifications.isActive())
.and(GroupSpecifications.userIsMember(user));
final Set<String> excludedGroupUids = excludedGroupsByTimeChanged.keySet();
if (!excludedGroupsByTimeChanged.isEmpty()) {
specifications = specifications.and(
Specification.not(GroupSpecifications.uidIn(excludedGroupUids)));
}
Set<String> newGroupUids = groupRepository.findAll(specifications)
.stream()
.map(Group::getUid)
.collect(Collectors.toSet());
Set<String> uidsToLookUp = new HashSet<>(excludedGroupUids);
uidsToLookUp.addAll(newGroupUids);
final Set<Group> groups = this.groupRepository.findByUidIn(uidsToLookUp);
final List<GroupTimeChangedDTO> groupTimeChangedDTOS = groups.stream()
.map(group -> new GroupTimeChangedDTO(group, membershipRepository))
.collect(Collectors.toList());
return groupTimeChangedDTOS.stream()
.filter(gl -> {
Instant storedLastChange = excludedGroupsByTimeChanged.containsKey(gl.getGroupUid()) ?
Instant.ofEpochMilli(excludedGroupsByTimeChanged.get(gl.getGroupUid())) : Instant.MIN;
return storedLastChange.isBefore(gl.getLastGroupChange()); // keep eye out for microsecond differences...
})
.collect(Collectors.toSet());
}
@Override
@Transactional(readOnly = true)
public Set<GroupMinimalDTO> fetchGroupNamesUidsOnly(String userUid, Set<String> groupUids) {
if (groupUids == null || groupUids.isEmpty()) {
return new HashSet<>();
}
final User user = userRepository.findOneByUid(userUid);
return user.getMemberships().stream()
.filter(membership -> groupUids.contains(membership.getGroup().getUid()))
.map(membership -> new GroupMinimalDTO(membership.getGroup(), membership, this.membershipRepository))
.collect(Collectors.toSet());
}
@Override
@Transactional(readOnly = true)
public GroupFullDTO fetchGroupFullInfo(String userUid, String groupUid, boolean includeAllMembers, boolean includeAllSubgroups, boolean includeMemberHistory) {
Stopwatch stopwatch = Stopwatch.createStarted();
final User user = userRepository.findOneByUid(userUid);
final Group group = groupRepository.findOneByUid(groupUid);
log.debug("fetching heavy group, group uid = {}, user = {}", groupUid, user.getName());
final Membership membership = user.getMembership(group);
if (membership == null) {
log.error("Error! Non existent group or membership passed to query: group UID: {}", groupUid);
return null;
}
final GroupFullDTO groupFullDTO = new GroupFullDTO(group, membership, this.membershipRepository);
final boolean hasMemberDetailsPerm = permissionBroker.isGroupPermissionAvailable(user, group, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
if (includeAllMembers && hasMemberDetailsPerm) {
final Pageable page = PageRequest.of(0, MAX_DTO_MEMBERS, Sort.Direction.DESC, "joinTime");
final Page<Membership> membershipPage = membershipRepository.findByGroupUid(group.getUid(), page);
final List<Membership> memberships = membershipPage.getContent();
final Set<MembershipDTO> membershipDTOS = memberships.stream().map(MembershipDTO::new).collect(Collectors.toSet());
groupFullDTO.setMembers(membershipDTOS);
}
if (includeMemberHistory && hasMemberDetailsPerm) {
final Instant sinceInstant = Instant.now().minus(180L, ChronoUnit.DAYS);
final List<MembershipRecordDTO> membershipRecordDTOS = fetchRecentMembershipChanges(user.getUid(), group.getUid(), sinceInstant);
groupFullDTO.setMemberHistory(membershipRecordDTOS);
}
if (includeAllSubgroups) {
final List<Group> subgroups = groupRepository.findAll(Specification.where(hasParent(group)).and(isActive()));
final List<GroupMembersDTO> groupMembersDTOS = subgroups.stream()
.map(g -> new GroupMembersDTO(g, membershipRepository))
.collect(Collectors.toList());
groupFullDTO.setSubGroups(groupMembersDTOS);
}
if (hasMemberDetailsPerm) {
long groupLogCount = groupLogRepository.count(GroupLogSpecifications.forInboundMessages(group, group.getCreatedDateTime(), Instant.now(), null));
groupFullDTO.setHasInboundMessages(groupLogCount > 0);
}
log.info("heavy group info fetch, for group {}, members: {}, subgroups: {}, m history: {}, took {} msecs",
group.getName(), includeAllMembers, includeAllSubgroups, includeMemberHistory, stopwatch.elapsed(TimeUnit.MILLISECONDS));
return groupFullDTO;
}
@Override
@Transactional(readOnly = true)
public GroupFullDTO fetchSubGroupDetails(String userUid, String parentGroupUid, String childGroupUid) {
final User user = userRepository.findOneByUid(userUid);
final Membership parentGroupMembership = user.getMemberships().stream()
.filter(membership -> membership.getGroup().getUid().equals(parentGroupUid))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("No membership group under UID " + parentGroupUid + " for user " + user));
final Group parentGroup = parentGroupMembership.getGroup();
final Group childGroup = groupRepository.findOneByUid(childGroupUid);
if (!parentGroup.equals(childGroup.getParent())) {
throw new IllegalArgumentException("Error! Parent/child mismatch");
}
if (permissionBroker.isGroupPermissionAvailable(user, parentGroup, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS) ||
permissionBroker.isGroupPermissionAvailable(user, childGroup, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS)) {
final Membership membership = user.getMembershipOptional(childGroup).orElse(parentGroupMembership);
return new GroupFullDTO(childGroup, membership, this.membershipRepository);
} else {
throw new MemberLacksPermissionException(Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
}
}
@Override
@Transactional(readOnly = true)
public List<MembershipRecordDTO> fetchRecentMembershipChanges(String userUid, String groupUid, Instant fromDate) {
Group group = groupRepository.findOneByUid(groupUid);
User user = userRepository.findOneByUid(userUid);
try {
permissionBroker.validateGroupPermission(user, group, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
} catch (AccessDeniedException e) {
throw new MemberLacksPermissionException(Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
}
List<GroupLog> groupLogs = groupLogRepository.findAll(
GroupLogSpecifications.memberChangeRecords(group, fromDate),
new Sort(Sort.Direction.DESC, "createdDateTime"));
// a little bit circuitous, but doing this to avoid possibly hundreds of separate calls
// to group.getMembership (triggering single SQL calls) -- and in any case, keep profiling
final Set<User> targetUsers = groupLogs.stream()
.filter(GroupLog::hasTargetUser)
.map(GroupLog::getTargetUser)
.collect(Collectors.toSet());
final List<Membership> memberships = membershipRepository.findByGroupAndUserIn(group, targetUsers);
Map<Long, Membership> membershipMap = memberships.stream()
.collect(Collectors.toMap(m -> m.getUser().getId(), Function.identity()));
return groupLogs.stream()
.filter(log -> log.getUser() != null && log.getTargetUser() != null)
.map(log -> new MembershipRecordDTO(membershipMap.get(log.getTargetUser().getId()), log))
.sorted(Comparator.comparing(MembershipRecordDTO::getChangeDateTimeMillis, Comparator.reverseOrder()))
.collect(Collectors.toList());
}
@Override
@Transactional
public Page<GroupLogDTO> getInboundMessageLogs(User user, Group group, Instant from, Instant to, String keyword, Pageable pageable) {
permissionBroker.validateGroupPermission(user, group, Permission.GROUP_PERMISSION_UPDATE_GROUP_DETAILS);
Page<GroupLog> page = groupLogRepository.findAll(Specification.where(GroupLogSpecifications.forInboundMessages(group, from, to, keyword)), pageable);
return page.map(GroupLogDTO::new);
}
@Override
@Transactional
public List<GroupLogDTO> getInboundMessagesForExport(User user, Group group, Instant from, Instant to, String keyword) {
permissionBroker.validateGroupPermission(user, group, Permission.GROUP_PERMISSION_UPDATE_GROUP_DETAILS);
List<GroupLog> list = groupLogRepository.findAll(Specification.where(GroupLogSpecifications.forInboundMessages(group, from, to, keyword)));
return list.stream().map(GroupLogDTO::new).collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public List<GroupWebDTO> fetchGroupWebInfo(String userUid, boolean includeSubgroups) {
User user = userRepository.findOneByUid(userUid);
List<Group> groups = groupRepository.findByMembershipsUserAndActiveTrueAndParentIsNull(user);
List<GroupWebDTO> dtos = groups.stream()
.map(gr -> {
final Membership membership = membershipRepository.findByGroupAndUser(gr, user);
List<GroupRefDTO> subGroups = includeSubgroups ? getSubgroups(gr) : Collections.emptyList();
return new GroupWebDTO(gr, membership, subGroups, this.membershipRepository);
})
.collect(Collectors.toList());
return dtos.stream()
.sorted(Comparator.comparing(GroupMinimalDTO::getLastTaskOrChangeTime, Comparator.reverseOrder()))
.collect(Collectors.toList());
}
@Override
@Transactional(readOnly = true)
public List<GroupRefDTO> fetchGroupNamesUidsOnly(String userUid) {
User user = userRepository.findOneByUid(Objects.requireNonNull(userUid));
// note: for present, since this is minimal, not even getting member count
return groupRepository.findByMembershipsUserAndActiveTrueAndParentIsNull(user).stream()
.map(group -> new GroupRefDTO(group, this.membershipRepository))
.collect(Collectors.toList());
}
@Override
public Page<Group> fetchGroupFiltered(String userUid, Permission requiredPermission, String searchTerm, Pageable pageable) {
User user = userRepository.findOneByUid(Objects.requireNonNull(userUid));
// note : monitor this and if takes strain, optimize
long startTime = System.currentTimeMillis();
log.info("Fetching minimal groups, pageable = {}", pageable);
Pageable pageRequest = pageable == null ? PageRequest.of(0, 10) : pageable;
Page<Group> groupsFomDb;
if (!StringUtils.isEmpty(searchTerm)) {
final String tsEncodedTerm = FullTextSearchUtils.encodeAsTsQueryText(searchTerm, true, true);
log.info("For search term {}, encoded version {}", searchTerm, tsEncodedTerm);
groupsFomDb = groupRepository.findUsersGroupsWithSearchTermOrderedByActivity(user.getId(), requiredPermission.name(), tsEncodedTerm, pageRequest);
} else {
log.info("No search term, but required permission: {}", requiredPermission);
groupsFomDb = groupRepository.findUsersGroupsOrderedByActivity(user.getId(), requiredPermission.name(), pageRequest);
}
log.info("Content of page: {}", groupsFomDb.getContent());
log.info("Time taken for WhatsApp group list: {} msecs", System.currentTimeMillis() - startTime);
return groupsFomDb;
}
@Override
public Page<Membership> fetchGroupMembers(User user, String groupUid, Pageable pageable) {
Objects.requireNonNull(groupUid);
Group group = groupRepository.findOneByUid(groupUid);
try {
if (group.hasParent() && !user.isMemberOf(group)) {
permissionBroker.validateGroupPermission(user, group.getParent(), Permission.GROUP_PERMISSION_CREATE_SUBGROUP);
} else {
permissionBroker.validateGroupPermission(user, group, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
}
} catch (AccessDeniedException e) {
throw new MemberLacksPermissionException(Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
}
return membershipRepository.findByGroupUid(group.getUid(), pageable);
}
@Override
public List<Membership> filterGroupMembers(User user, String groupUid,
Collection<Province> provinces,
Boolean noProvince,
Collection<String> taskTeamsUids,
Collection<String> topics,
Collection<String> affiliations,
Collection<GroupJoinMethod> joinMethods,
Collection<String> joinedCampaignsUids,
Integer joinDaysAgo,
LocalDate joinDate,
JoinDateCondition joinDateCondition,
String namePhoneOrEmail, Collection<String> languages, GroupRole groupRole) {
Objects.requireNonNull(groupUid);
Group group = groupRepository.findOneByUid(groupUid);
try {
permissionBroker.validateGroupPermission(user, group, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
} catch (AccessDeniedException e) {
throw new MemberLacksPermissionException(Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
}
log.info("filtering on, user name: {}, join date condition: {}, join date: {}, provinces: {}, taskTeams: {}",
namePhoneOrEmail, joinDateCondition, joinDate, provinces, taskTeamsUids);
List<Membership> members = membershipRepository.findAll(
MembershipSpecifications.filterGroupMembership(group, provinces, noProvince, taskTeamsUids, joinMethods, joinDaysAgo, joinDate, joinDateCondition, namePhoneOrEmail, languages, groupRole)
);
log.info("post-filtering, have {} members", members.size());
if(topics != null && topics.size() > 0){
// this is an "and" filter, at present
members = members.stream()
.filter(m -> m.getTopics().containsAll(topics))
.collect(Collectors.toList());
}
if (affiliations != null && !affiliations.isEmpty()) {
// i.e., this is an "or" filtering
Set<String> affils = new HashSet<>(affiliations);
log.info("filtering {} members, looking for affiliations {}", members.size(), affils.toString());
members = members.stream().filter(m -> m.getAffiliations().stream().anyMatch(affils::contains))
.collect(Collectors.toList());
}
//this is an alternative to very complicated query
if (joinedCampaignsUids != null && joinedCampaignsUids.size() > 0) {
List<CampaignLog> campLogs = campaignLogRepository.findByCampaignLogTypeAndCampaignMasterGroupUid(CampaignLogType.CAMPAIGN_USER_ADDED_TO_MASTER_GROUP, groupUid);
campLogs = campLogs.stream().filter(cl -> joinedCampaignsUids.contains(cl.getCampaign().getUid())).collect(Collectors.toList());
List<User> usersAddedByCampaigns = campLogs.stream().map(cl -> cl.getUser()).collect(Collectors.toList());
members = members.stream().filter( m -> usersAddedByCampaigns.contains(m.getUser())).collect(Collectors.toList());
}
return members;
}
@Override
@Transactional(readOnly = true)
public MembershipFullDTO fetchGroupMember(String userUid, String groupUid, String memberUid) {
Objects.requireNonNull(userUid);
Objects.requireNonNull(groupUid);
User user = userRepository.findOneByUid(userUid);
Group group = groupRepository.findOneByUid(groupUid);
if (!permissionBroker.isGroupPermissionAvailable(user, group, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS) &&
!(group.hasParent() && permissionBroker.isGroupPermissionAvailable(user, group.getParent(), Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS))) {
throw new MemberLacksPermissionException(Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
}
final Membership membership = membershipRepository.findByGroupUidAndUserUid(groupUid, memberUid);
return new MembershipFullDTO(membership, this.membershipRepository);
}
@Override
public Page<Membership> fetchUserGroupsNewMembers(User user, Instant from, Pageable pageable) {
List<Long> groupsWhereUserCanSeeMemberDetails = groupRepository.findGroupIdsWhereMemberHasPermission(user, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
if (!groupsWhereUserCanSeeMemberDetails.isEmpty()) {
Specification<Membership> spec = MembershipSpecifications
.recentMembershipsInGroups(groupsWhereUserCanSeeMemberDetails, from, user);
return membershipRepository.findAll(spec, pageable);
} else {
return new PageImpl<>(new ArrayList<>());
}
}
@Override
public Group fetchGroupByGroupUid(String groupUid) {
return groupRepository.findOneByUid(groupUid);
}
@Override
public List<ActionLog> fetchUserActivityDetails(String queryingUserUid, String groupUid, String memberUid) {
Group group = groupRepository.findOneByUid(groupUid);
User qUser = userRepository.findOneByUid(queryingUserUid);
permissionBroker.validateGroupPermission(qUser, group, Permission.GROUP_PERMISSION_SEE_MEMBER_DETAILS);
Membership membership = membershipRepository.findByGroupUidAndUserUid(groupUid, memberUid);
// and add a bunch more too ...
return logsBroker.fetchMembershipLogs(membership);
}
private List<GroupRefDTO> getSubgroups(Group group) {
final List<Group> groups = groupRepository.findAll(Specification.where(hasParent(group)).and(isActive()));
return groups.stream()
.map(gr -> new GroupRefDTO(gr, this.membershipRepository))
.collect(Collectors.toList());
}
}
| {
"content_hash": "cc9fd24a05607e149fb757f9b31f05b4",
"timestamp": "",
"source": "github",
"line_count": 453,
"max_line_length": 202,
"avg_line_length": 52.560706401766005,
"alnum_prop": 0.6960940781184376,
"repo_name": "grassrootza/grassroot-platform",
"id": "528224276d72a84bebe3a950944d6dd1fb3ce91b",
"size": "23810",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "grassroot-services/src/main/java/za/org/grassroot/services/group/GroupFetchBrokerImpl.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "ASP",
"bytes": "15432"
},
{
"name": "CSS",
"bytes": "876"
},
{
"name": "Dockerfile",
"bytes": "827"
},
{
"name": "HTML",
"bytes": "29802"
},
{
"name": "Java",
"bytes": "3488612"
},
{
"name": "PLSQL",
"bytes": "3059"
},
{
"name": "PLpgSQL",
"bytes": "5246"
},
{
"name": "SQLPL",
"bytes": "2733"
},
{
"name": "Shell",
"bytes": "6615"
},
{
"name": "TSQL",
"bytes": "45559"
}
],
"symlink_target": ""
} |
package com.github.tomakehurst.wiremock.extension.responsetemplating;
import com.github.jknack.handlebars.EscapingStrategy;
import com.github.jknack.handlebars.Handlebars;
import com.github.jknack.handlebars.Helper;
import com.github.jknack.handlebars.Options;
import com.github.tomakehurst.wiremock.client.ResponseDefinitionBuilder;
import com.github.tomakehurst.wiremock.extension.Parameters;
import com.github.tomakehurst.wiremock.http.Request;
import com.github.tomakehurst.wiremock.http.ResponseDefinition;
import org.junit.Before;
import org.junit.Test;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import static com.github.tomakehurst.wiremock.client.WireMock.aResponse;
import static com.github.tomakehurst.wiremock.matching.MockRequest.mockRequest;
import static com.github.tomakehurst.wiremock.testsupport.NoFileSource.noFileSource;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
public class ResponseTemplateTransformerTest {
private ResponseTemplateTransformer transformer;
@Before
public void setup() {
transformer = new ResponseTemplateTransformer(true);
}
@Test
public void queryParameters() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things?multi_param=one&multi_param=two&single-param=1234"),
aResponse().withBody(
"Multi 1: {{request.query.multi_param.[0]}}, Multi 2: {{request.query.multi_param.[1]}}, Single 1: {{request.query.single-param}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"Multi 1: one, Multi 2: two, Single 1: 1234"
));
}
@Test
public void showsNothingWhenNoQueryParamsPresent() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things"),
aResponse().withBody(
"{{request.query.multi_param.[0]}}"
)
);
assertThat(transformedResponseDef.getBody(), is(""));
}
@Test
public void requestHeaders() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.header("X-Request-Id", "req-id-1234")
.header("123$%$^&__why_o_why", "foundit"),
aResponse().withBody(
"Request ID: {{request.headers.X-Request-Id}}, Awkward named header: {{request.headers.[123$%$^&__why_o_why]}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"Request ID: req-id-1234, Awkward named header: foundit"
));
}
@Test
public void cookies() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.cookie("session", "session-1234")
.cookie(")((**#$@#", "foundit"),
aResponse().withBody(
"session: {{request.cookies.session}}, Awkward named cookie: {{request.cookies.[)((**#$@#]}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"session: session-1234, Awkward named cookie: foundit"
));
}
@Test
public void multiValueCookies() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.cookie("multi", "one", "two"),
aResponse().withBody(
"{{request.cookies.multi}}, {{request.cookies.multi.[0]}}, {{request.cookies.multi.[1]}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"one, one, two"
));
}
@Test
public void urlPath() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/the/entire/path"),
aResponse().withBody(
"Path: {{request.path}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"Path: /the/entire/path"
));
}
@Test
public void urlPathNodes() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/the/entire/path"),
aResponse().withBody(
"First: {{request.path.[0]}}, Last: {{request.path.[2]}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"First: the, Last: path"
));
}
@Test
public void urlPathNodesForRootPath() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/"),
aResponse().withBody(
"{{request.path.[0]}}"
)
);
assertThat(transformedResponseDef.getBody(), is(""));
}
@Test
public void fullUrl() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/the/entire/path?query1=one&query2=two"),
aResponse().withBody(
"URL: {{{request.url}}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"URL: /the/entire/path?query1=one&query2=two"
));
}
@Test
public void requestBody() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.body("All of the body content"),
aResponse().withBody(
"Body: {{{request.body}}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"Body: All of the body content"
));
}
@Test
public void singleValueTemplatedResponseHeaders() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.header("X-Correlation-Id", "12345"),
aResponse().withHeader("X-Correlation-Id", "{{request.headers.X-Correlation-Id}}")
);
assertThat(transformedResponseDef
.getHeaders()
.getHeader("X-Correlation-Id")
.firstValue(),
is("12345")
);
}
@Test
public void multiValueTemplatedResponseHeaders() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.header("X-Correlation-Id-1", "12345")
.header("X-Correlation-Id-2", "56789"),
aResponse().withHeader("X-Correlation-Id",
"{{request.headers.X-Correlation-Id-1}}",
"{{request.headers.X-Correlation-Id-2}}")
);
List<String> headerValues = transformedResponseDef
.getHeaders()
.getHeader("X-Correlation-Id")
.values();
assertThat(headerValues.get(0), is("12345"));
assertThat(headerValues.get(1), is("56789"));
}
@Test
public void stringHelper() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.body("some text"),
aResponse().withBody(
"{{{ capitalize request.body }}}"
)
);
assertThat(transformedResponseDef.getBody(), is(
"Some Text"
));
}
@Test
public void customHelper() {
Helper<String> helper = new Helper<String>() {
@Override
public Object apply(String context, Options options) throws IOException {
return context.length();
}
};
transformer = new ResponseTemplateTransformer(false, "string-length", helper);
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.body("fiver"),
aResponse().withBody(
"{{{ string-length request.body }}}"
)
);
assertThat(transformedResponseDef.getBody(), is("5"));
}
@Test
public void proxyBaseUrl() {
ResponseDefinition transformedResponseDef = transform(mockRequest()
.url("/things")
.header("X-WM-Uri", "http://localhost:8000"),
aResponse().proxiedFrom("{{request.headers.X-WM-Uri}}")
);
assertThat(transformedResponseDef.getProxyBaseUrl(), is(
"http://localhost:8000"
));
}
@Test
public void escapingIsTheDefault() {
final ResponseDefinition responseDefinition = this.transformer.transform(
mockRequest()
.url("/json").
body("{\"a\": {\"test\": \"look at my 'single quotes'\"}}"),
aResponse()
.withBody("{\"test\": \"{{jsonPath request.body '$.a.test'}}\"}").build(),
noFileSource(),
Parameters.empty());
assertThat(responseDefinition.getBody(), is("{\"test\": \"look at my 'single quotes'\"}"));
}
@Test
public void escapingCanBeDisabled() {
Handlebars handlebars = new Handlebars().with(EscapingStrategy.NOOP);
ResponseTemplateTransformer transformerWithEscapingDisabled = new ResponseTemplateTransformer(true, handlebars, Collections.<String, Helper>emptyMap());
final ResponseDefinition responseDefinition = transformerWithEscapingDisabled.transform(
mockRequest()
.url("/json").
body("{\"a\": {\"test\": \"look at my 'single quotes'\"}}"),
aResponse()
.withBody("{\"test\": \"{{jsonPath request.body '$.a.test'}}\"}").build(),
noFileSource(),
Parameters.empty());
assertThat(responseDefinition.getBody(), is("{\"test\": \"look at my 'single quotes'\"}"));
}
@Test
public void transformerParametersAreAppliedToTemplate() throws Exception {
ResponseDefinition responseDefinition = transformer.transform(
mockRequest()
.url("/json").
body("{\"a\": {\"test\": \"look at my 'single quotes'\"}}"),
aResponse()
.withBody("{\"test\": \"{{parameters.variable}}\"}").build(),
noFileSource(),
Parameters.one("variable", "some.value")
);
assertThat(responseDefinition.getBody(), is("{\"test\": \"some.value\"}"));
}
@Test
public void unknownTransformerParametersAreNotCausingIssues() throws Exception {
ResponseDefinition responseDefinition = transformer.transform(
mockRequest()
.url("/json").
body("{\"a\": {\"test\": \"look at my 'single quotes'\"}}"),
aResponse()
.withBody("{\"test1\": \"{{parameters.variable}}\", \"test2\": \"{{parameters.unknown}}\"}").build(),
noFileSource(),
Parameters.one("variable", "some.value")
);
assertThat(responseDefinition.getBody(), is("{\"test1\": \"some.value\", \"test2\": \"\"}"));
}
private ResponseDefinition transform(Request request, ResponseDefinitionBuilder responseDefinitionBuilder) {
return transformer.transform(
request,
responseDefinitionBuilder.build(),
noFileSource(),
Parameters.empty()
);
}
}
| {
"content_hash": "e0d1e468ec47755c1ea2f8ddcb54d7c4",
"timestamp": "",
"source": "github",
"line_count": 330,
"max_line_length": 160,
"avg_line_length": 34.7030303030303,
"alnum_prop": 0.5636570031435557,
"repo_name": "tricker/wiremock",
"id": "83056ea7d8b5f73eb37d58d12360b8057bd662a0",
"size": "12050",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/com/github/tomakehurst/wiremock/extension/responsetemplating/ResponseTemplateTransformerTest.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "167653"
},
{
"name": "HTML",
"bytes": "114176"
},
{
"name": "Java",
"bytes": "1873850"
},
{
"name": "JavaScript",
"bytes": "2523432"
},
{
"name": "RAML",
"bytes": "10070"
},
{
"name": "Ruby",
"bytes": "3341"
},
{
"name": "Scala",
"bytes": "2397"
},
{
"name": "Shell",
"bytes": "300"
},
{
"name": "XSLT",
"bytes": "14502"
}
],
"symlink_target": ""
} |
/*
* HeartBeatCommand.h
*
* Created on: Sep 5, 2012
* Author: mike
*/
#ifndef HEARTBEATCOMMAND_H_
#define HEARTBEATCOMMAND_H_
#include "Command.h"
#include <sys/time.h>
#include <string>
namespace Coaster {
class HeartBeatCommand: public Command {
private:
long sendtime;
public:
static std::string NAME;
HeartBeatCommand();
virtual ~HeartBeatCommand();
virtual void send(CoasterChannel* channel, CommandCallback* cb);
virtual void dataSent(Buffer* buf);
virtual void replyReceived();
};
}
#endif /* HEARTBEATCOMMAND_H_ */
| {
"content_hash": "e866f895ca71a64020f1ab05afcb6870",
"timestamp": "",
"source": "github",
"line_count": 34,
"max_line_length": 66,
"avg_line_length": 16.441176470588236,
"alnum_prop": 0.7030411449016101,
"repo_name": "swift-lang/swift-k",
"id": "8e53803482cde265a3f84e055434a18904c2623c",
"size": "1231",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "cogkit/modules/provider-coaster-c-client/src/HeartBeatCommand.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "3839"
},
{
"name": "C",
"bytes": "63095"
},
{
"name": "C++",
"bytes": "199455"
},
{
"name": "CSS",
"bytes": "66734"
},
{
"name": "GAP",
"bytes": "32217"
},
{
"name": "Gnuplot",
"bytes": "9817"
},
{
"name": "HTML",
"bytes": "86466"
},
{
"name": "Java",
"bytes": "6110466"
},
{
"name": "JavaScript",
"bytes": "736447"
},
{
"name": "M4",
"bytes": "3799"
},
{
"name": "Makefile",
"bytes": "17428"
},
{
"name": "Perl",
"bytes": "162187"
},
{
"name": "Perl 6",
"bytes": "31060"
},
{
"name": "Python",
"bytes": "60124"
},
{
"name": "Shell",
"bytes": "373931"
},
{
"name": "Swift",
"bytes": "163182"
},
{
"name": "Tcl",
"bytes": "10821"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources/log4j.properties" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/test/java/resources" charset="UTF-8" />
</component>
</project> | {
"content_hash": "ba4ae3c92293a7ad21db9a07da51c755",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 91,
"avg_line_length": 43,
"alnum_prop": 0.6482558139534884,
"repo_name": "langping86/websmart",
"id": "9ef4163a3dc3d59ba17ffeafa0bb892e9f163acc",
"size": "344",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": ".idea/encodings.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "117302"
}
],
"symlink_target": ""
} |
from django.core.management.base import BaseCommand
import datetime
from deck.models import Deck
class Command(BaseCommand):
def handle(self, *args, **options):
two_weeks_ago = datetime.datetime.now() - datetime.timedelta(days=100)
decks = Deck.objects.filter(last_used__lt=two_weeks_ago)
num = decks.count()
decks.delete()
print(str(num) + " decks deleted from db.") | {
"content_hash": "8416ad0e67d00d006da1fee94290a24a",
"timestamp": "",
"source": "github",
"line_count": 11,
"max_line_length": 78,
"avg_line_length": 37.45454545454545,
"alnum_prop": 0.6796116504854369,
"repo_name": "foxbenjaminfox/deckofcards",
"id": "93fd2266f6a1b4552bb13f575ac13a278dea59b1",
"size": "412",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "deck/management/commands/clean.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "49349"
},
{
"name": "HTML",
"bytes": "12020"
},
{
"name": "JavaScript",
"bytes": "75173"
},
{
"name": "Python",
"bytes": "24548"
}
],
"symlink_target": ""
} |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>error-handlers: 13 s 🏆</title>
<link rel="shortcut icon" type="image/png" href="../../../../../favicon.png" />
<link href="../../../../../bootstrap.min.css" rel="stylesheet">
<link href="../../../../../bootstrap-custom.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script src="../../../../../moment.min.js"></script>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="container">
<div class="navbar navbar-default" role="navigation">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="../../../../.."><i class="fa fa-lg fa-flag-checkered"></i> Coq bench</a>
</div>
<div id="navbar" class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li><a href="../..">clean / released</a></li>
<li class="active"><a href="">8.9.0 / error-handlers - 1.0.0</a></li>
</ul>
</div>
</div>
</div>
<div class="article">
<div class="row">
<div class="col-md-12">
<a href="../..">« Up</a>
<h1>
error-handlers
<small>
1.0.0
<span class="label label-success">13 s 🏆</span>
</small>
</h1>
<p>📅 <em><script>document.write(moment("2022-08-30 23:26:01 +0000", "YYYY-MM-DD HH:mm:ss Z").fromNow());</script> (2022-08-30 23:26:01 UTC)</em><p>
<h2>Context</h2>
<pre># Packages matching: installed
# Name # Installed # Synopsis
base-bigarray base
base-num base Num library distributed with the OCaml compiler
base-threads base
base-unix base
camlp5 7.14 Preprocessor-pretty-printer of OCaml
conf-findutils 1 Virtual package relying on findutils
conf-perl 2 Virtual package relying on perl
coq 8.9.0 Formal proof management system
num 0 The Num library for arbitrary-precision integer and rational arithmetic
ocaml 4.04.2 The OCaml compiler (virtual package)
ocaml-base-compiler 4.04.2 Official 4.04.2 release
ocaml-config 1 OCaml Switch Configuration
ocamlfind 1.9.5 A library manager for OCaml
# opam file:
opam-version: "2.0"
maintainer: "dev@clarus.me"
homepage: "https://github.com/clarus/coq-error-handlers"
dev-repo: "git+https://github.com/clarus/coq-error-handlers.git"
bug-reports: "https://github.com/clarus/coq-error-handlers/issues"
authors: ["Guillaume Claret"]
license: "MIT"
build: [
["./configure.sh"]
[make "-j%{jobs}%"]
]
install: [
[make "install"]
]
remove: ["rm" "-R" "%{lib}%/coq/user-contrib/ErrorHandlers"]
depends: [
"ocaml"
"coq" {>= "8.4pl4"}
]
synopsis: "Simple and robust error handling functions"
flags: light-uninstall
url {
src: "https://github.com/clarus/coq-error-handlers/archive/1.0.0.tar.gz"
checksum: "md5=1e69cdf94ba20cc0b7ac89fc0644c840"
}
</pre>
<h2>Lint</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Dry install 🏜️</h2>
<p>Dry install with the current Coq version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam install -y --show-action coq-error-handlers.1.0.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<p>Dry install without Coq/switch base, to test if the problem was incompatibility with the current Coq/OCaml version:</p>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>true</code></dd>
<dt>Return code</dt>
<dd>0</dd>
</dl>
<h2>Install dependencies</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 4000000; timeout 4h opam install -y --deps-only coq-error-handlers.1.0.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>11 s</dd>
</dl>
<h2>Install 🚀</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam list; echo; ulimit -Sv 16000000; timeout 4h opam install -y -v coq-error-handlers.1.0.0 coq.8.9.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Duration</dt>
<dd>13 s</dd>
</dl>
<h2>Installation size</h2>
<p>Total: 5 K</p>
<ul>
<li>3 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/ErrorHandlers/All.vo</code></li>
<li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/ErrorHandlers/All.glob</code></li>
<li>1 K <code>../ocaml-base-compiler.4.04.2/lib/coq/user-contrib/ErrorHandlers/All.v</code></li>
</ul>
<h2>Uninstall 🧹</h2>
<dl class="dl-horizontal">
<dt>Command</dt>
<dd><code>opam remove -y coq-error-handlers.1.0.0</code></dd>
<dt>Return code</dt>
<dd>0</dd>
<dt>Missing removes</dt>
<dd>
none
</dd>
<dt>Wrong removes</dt>
<dd>
none
</dd>
</dl>
</div>
</div>
</div>
<hr/>
<div class="footer">
<p class="text-center">
Sources are on <a href="https://github.com/coq-bench">GitHub</a> © Guillaume Claret 🐣
</p>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="../../../../../bootstrap.min.js"></script>
</body>
</html>
| {
"content_hash": "4fab1b92c3d3bacf7be76028d9072a0e",
"timestamp": "",
"source": "github",
"line_count": 164,
"max_line_length": 159,
"avg_line_length": 41.50609756097561,
"alnum_prop": 0.5309240487733216,
"repo_name": "coq-bench/coq-bench.github.io",
"id": "8f2bffdd72a14884ff54b9031a249da8c17b013c",
"size": "6832",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "clean/Linux-x86_64-4.04.2-2.0.5/released/8.9.0/error-handlers/1.0.0.html",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
package io.tracee.contextlogger.testdata;
import io.tracee.contextlogger.contextprovider.api.Profile;
import io.tracee.contextlogger.outputgenerator.api.TraceeContextStringRepresentationBuilder;
import io.tracee.contextlogger.outputgenerator.writer.OutputWriterConfiguration;
import io.tracee.contextlogger.profile.ProfileSettings;
import java.util.Map;
/**
* Helper class for creating ProfileSettings.
*/
public class ProfileSettingsBuilder {
public static ProfileSettings create(final Profile profile, final Map<String, Boolean> manualContextOverrides) {
return new ProfileSettings(new TraceeContextStringRepresentationBuilder() {
@Override
public boolean getEnforceOrder() {
return false;
}
@Override
public void setEnforceOrder(final boolean keepOrder) {
}
@Override
public String createStringRepresentation(final Object... instancesToProcess) {
return null;
}
@Override
public void setOutputWriterConfiguration(final OutputWriterConfiguration outputWriterConfiguration) {
}
@Override
public void setManualContextOverrides(final Map<String, Boolean> manualContextOverrides) {
}
@Override
public Map<String, Boolean> getManualContextOverrides() {
return manualContextOverrides;
}
@Override
public TraceeContextStringRepresentationBuilder cloneStringRepresentationBuilder() {
return null;
}
@Override
public void setProfile(final Profile profile) {
}
@Override
public Profile getProfile() {
return profile;
}
});
}
}
| {
"content_hash": "1c6453edc508beb598c51db3e377a7a6",
"timestamp": "",
"source": "github",
"line_count": 67,
"max_line_length": 113,
"avg_line_length": 23.104477611940297,
"alnum_prop": 0.7667958656330749,
"repo_name": "tracee/contextlogger",
"id": "c8663f9f9dbc9a1eb43376250d568c06de50b73d",
"size": "1548",
"binary": false,
"copies": "3",
"ref": "refs/heads/master",
"path": "core/src/test/java/io/tracee/contextlogger/testdata/ProfileSettingsBuilder.java",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Java",
"bytes": "667029"
}
],
"symlink_target": ""
} |
package org.apache.hyracks.control.nc.profiling;
import java.nio.ByteBuffer;
import org.apache.hyracks.api.comm.IFrameWriter;
import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.dataflow.ConnectorDescriptorId;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.job.profiling.counters.ICounter;
public class ConnectorSenderProfilingFrameWriter implements IFrameWriter {
private final IFrameWriter writer;
private final ICounter openCounter;
private final ICounter closeCounter;
private final ICounter frameCounter;
public ConnectorSenderProfilingFrameWriter(IHyracksTaskContext ctx, IFrameWriter writer,
ConnectorDescriptorId cdId, int senderIndex, int receiverIndex) {
this.writer = writer;
int attempt = ctx.getTaskAttemptId().getAttempt();
this.openCounter = ctx.getCounterContext().getCounter(
cdId + ".sender." + attempt + "." + senderIndex + "." + receiverIndex + ".open", true);
this.closeCounter = ctx.getCounterContext().getCounter(
cdId + ".sender." + attempt + "." + senderIndex + "." + receiverIndex + ".close", true);
this.frameCounter = ctx.getCounterContext().getCounter(
cdId + ".sender." + attempt + "." + senderIndex + "." + receiverIndex + ".nextFrame", true);
}
@Override
public void open() throws HyracksDataException {
writer.open();
openCounter.update(1);
}
@Override
public void nextFrame(ByteBuffer buffer) throws HyracksDataException {
frameCounter.update(1);
writer.nextFrame(buffer);
}
@Override
public void close() throws HyracksDataException {
closeCounter.update(1);
writer.close();
}
@Override
public void fail() throws HyracksDataException {
writer.fail();
}
} | {
"content_hash": "c57975a571112d45bbf7a25f6922e582",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 108,
"avg_line_length": 36.69230769230769,
"alnum_prop": 0.6886792452830188,
"repo_name": "amoudi87/hyracks",
"id": "09dd03db5bd21bffbcd6f8cff7bdba511e134771",
"size": "2715",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "hyracks/hyracks-control/hyracks-control-nc/src/main/java/org/apache/hyracks/control/nc/profiling/ConnectorSenderProfilingFrameWriter.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "2606"
},
{
"name": "CSS",
"bytes": "893"
},
{
"name": "HTML",
"bytes": "8762"
},
{
"name": "Java",
"bytes": "8496468"
},
{
"name": "JavaScript",
"bytes": "24904"
},
{
"name": "Shell",
"bytes": "16545"
}
],
"symlink_target": ""
} |
<?php
/**
* Author: Andrey Morozov
* Email: andrey@3davinci.ru
* Date: 19.04.2017
*/
namespace Sberbank\Message;
use Sberbank\Entity\OrderBundle;
use Sberbank\Exception\InvalidRequestException;
/**
* Class RegisterOrderRequest
* @package Sberbank\Message
*/
class RegisterOrderRequest extends RequestAbstract
{
const PAGE_VIEW_DESKTOP = 'DESKTOP';
const PAGE_VIEW_MOBILE = 'MOBILE';
/**
* Номер (идентификатор) заказа в системе магазина, уникален для каждого магазина в пределах системы
*
* @param string|int $value
* @return RequestAbstract
*/
public function setOrderNumber($value): RequestAbstract
{
return $this->setParameter('orderNumber', $value);
}
/**
* Сумма платежа в копейках (или центах)
*
* @param int $value
* @return RequestAbstract
*/
public function setAmount(int $value): RequestAbstract
{
return $this->setParameter('amount', $value);
}
/**
* Адрес, на который требуется перенаправить пользователя в случае успешной оплаты. Адрес должен быть указан полностью,
* включая используемый протокол (например, https://test.ru вместо tes t.ru). В противном случае пользователь будет
* перенаправлен по адресу следующего вида: http://<ад рес_платёжного_шлюза>/<адрес_продавца>.
*
* @param string $value
* @return RequestAbstract
*/
public function setReturnUrl(string $value): RequestAbstract
{
return $this->setParameter('returnUrl', $value);
}
/**
* Адрес, на который требуется перенаправить пользователя в случае неуспешной оплаты. Адрес должен быть указан полностью,
* включая используемый протокол (например, https://test.ru вместо tes t.ru). В противном случае пользователь будет
* перенаправлен по адресу следующего вида: http://<ад рес_платёжного_шлюза>/<адрес_продавца>.
*
* @param string $value
* @return RequestAbstract
*/
public function setFailUrl(string $value): RequestAbstract
{
return $this->setParameter('failUrl', $value);
}
/**
* По значению данного параметра определяется, какие страницы платёжного интерфейса должны загружаться для клиента.
* Возможные значения:
* DESKTOP – для загрузки страниц, верстка которых предназначена для отображения на экранах ПК;
* MOBILE – для загрузки страниц, верстка которых предназначена для отображения на экранах мобильных устройств;
* Если магазин создал страницы платёжного интерфейса, добавив в название файлов страниц произвольные префиксы,
* передайте значение нужного префикса в параметре pageView для загрузки соответствующей страницы. Например,
* при передаче значения iphone в архиве страниц платёжного интерфейса будет осуществляться поиск страниц с
* названиями iphone_p ayment_<locale>.html и iphone_error_<locale>.html.
*
* @param string $value
* @return RequestAbstract
*/
public function setPageView(string $value): RequestAbstract
{
return $this->setParameter('pageView', $value);
}
/**
* Продолжительность жизни заказа в секундах.
* В случае если параметр не задан, будет использовано значение, указанное в настройках мерчанта или время по
* умолчанию (1200 секунд = 20 минут).
*
* @param int $value
* @return RequestAbstract
*/
public function setSessionTimeoutSecs(int $value): RequestAbstract
{
return $this->setParameter('sessionTimeoutSecs', $value);
}
/**
* Номер (идентификатор) клиента в системе магазина. Используется для реализации функционала связок.
* Может присутствовать, если магазину разрешено создание связок.
*
* @param string $value
* @return RequestAbstract
*/
public function setClientId(string $value): RequestAbstract
{
return $this->setParameter('clientId', $value);
}
/**
* Код валюты платежа ISO 4217. Если не указан, считается равным коду валюты по умолчанию.
*
* @param string $value
* @return RequestAbstract
*/
public function setCurrency(string $value): RequestAbstract
{
return $this->setParameter('currency', $value);
}
/**
* Язык в кодировке ISO 639-1. Если не указан, будет использован язык, указанный в настройках магазина как язык по умолчанию (default language).
*
* @param string $value
* @return RequestAbstract
*/
public function setLanguage(string $value): RequestAbstract
{
return $this->setParameter('language', $value);
}
/**
* Чтобы зарегистрировать заказ от имени дочернего мерчанта, укажите его логин в этом параметре.
*
* @param string $value
* @return RequestAbstract
*/
public function setMerchantLogin(string $value): RequestAbstract
{
return $this->setParameter('merchantLogin', $value);
}
/**
* Идентификатор связки, созданной ранее. Может использоваться, только если у магазина есть разрешение на работу со связками.
* Если этот параметр передаётся в данном запросе, то это означает:
* 1. Данный заказ может быть оплачен только с помощью связки;
* 2. Плательщик будет перенаправлен на платёжную страницу, где требуется только ввод CVC.
*
* @param string $value
* @return RequestAbstract
*/
public function setBindingId(string $value): RequestAbstract
{
return $this->setParameter('bindingId', $value);
}
/**
* Описание заказа в свободной форме
*
* @param string $value
* @return RequestAbstract
*/
public function setDescription(string $value): RequestAbstract
{
return $this->setParameter('description', mb_substr($value, 0, 512));
}
/**
* Номер телефона клиента. Может быть следующего формата: ^((+7|7|8)?([0-9]){10})$.
*
* @param string $value
* @return RequestAbstract
*/
public function setPhone(string $value): RequestAbstract
{
return $this->setParameter('phone', $value);
}
/**
* Адрес электронной почты покупателя.
*
* @param string $value
* @return RequestAbstract
*/
public function setEmail(string $value): RequestAbstract
{
return $this->setParameter('email', $value);
}
/**
* Блок, содержащий корзину товаров заказа.
*
* @param OrderBundle $value
* @return RequestAbstract
*/
public function setOrderBundle(OrderBundle $value): RequestAbstract
{
return $this->setParameter('orderBundle', json_encode($value->toArray()));
}
/**
* @throws InvalidRequestException
*/
public function validate()
{
parent::validate('orderNumber', 'amount', 'returnUrl');
}
/**
* @return string
*/
public function getMethodName(): string
{
return 'rest/register.do';
}
} | {
"content_hash": "77e99a9224440ad7dcaf4b043e536860",
"timestamp": "",
"source": "github",
"line_count": 218,
"max_line_length": 148,
"avg_line_length": 31.788990825688074,
"alnum_prop": 0.6617604617604618,
"repo_name": "3DaVinci/sberbank-gateway",
"id": "5353eef7fe8299cfd657f45c5be4645867889c4f",
"size": "9005",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Sberbank/Message/RegisterOrderRequest.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "PHP",
"bytes": "107325"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<!--
~ The MIT License (MIT)
~
~ Copyright (c) 2014 Vitaliy Zasadnyy
~
~ Permission is hereby granted, free of charge, to any person obtaining a copy of
~ this software and associated documentation files (the "Software"), to deal in
~ the Software without restriction, including without limitation the rights to
~ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
~ the Software, and to permit persons to whom the Software is furnished to do so,
~ subject to the following conditions:
~
~ The above copyright notice and this permission notice shall be included in all
~ copies or substantial portions of the Software.
~
~ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
~ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
~ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
~ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
~ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
~ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ua.org.zasadnyy.visiontrainer">
<uses-feature android:name="android.hardware.type.watch"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.DeviceDefault">
<activity
android:name=".wear.WorkoutActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="com.google.android.voicesearch.TRACK"/>
<data android:mimeType="vnd.google.fitness.activity/other"/>
</intent-filter>
</activity>
<activity android:name="android.support.wearable.activity.ConfirmationActivity"/>
</application>
</manifest>
| {
"content_hash": "470b542c6db64a0a8b8297f0845cb3f1",
"timestamp": "",
"source": "github",
"line_count": 52,
"max_line_length": 89,
"avg_line_length": 46.53846153846154,
"alnum_prop": 0.6776859504132231,
"repo_name": "zasadnyy/vision-trainer-sw2",
"id": "ddec5bbbd8f8e1cc4bed45e37f3e0e5afb06ed6a",
"size": "2420",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/visionTrainingWear/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Groovy",
"bytes": "6302"
},
{
"name": "Java",
"bytes": "670394"
}
],
"symlink_target": ""
} |
This application makes use of the following third party libraries:
## RMStyleManager
Copyright (c) 2016 Maks Petrovsky <petrovskiy@real.me>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
## UIColor+InputMethods
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
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.
Generated by CocoaPods - https://cocoapods.org
| {
"content_hash": "d76e22ed889d7b656551848ea757e81f",
"timestamp": "",
"source": "github",
"line_count": 231,
"max_line_length": 77,
"avg_line_length": 54.3982683982684,
"alnum_prop": 0.7408085309565494,
"repo_name": "byzyn4ik/RMStyleManager",
"id": "b80351f27643213aaacbbff1806baaa5bbac5536",
"size": "12585",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Example/Pods/Target Support Files/Pods-RMStyleManager_Example/Pods-RMStyleManager_Example-acknowledgements.markdown",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Objective-C",
"bytes": "72339"
},
{
"name": "Ruby",
"bytes": "1909"
},
{
"name": "Shell",
"bytes": "9100"
}
],
"symlink_target": ""
} |
package at.ac.tuwien.big.xmlintelledit.intelledit.search.local.impl;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.eclipse.emf.ecore.EAttribute;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.resource.Resource;
import at.ac.tuwien.big.xmlintelledit.intelledit.change.Change;
import at.ac.tuwien.big.xmlintelledit.intelledit.change.Undoer;
import at.ac.tuwien.big.xmlintelledit.intelledit.ecore.util.MyResource;
import at.ac.tuwien.big.xmlintelledit.intelledit.evaluate.Evaluable;
import at.ac.tuwien.big.xmlintelledit.intelledit.evaluate.EvaluableManager;
import at.ac.tuwien.big.xmlintelledit.intelledit.evaluate.EvaluationState;
import at.ac.tuwien.big.xmlintelledit.intelledit.evaluate.impl.EvaluableManagerImpl;
import at.ac.tuwien.big.xmlintelledit.intelledit.evaluate.impl.MultiplicityEvaluable;
import at.ac.tuwien.big.xmlintelledit.intelledit.evaluate.impl.OCLExpressionEvaluable;
import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.FixAttempt;
import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.SetAdd;
import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.SetAddAny;
import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.SetRemove;
import at.ac.tuwien.big.xmlintelledit.intelledit.fixer.SetRemoveAny;
import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.EvalResult;
import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.FixAttemptFeatureReferenceImpl;
import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.FixAttemptReference;
import at.ac.tuwien.big.xmlintelledit.intelledit.oclvisit.FixAttemptReferenceImpl;
import at.ac.tuwien.big.xmlintelledit.intelledit.transfer.EcoreTransferFunction;
import at.ac.tuwien.big.xtext.util.MyEcoreUtil;
public class ViolatedConstraintsEvaluator implements ResourceEvaluator<Evaluation>{
public static final int GRAMMAR_ERRORS = 8;
@Override
/**
* First -violated constraints currently, costs, resolved constraints, removed violations, removed fulfilled, added constraints, added fulfilled, invalidated constraints
*/
public double[] evaluate(Change<?> ch, Evaluation ref) {
Resource res = ch.forResource();
MyResource myres = ch.forMyResource();
//Validate ...
EvaluableManager man = new EvaluableManagerImpl();
Map extents = null;
Map<Object, Map<Evaluable<?, ?>, Double>> curEvaluation = ref.eval;
double resolvedViolations = 0.0;
double removedViolations = 0.0;
double addedViolations = 0.0;
double wrongifyedViolations = 0.0;
double removedFulfilled = 0.0;
double addedFulfilled = 0.0;
double grammarProblemsIntroduced = 0.0;
Map<EAttribute,Map<Object,Set<Object>>> idOccurrences = ref.ids;
synchronized(ref) {
if (curEvaluation == null) {
curEvaluation = ref.eval = new HashMap<Object, Map<Evaluable<?,?>,Double>>();
idOccurrences = ref.ids = new HashMap<EAttribute, Map<Object,Set<Object>>>();
MyResource res_;
for (EObject obj: myres.iterateAllContents()) {
if (obj == null || obj.eClass() == null) {
continue;
}
EClass curCl = obj.eClass();
EAttribute idAttr = curCl.getEIDAttribute();
if (idAttr != null) {
Map<Object,Set<Object>> curMap = idOccurrences.get(idAttr);
if (curMap == null) {
idOccurrences.put(idAttr, curMap = new HashMap<>());
}
Object id = obj.eGet(idAttr);
if (id != null) {
Set<Object> curObjs = curMap.get(id);
if (curObjs == null) {
curMap.put(id, curObjs = new HashSet<Object>());
}
curObjs.add(obj);
}
}
Collection<Evaluable<?, ?>> evalcol = myres.getApplicableEvaluators(obj);
Map<Evaluable<?, ?>, Double> emap = new HashMap<>();
curEvaluation.put(obj, emap);
for (Evaluable expr: evalcol) {
EvaluationState state = man.basicEvaluate(myres, expr, obj);
if (state.getBasicResult() instanceof Boolean && ((Boolean)state.getBasicResult())) {
emap.put(expr,1.0);
continue;
}
state = man.fullEvaluate(myres, expr, obj);
EvalResult evalRes = state.getResult();
double q = state.getQuality();
emap.put(expr, q);
}
}
}
}
Map<Object, Map<Evaluable<?,?>, Double>> remaining = new HashMap<>(curEvaluation);
Map<EAttribute,Map<Object,Set<Object>>> newidOccurrences = ref.ids;
Resource[] resObj = new Resource[1];
EcoreTransferFunction clonedFunc = ch.forMyResource().cloneFunc(resObj);
Undoer undoer = ch.execute();
double costs = ch.getCosts();
double ret = 0.0;
try {
int haveContainer = 0;
for (EObject obj: myres.iterateAllContents()) {
if (obj == null || obj.eClass() == null) {
continue;
}
if (obj.eContainer() == null) {
++haveContainer;
}
EClass curCl = obj.eClass();
EAttribute idAttr = curCl.getEIDAttribute();
if (idAttr != null) {
Map<Object,Set<Object>> curMap = newidOccurrences.get(idAttr);
if (curMap == null) {
newidOccurrences.put(idAttr, curMap = new HashMap<>());
}
Object id = obj.eGet(idAttr);
if (id != null) {
Set<Object> curObjs = curMap.get(id);
if (curObjs == null) {
curMap.put(id, curObjs = new HashSet<Object>());
}
curObjs.add(obj);
}
}
Collection<Evaluable<?, ?>> evalcol = myres.getApplicableEvaluators(obj);
Map<Evaluable<?, ?>, Double> emap = curEvaluation.getOrDefault(obj,Collections.emptyMap());
Map<Evaluable<?, ?>, Double> subremaining = new HashMap<>(remaining.getOrDefault(obj, Collections.emptyMap()));
for (Evaluable expr: evalcol) {
Double cur = emap.get(expr);
subremaining.remove(expr);
EvaluationState state = man.basicEvaluate(myres, expr, obj);
if (state.getBasicResult() instanceof Boolean && ((Boolean)state.getBasicResult())) {
if (cur == null) {
addedFulfilled+= 1.0;
} else {
resolvedViolations+= 1.0-cur;
}
continue;
}
state = man.fullEvaluate(myres, expr, obj);
EvalResult evalRes = state.getResult();
double q = state.getQuality();
if (q > 1.0) {
System.err.println("Strange quality ...");
q = 1.0;
}
ret+= 1.0-q;
if (q < 1.0 && (cur == null || q < cur )) {
if (expr instanceof MultiplicityEvaluable) {
boolean isAdd = false;
boolean isRemove = false;
for (FixAttempt at: state.getResult().getPossibleFixes()) {
if (at instanceof SetAddAny || at instanceof SetAdd) {
isAdd = true;
}
if (at instanceof SetRemoveAny || at instanceof SetRemove) {
isRemove = true;
}
}
if (isAdd) {
grammarProblemsIntroduced+= 1.0-q;
}
}
}
if (cur == null) {
addedViolations+= 1.0-q;
addedFulfilled+= q;
} else {
if (cur > q) {
//Quality now less --> bad
wrongifyedViolations+= cur-q;
} else {
//Quality now better or equal --> good or ok
resolvedViolations+= q-cur;
}
}
}
for (Double d: subremaining.values()) {
removedViolations+= 1.0-d;
removedFulfilled+= d;
}
remaining.remove(obj);
}
for (Map<Evaluable<?,?>,Double> map: remaining.values()) {
for (Double q: map.values()) {
removedViolations+= 1.0-q;
removedFulfilled+= q;
}
}
if (haveContainer == 0) {
//No container - great problem!
ret+= 99999999.0E10;
grammarProblemsIntroduced+=1.0;
resolvedViolations-=1.0E10;
} else {
ret+= haveContainer-1;
}
} finally {
undoer.undo();
}
if (!ch.forMyResource().equalsTarget(clonedFunc)) {
System.out.println(ch.forMyResource().getResource() + " VS "+clonedFunc.forwardResource()+" VS "+clonedFunc.backResource()+"!");
ch.forMyResource().equalsTarget(clonedFunc);
throw new RuntimeException();
}
Map<Object,Integer> oldviolationCount = new HashMap<Object, Integer>();
Map<Object,Integer> newviolationCount = new HashMap<Object, Integer>();
int removedIdViolations = 0;
for (Entry<EAttribute, Map<Object, Set<Object>>> entry: idOccurrences.entrySet()) {
for (Entry<Object,Set<Object>> entry2: entry.getValue().entrySet()) {
if (entry2.getValue().size() > 1) {
Set<Object> withoutRemoved = new HashSet<Object>(entry2.getValue());
withoutRemoved.removeAll(remaining.keySet());
for (Object o: entry2.getValue()) {
oldviolationCount.put(o, oldviolationCount.getOrDefault(o, 0)+1);
}
if (withoutRemoved.size() > 1) {
removedIdViolations+= entry2.getValue().size()-withoutRemoved.size();
} else {
removedIdViolations+= entry2.getValue().size();
}
}
}
}
int addedIdViolations = 0;
for (Entry<EAttribute, Map<Object, Set<Object>>> entry: newidOccurrences.entrySet()) {
for (Entry<Object,Set<Object>> entry2: entry.getValue().entrySet()) {
if (entry2.getValue().size() > 1) {
Set<Object> withoutAdded = new HashSet<Object>(entry2.getValue());
withoutAdded.retainAll(curEvaluation.keySet());
for (Object o: entry2.getValue()) {
newviolationCount.put(o, newviolationCount.getOrDefault(o, 0)+1);
}
if (withoutAdded.size() != entry2.getValue().size()) {
if (withoutAdded.size() > 1) {
addedIdViolations+= entry2.getValue().size()-withoutAdded.size();
} else {
addedIdViolations+= entry2.getValue().size();
}
}
}
}
}
int resolvedOrRemovedId = 0;
int introducedOrAddedId = 0;
for (Entry<Object, Integer> entry: oldviolationCount.entrySet()) {
Integer newC = newviolationCount.getOrDefault(entry.getKey(),0);
if (newC > entry.getValue()) {
introducedOrAddedId+= newC-entry.getValue();
} else {
resolvedOrRemovedId+= entry.getValue()-newC;
}
}
int haveIdViolations = 0;
for (Entry<Object, Integer> entry: newviolationCount.entrySet()) {
if (oldviolationCount.containsKey(entry.getKey())) {continue;}
introducedOrAddedId+= entry.getValue();
haveIdViolations+= entry.getValue();
}
int resolvedId = resolvedOrRemovedId-removedIdViolations;
int introducedId = introducedOrAddedId-addedIdViolations;
resolvedViolations+= resolvedId;
removedViolations+= removedIdViolations;
addedViolations+= addedIdViolations;
wrongifyedViolations+= introducedId;
ret+= haveIdViolations;
return new double[]{-ret,costs, resolvedViolations, removedViolations, removedFulfilled, addedViolations, addedFulfilled, wrongifyedViolations, grammarProblemsIntroduced};
}
public void augmentSet(Set<FixAttemptReference> toAdd) {
int curSize;
do {
curSize = toAdd.size();
Set<FixAttemptReference> next = new HashSet<FixAttemptReference>();
for (FixAttemptReference ref: toAdd) {
if (ref instanceof FixAttemptReferenceImpl) {
FixAttemptReferenceImpl impl = (FixAttemptReferenceImpl)ref;
//All set features
EAttribute idAttr = null;
if (!impl.isCompleteObject()) {
idAttr = ref.forObject().eClass().getEIDAttribute();
if (idAttr == null) {
EStructuralFeature esf = ref.forObject().eClass().getEStructuralFeature("name");
if (esf instanceof EAttribute) {
idAttr = (EAttribute)esf;
}
}
}
boolean ok = false;
if (idAttr != null) {
Collection col = MyEcoreUtil.getAsCollection(ref.forObject(), idAttr);
if (!col.isEmpty()) {
ok = true;
next.add(new FixAttemptFeatureReferenceImpl(ref.forObject(), idAttr));
}
}
if (!ok) {
for (EStructuralFeature feat: ref.forObject().eClass().getEAllStructuralFeatures()) {
Collection col = MyEcoreUtil.getAsCollection(ref.forObject(), feat);
if (feat instanceof EReference && ((EReference) feat).isContainment()) {
for (Object o: col) {
next.add(new FixAttemptReferenceImpl((EObject)o,idAttr==null));
}
}
if (!col.isEmpty()) {
next.add(new FixAttemptFeatureReferenceImpl(ref.forObject(), feat));
int ind = 0;
for (Object o: col) {
next.add(new FixAttemptFeatureReferenceImpl(ref.forObject(), feat, ind, o));
++ind;
}
}
}
}
} else if (ref instanceof FixAttemptFeatureReferenceImpl) {
FixAttemptFeatureReferenceImpl fref = (FixAttemptFeatureReferenceImpl)ref;
if (((FixAttemptFeatureReferenceImpl) ref).getValueIndex() == -1) {
Object val = ((FixAttemptFeatureReferenceImpl) ref).getValue();
Collection col = MyEcoreUtil.getAsCollection(ref.forObject(), ((FixAttemptFeatureReferenceImpl) ref).getFeature());
if (!col.isEmpty() && !col.contains(val)) {
int ind = 0;
for (Object o: col) {
next.add(new FixAttemptFeatureReferenceImpl(ref.forObject(), ((FixAttemptFeatureReferenceImpl) ref).getFeature(), ind, o));
++ind;
}
} else if (col.contains(val)) {
int ind = 0;
for (Object o: col) {
if (o.equals(val)) {
next.add(new FixAttemptFeatureReferenceImpl(ref.forObject(), ((FixAttemptFeatureReferenceImpl) ref).getFeature(), ind, o));
}
++ind;
}
}
}
if (fref.getFeature() instanceof EReference && ((EReference) fref.getFeature()).isContainment()) {
Collection col = MyEcoreUtil.getAsCollection(ref.forObject(), fref.getFeature());
for (Object o: col) {
next.add(new FixAttemptReferenceImpl((EObject)o,false));
}
}
}
}
toAdd.addAll(next);
} while (curSize != toAdd.size());
}
public boolean calcMyErrorFixAttemptReference(MyResource myres, Set<FixAttemptReference> myAlgorithm, Set<FixAttemptReference> xtextAlgorithm) {
EvaluableManager man = new EvaluableManagerImpl();
boolean onlyMultiplicity = true;
for (EObject obj: myres.iterateAllContents()) {
Collection<Evaluable<?, ?>> evalcol = myres.getApplicableEvaluators(obj);
for (Evaluable expr: evalcol) {
EvaluationState state = man.fullEvaluate(myres, expr, obj);
if (state.getBasicResult() instanceof Boolean && ((Boolean)state.getBasicResult())) {
continue;
}
myAlgorithm.addAll(state.getResult().getCompleteReferenceInfo().getFixAttemptReferences());
if (expr instanceof OCLExpressionEvaluable) {
xtextAlgorithm.add(new FixAttemptReferenceImpl(obj,true));
onlyMultiplicity = false;
} else if (expr instanceof MultiplicityEvaluable){
xtextAlgorithm.add(new FixAttemptFeatureReferenceImpl(obj, ((MultiplicityEvaluable) expr).getFeature()));
}
}
}
augmentSet(myAlgorithm);
augmentSet(xtextAlgorithm);
return onlyMultiplicity;
}
}
| {
"content_hash": "a535122062450dd3e7200608ef3f8182",
"timestamp": "",
"source": "github",
"line_count": 396,
"max_line_length": 173,
"avg_line_length": 37.446969696969695,
"alnum_prop": 0.6699710027648527,
"repo_name": "patrickneubauer/XMLIntellEdit",
"id": "c8d4c022279ad9e0ed7d074c74a4ddcb8f847ad3",
"size": "14829",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "xmlintelledit/intelledit/src/main/java/at/ac/tuwien/big/xmlintelledit/intelledit/search/local/impl/ViolatedConstraintsEvaluator.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "94"
},
{
"name": "C",
"bytes": "20422"
},
{
"name": "GAP",
"bytes": "2260869"
},
{
"name": "HTML",
"bytes": "91232"
},
{
"name": "Java",
"bytes": "35159898"
},
{
"name": "Makefile",
"bytes": "848"
},
{
"name": "Roff",
"bytes": "7706"
},
{
"name": "Xtend",
"bytes": "53972"
}
],
"symlink_target": ""
} |
package vanenkoviliya.ChessBoard;
/**
* @author vanenkov_ia
* @version 1
* @since 10.01.2017
**/
public class ImpossibleMoveException extends Exception {
public ImpossibleMoveException(String msg) {
super(msg);
}
}
| {
"content_hash": "b3050b59d9f4a4b2c48cdd38fabc44ea",
"timestamp": "",
"source": "github",
"line_count": 12,
"max_line_length": 56,
"avg_line_length": 19.666666666666668,
"alnum_prop": 0.690677966101695,
"repo_name": "iliya-84/Java_study",
"id": "c5e3908bf32bece738ffcd6ce68f059f66896c52",
"size": "236",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Chapter002/src/main/java/vanenkoviliya/ChessBoard/ImpossibleMoveException.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "53148"
}
],
"symlink_target": ""
} |
// SpotOn.java
// Activity for the Buggz app
package com.sparetimegames.buggz;
import android.app.Activity;
import android.media.AudioManager;
import android.os.Bundle;
public class Buggz extends Activity
{
//private SpotOnView view; // displays and manages the game
private BugzView view;
// called when this Activity is first created
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
view = (BugzView)findViewById(R.id.bugzView);
// allow volume keys to set game volume
setVolumeControlStream(AudioManager.STREAM_MUSIC);
} // end method onCreate
// called when this Activity moves to the background
@Override
public void onPause()
{
super.onPause();
view.stopRunning(); // release resources held by the View
} // end method onPause
@Override
protected void onDestroy()
{
super.onDestroy();
view.stopRunning();
}
// called when this Activity is brought to the foreground
@Override
public void onResume()
{
super.onResume();
view.resume(this); // re-initialize resources released in onPause
} // end method onResume
} // end class Buggz
| {
"content_hash": "a9be706e467c1810866318aafabf4730",
"timestamp": "",
"source": "github",
"line_count": 51,
"max_line_length": 73,
"avg_line_length": 25.41176470588235,
"alnum_prop": 0.6682098765432098,
"repo_name": "CrystalVisions/Buggz",
"id": "44bd239f04d8f3840b283cf7a173e0b47161388a",
"size": "2360",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/com/sparetimegames/buggz/Buggz.java",
"mode": "33261",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "62666"
}
],
"symlink_target": ""
} |
<?php
final class SERVER_TYPE
{
const AWS_INSTANCE = "aws_instance";
const RACKSPACE_INSTANCE = "rackspace_instance";
const SIMPLE = "simple";
}
?> | {
"content_hash": "a533ee284f921504fbf23d3fd0eac63e",
"timestamp": "",
"source": "github",
"line_count": 8,
"max_line_length": 56,
"avg_line_length": 23.75,
"alnum_prop": 0.5578947368421052,
"repo_name": "kikov79/scalr",
"id": "ad20eed4ead007784e1967d2686002cd204eab96",
"size": "190",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "app/src/types/enum.SERVER_TYPE.php",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ApacheConf",
"bytes": "4249"
},
{
"name": "CSS",
"bytes": "86731"
},
{
"name": "Cucumber",
"bytes": "72478"
},
{
"name": "HTML",
"bytes": "2474225"
},
{
"name": "JavaScript",
"bytes": "16934089"
},
{
"name": "PHP",
"bytes": "20637716"
},
{
"name": "Python",
"bytes": "350030"
},
{
"name": "Ruby",
"bytes": "9397"
},
{
"name": "Shell",
"bytes": "17207"
},
{
"name": "Smarty",
"bytes": "2245"
},
{
"name": "XSLT",
"bytes": "29678"
}
],
"symlink_target": ""
} |
.class public Lcom/android/internal/telephony/DefaultSIMSettings;
.super Ljava/lang/Object;
.source "DefaultSIMSettings.java"
# static fields
.field public static final ACTION_ON_SIM_DETECTED:Ljava/lang/String; = "ACTION_ON_SIM_DETECTED"
.field public static final EXTRA_VALUE_NEW_SIM:Ljava/lang/String; = "NEW"
.field public static final EXTRA_VALUE_REMOVE_SIM:Ljava/lang/String; = "REMOVE"
.field public static final EXTRA_VALUE_SWAP_SIM:Ljava/lang/String; = "SWAP"
.field public static final INTENT_KEY_DETECT_STATUS:Ljava/lang/String; = "simDetectStatus"
.field public static final INTENT_KEY_NEW_SIM_SLOT:Ljava/lang/String; = "newSIMSlot"
.field public static final INTENT_KEY_NEW_SIM_STATUS:Ljava/lang/String; = "newSIMStatus"
.field public static final INTENT_KEY_SIM_COUNT:Ljava/lang/String; = "simCount"
.field private static final LOG_TAG:Ljava/lang/String; = "PHONE"
.field private static final STATUS_DUAL_SIM_INSERTED:I = 0x3
.field private static final STATUS_NO_SIM_INSERTED:I = 0x0
.field private static final STATUS_SIM1_INSERTED:I = 0x1
.field private static final STATUS_SIM2_INSERTED:I = 0x2
# direct methods
.method public constructor <init>()V
.locals 0
.prologue
.line 64
invoke-direct {p0}, Ljava/lang/Object;-><init>()V
return-void
.end method
.method public static broadCastDefaultSIMRemoved(I)V
.locals 3
.parameter "nSIMCount"
.prologue
.line 569
new-instance v0, Landroid/content/Intent;
const-string v1, "android.intent.action.ACTION_SIM_DETECTED"
invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 570
.local v0, intent:Landroid/content/Intent;
const-string/jumbo v1, "simDetectStatus"
const-string v2, "REMOVE"
invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;
.line 571
const-string/jumbo v1, "simCount"
invoke-virtual {v0, v1, p0}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 572
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string v2, "broadCast intent ACTION_SIM_DETECTED [REMOVE, "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v1
const-string v2, "]"
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 573
const-string v1, "android.permission.READ_PHONE_STATE"
invoke-static {v0, v1}, Landroid/app/ActivityManagerNative;->broadcastStickyIntent(Landroid/content/Intent;Ljava/lang/String;)V
.line 574
return-void
.end method
.method public static broadCastNewSIMDetected(II)V
.locals 3
.parameter "nSIMCount"
.parameter "nNewSIMSlot"
.prologue
.line 560
new-instance v0, Landroid/content/Intent;
const-string v1, "android.intent.action.ACTION_SIM_DETECTED"
invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 561
.local v0, intent:Landroid/content/Intent;
const-string/jumbo v1, "simDetectStatus"
const-string v2, "NEW"
invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;
.line 562
const-string/jumbo v1, "simCount"
invoke-virtual {v0, v1, p0}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 563
const-string/jumbo v1, "newSIMSlot"
invoke-virtual {v0, v1, p1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 564
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string v2, "broadCast intent ACTION_SIM_DETECTED [NEW, "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v1
const-string v2, ", "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v1
const-string v2, "]"
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 565
const-string v1, "android.permission.READ_PHONE_STATE"
invoke-static {v0, v1}, Landroid/app/ActivityManagerNative;->broadcastStickyIntent(Landroid/content/Intent;Ljava/lang/String;)V
.line 566
return-void
.end method
.method public static broadCastSIMInsertedStatus(I)V
.locals 3
.parameter "nSIMInsertStatus"
.prologue
.line 585
new-instance v0, Landroid/content/Intent;
const-string v1, "android.intent.action.SIM_INSERTED_STATUS"
invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 586
.local v0, intent:Landroid/content/Intent;
const-string/jumbo v1, "simCount"
invoke-virtual {v0, v1, p0}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 587
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string v2, "broadCast intent ACTION_SIM_INSERTED_STATUS "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 588
const-string v1, "android.permission.READ_PHONE_STATE"
invoke-static {v0, v1}, Landroid/app/ActivityManagerNative;->broadcastStickyIntent(Landroid/content/Intent;Ljava/lang/String;)V
.line 589
return-void
.end method
.method public static broadCastSIMSwapped(I)V
.locals 3
.parameter "nSIMCount"
.prologue
.line 577
new-instance v0, Landroid/content/Intent;
const-string v1, "android.intent.action.ACTION_SIM_DETECTED"
invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 578
.local v0, intent:Landroid/content/Intent;
const-string/jumbo v1, "simDetectStatus"
const-string v2, "SWAP"
invoke-virtual {v0, v1, v2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;
.line 579
const-string/jumbo v1, "simCount"
invoke-virtual {v0, v1, p0}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 580
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string v2, "broadCast intent ACTION_SIM_DETECTED [SWAP, "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v1
const-string v2, "]"
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 581
const-string v1, "android.permission.READ_PHONE_STATE"
invoke-static {v0, v1}, Landroid/app/ActivityManagerNative;->broadcastStickyIntent(Landroid/content/Intent;Ljava/lang/String;)V
.line 582
return-void
.end method
.method private static isSIMRemoved(JJJ)Z
.locals 3
.parameter "defSIMId"
.parameter "curSIM1"
.parameter "curSIM2"
.prologue
const/4 v0, 0x0
.line 543
const-wide/16 v1, 0x0
cmp-long v1, p0, v1
if-gtz v1, :cond_1
.line 548
:cond_0
:goto_0
return v0
.line 545
:cond_1
cmp-long v1, p0, p2
if-eqz v1, :cond_0
cmp-long v1, p0, p4
if-eqz v1, :cond_0
.line 546
const/4 v0, 0x1
goto :goto_0
.end method
.method private static logd(Ljava/lang/String;)V
.locals 3
.parameter "message"
.prologue
.line 592
const-string v0, "PHONE"
new-instance v1, Ljava/lang/StringBuilder;
invoke-direct {v1}, Ljava/lang/StringBuilder;-><init>()V
const-string v2, "[DefaultSIMSettings] "
invoke-virtual {v1, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1, p0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v1
invoke-virtual {v1}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v1
invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I
.line 593
return-void
.end method
.method public static declared-synchronized onAllIccidQueryComplete(Landroid/content/Context;Lcom/android/internal/telephony/Phone;Ljava/lang/String;Ljava/lang/String;ZZ)V
.locals 50
.parameter "context"
.parameter "phone"
.parameter "iccid1"
.parameter "iccid2"
.parameter "is3GSwitched"
.parameter "isToSwitch3G"
.prologue
.line 86
const-class v49, Lcom/android/internal/telephony/DefaultSIMSettings;
monitor-enter v49
:try_start_0
const-string/jumbo v11, "onAllIccidQueryComplete start"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 87
invoke-virtual/range {p0 .. p0}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v19
.line 88
.local v19, contentResolver:Landroid/content/ContentResolver;
const/16 v36, 0x0
.line 89
.local v36, oldIccIdInSlot1:Ljava/lang/String;
const/16 v37, 0x0
.line 90
.local v37, oldIccIdInSlot2:Ljava/lang/String;
if-nez p2, :cond_0
const-string p2, ""
.line 91
:cond_0
if-nez p3, :cond_1
const-string p3, ""
.line 92
:cond_1
const-string v11, ""
move-object/from16 v0, p2
invoke-virtual {v11, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_d
const/16 v28, 0x1
.line 93
.local v28, isSIM1Inserted:Z
:goto_0
const-string v11, ""
move-object/from16 v0, p3
invoke-virtual {v11, v0}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_0
move-result v11
if-nez v11, :cond_e
const/16 v29, 0x1
.line 95
.local v29, isSIM2Inserted:Z
:goto_1
const/16 v46, 0x0
.line 97
.local v46, telephonyExt:Lcom/mediatek/common/telephony/ITelephonyExt;
:try_start_1
const-class v11, Lcom/mediatek/common/telephony/ITelephonyExt;
const/4 v12, 0x0
new-array v12, v12, [Ljava/lang/Object;
invoke-static {v11, v12}, Lcom/mediatek/common/MediatekClassFactory;->createInstance(Ljava/lang/Class;[Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v11
move-object v0, v11
check-cast v0, Lcom/mediatek/common/telephony/ITelephonyExt;
move-object/from16 v46, v0
:try_end_1
.catchall {:try_start_1 .. :try_end_1} :catchall_0
.catch Ljava/lang/Exception; {:try_start_1 .. :try_end_1} :catch_0
.line 102
:goto_2
const/4 v11, 0x0
:try_start_2
move-object/from16 v0, p0
invoke-static {v0, v11}, Landroid/provider/Telephony$SIMInfo;->getSIMInfoBySlot(Landroid/content/Context;I)Landroid/provider/Telephony$SIMInfo;
move-result-object v38
.line 103
.local v38, oldSimInfo1:Landroid/provider/Telephony$SIMInfo;
if-eqz v38, :cond_f
.line 104
move-object/from16 v0, v38
iget-object v0, v0, Landroid/provider/Telephony$SIMInfo;->mICCId:Ljava/lang/String;
move-object/from16 v36, v0
.line 105
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete old IccId In Slot0 is "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, v36
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 106
if-eqz v28, :cond_2
move-object/from16 v0, p2
move-object/from16 v1, v36
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_3
.line 107
:cond_2
new-instance v48, Landroid/content/ContentValues;
const/4 v11, 0x1
move-object/from16 v0, v48
invoke-direct {v0, v11}, Landroid/content/ContentValues;-><init>(I)V
.line 108
.local v48, value:Landroid/content/ContentValues;
const-string/jumbo v11, "slot"
const/4 v12, -0x1
invoke-static {v12}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
move-result-object v12
move-object/from16 v0, v48
invoke-virtual {v0, v11, v12}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V
.line 109
sget-object v11, Landroid/provider/Telephony$SimInfo;->CONTENT_URI:Landroid/net/Uri;
move-object/from16 v0, v38
iget-wide v12, v0, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {v11, v12, v13}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;
move-result-object v11
const/4 v12, 0x0
const/4 v13, 0x0
move-object/from16 v0, v19
move-object/from16 v1, v48
invoke-virtual {v0, v11, v1, v12, v13}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
.line 111
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete reset Slot0 to -1, iccid1 = "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, p2
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, " "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 117
.end local v48 #value:Landroid/content/ContentValues;
:cond_3
:goto_3
const/4 v11, 0x1
move-object/from16 v0, p0
invoke-static {v0, v11}, Landroid/provider/Telephony$SIMInfo;->getSIMInfoBySlot(Landroid/content/Context;I)Landroid/provider/Telephony$SIMInfo;
move-result-object v39
.line 118
.local v39, oldSimInfo2:Landroid/provider/Telephony$SIMInfo;
if-eqz v39, :cond_10
.line 119
move-object/from16 v0, v39
iget-object v0, v0, Landroid/provider/Telephony$SIMInfo;->mICCId:Ljava/lang/String;
move-object/from16 v37, v0
.line 120
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete old IccId In Slot1 is "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, v37
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 121
if-eqz v29, :cond_4
move-object/from16 v0, p3
move-object/from16 v1, v37
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_5
.line 122
:cond_4
new-instance v48, Landroid/content/ContentValues;
const/4 v11, 0x1
move-object/from16 v0, v48
invoke-direct {v0, v11}, Landroid/content/ContentValues;-><init>(I)V
.line 123
.restart local v48 #value:Landroid/content/ContentValues;
const-string/jumbo v11, "slot"
const/4 v12, -0x1
invoke-static {v12}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
move-result-object v12
move-object/from16 v0, v48
invoke-virtual {v0, v11, v12}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V
.line 124
sget-object v11, Landroid/provider/Telephony$SimInfo;->CONTENT_URI:Landroid/net/Uri;
move-object/from16 v0, v39
iget-wide v12, v0, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {v11, v12, v13}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;
move-result-object v11
const/4 v12, 0x0
const/4 v13, 0x0
move-object/from16 v0, v19
move-object/from16 v1, v48
invoke-virtual {v0, v11, v1, v12, v13}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
.line 126
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete reset Slot1 to -1, iccid2 = "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, p3
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, " "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 133
.end local v48 #value:Landroid/content/ContentValues;
:cond_5
:goto_4
if-nez v36, :cond_6
const-string v36, ""
.line 134
:cond_6
if-nez v37, :cond_7
const-string v37, ""
.line 137
:cond_7
const/16 v31, 0x0
.line 138
.local v31, nNewCardCount:I
const/16 v32, 0x0
.line 139
.local v32, nNewSIMStatus:I
if-eqz p2, :cond_8
const-string v11, ""
move-object/from16 v0, p2
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_11
.line 140
:cond_8
const-string/jumbo v11, "onAllIccidQueryComplete No SIM inserted in Slot 0, set the slot for Removed SIM to NONE "
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 159
:cond_9
:goto_5
if-eqz p3, :cond_a
const-string v11, ""
move-object/from16 v0, p3
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_15
.line 160
:cond_a
const-string/jumbo v11, "onAllIccidQueryComplete No SIM inserted in Slot 1, set the slot for Removed SIM to NONE "
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 177
:cond_b
:goto_6
const-wide/16 v5, -0x3
.line 178
.local v5, simIdForSlot1:J
const-wide/16 v7, -0x3
.line 179
.local v7, simIdForSlot2:J
invoke-static/range {p0 .. p0}, Landroid/provider/Telephony$SIMInfo;->getInsertedSIMList(Landroid/content/Context;)Ljava/util/List;
move-result-object v44
.line 180
.local v44, simInfos:Ljava/util/List;,"Ljava/util/List<Landroid/provider/Telephony$SIMInfo;>;"
if-nez v44, :cond_19
const/16 v33, 0x0
.line 181
.local v33, nSIMCount:I
:goto_7
const/16 v26, 0x0
.local v26, i:I
:goto_8
move/from16 v0, v26
move/from16 v1, v33
if-ge v0, v1, :cond_1b
.line 182
move-object/from16 v0, v44
move/from16 v1, v26
invoke-interface {v0, v1}, Ljava/util/List;->get(I)Ljava/lang/Object;
move-result-object v47
check-cast v47, Landroid/provider/Telephony$SIMInfo;
.line 183
.local v47, temp:Landroid/provider/Telephony$SIMInfo;
move-object/from16 v0, v47
iget v11, v0, Landroid/provider/Telephony$SIMInfo;->mSlot:I
if-nez v11, :cond_1a
.line 184
move-object/from16 v0, v47
iget-wide v5, v0, Landroid/provider/Telephony$SIMInfo;->mSimId:J
.line 181
:cond_c
:goto_9
add-int/lit8 v26, v26, 0x1
goto :goto_8
.line 92
.end local v5 #simIdForSlot1:J
.end local v7 #simIdForSlot2:J
.end local v26 #i:I
.end local v28 #isSIM1Inserted:Z
.end local v29 #isSIM2Inserted:Z
.end local v31 #nNewCardCount:I
.end local v32 #nNewSIMStatus:I
.end local v33 #nSIMCount:I
.end local v38 #oldSimInfo1:Landroid/provider/Telephony$SIMInfo;
.end local v39 #oldSimInfo2:Landroid/provider/Telephony$SIMInfo;
.end local v44 #simInfos:Ljava/util/List;,"Ljava/util/List<Landroid/provider/Telephony$SIMInfo;>;"
.end local v46 #telephonyExt:Lcom/mediatek/common/telephony/ITelephonyExt;
.end local v47 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_d
const/16 v28, 0x0
goto/16 :goto_0
.line 93
.restart local v28 #isSIM1Inserted:Z
:cond_e
const/16 v29, 0x0
goto/16 :goto_1
.line 98
.restart local v29 #isSIM2Inserted:Z
.restart local v46 #telephonyExt:Lcom/mediatek/common/telephony/ITelephonyExt;
:catch_0
move-exception v22
.line 99
.local v22, e:Ljava/lang/Exception;
invoke-virtual/range {v22 .. v22}, Ljava/lang/Exception;->printStackTrace()V
:try_end_2
.catchall {:try_start_2 .. :try_end_2} :catchall_0
goto/16 :goto_2
.line 86
.end local v19 #contentResolver:Landroid/content/ContentResolver;
.end local v22 #e:Ljava/lang/Exception;
.end local v28 #isSIM1Inserted:Z
.end local v29 #isSIM2Inserted:Z
.end local v36 #oldIccIdInSlot1:Ljava/lang/String;
.end local v37 #oldIccIdInSlot2:Ljava/lang/String;
.end local v46 #telephonyExt:Lcom/mediatek/common/telephony/ITelephonyExt;
:catchall_0
move-exception v11
monitor-exit v49
throw v11
.line 114
.restart local v19 #contentResolver:Landroid/content/ContentResolver;
.restart local v28 #isSIM1Inserted:Z
.restart local v29 #isSIM2Inserted:Z
.restart local v36 #oldIccIdInSlot1:Ljava/lang/String;
.restart local v37 #oldIccIdInSlot2:Ljava/lang/String;
.restart local v38 #oldSimInfo1:Landroid/provider/Telephony$SIMInfo;
.restart local v46 #telephonyExt:Lcom/mediatek/common/telephony/ITelephonyExt;
:cond_f
:try_start_3
const-string/jumbo v11, "onAllIccidQueryComplete No sim in slot0 for last time "
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
goto/16 :goto_3
.line 129
.restart local v39 #oldSimInfo2:Landroid/provider/Telephony$SIMInfo;
:cond_10
const-string/jumbo v11, "onAllIccidQueryComplete No sim in slot1 for last time "
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
goto :goto_4
.line 142
.restart local v31 #nNewCardCount:I
.restart local v32 #nNewSIMStatus:I
:cond_11
const-string v11, "ff"
move-object/from16 v0, p2
invoke-virtual {v0, v11}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z
move-result v11
if-nez v11, :cond_12
invoke-virtual/range {p2 .. p3}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_14
.line 145
:cond_12
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
move-object/from16 v0, p2
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, "1"
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
const/4 v12, 0x0
move-object/from16 v0, p0
invoke-static {v0, v11, v12}, Landroid/provider/Telephony$SIMInfo;->insertICCId(Landroid/content/Context;Ljava/lang/String;I)Landroid/net/Uri;
.line 146
const-string/jumbo v11, "onAllIccidQueryComplete special SIM with invalid ICCID is inserted in slot1"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 150
:cond_13
:goto_a
move-object/from16 v0, p2
move-object/from16 v1, v36
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_9
.line 153
add-int/lit8 v31, v31, 0x1
.line 154
or-int/lit8 v32, v32, 0x1
goto/16 :goto_5
.line 147
:cond_14
move-object/from16 v0, p2
move-object/from16 v1, v36
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_13
.line 148
const/4 v11, 0x0
move-object/from16 v0, p0
move-object/from16 v1, p2
invoke-static {v0, v1, v11}, Landroid/provider/Telephony$SIMInfo;->insertICCId(Landroid/content/Context;Ljava/lang/String;I)Landroid/net/Uri;
goto :goto_a
.line 162
:cond_15
const-string v11, "ff"
move-object/from16 v0, p3
invoke-virtual {v0, v11}, Ljava/lang/String;->startsWith(Ljava/lang/String;)Z
move-result v11
if-nez v11, :cond_16
move-object/from16 v0, p3
move-object/from16 v1, p2
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_18
.line 163
:cond_16
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
move-object/from16 v0, p3
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, "2"
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
const/4 v12, 0x1
move-object/from16 v0, p0
invoke-static {v0, v11, v12}, Landroid/provider/Telephony$SIMInfo;->insertICCId(Landroid/content/Context;Ljava/lang/String;I)Landroid/net/Uri;
.line 164
const-string/jumbo v11, "onAllIccidQueryComplete special SIM with invalid ICCID is inserted in slot2"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 168
:cond_17
:goto_b
move-object/from16 v0, p3
move-object/from16 v1, v37
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_b
.line 171
add-int/lit8 v31, v31, 0x1
.line 172
or-int/lit8 v32, v32, 0x2
goto/16 :goto_6
.line 165
:cond_18
move-object/from16 v0, p3
move-object/from16 v1, v37
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_17
.line 166
const/4 v11, 0x1
move-object/from16 v0, p0
move-object/from16 v1, p3
invoke-static {v0, v1, v11}, Landroid/provider/Telephony$SIMInfo;->insertICCId(Landroid/content/Context;Ljava/lang/String;I)Landroid/net/Uri;
goto :goto_b
.line 180
.restart local v5 #simIdForSlot1:J
.restart local v7 #simIdForSlot2:J
.restart local v44 #simInfos:Ljava/util/List;,"Ljava/util/List<Landroid/provider/Telephony$SIMInfo;>;"
:cond_19
invoke-interface/range {v44 .. v44}, Ljava/util/List;->size()I
move-result v33
goto/16 :goto_7
.line 185
.restart local v26 #i:I
.restart local v33 #nSIMCount:I
.restart local v47 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_1a
move-object/from16 v0, v47
iget v11, v0, Landroid/provider/Telephony$SIMInfo;->mSlot:I
const/4 v12, 0x1
if-ne v11, v12, :cond_c
.line 186
move-object/from16 v0, v47
iget-wide v7, v0, Landroid/provider/Telephony$SIMInfo;->mSimId:J
goto/16 :goto_9
.line 189
.end local v47 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_1b
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete simIdForSlot ["
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11, v5, v6}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11, v7, v8}, Ljava/lang/StringBuilder;->append(J)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, "]"
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 191
if-lez v31, :cond_1c
.line 192
const-string/jumbo v11, "onAllIccidQueryComplete New SIM detected. "
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 193
move-object/from16 v0, v44
move-object/from16 v1, p0
invoke-static {v0, v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->setColorForNewSIM(Ljava/util/List;Landroid/content/Context;)V
.line 194
const-string v11, "airplane_mode_on"
const/4 v12, 0x0
move-object/from16 v0, v19
invoke-static {v0, v11, v12}, Landroid/provider/Settings$System;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I
move-result v17
.line 195
.local v17, airplaneMode:I
if-lez v17, :cond_28
.line 196
move-object/from16 v0, v44
move-object/from16 v1, p0
invoke-static {v0, v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->setDefaultNameForAllNewSIM(Ljava/util/List;Landroid/content/Context;)V
.line 205
.end local v17 #airplaneMode:I
:cond_1c
:goto_c
const-string/jumbo v11, "video_call_sim_setting"
const-wide/16 v12, -0x5
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->getLong(Landroid/content/ContentResolver;Ljava/lang/String;J)J
move-result-wide v40
.line 206
.local v40, oldVTDefaultSIM:J
const-string/jumbo v11, "voice_call_sim_setting"
const-wide/16 v12, -0x5
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->getLong(Landroid/content/ContentResolver;Ljava/lang/String;J)J
move-result-wide v3
.line 208
.local v3, oldVoiceCallDefaultSIM:J
const-string/jumbo v11, "sms_sim_setting"
const-wide/16 v12, -0x5
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->getLong(Landroid/content/ContentResolver;Ljava/lang/String;J)J
move-result-wide v9
.line 209
.local v9, oldSmsDefaultSIM:J
const-string v11, "gprs_connection_sim_setting"
const-wide/16 v12, -0x5
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->getLong(Landroid/content/ContentResolver;Ljava/lang/String;J)J
move-result-wide v34
.line 229
.local v34, oldGprsDefaultSIM:J
const-string v11, "connectivity"
move-object/from16 v0, p0
invoke-virtual {v0, v11}, Landroid/content/Context;->getSystemService(Ljava/lang/String;)Ljava/lang/Object;
move-result-object v18
check-cast v18, Landroid/net/ConnectivityManager;
.line 230
.local v18, connectivityManager:Landroid/net/ConnectivityManager;
const/4 v11, 0x1
move/from16 v0, v33
if-le v0, v11, :cond_2b
.line 231
const-wide/16 v11, -0x5
cmp-long v11, v3, v11
if-nez v11, :cond_1d
.line 232
const-string/jumbo v11, "voice_call_sim_setting"
const-wide/16 v12, -0x1
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
.line 236
:cond_1d
const-wide/16 v11, -0x5
cmp-long v11, v9, v11
if-nez v11, :cond_1e
.line 237
const-string/jumbo v11, "sms_sim_setting"
const-wide/16 v12, -0x1
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
.line 241
:cond_1e
const-wide/16 v11, -0x5
cmp-long v11, v34, v11
if-nez v11, :cond_1f
.line 242
invoke-interface/range {v46 .. v46}, Lcom/mediatek/common/telephony/ITelephonyExt;->isDefaultDataOn()Z
move-result v11
if-eqz v11, :cond_2a
.line 243
if-eqz p4, :cond_29
.line 244
const/4 v11, 0x1
move-object/from16 v0, v18
invoke-virtual {v0, v11}, Landroid/net/ConnectivityManager;->setMobileDataEnabledGemini(I)Z
.line 280
:cond_1f
:goto_d
const-string v11, ""
move-object/from16 v0, p2
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_20
const-string v11, ""
move-object/from16 v0, v36
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_21
:cond_20
const-string v11, ""
move-object/from16 v0, p3
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_2e
const-string v11, ""
move-object/from16 v0, v37
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_2e
:cond_21
const/16 v25, 0x1
.line 281
.local v25, hasSIMRemoved:Z
:goto_e
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete. handling SIM detect dialog ["
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, p2
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, p3
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, v36
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move-object/from16 v0, v37
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move/from16 v0, v31
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move/from16 v0, v25
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(Z)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, ", "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
move/from16 v0, v33
invoke-virtual {v11, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, "]"
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 284
const-wide/16 v20, -0x5
.line 285
.local v20, defSIM:J
const/4 v11, 0x1
move/from16 v0, v33
if-le v0, v11, :cond_2f
.line 286
const-wide/16 v20, -0x1
.line 291
:cond_22
:goto_f
invoke-static/range {v3 .. v8}, Lcom/android/internal/telephony/DefaultSIMSettings;->isSIMRemoved(JJJ)Z
move-result v11
if-eqz v11, :cond_23
.line 292
const-string/jumbo v11, "voice_call_sim_setting"
move-object/from16 v0, v19
move-wide/from16 v1, v20
invoke-static {v0, v11, v1, v2}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
:cond_23
move-wide v11, v5
move-wide v13, v7
.line 295
invoke-static/range {v9 .. v14}, Lcom/android/internal/telephony/DefaultSIMSettings;->isSIMRemoved(JJJ)Z
move-result v11
if-eqz v11, :cond_24
.line 296
const-string/jumbo v11, "sms_sim_setting"
move-object/from16 v0, v19
move-wide/from16 v1, v20
invoke-static {v0, v11, v1, v2}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
:cond_24
move-wide/from16 v11, v34
move-wide v13, v5
move-wide v15, v7
.line 347
invoke-static/range {v11 .. v16}, Lcom/android/internal/telephony/DefaultSIMSettings;->isSIMRemoved(JJJ)Z
move-result v11
if-eqz v11, :cond_25
.line 348
const-string v11, "gprs_connection_sim_setting"
const-wide/16 v12, 0x0
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
.line 353
:cond_25
if-nez v31, :cond_34
.line 354
if-nez v25, :cond_30
move-object/from16 v0, p2
move-object/from16 v1, v36
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_30
move-object/from16 v0, p3
move-object/from16 v1, v37
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_30
.line 355
const-string/jumbo v11, "onAllIccidQueryComplete. all SIM inserted into the same slot"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 370
:cond_26
:goto_10
const-string v11, "gprs_connection_sim_setting"
const-wide/16 v12, -0x5
move-object/from16 v0, v19
invoke-static {v0, v11, v12, v13}, Landroid/provider/Settings$System;->getLong(Landroid/content/ContentResolver;Ljava/lang/String;J)J
move-result-wide v23
.line 371
.local v23, gprsDefaultSIM:J
const-wide/16 v11, -0x5
cmp-long v11, v23, v11
if-eqz v11, :cond_27
const-wide/16 v11, 0x0
cmp-long v11, v23, v11
if-eqz v11, :cond_27
.line 372
move-object/from16 v0, p0
move-wide/from16 v1, v23
invoke-static {v0, v1, v2}, Landroid/provider/Telephony$SIMInfo;->getSlotById(Landroid/content/Context;J)I
move-result v45
.line 373
.local v45, slot:I
const/4 v11, -0x1
move/from16 v0, v45
if-eq v0, v11, :cond_35
.line 376
move-object/from16 v0, v18
move/from16 v1, v45
invoke-virtual {v0, v1}, Landroid/net/ConnectivityManager;->setMobileDataEnabledGemini(I)Z
.line 425
.end local v45 #slot:I
:cond_27
:goto_11
const-string v11, "gsm.siminfo.ready"
const-string/jumbo v12, "true"
invoke-static {v11, v12}, Landroid/os/SystemProperties;->set(Ljava/lang/String;Ljava/lang/String;)V
.line 426
new-instance v11, Ljava/lang/StringBuilder;
invoke-direct {v11}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v12, "onAllIccidQueryComplete PROPERTY_SIM_INFO_READY after set is "
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
const-string v12, "gsm.siminfo.ready"
const/4 v13, 0x0
invoke-static {v12, v13}, Landroid/os/SystemProperties;->get(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
move-result-object v12
invoke-virtual {v11, v12}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v11
invoke-virtual {v11}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v11
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 428
new-instance v27, Landroid/content/Intent;
const-string v11, "android.intent.action.SIM_INFO_UPDATE"
move-object/from16 v0, v27
invoke-direct {v0, v11}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 429
.local v27, intent:Landroid/content/Intent;
const-string v11, "broadCast intent ACTION_SIM_INFO_UPDATE"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 430
const-string v11, "android.permission.READ_PHONE_STATE"
move-object/from16 v0, v27
invoke-static {v0, v11}, Landroid/app/ActivityManagerNative;->broadcastStickyIntent(Landroid/content/Intent;Ljava/lang/String;)V
:try_end_3
.catchall {:try_start_3 .. :try_end_3} :catchall_0
.line 436
monitor-exit v49
return-void
.line 198
.end local v3 #oldVoiceCallDefaultSIM:J
.end local v9 #oldSmsDefaultSIM:J
.end local v18 #connectivityManager:Landroid/net/ConnectivityManager;
.end local v20 #defSIM:J
.end local v23 #gprsDefaultSIM:J
.end local v25 #hasSIMRemoved:Z
.end local v27 #intent:Landroid/content/Intent;
.end local v34 #oldGprsDefaultSIM:J
.end local v40 #oldVTDefaultSIM:J
.restart local v17 #airplaneMode:I
:cond_28
:try_start_4
move-object/from16 v0, v44
move-object/from16 v1, p0
invoke-static {v0, v1}, Lcom/android/internal/telephony/DefaultSIMSettings;->setDefaultNameIfImsiReadyOrLocked(Ljava/util/List;Landroid/content/Context;)V
goto/16 :goto_c
.line 246
.end local v17 #airplaneMode:I
.restart local v3 #oldVoiceCallDefaultSIM:J
.restart local v9 #oldSmsDefaultSIM:J
.restart local v18 #connectivityManager:Landroid/net/ConnectivityManager;
.restart local v34 #oldGprsDefaultSIM:J
.restart local v40 #oldVTDefaultSIM:J
:cond_29
const/4 v11, 0x0
move-object/from16 v0, v18
invoke-virtual {v0, v11}, Landroid/net/ConnectivityManager;->setMobileDataEnabledGemini(I)Z
goto/16 :goto_d
.line 248
:cond_2a
const/4 v11, 0x0
move-object/from16 v0, v18
invoke-virtual {v0, v11}, Landroid/net/ConnectivityManager;->setMobileDataEnabled(Z)V
goto/16 :goto_d
.line 251
:cond_2b
const/4 v11, 0x1
move/from16 v0, v33
if-ne v0, v11, :cond_1f
.line 252
const/4 v11, 0x0
move-object/from16 v0, v44
invoke-interface {v0, v11}, Ljava/util/List;->get(I)Ljava/lang/Object;
move-result-object v11
check-cast v11, Landroid/provider/Telephony$SIMInfo;
iget-wide v0, v11, Landroid/provider/Telephony$SIMInfo;->mSimId:J
move-wide/from16 v42, v0
.line 253
.local v42, simId:J
const-string v11, "enable_internet_call_value"
const/4 v12, 0x0
move-object/from16 v0, v19
invoke-static {v0, v11, v12}, Landroid/provider/Settings$System;->getInt(Landroid/content/ContentResolver;Ljava/lang/String;I)I
move-result v30
.line 254
.local v30, isVoipEnabled:I
invoke-static/range {p0 .. p0}, Landroid/net/sip/SipManager;->isVoipSupported(Landroid/content/Context;)Z
move-result v11
if-eqz v11, :cond_2c
if-eqz v30, :cond_2c
const-wide/16 v11, -0x5
cmp-long v11, v3, v11
if-nez v11, :cond_2d
.line 257
:cond_2c
const-string/jumbo v11, "voice_call_sim_setting"
move-object/from16 v0, v19
move-wide/from16 v1, v42
invoke-static {v0, v11, v1, v2}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
.line 260
:cond_2d
const-string/jumbo v11, "sms_sim_setting"
move-object/from16 v0, v19
move-wide/from16 v1, v42
invoke-static {v0, v11, v1, v2}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
.line 274
const-wide/16 v11, -0x5
cmp-long v11, v34, v11
if-nez v11, :cond_1f
.line 275
const-string v11, "gprs_connection_sim_setting"
move-object/from16 v0, v19
move-wide/from16 v1, v42
invoke-static {v0, v11, v1, v2}, Landroid/provider/Settings$System;->putLong(Landroid/content/ContentResolver;Ljava/lang/String;J)Z
goto/16 :goto_d
.line 280
.end local v30 #isVoipEnabled:I
.end local v42 #simId:J
:cond_2e
const/16 v25, 0x0
goto/16 :goto_e
.line 287
.restart local v20 #defSIM:J
.restart local v25 #hasSIMRemoved:Z
:cond_2f
const/4 v11, 0x1
move/from16 v0, v33
if-ne v0, v11, :cond_22
.line 288
const/4 v11, 0x0
move-object/from16 v0, v44
invoke-interface {v0, v11}, Ljava/util/List;->get(I)Ljava/lang/Object;
move-result-object v11
check-cast v11, Landroid/provider/Telephony$SIMInfo;
iget-wide v0, v11, Landroid/provider/Telephony$SIMInfo;->mSimId:J
move-wide/from16 v20, v0
goto/16 :goto_f
.line 357
:cond_30
const-string v11, ""
move-object/from16 v0, p2
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_31
move-object/from16 v0, p2
move-object/from16 v1, v37
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_32
:cond_31
const-string v11, ""
move-object/from16 v0, p3
invoke-virtual {v0, v11}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-nez v11, :cond_33
move-object/from16 v0, p3
move-object/from16 v1, v36
invoke-virtual {v0, v1}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v11
if-eqz v11, :cond_33
.line 358
:cond_32
const-string/jumbo v11, "onAllIccidQueryComplete. SIM swapped"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 359
const-string v11, "SWAP"
move-object/from16 v0, p0
move/from16 v1, v33
move/from16 v2, v32
invoke-static {v0, v11, v1, v2}, Lcom/android/internal/telephony/DefaultSIMSettings;->onSIMDetected(Landroid/content/Context;Ljava/lang/String;II)V
goto/16 :goto_10
.line 360
:cond_33
if-lez v33, :cond_26
.line 361
const-string/jumbo v11, "onAllIccidQueryComplete No new SIM detected and Default SIM for some service has been removed[A]"
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 362
const-string v11, "REMOVE"
move-object/from16 v0, p0
move/from16 v1, v33
move/from16 v2, v32
invoke-static {v0, v11, v1, v2}, Lcom/android/internal/telephony/DefaultSIMSettings;->onSIMDetected(Landroid/content/Context;Ljava/lang/String;II)V
goto/16 :goto_10
.line 366
:cond_34
const-string v11, "getAllIccIdsDone. New SIM detected."
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 367
const-string v11, "NEW"
move-object/from16 v0, p0
move/from16 v1, v33
move/from16 v2, v32
invoke-static {v0, v11, v1, v2}, Lcom/android/internal/telephony/DefaultSIMSettings;->onSIMDetected(Landroid/content/Context;Ljava/lang/String;II)V
goto/16 :goto_10
.line 378
.restart local v23 #gprsDefaultSIM:J
.restart local v45 #slot:I
:cond_35
const-string/jumbo v11, "onAllIccidQueryComplete: gprsDefaultSIM does not exist in slot then skip."
invoke-static {v11}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
:try_end_4
.catchall {:try_start_4 .. :try_end_4} :catchall_0
goto/16 :goto_11
.end method
.method private static onSIMDetected(Landroid/content/Context;Ljava/lang/String;II)V
.locals 2
.parameter "context"
.parameter "detectStatus"
.parameter "nSIMCount"
.parameter "nNewSIMStatus"
.prologue
.line 552
new-instance v0, Landroid/content/Intent;
const-string v1, "ACTION_ON_SIM_DETECTED"
invoke-direct {v0, v1}, Landroid/content/Intent;-><init>(Ljava/lang/String;)V
.line 553
.local v0, intent:Landroid/content/Intent;
const-string/jumbo v1, "simCount"
invoke-virtual {v0, v1, p2}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 554
const-string/jumbo v1, "newSIMStatus"
invoke-virtual {v0, v1, p3}, Landroid/content/Intent;->putExtra(Ljava/lang/String;I)Landroid/content/Intent;
.line 555
const-string/jumbo v1, "simDetectStatus"
invoke-virtual {v0, v1, p1}, Landroid/content/Intent;->putExtra(Ljava/lang/String;Ljava/lang/String;)Landroid/content/Intent;
.line 556
invoke-virtual {p0, v0}, Landroid/content/Context;->sendBroadcast(Landroid/content/Intent;)V
.line 557
return-void
.end method
.method private static setColorForNewSIM(Ljava/util/List;Landroid/content/Context;)V
.locals 13
.parameter
.parameter "context"
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/util/List",
"<",
"Landroid/provider/Telephony$SIMInfo;",
">;",
"Landroid/content/Context;",
")V"
}
.end annotation
.prologue
.line 472
.local p0, simInfos:Ljava/util/List;,"Ljava/util/List<Landroid/provider/Telephony$SIMInfo;>;"
const/4 v4, 0x0
.line 473
.local v4, simToSet:I
const/4 v9, 0x0
invoke-static {p1, v9}, Landroid/provider/Telephony$SIMInfo;->getSIMInfoBySlot(Landroid/content/Context;I)Landroid/provider/Telephony$SIMInfo;
move-result-object v2
.line 474
.local v2, simInfo1:Landroid/provider/Telephony$SIMInfo;
const/4 v0, -0x1
.line 475
.local v0, sim1Color:I
const/4 v1, -0x1
.line 476
.local v1, sim2Color:I
if-eqz v2, :cond_2
.line 477
iget v0, v2, Landroid/provider/Telephony$SIMInfo;->mColor:I
.line 478
if-ltz v0, :cond_0
const/4 v9, 0x3
if-le v0, v9, :cond_1
.line 479
:cond_0
or-int/lit8 v4, v4, 0x1
.line 481
:cond_1
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v10, "setColorForNewSIM SimInfo sim1Color is "
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 483
:cond_2
const/4 v9, 0x1
invoke-static {p1, v9}, Landroid/provider/Telephony$SIMInfo;->getSIMInfoBySlot(Landroid/content/Context;I)Landroid/provider/Telephony$SIMInfo;
move-result-object v3
.line 484
.local v3, simInfo2:Landroid/provider/Telephony$SIMInfo;
if-eqz v3, :cond_5
.line 485
iget v1, v3, Landroid/provider/Telephony$SIMInfo;->mColor:I
.line 486
if-ltz v1, :cond_3
const/4 v9, 0x3
if-le v1, v9, :cond_4
.line 487
:cond_3
or-int/lit8 v4, v4, 0x2
.line 489
:cond_4
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v10, "setColorForNewSIM SimInfo sim2Color is "
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 491
:cond_5
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v10, "simToSet is"
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 492
packed-switch v4, :pswitch_data_0
.line 536
const-string v9, "No need to set color"
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 539
:goto_0
return-void
.line 494
:pswitch_0
new-instance v5, Landroid/content/ContentValues;
const/4 v9, 0x1
invoke-direct {v5, v9}, Landroid/content/ContentValues;-><init>(I)V
.line 495
.local v5, value1:Landroid/content/ContentValues;
iget-wide v9, v2, Landroid/provider/Telephony$SIMInfo;->mSimId:J
const-wide/16 v11, 0x1
sub-long/2addr v9, v11
long-to-int v9, v9
rem-int/lit8 v0, v9, 0x4
.line 496
const-string v9, "color"
invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
move-result-object v10
invoke-virtual {v5, v9, v10}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V
.line 497
invoke-virtual {p1}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v9
sget-object v10, Landroid/provider/Telephony$SimInfo;->CONTENT_URI:Landroid/net/Uri;
iget-wide v11, v2, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {v10, v11, v12}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;
move-result-object v10
const/4 v11, 0x0
const/4 v12, 0x0
invoke-virtual {v9, v10, v5, v11, v12}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
.line 499
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string v10, "case3: setColorForNewSIM SimInfo set color SIM in slot0 to "
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 500
new-instance v6, Landroid/content/ContentValues;
const/4 v9, 0x1
invoke-direct {v6, v9}, Landroid/content/ContentValues;-><init>(I)V
.line 501
.local v6, value2:Landroid/content/ContentValues;
iget-wide v9, v3, Landroid/provider/Telephony$SIMInfo;->mSimId:J
const-wide/16 v11, 0x1
sub-long/2addr v9, v11
long-to-int v9, v9
rem-int/lit8 v1, v9, 0x4
.line 502
const-string v9, "color"
invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
move-result-object v10
invoke-virtual {v6, v9, v10}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V
.line 503
invoke-virtual {p1}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v9
sget-object v10, Landroid/provider/Telephony$SimInfo;->CONTENT_URI:Landroid/net/Uri;
iget-wide v11, v3, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {v10, v11, v12}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;
move-result-object v10
const/4 v11, 0x0
const/4 v12, 0x0
invoke-virtual {v9, v10, v6, v11, v12}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
.line 505
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string v10, "case3: setColorForNewSIM SimInfo set color SIM in slot1 to "
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
goto :goto_0
.line 508
.end local v5 #value1:Landroid/content/ContentValues;
.end local v6 #value2:Landroid/content/ContentValues;
:pswitch_1
new-instance v7, Landroid/content/ContentValues;
const/4 v9, 0x1
invoke-direct {v7, v9}, Landroid/content/ContentValues;-><init>(I)V
.line 509
.local v7, valueColor:Landroid/content/ContentValues;
iget-wide v9, v3, Landroid/provider/Telephony$SIMInfo;->mSimId:J
const-wide/16 v11, 0x1
sub-long/2addr v9, v11
long-to-int v9, v9
rem-int/lit8 v1, v9, 0x4
.line 510
if-ne v1, v0, :cond_6
.line 511
add-int/lit8 v9, v0, 0x1
rem-int/lit8 v1, v9, 0x4
.line 513
:cond_6
const-string v9, "color"
invoke-static {v1}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
move-result-object v10
invoke-virtual {v7, v9, v10}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V
.line 514
invoke-virtual {p1}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v9
sget-object v10, Landroid/provider/Telephony$SimInfo;->CONTENT_URI:Landroid/net/Uri;
iget-wide v11, v3, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {v10, v11, v12}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;
move-result-object v10
const/4 v11, 0x0
const/4 v12, 0x0
invoke-virtual {v9, v10, v7, v11, v12}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
.line 516
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string v10, "case2: setColorForNewSIM SimInfo set color SIM in slot1 to "
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
goto/16 :goto_0
.line 519
.end local v7 #valueColor:Landroid/content/ContentValues;
:pswitch_2
new-instance v8, Landroid/content/ContentValues;
const/4 v9, 0x1
invoke-direct {v8, v9}, Landroid/content/ContentValues;-><init>(I)V
.line 522
.local v8, valueColor1:Landroid/content/ContentValues;
const/4 v0, 0x0
.line 530
const-string v9, "color"
invoke-static {v0}, Ljava/lang/Integer;->valueOf(I)Ljava/lang/Integer;
move-result-object v10
invoke-virtual {v8, v9, v10}, Landroid/content/ContentValues;->put(Ljava/lang/String;Ljava/lang/Integer;)V
.line 531
invoke-virtual {p1}, Landroid/content/Context;->getContentResolver()Landroid/content/ContentResolver;
move-result-object v9
sget-object v10, Landroid/provider/Telephony$SimInfo;->CONTENT_URI:Landroid/net/Uri;
iget-wide v11, v2, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {v10, v11, v12}, Landroid/content/ContentUris;->withAppendedId(Landroid/net/Uri;J)Landroid/net/Uri;
move-result-object v10
const/4 v11, 0x0
const/4 v12, 0x0
invoke-virtual {v9, v10, v8, v11, v12}, Landroid/content/ContentResolver;->update(Landroid/net/Uri;Landroid/content/ContentValues;Ljava/lang/String;[Ljava/lang/String;)I
.line 533
new-instance v9, Ljava/lang/StringBuilder;
invoke-direct {v9}, Ljava/lang/StringBuilder;-><init>()V
const-string v10, "case1:setColorForNewSIM SimInfo set color SIM in slot0 to "
invoke-virtual {v9, v10}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v9
invoke-virtual {v9}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v9
invoke-static {v9}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
goto/16 :goto_0
.line 492
nop
:pswitch_data_0
.packed-switch 0x1
:pswitch_2
:pswitch_1
:pswitch_0
.end packed-switch
.end method
.method private static setDefaultNameForAllNewSIM(Ljava/util/List;Landroid/content/Context;)V
.locals 6
.parameter
.parameter "context"
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/util/List",
"<",
"Landroid/provider/Telephony$SIMInfo;",
">;",
"Landroid/content/Context;",
")V"
}
.end annotation
.prologue
.line 439
.local p0, simInfos:Ljava/util/List;,"Ljava/util/List<Landroid/provider/Telephony$SIMInfo;>;"
if-nez p0, :cond_1
const/4 v1, 0x0
.line 440
.local v1, nSIMCount:I
:goto_0
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v4, "setDefaultNameForAll nSIMCount is "
invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v3}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 441
const/4 v0, 0x0
.local v0, i:I
:goto_1
if-ge v0, v1, :cond_2
.line 442
invoke-interface {p0, v0}, Ljava/util/List;->get(I)Ljava/lang/Object;
move-result-object v2
check-cast v2, Landroid/provider/Telephony$SIMInfo;
.line 443
.local v2, temp:Landroid/provider/Telephony$SIMInfo;
iget-object v3, v2, Landroid/provider/Telephony$SIMInfo;->mDisplayName:Ljava/lang/String;
if-nez v3, :cond_0
.line 444
new-instance v3, Ljava/lang/StringBuilder;
invoke-direct {v3}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v4, "setDefaultNameForAll set default name for slot"
invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v3
iget v4, v2, Landroid/provider/Telephony$SIMInfo;->mSlot:I
invoke-virtual {v3, v4}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v3
invoke-virtual {v3}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v3
invoke-static {v3}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 445
iget-wide v3, v2, Landroid/provider/Telephony$SIMInfo;->mSimId:J
const/4 v5, 0x0
invoke-static {p1, v3, v4, v5}, Landroid/provider/Telephony$SIMInfo;->setDefaultName(Landroid/content/Context;JLjava/lang/String;)I
.line 441
:cond_0
add-int/lit8 v0, v0, 0x1
goto :goto_1
.line 439
.end local v0 #i:I
.end local v1 #nSIMCount:I
.end local v2 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_1
invoke-interface {p0}, Ljava/util/List;->size()I
move-result v1
goto :goto_0
.line 448
.restart local v0 #i:I
.restart local v1 #nSIMCount:I
:cond_2
return-void
.end method
.method private static setDefaultNameIfImsiReadyOrLocked(Ljava/util/List;Landroid/content/Context;)V
.locals 6
.parameter
.parameter "context"
.annotation system Ldalvik/annotation/Signature;
value = {
"(",
"Ljava/util/List",
"<",
"Landroid/provider/Telephony$SIMInfo;",
">;",
"Landroid/content/Context;",
")V"
}
.end annotation
.prologue
.line 451
.local p0, simInfos:Ljava/util/List;,"Ljava/util/List<Landroid/provider/Telephony$SIMInfo;>;"
if-nez p0, :cond_2
const/4 v1, 0x0
.line 452
.local v1, nSIMCount:I
:goto_0
new-instance v4, Ljava/lang/StringBuilder;
invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "setDefaultNameIfImsiReadyOrLocked nSIMCount is "
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, v1}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v4
invoke-static {v4}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 453
const/4 v2, 0x0
.line 454
.local v2, operatorName:Ljava/lang/String;
const/4 v0, 0x0
.local v0, i:I
:goto_1
if-ge v0, v1, :cond_4
.line 455
invoke-interface {p0, v0}, Ljava/util/List;->get(I)Ljava/lang/Object;
move-result-object v3
check-cast v3, Landroid/provider/Telephony$SIMInfo;
.line 456
.local v3, temp:Landroid/provider/Telephony$SIMInfo;
iget-object v4, v3, Landroid/provider/Telephony$SIMInfo;->mDisplayName:Ljava/lang/String;
if-nez v4, :cond_1
.line 457
new-instance v4, Ljava/lang/StringBuilder;
invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "setDefaultNameIfImsiReadyOrLocked the "
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, v0}, Ljava/lang/StringBuilder;->append(I)Ljava/lang/StringBuilder;
move-result-object v4
const-string/jumbo v5, "th mDisplayName is null "
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v4
invoke-static {v4}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 458
iget v4, v3, Landroid/provider/Telephony$SIMInfo;->mSlot:I
if-nez v4, :cond_3
.line 459
const-string v4, "gsm.sim.operator.default-name"
invoke-static {v4}, Landroid/os/SystemProperties;->get(Ljava/lang/String;)Ljava/lang/String;
move-result-object v2
.line 463
:cond_0
:goto_2
new-instance v4, Ljava/lang/StringBuilder;
invoke-direct {v4}, Ljava/lang/StringBuilder;-><init>()V
const-string/jumbo v5, "setDefaultNameIfImsiReadyOrLocked operatorName is "
invoke-virtual {v4, v5}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4, v2}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;
move-result-object v4
invoke-virtual {v4}, Ljava/lang/StringBuilder;->toString()Ljava/lang/String;
move-result-object v4
invoke-static {v4}, Lcom/android/internal/telephony/DefaultSIMSettings;->logd(Ljava/lang/String;)V
.line 464
if-eqz v2, :cond_1
const-string v4, ""
invoke-virtual {v2, v4}, Ljava/lang/String;->equals(Ljava/lang/Object;)Z
move-result v4
if-nez v4, :cond_1
.line 465
iget-wide v4, v3, Landroid/provider/Telephony$SIMInfo;->mSimId:J
invoke-static {p1, v4, v5, v2}, Landroid/provider/Telephony$SIMInfo;->setDefaultName(Landroid/content/Context;JLjava/lang/String;)I
.line 454
:cond_1
add-int/lit8 v0, v0, 0x1
goto :goto_1
.line 451
.end local v0 #i:I
.end local v1 #nSIMCount:I
.end local v2 #operatorName:Ljava/lang/String;
.end local v3 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_2
invoke-interface {p0}, Ljava/util/List;->size()I
move-result v1
goto :goto_0
.line 460
.restart local v0 #i:I
.restart local v1 #nSIMCount:I
.restart local v2 #operatorName:Ljava/lang/String;
.restart local v3 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_3
const/4 v4, 0x1
iget v5, v3, Landroid/provider/Telephony$SIMInfo;->mSlot:I
if-ne v4, v5, :cond_0
.line 461
const-string v4, "gsm.sim.operator.default-name.2"
invoke-static {v4}, Landroid/os/SystemProperties;->get(Ljava/lang/String;)Ljava/lang/String;
move-result-object v2
goto :goto_2
.line 469
.end local v3 #temp:Landroid/provider/Telephony$SIMInfo;
:cond_4
return-void
.end method
| {
"content_hash": "d66d850446d22132d117a6493002e32a",
"timestamp": "",
"source": "github",
"line_count": 2836,
"max_line_length": 173,
"avg_line_length": 26.2277856135402,
"alnum_prop": 0.6840095722083299,
"repo_name": "baidurom/devices-g520",
"id": "b46a75b210eb09bda9dfcf2b5e478470e28127a7",
"size": "74382",
"binary": false,
"copies": "2",
"ref": "refs/heads/coron-4.1",
"path": "framework.jar.out/smali/com/android/internal/telephony/DefaultSIMSettings.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Makefile",
"bytes": "12575"
},
{
"name": "Python",
"bytes": "1261"
},
{
"name": "Shell",
"bytes": "2159"
}
],
"symlink_target": ""
} |
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="description" content="BIT-101 Daily Open Source JavaScript and HTML Canvas Experiments">
<link rel="stylesheet" type="text/css" href="../styles/daily.css">
</head>
<body>
<script src="../js/ui.js"></script>
<script src="../libs/quicksettings_3_0_2.min.js"></script>
<script src="../libs/bitlib_1_0_5.min.js"></script>
<script>
var date = 170222;
var desc = "Splat!";
var issueNumber = 53;
setup(date, date - 1, date + 1, desc, issueNumber);
</script>
</body>
</html>
| {
"content_hash": "234f961b3418aa958823a8c85a4f58cf",
"timestamp": "",
"source": "github",
"line_count": 20,
"max_line_length": 104,
"avg_line_length": 28.55,
"alnum_prop": 0.637478108581436,
"repo_name": "bit101/lab",
"id": "ba4981092215ec8a21a7ebd01b888cd746bc5134",
"size": "571",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "dailies/170222.html",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3878"
},
{
"name": "HTML",
"bytes": "122218"
},
{
"name": "JavaScript",
"bytes": "545150"
},
{
"name": "Shell",
"bytes": "1166"
}
],
"symlink_target": ""
} |
require 'net/http'
module Stocktwits
module PlainUser
def self.included(base)
base.class_eval do
end
base.extend Stocktwits::PlainUser::ClassMethods
end
module ClassMethods
def verify_credentials(login, password)
response = Stocktwits.net.start { |http|
request = Net::HTTP::Get.new(Stocktwits.base_url + "/users/show/#{login}.json")
http.request(request)
}
if response.code == '200'
JSON.parse(response.body)
else
false
end
end
def authenticate(login, password = nil)
if stocktwits_hash = verify_credentials(login, password)
user = identify_or_create_from_stocktwits_hash_and_password(stocktwits_hash, password)
user
else
nil
end
end
def identify_or_create_from_stocktwits_hash_and_password(stocktwits_hash, password)
if user = User.find_by_stocktwits_id(stocktwits_hash['id'].to_s)
user.login = stocktwits_hash['login']
user.assign_stocktwits_attributes(stocktwits_hash)
user.save
user
else
user = User.new_from_stocktwits_hash(stocktwits_hash)
user.save
user
end
end
end
end
end
| {
"content_hash": "87b2efbad9f941620e76a90a1ef4081d",
"timestamp": "",
"source": "github",
"line_count": 53,
"max_line_length": 97,
"avg_line_length": 25.22641509433962,
"alnum_prop": 0.5781600598354525,
"repo_name": "eladmeidar/StockTwits",
"id": "3722b3d07be386e2656ea427c889a5ad85d0c812",
"size": "1337",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/stocktwits/plain_user.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Ruby",
"bytes": "73117"
}
],
"symlink_target": ""
} |
<!doctype html public "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=us-ascii">
<title> Postfix manual - pcre_table(5) </title>
</head> <body> <pre>
PCRE_TABLE(5) PCRE_TABLE(5)
<b>NAME</b>
pcre_table - format of Postfix PCRE tables
<b>SYNOPSIS</b>
<b>postmap -q "</b><i>string</i><b>" <a href="pcre_table.5.html">pcre</a>:/etc/postfix/</b><i>filename</i>
<b>postmap -q - <a href="pcre_table.5.html">pcre</a>:/etc/postfix/</b><i>filename</i> <<i>inputfile</i>
<b>DESCRIPTION</b>
The Postfix mail system uses optional tables for address rewriting,
mail routing, or access control. These tables are usually in <b>dbm</b> or <b>db</b>
format.
Alternatively, lookup tables can be specified in Perl Compatible Regu-
lar Expression form. In this case, each input is compared against a
list of patterns. When a match is found, the corresponding result is
returned and the search is terminated.
To find out what types of lookup tables your Postfix system supports
use the "<b>postconf -m</b>" command.
To test lookup tables, use the "<b>postmap -q</b>" command as described in the
SYNOPSIS above.
<b>COMPATIBILITY</b>
With Postfix version 2.2 and earlier specify "<b>postmap -fq</b>" to query a
table that contains case sensitive patterns. Patterns are case insensi-
tive by default.
<b>TABLE FORMAT</b>
The general form of a PCRE table is:
<b>/</b><i>pattern</i><b>/</b><i>flags result</i>
When <i>pattern</i> matches the input string, use the corresponding
<i>result</i> value.
<b>!/</b><i>pattern</i><b>/</b><i>flags result</i>
When <i>pattern</i> does <b>not</b> match the input string, use the corre-
sponding <i>result</i> value.
<b>if /</b><i>pattern</i><b>/</b><i>flags</i>
<b>endif</b> Match the input string against the patterns between <b>if</b> and
<b>endif</b>, if and only if that same input string also matches <i>pat-</i>
<i>tern</i>. The <b>if</b>..<b>endif</b> can nest.
Note: do not prepend whitespace to patterns inside <b>if</b>..<b>endif</b>.
This feature is available in Postfix 2.1 and later.
<b>if !/</b><i>pattern</i><b>/</b><i>flags</i>
<b>endif</b> Match the input string against the patterns between <b>if</b> and
<b>endif</b>, if and only if that same input string does <b>not</b> match <i>pat-</i>
<i>tern</i>. The <b>if</b>..<b>endif</b> can nest.
Note: do not prepend whitespace to patterns inside <b>if</b>..<b>endif</b>.
This feature is available in Postfix 2.1 and later.
blank lines and comments
Empty lines and whitespace-only lines are ignored, as are lines
whose first non-whitespace character is a `#'.
multi-line text
A logical line starts with non-whitespace text. A line that
starts with whitespace continues a logical line.
Each pattern is a perl-like regular expression. The expression delim-
iter can be any non-alphanumerical character, except whitespace or
characters that have special meaning (traditionally the forward slash
is used). The regular expression can contain whitespace.
By default, matching is case-insensitive, and newlines are not treated
as special characters. The behavior is controlled by flags, which are
toggled by appending one or more of the following characters after the
pattern:
<b>i</b> (default: on)
Toggles the case sensitivity flag. By default, matching is case
insensitive.
<b>m</b> (default: off)
Toggles the PCRE_MULTILINE flag. When this flag is on, the <b>^</b> and
<b>$</b> metacharacters match immediately after and immediately before
a newline character, respectively, in addition to matching at
the start and end of the subject string.
<b>s</b> (default: on)
Toggles the PCRE_DOTALL flag. When this flag is on, the <b>.</b>
metacharacter matches the newline character. With Postfix ver-
sions prior to 2.0, the flag is off by default, which is incon-
venient for multi-line message header matching.
<b>x</b> (default: off)
Toggles the pcre extended flag. When this flag is on, whitespace
characters in the pattern (other than in a character class) are
ignored. To include a whitespace character as part of the pat-
tern, escape it with backslash.
Note: do not use <b>#</b><i>comment</i> after patterns.
<b>A</b> (default: off)
Toggles the PCRE_ANCHORED flag. When this flag is on, the pat-
tern is forced to be "anchored", that is, it is constrained to
match only at the start of the string which is being searched
(the "subject string"). This effect can also be achieved by
appropriate constructs in the pattern itself.
<b>E</b> (default: off)
Toggles the PCRE_DOLLAR_ENDONLY flag. When this flag is on, a <b>$</b>
metacharacter in the pattern matches only at the end of the sub-
ject string. Without this flag, a dollar also matches immedi-
ately before the final character if it is a newline character
(but not before any other newline characters). This flag is
ignored if PCRE_MULTILINE flag is set.
<b>U</b> (default: off)
Toggles the ungreedy matching flag. When this flag is on, the
pattern matching engine inverts the "greediness" of the quanti-
fiers so that they are not greedy by default, but become greedy
if followed by "?". This flag can also set by a (?U) modifier
within the pattern.
<b>X</b> (default: off)
Toggles the PCRE_EXTRA flag. When this flag is on, any back-
slash in a pattern that is followed by a letter that has no spe-
cial meaning causes an error, thus reserving these combinations
for future expansion.
<b>SEARCH ORDER</b>
Patterns are applied in the order as specified in the table, until a
pattern is found that matches the input string.
Each pattern is applied to the entire input string. Depending on the
application, that string is an entire client hostname, an entire client
IP address, or an entire mail address. Thus, no parent domain or par-
ent network search is done, and <i>user@domain</i> mail addresses are not bro-
ken up into their <i>user</i> and <i>domain</i> constituent parts, nor is <i>user+foo</i>
broken up into <i>user</i> and <i>foo</i>.
<b>TEXT SUBSTITUTION</b>
Substitution of substrings (text that matches patterns inside "()")
from the matched expression into the result string is requested with
$1, $2, etc.; specify $$ to produce a $ character as output. The
macros in the result string may need to be written as ${n} or $(n) if
they aren't followed by whitespace.
Note: since negated patterns (those preceded by <b>!</b>) return a result when
the expression does not match, substitutions are not available for
negated patterns.
<b>EXAMPLE SMTPD ACCESS MAP</b>
# Protect your outgoing majordomo exploders
/^(?!owner-)(.*)-outgoing@(.*)/ 550 Use ${1}@${2} instead
# Bounce friend@whatever, except when whatever is our domain (you would
# be better just bouncing all friend@ mail - this is just an example).
/^(friend@(?!my\.domain$).*)$/ 550 Stick this in your pipe $1
# A multi-line entry. The text is sent as one line.
#
/^noddy@my\.domain$/
550 This user is a funny one. You really don't want to send mail to
them as it only makes their head spin.
<b>EXAMPLE HEADER FILTER MAP</b>
/^Subject: make money fast/ REJECT
/^To: friend@public\.com/ REJECT
<b>EXAMPLE BODY FILTER MAP</b>
# First skip over base 64 encoded text to save CPU cycles.
# Requires PCRE version 3.
~^[[:alnum:]+/]{60,}$~ OK
# Put your own body patterns here.
<b>SEE ALSO</b>
<a href="postmap.1.html">postmap(1)</a>, Postfix lookup table manager
<a href="postconf.5.html">postconf(5)</a>, configuration parameters
<a href="regexp_table.5.html">regexp_table(5)</a>, format of POSIX regular expression tables
<b>README FILES</b>
<a href="DATABASE_README.html">DATABASE_README</a>, Postfix lookup table overview
<b>AUTHOR(S)</b>
The PCRE table lookup code was originally written by:
Andrew McNamara
andrewm@connect.com.au
connect.com.au Pty. Ltd.
Level 3, 213 Miller St
North Sydney, NSW, Australia
Adopted and adapted by:
Wietse Venema
IBM T.J. Watson Research
P.O. Box 704
Yorktown Heights, NY 10598, USA
PCRE_TABLE(5)
</pre> </body> </html>
| {
"content_hash": "8b1f76e7fc9f3c75b935cd5bb43c795f",
"timestamp": "",
"source": "github",
"line_count": 209,
"max_line_length": 113,
"avg_line_length": 46.13875598086124,
"alnum_prop": 0.6085243181582495,
"repo_name": "execunix/vinos",
"id": "e686a7324bb612895e050f5cf7e9c83d1d4f81d3",
"size": "9643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "external/ibm-public/postfix/dist/html/pcre_table.5.html",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
FROM balenalib/beaglebone-pocket-debian:stretch-run
ENV GO_VERSION 1.15.11
# gcc for cgo
RUN apt-get update && apt-get install -y --no-install-recommends \
g++ \
gcc \
libc6-dev \
make \
pkg-config \
git \
&& rm -rf /var/lib/apt/lists/*
RUN set -x \
&& fetchDeps=' \
curl \
' \
&& apt-get update && apt-get install -y $fetchDeps --no-install-recommends && rm -rf /var/lib/apt/lists/* \
&& mkdir -p /usr/local/go \
&& curl -SLO "http://resin-packages.s3.amazonaws.com/golang/v$GO_VERSION/go$GO_VERSION.linux-armv7hf.tar.gz" \
&& echo "f5253eb04ed6b92e49cb0cbc57a80b4777ce27c6590e05a5c91095870e8632a0 go$GO_VERSION.linux-armv7hf.tar.gz" | sha256sum -c - \
&& tar -xzf "go$GO_VERSION.linux-armv7hf.tar.gz" -C /usr/local/go --strip-components=1 \
&& rm -f go$GO_VERSION.linux-armv7hf.tar.gz
ENV GOROOT /usr/local/go
ENV GOPATH /go
ENV PATH $GOPATH/bin:/usr/local/go/bin:$PATH
RUN mkdir -p "$GOPATH/src" "$GOPATH/bin" && chmod -R 777 "$GOPATH"
WORKDIR $GOPATH
CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"]
RUN curl -SLO "https://raw.githubusercontent.com/balena-io-library/base-images/8accad6af708fca7271c5c65f18a86782e19f877/scripts/assets/tests/test-stack@golang.sh" \
&& echo "Running test-stack@golang" \
&& chmod +x test-stack@golang.sh \
&& bash test-stack@golang.sh \
&& rm -rf test-stack@golang.sh
RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Debian Stretch \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nGo v1.15.11 \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info
RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \
&& chmod +x /bin/sh-shim \
&& cp /bin/sh /bin/sh.real \
&& mv /bin/sh-shim /bin/sh | {
"content_hash": "36055f5d7383832078e608548f28c692",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 674,
"avg_line_length": 50.95652173913044,
"alnum_prop": 0.7077645051194539,
"repo_name": "nghiant2710/base-images",
"id": "2c453e5b98f90a09a5d49103e15aac01c1f48d3d",
"size": "2365",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "balena-base-images/golang/beaglebone-pocket/debian/stretch/1.15.11/run/Dockerfile",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Dockerfile",
"bytes": "144558581"
},
{
"name": "JavaScript",
"bytes": "16316"
},
{
"name": "Shell",
"bytes": "368690"
}
],
"symlink_target": ""
} |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("eXpand.XafMVVM.Module.Win")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("-")]
[assembly: AssemblyProduct("eXpand.XafMVVM.Module.Win")]
[assembly: AssemblyCopyright("Copyright © - 2007")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
| {
"content_hash": "7652a713a4eea5a66125082552505454",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 84,
"avg_line_length": 37.4375,
"alnum_prop": 0.7462437395659433,
"repo_name": "biohazard999/XafMVVM",
"id": "727bd131d59555abe3bb7ecfb41fa049e21e95e1",
"size": "1201",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/XMVVM/XMVVM.ExpressApp.Demos/XMVVM.ExpressApp.Demos.Module.Win/Properties/AssemblyInfo.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "10155"
},
{
"name": "C#",
"bytes": "54237"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
Interim Register of Marine and Nonmarine Genera
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "74ae51aea1e809fc0aa0fc48d6690726",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 47,
"avg_line_length": 10.923076923076923,
"alnum_prop": 0.7183098591549296,
"repo_name": "mdoering/backbone",
"id": "d1494ee8abac9d140fdeeee7ce69f81badc380c7",
"size": "215",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Quilonipollenites/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
package org.springframework.web.servlet.tags;
import junit.framework.TestCase;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockPageContext;
import org.springframework.mock.web.MockServletContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.SimpleWebApplicationContext;
import org.springframework.web.servlet.ThemeResolver;
import org.springframework.web.servlet.i18n.AcceptHeaderLocaleResolver;
import org.springframework.web.servlet.theme.FixedThemeResolver;
/**
* Abstract base class for testing tags: provides createPageContext.
* @author Alef Arendsen
*/
public abstract class AbstractTagTests extends TestCase {
protected MockPageContext createPageContext() {
MockServletContext sc = new MockServletContext();
SimpleWebApplicationContext wac = new SimpleWebApplicationContext();
wac.setServletContext(sc);
wac.setNamespace("test");
wac.refresh();
MockHttpServletRequest request = new MockHttpServletRequest(sc);
request.setAttribute(DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE, wac);
LocaleResolver lr = new AcceptHeaderLocaleResolver();
request.setAttribute(DispatcherServlet.LOCALE_RESOLVER_ATTRIBUTE, lr);
ThemeResolver tr = new FixedThemeResolver();
request.setAttribute(DispatcherServlet.THEME_RESOLVER_ATTRIBUTE, tr);
return new MockPageContext(sc, request);
}
}
| {
"content_hash": "318176e3d389fad6f3f01b6d9c585cf3",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 81,
"avg_line_length": 37.05,
"alnum_prop": 0.8232118758434548,
"repo_name": "dachengxi/spring1.1.1_source",
"id": "b7e8be4f0821a8d9a2619b237da95367fbfcf8f5",
"size": "2105",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "test/org/springframework/web/servlet/tags/AbstractTagTests.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "163"
},
{
"name": "FreeMarker",
"bytes": "8024"
},
{
"name": "HTML",
"bytes": "34675"
},
{
"name": "Java",
"bytes": "5934573"
}
],
"symlink_target": ""
} |
START_ATF_NAMESPACE
namespace Info
{
using _INVEN_DB_BASEInit2_ptr = void (WINAPIV*)(struct _INVEN_DB_BASE*);
using _INVEN_DB_BASEInit2_clbk = void (WINAPIV*)(struct _INVEN_DB_BASE*, _INVEN_DB_BASEInit2_ptr);
using _INVEN_DB_BASEctor__INVEN_DB_BASE4_ptr = void (WINAPIV*)(struct _INVEN_DB_BASE*);
using _INVEN_DB_BASEctor__INVEN_DB_BASE4_clbk = void (WINAPIV*)(struct _INVEN_DB_BASE*, _INVEN_DB_BASEctor__INVEN_DB_BASE4_ptr);
}; // end namespace Info
END_ATF_NAMESPACE
| {
"content_hash": "d22e67639ae47652cf5e6e377bcc2f3c",
"timestamp": "",
"source": "github",
"line_count": 10,
"max_line_length": 136,
"avg_line_length": 52.2,
"alnum_prop": 0.6551724137931034,
"repo_name": "goodwinxp/Yorozuya",
"id": "fa88c5fb01b5b6629a4598e7c53dfe3a2724248c",
"size": "704",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "library/ATF/_INVEN_DB_BASEInfo.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "207291"
},
{
"name": "C++",
"bytes": "21670817"
}
],
"symlink_target": ""
} |
class ZTileInfo
{
public:
ZTileInfo();
inline const std::string& getSource() const {
return m_source;
}
inline const ZPoint& getOffset() const {
return m_offset;
}
inline int getWidth() const {
return m_dim[0];
}
inline int getHeight() const {
return m_dim[1];
}
inline int getDepth() const {
return m_dim[2];
}
inline const std::string& getImageSource() const {
return m_imageSourse;
}
bool loadJsonObject(const ZJsonObject &obj,QString tileFilePath);
private:
std::string m_source;
std::string m_imageSourse; //for projection
ZPoint m_offset;
int m_dim[3];
};
#endif // ZTILEINFO_H
| {
"content_hash": "e9704cecd6d02ce018396b1fdd290e3e",
"timestamp": "",
"source": "github",
"line_count": 40,
"max_line_length": 67,
"avg_line_length": 16.4,
"alnum_prop": 0.649390243902439,
"repo_name": "stephenplaza/NeuTu",
"id": "afe6d360e09000acb5bd78101d8be6a376fd9ca5",
"size": "780",
"binary": false,
"copies": "1",
"ref": "refs/heads/public",
"path": "neurolabi/gui/ztileinfo.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "Awk",
"bytes": "9874"
},
{
"name": "Batchfile",
"bytes": "5453"
},
{
"name": "C",
"bytes": "9049106"
},
{
"name": "C++",
"bytes": "111553246"
},
{
"name": "CMake",
"bytes": "110386"
},
{
"name": "CSS",
"bytes": "3042"
},
{
"name": "GLSL",
"bytes": "60560"
},
{
"name": "Gnuplot",
"bytes": "648"
},
{
"name": "HTML",
"bytes": "261818"
},
{
"name": "Makefile",
"bytes": "50563"
},
{
"name": "Matlab",
"bytes": "315"
},
{
"name": "Objective-C",
"bytes": "3265"
},
{
"name": "OpenEdge ABL",
"bytes": "499216"
},
{
"name": "Perl",
"bytes": "73775"
},
{
"name": "Perl6",
"bytes": "281846"
},
{
"name": "Python",
"bytes": "316458"
},
{
"name": "QMake",
"bytes": "62101"
},
{
"name": "RAML",
"bytes": "5215"
},
{
"name": "Shell",
"bytes": "486819"
}
],
"symlink_target": ""
} |
<?php
namespace Oro\Bundle\DataGridBundle\Tests\Functional\DataFixtures;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Oro\Bundle\OrganizationBundle\Entity\Organization;
use Oro\Bundle\UserBundle\Entity\Role;
use Oro\Bundle\UserBundle\Entity\User;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadUserData extends AbstractFixture implements ContainerAwareInterface
{
const SIMPLE_USER = 'simple_user';
const SIMPLE_USER_2 = 'simple_user2';
/** @var ContainerInterface */
protected $container;
/**
* {@inheritdoc}
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* {@inheritdoc}
*/
public function load(ObjectManager $manager)
{
$userManager = $this->container->get('oro_user.manager');
$organization = $manager->getRepository(Organization::class)->getFirst();
$role = $manager->getRepository(Role::class)->findOneBy(['role' => User::ROLE_DEFAULT]);
$user = $userManager->createUser();
$user->setUsername(self::SIMPLE_USER)
->setPlainPassword('simple_password')
->setEmail('simple_user@example.com')
->setFirstName('First Name')
->setLastName('Last Name')
->setOrganization($organization)
->setOrganizations(new ArrayCollection([$organization]))
->setOwner($organization->getBusinessUnits()->first())
->addRole($role)
->setEnabled(true);
$userManager->updateUser($user);
$this->setReference($user->getUsername(), $user);
$user = $userManager->createUser();
$user->setUsername(self::SIMPLE_USER_2)
->setPlainPassword('simple_password2')
->setEmail('simple_user2@example.com')
->setFirstName('First Name')
->setLastName('Last Name')
->setOrganization($organization)
->setOrganizations(new ArrayCollection([$organization]))
->setOwner($organization->getBusinessUnits()->first())
->addRole($role)
->setEnabled(true);
$userManager->updateUser($user);
$this->setReference($user->getUsername(), $user);
}
}
| {
"content_hash": "6a63a278443835df303f425693cca663",
"timestamp": "",
"source": "github",
"line_count": 68,
"max_line_length": 96,
"avg_line_length": 35.911764705882355,
"alnum_prop": 0.6482391482391482,
"repo_name": "orocrm/platform",
"id": "6e9cab0704c9fdb21c8099f295507ef99df914cb",
"size": "2442",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/Oro/Bundle/DataGridBundle/Tests/Functional/DataFixtures/LoadUserData.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "618485"
},
{
"name": "Gherkin",
"bytes": "158217"
},
{
"name": "HTML",
"bytes": "1648915"
},
{
"name": "JavaScript",
"bytes": "3326127"
},
{
"name": "PHP",
"bytes": "37828618"
}
],
"symlink_target": ""
} |
import torch
from allennlp.nn import util
from allennlp.common.testing import requires_gpu
@requires_gpu
def bench_add_sentence_boundary_token_ids(benchmark):
device = torch.device("cuda")
# shape: (32, 50)
tensor = torch.tensor([[3] * 50] * 32, device=device)
# shape: (32, 50)
mask = torch.tensor([[True] * 50, [True] * 30 + [False] * 20] * 16, device=device)
begin_token = 1
end_token = 2
benchmark(util.add_sentence_boundary_token_ids, tensor, mask, begin_token, end_token)
@requires_gpu
def bench_remove_sentence_boundaries(benchmark):
device = torch.device("cuda")
# shape: (32, 50, 1)
tensor = torch.tensor([[3] * 50] * 32, device=device).unsqueeze(-1)
# shape: (32, 50)
mask = torch.tensor([[True] * 50, [True] * 30 + [False] * 20] * 16, device=device)
benchmark(util.remove_sentence_boundaries, tensor, mask)
@requires_gpu
def bench_create_tensor_then_send_to_device(benchmark):
device = torch.device("cuda:0")
def create_tensor():
return torch.rand((32, 50)).to(device)
benchmark(create_tensor)
@requires_gpu
def bench_create_tensor_directly_on_device(benchmark):
device = torch.device("cuda:0")
def create_tensor():
return torch.rand((32, 50), device=device)
benchmark(create_tensor)
| {
"content_hash": "ef5efc8ee811e10a92d2ba439d78748f",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 89,
"avg_line_length": 28.347826086956523,
"alnum_prop": 0.6579754601226994,
"repo_name": "allenai/allennlp",
"id": "9f3d31e6a474214015549053b221ac238e0532d0",
"size": "1304",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "benchmarks/nn/util_bench.py",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "39870"
},
{
"name": "Dockerfile",
"bytes": "1190"
},
{
"name": "Jsonnet",
"bytes": "4469"
},
{
"name": "Makefile",
"bytes": "5306"
},
{
"name": "Perl",
"bytes": "101"
},
{
"name": "Python",
"bytes": "3575059"
},
{
"name": "Scilab",
"bytes": "4085"
},
{
"name": "Shell",
"bytes": "2092"
}
],
"symlink_target": ""
} |
package org.wyona.yanel.core.api.attributes;
/**
* RELEASED, do NOT change
*/
public interface VersionableV1 {
/**
*
*/
public String[] getRevisions();
}
| {
"content_hash": "1d374246875edb13748ca853dfa7ac29",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 44,
"avg_line_length": 12.714285714285714,
"alnum_prop": 0.6067415730337079,
"repo_name": "baszero/yanel",
"id": "86b538fd2d09926df9cb93c5430f9dfcbdef4980",
"size": "781",
"binary": false,
"copies": "2",
"ref": "refs/heads/upgrade8",
"path": "src/core/java/org/wyona/yanel/core/api/attributes/VersionableV1.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "29314"
},
{
"name": "CSS",
"bytes": "78551"
},
{
"name": "HTML",
"bytes": "1333652"
},
{
"name": "Java",
"bytes": "2394273"
},
{
"name": "JavaScript",
"bytes": "1489720"
},
{
"name": "NSIS",
"bytes": "6865"
},
{
"name": "Perl",
"bytes": "9821"
},
{
"name": "Python",
"bytes": "3285"
},
{
"name": "Shell",
"bytes": "48928"
},
{
"name": "XSLT",
"bytes": "599717"
}
],
"symlink_target": ""
} |
ActiveRecord::Schema.define(version: 2014_05_19_231105) do
create_table "museum_case_details", force: :cascade do |t|
t.integer "museum_case_id"
t.integer "museum_loupe_id"
t.string "key"
t.text "value"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["museum_loupe_id", "museum_case_id", "key"], name: "key", unique: true
end
create_table "museum_cases", force: :cascade do |t|
t.string "name"
t.string "title"
t.text "sort"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["name"], name: "index_museum_cases_on_name", unique: true
end
create_table "museum_loupes", force: :cascade do |t|
t.string "title"
t.string "slug"
t.string "uri_template"
t.string "data_format"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["slug"], name: "index_museum_loupes_on_slug", unique: true
end
end
| {
"content_hash": "5e1dc6dddc41b6bc1b7399aaff1302aa",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 83,
"avg_line_length": 30.75,
"alnum_prop": 0.6443089430894309,
"repo_name": "gemvein/museum",
"id": "bdb14fe6f9406b6ea9fd239cbd6cc3e64a0a87c6",
"size": "1707",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/dummy/db/schema.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "477"
},
{
"name": "HTML",
"bytes": "5177"
},
{
"name": "Ruby",
"bytes": "61004"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?><!--
Copyright (C) 2016 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.
-->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.android.explicitintent">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Android Studio will have created an Activity tag if you followed step 1 properly. Do -->
<!-- steps 8 - 11 within that tag. Please see the solution code if you get stuck. -->
<!-- COMPLETE (8) Specify ChildActivity's parent using android:parentActivityName -->
<!-- COMPLETE (9) Create a meta-data tag for this Activity -->
<!-- COMPLETE (10) Specify the name of the meta-data as android.support.PARENT_ACTIVITY -->
<!-- COMPLETE (11) Specify the value of the meta data as .MainActivity -->
<activity android:name=".ChildActivity">
android:name="com.example.android.explicitintent.ChildActivity"
android:parentActivityName=".MainActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".MainActivity" />
</activity>
</application>
</manifest> | {
"content_hash": "a73cda037a01caf7329f04a8080b2a44",
"timestamp": "",
"source": "github",
"line_count": 48,
"max_line_length": 101,
"avg_line_length": 45,
"alnum_prop": 0.662962962962963,
"repo_name": "CHaller6/ud851-Exercises",
"id": "e1d0de8e6f92b466ee06e69c9539b725813fb32d",
"size": "2160",
"binary": false,
"copies": "1",
"ref": "refs/heads/student",
"path": "Lesson04a-Starting-New-Activities/T04a.01-Exercise-AddNewActivity/app/src/main/AndroidManifest.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Java",
"bytes": "2408980"
},
{
"name": "Python",
"bytes": "4312"
}
],
"symlink_target": ""
} |
#include "condor_common.h"
#include "condor_config.h"
#include "condor_distribution.h"
#include "ca_utils.h"
#include "CondorError.h"
#include "string_list.h"
#include "MyString.h"
#include <openssl/err.h>
#include <openssl/pem.h>
#include <openssl/x509.h>
#include <iomanip>
#include <memory>
#include <sstream>
#include <string>
#include <unordered_set>
namespace {
void print_usage(FILE* fp, const char *argv0)
{
fprintf(fp, "Usage: %s [FILE]\n"
"Prints the fingerprint of the first X509 certificate found at FILE or\n"
"the contents of a condor known_hosts file.\n"
"\n"
"If FILE is not provided, the prints the user's default known_hosts file.\n"
"\n", argv0);
}
int print_known_hosts_file(std::string desired_fname = "")
{
auto fname = desired_fname.empty() ? htcondor::get_known_hosts_filename() : desired_fname;
std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(fname.c_str(), "r"), &fclose);
if (!fp) {
fprintf(stderr, "Failed to open %s for reading: %s (errno=%d)\n",
fname.c_str(), strerror(errno), errno);
exit(2);
}
std::unordered_set<std::string> observed_hostnames;
for (std::string line; readLine(line, fp.get(), false);)
{
trim(line);
if (line.empty() || line[0] == '#') continue;
StringList splitter(line, " ");
splitter.rewind();
char *token;
std::vector<std::string> tokens;
tokens.reserve(3);
while ( (token = splitter.next()) ) {
tokens.emplace_back(token);
}
if (tokens.size() < 3 || !tokens[0].size() || !tokens[1].size()) {
fprintf(stderr, "No PEM-formatted certificate found; incorrect format for known_hosts file.\n");
exit(5);
}
bool permitted = tokens[0][0] != '!';
std::string hostname = permitted ? tokens[0] : tokens[0].substr(1);
auto result = observed_hostnames.insert(hostname);
// Only print out the first match for each condor name.
if (!result.second) {continue;}
std::string method_info = tokens[2];
if (tokens[1] == "SSL" && method_info != "@trusted") {
CondorError err;
auto cert = htcondor::load_x509_from_b64(method_info, err);
if (!cert) {
fprintf(stderr, "Failed to parse the X.509 certificate for %s.\n",
hostname.c_str());
fprintf(stderr, "%s\n", err.getFullText(true).c_str());
exit(6);
}
std::string fingerprint;
if (!htcondor::generate_fingerprint(cert.get(), fingerprint, err)) {
fprintf(stderr, "Failed to generate fingerprint for %s.\n", hostname.c_str());
fprintf(stderr, "%s\n", err.getFullText(true).c_str());
exit(7);
}
method_info = fingerprint;
} else {
continue;
}
printf("%c%s %s %s\n", permitted ? ' ' : '!', hostname.c_str(), tokens[1].c_str(),
method_info.c_str());
}
return 0;
}
}
int main(int argc, const char *argv[]) {
set_priv_initialize();
config();
#if (OPENSSL_VERSION_NUMBER < 0x10100000L)
ERR_load_crypto_strings();
OpenSSL_add_all_digests();
#endif
if (argc == 1) {
return print_known_hosts_file();
} else if (argc != 2) {
print_usage(stdout, argv[0]);
exit(1);
}
std::unique_ptr<FILE, decltype(&fclose)> fp(fopen(argv[1], "r"), &fclose);
if (!fp) {
fprintf(stderr, "Failed to open %s for reading: %s (errno=%d)\n",
argv[1], strerror(errno), errno);
exit(2);
}
std::unique_ptr<X509, decltype(&X509_free)> cert(PEM_read_X509(fp.get(), NULL, NULL, NULL), X509_free);
if (!cert) {
return print_known_hosts_file(argv[1]);
}
std::string fingerprint;
CondorError err;
if (!htcondor::generate_fingerprint(cert.get(), fingerprint, err)) {
fprintf(stderr, "Failed to generate fingerprint from %s:\n", argv[1]);
fprintf(stderr, "%s\n", err.getFullText(true).c_str());
exit(err.code() ? err.code() : 4);
}
fprintf(stderr, "%s\n", fingerprint.c_str());
return 0;
}
| {
"content_hash": "45609478356ec440c77aa5e1ba809609",
"timestamp": "",
"source": "github",
"line_count": 142,
"max_line_length": 104,
"avg_line_length": 26.281690140845072,
"alnum_prop": 0.6430868167202572,
"repo_name": "htcondor/htcondor",
"id": "a0d5fcae868be283d164044ddb1b93f248cb2098",
"size": "4534",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/condor_tools/ssl_fingerprint.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Ada",
"bytes": "71055"
},
{
"name": "Awk",
"bytes": "9454"
},
{
"name": "Batchfile",
"bytes": "146264"
},
{
"name": "C",
"bytes": "1651049"
},
{
"name": "C++",
"bytes": "31790435"
},
{
"name": "CMake",
"bytes": "468527"
},
{
"name": "CSS",
"bytes": "9738"
},
{
"name": "Dockerfile",
"bytes": "75955"
},
{
"name": "Fortran",
"bytes": "1279"
},
{
"name": "HTML",
"bytes": "59724"
},
{
"name": "Java",
"bytes": "43977"
},
{
"name": "JavaScript",
"bytes": "130293"
},
{
"name": "M4",
"bytes": "20440"
},
{
"name": "Makefile",
"bytes": "68811"
},
{
"name": "Perl",
"bytes": "3761627"
},
{
"name": "PowerShell",
"bytes": "5412"
},
{
"name": "Python",
"bytes": "1593654"
},
{
"name": "Roff",
"bytes": "2353"
},
{
"name": "Shell",
"bytes": "579393"
},
{
"name": "VBScript",
"bytes": "8734"
},
{
"name": "Yacc",
"bytes": "13532"
}
],
"symlink_target": ""
} |
static NSString * const base = @"http://api.wunderground.com/api";
// Name of the service
static NSString * const serviceName = @"Weather Underground";
#pragma mark - CZWundergroundService Implementation
@implementation CZWundergroundService
@synthesize key = _key, serviceName = _serviceName;
#pragma mark Creating a Weather Service
- (instancetype)init
{
if (self = [super init]) {
}
return self;
}
- (instancetype)initWithKey:(NSString *)key
{
if (self = [super init]) {
_key = key;
_serviceName = serviceName;
}
return self;
}
+ (instancetype)serviceWithKey:(NSString *)key
{
return [[CZWundergroundService alloc]initWithKey:key];
}
#pragma mark Using a Weather Service
- (NSURL *)urlForRequest:(CZWeatherRequest *)request
{
if ([self.key length] == 0) {
return nil;
}
NSString *url = [NSString stringWithFormat:@"%@/%@/", base, self.key];
if (request.requestType == CZCurrentConditionsRequestType) {
url = [url stringByAppendingString:@"conditions/"];
}else if (request.requestType == CZForecastRequestType && request.detailLevel == CZWeatherRequestLightDetail) {
url = [url stringByAppendingString:@"forecast/"];
} else if (request.requestType == CZForecastRequestType && request.detailLevel == CZWeatherRequestFullDetail) {
url = [url stringByAppendingString:@"forecast10day/"];
}
if ([request.language length] > 0) {
url = [url stringByAppendingString:[NSString stringWithFormat:@"lang:%@/", request.language]];
}
url = [url stringByAppendingString:@"q/"];
if (request.location.locationType == CZWeatherLocationCoordinateType) {
CGPoint coordinate = [request.location.locationData[CZWeatherLocationCoordinateName]CGPointValue];
url = [url stringByAppendingString:[NSString stringWithFormat:@"%.4f,%.4f", coordinate.x, coordinate.y]];
} else if (request.location.locationType == CZWeatherLocationZipcodeType) {
url = [url stringByAppendingString:request.location.locationData[CZWeatherLocationZipcodeName]];
} else if (request.location.locationType == CZWeatherLocationAutoIPType) {
url = [url stringByAppendingString:@"autoip"];
} else if (request.location.locationType == CZWeatherLocationCityStateType) {
NSString *city = request.location.locationData[CZWeatherLocationCityName];
city = [city stringByReplacingOccurrencesOfString:@" " withString:@"_"];
NSString *state = request.location.locationData[CZWeatherLocationStateName];
url = [url stringByAppendingString:[NSString stringWithFormat:@"%@/%@", state, city]];
} else if (request.location.locationType == CZWeatherLocationCityCountryType) {
NSString *city = request.location.locationData[CZWeatherLocationCityName];
city = [city stringByReplacingOccurrencesOfString:@" " withString:@"_"];
NSString *country = request.location.locationData[CZWeatherLocationCountryName];
country = [country stringByReplacingOccurrencesOfString:@" " withString:@"_"];
url = [url stringByAppendingString:[NSString stringWithFormat:@"%@/%@", country, city]];
} else {
return nil;
}
url = [url stringByAppendingString:@".json"];
return [NSURL URLWithString:url];
}
- (id)weatherDataForResponseData:(NSData *)data request:(CZWeatherRequest *)request
{
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingAllowFragments
error:nil];
if (!JSON) {
return nil;
}
if (request.requestType == CZCurrentConditionsRequestType) {
return [self parseCurrentConditionsFromJSON:JSON];
} else if (request.requestType == CZForecastRequestType) {
return [self parseForecastFromJSON:JSON];
}
return nil;
}
#pragma mark Helper
- (CZWeatherCondition *)parseCurrentConditionsFromJSON:(NSDictionary *)JSON
{
CZWeatherCondition *condition = [CZWeatherCondition new];
NSDictionary *currentObservation = JSON[@"current_observation"];
NSTimeInterval epoch = [currentObservation[@"observation_epoch"]doubleValue];
condition.date = [NSDate dateWithTimeIntervalSince1970:epoch];
condition.summary = currentObservation[@"weather"];
condition.climaconCharacter = [self climaconCharacterForDescription:condition.summary];
condition.temperature = (CZTemperature){[currentObservation[@"temp_f"]floatValue], [currentObservation[@"temp_c"]floatValue]};
condition.windDegrees = [currentObservation[@"wind_degrees"]floatValue];
condition.windSpeed = (CZWindSpeed){[currentObservation[@"wind_mph"]floatValue],[currentObservation[@"wind_kph"]floatValue]};
condition.humidity = [[currentObservation[@"relative_humidity"]stringByReplacingOccurrencesOfString:@"%" withString:@""]floatValue];
return condition;
}
- (NSArray *)parseForecastFromJSON:(NSDictionary *)JSON
{
NSMutableArray *forecasts = [NSMutableArray new];
NSArray *forecastDay = JSON[@"forecast"][@"simpleforecast"][@"forecastday"];
for (NSDictionary *day in forecastDay) {
CZWeatherCondition *condition = [CZWeatherCondition new];
NSTimeInterval epoch = [day[@"date"][@"epoch"]doubleValue];
condition.date = [NSDate dateWithTimeIntervalSince1970:epoch];
condition.summary = day[@"conditions"];
condition.highTemperature = (CZTemperature){[day[@"high"][@"fahrenheit"]floatValue], [day[@"high"][@"celsius"]floatValue]};
condition.lowTemperature = (CZTemperature){[day[@"low"][@"fahrenheit"]floatValue], [day[@"low"][@"celsius"]floatValue]};
condition.climaconCharacter = [self climaconCharacterForDescription:condition.summary];
condition.humidity = [day[@"avehumidity"]floatValue];
condition.windSpeed = (CZWindSpeed){[day[@"avewind"][@"mph"]floatValue], [day[@"avewind"][@"kph"]floatValue]};
condition.windDegrees = [day[@"avewind"][@"degrees"]floatValue];
[forecasts addObject:condition];
}
return [forecasts copy];
}
- (Climacon)climaconCharacterForDescription:(NSString *)description
{
Climacon icon = ClimaconSun;
NSString *lowercaseDescription = description.lowercaseString;
if([lowercaseDescription cz_contains:@"clear"]) {
icon = ClimaconSun;
} else if([lowercaseDescription cz_contains:@"cloud"]) {
icon = ClimaconCloud;
} else if([lowercaseDescription cz_contains:@"drizzle"]) {
icon = ClimaconDrizzle;
} else if([lowercaseDescription cz_contains:@"showers"]) {
icon = ClimaconShowers;
} else if([lowercaseDescription cz_contains:@"rain"] ||
[lowercaseDescription cz_contains:@"thunderstorm"]) {
icon = ClimaconRain;
} else if ([lowercaseDescription cz_contains:@"hail"]) {
icon = ClimaconHail;
} else if([lowercaseDescription cz_contains:@"snow"] ||
[lowercaseDescription cz_contains:@"ice"]) {
icon = ClimaconSnow;
} else if([lowercaseDescription cz_contains:@"fog"]) {
icon = ClimaconFog;
} else if ([lowercaseDescription cz_contains:@"overcast"] ||
[lowercaseDescription cz_contains:@"smoke"] ||
[lowercaseDescription cz_contains:@"dust"] ||
[lowercaseDescription cz_contains:@"ash"] ||
[lowercaseDescription cz_contains:@"mist"] ||
[lowercaseDescription cz_contains:@"haze"] ||
[lowercaseDescription cz_contains:@"spray"] ||
[lowercaseDescription cz_contains:@"squall"]) {
icon = ClimaconHaze;
}
return icon;
}
@end
| {
"content_hash": "3c8ee7485ab22b07120bb3155a3dcb92",
"timestamp": "",
"source": "github",
"line_count": 185,
"max_line_length": 136,
"avg_line_length": 42.362162162162164,
"alnum_prop": 0.6704095955084854,
"repo_name": "nagyistoce/CZWeatherKit",
"id": "a9f8101e0efae21a528005cbcd837a21bc88088e",
"size": "9529",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "CZWeatherKit/Service/CZWundergroundService.m",
"mode": "33261",
"license": "bsd-2-clause",
"language": [
{
"name": "C",
"bytes": "1602"
},
{
"name": "Objective-C",
"bytes": "149006"
},
{
"name": "Ruby",
"bytes": "836"
}
],
"symlink_target": ""
} |
// For conditions of distribution and use, see copyright notice in LICENSE
#include "StableHeaders.h"
#include "DebugOperatorNew.h"
#include "EC_DynamicComponent.h"
#include "SceneAPI.h"
#include "Entity.h"
#include "LoggingFunctions.h"
#include "Scene/Scene.h"
#include <QScriptEngine>
#include <QScriptValueIterator>
#include <kNet.h>
#include <QDomDocument>
#include "MemoryLeakCheck.h"
/** @cond PRIVATE */
struct DeserializeData
{
DeserializeData(const QString &id = "", const QString &type = "", const QString &value = ""):
id_(id),
type_(type),
value_(value)
{
}
QString id_;
QString type_;
QString value_;
};
/// Function that is used by std::sort algorithm to sort attributes by their ID.
bool CmpAttributeById(const IAttribute *a, const IAttribute *b)
{
return a->Id().compare(b->Id(), Qt::CaseInsensitive);
}
/// Function that is used by std::sort algorithm to sort DeserializeData by their ID.
bool CmpAttributeDataById(const DeserializeData &a, const DeserializeData &b)
{
return a.id_.compare(b.id_, Qt::CaseInsensitive);
}
/** @endcond */
EC_DynamicComponent::EC_DynamicComponent(Scene* scene):
IComponent(scene)
{
}
EC_DynamicComponent::~EC_DynamicComponent()
{
}
void EC_DynamicComponent::DeserializeFrom(QDomElement& element, AttributeChange::Type change)
{
if (!BeginDeserialization(element))
return;
std::vector<DeserializeData> deserializedAttributes;
QDomElement child = element.firstChildElement("attribute");
while(!child.isNull())
{
QString id = child.attribute("id");
// Fallback if ID is not defined
if (!id.length())
id = child.attribute("name");
QString type = child.attribute("type");
QString value = child.attribute("value");
DeserializeData attributeData(id, type, value);
deserializedAttributes.push_back(attributeData);
child = child.nextSiblingElement("attribute");
}
DeserializeCommon(deserializedAttributes, change);
}
void EC_DynamicComponent::DeserializeCommon(std::vector<DeserializeData>& deserializedAttributes, AttributeChange::Type change)
{
// Sort both lists in alphabetical order.
AttributeVector oldAttributes = NonEmptyAttributes();
std::stable_sort(oldAttributes.begin(), oldAttributes.end(), &CmpAttributeById);
std::stable_sort(deserializedAttributes.begin(), deserializedAttributes.end(), &CmpAttributeDataById);
std::vector<DeserializeData> addAttributes;
std::vector<DeserializeData> remAttributes;
AttributeVector::iterator iter1 = oldAttributes.begin();
std::vector<DeserializeData>::iterator iter2 = deserializedAttributes.begin();
// Check what attributes we need to add or remove from the dynamic component (done by comparing two list differences).
while(iter1 != oldAttributes.end() || iter2 != deserializedAttributes.end())
{
// No point to continue the iteration if other list is empty. We can just push all new attributes into the dynamic component.
if(iter1 == oldAttributes.end())
{
for(;iter2 != deserializedAttributes.end(); ++iter2)
addAttributes.push_back(*iter2);
break;
}
// Only old attributes are left and they can be removed from the dynamic component.
else if(iter2 == deserializedAttributes.end())
{
for(;iter1 != oldAttributes.end(); ++iter1)
remAttributes.push_back(DeserializeData((*iter1)->Id()));
break;
}
// Attribute has already created and we only need to update it's value.
if((*iter1)->Id() == (*iter2).id_)
{
//SetAttribute(QString::fromStdString(iter2->name_), QString::fromStdString(iter2->value_), change);
for(AttributeVector::const_iterator attr_iter = attributes.begin(); attr_iter != attributes.end(); ++attr_iter)
if((*attr_iter)->Id() == iter2->id_)
(*attr_iter)->FromString(iter2->value_.toStdString(), change);
++iter2;
++iter1;
}
// Found a new attribute that need to be created and added to the component.
else if((*iter1)->Id() > (*iter2).id_)
{
addAttributes.push_back(*iter2);
++iter2;
}
// Couldn't find the attribute in a new list so it need to be removed from the component.
else
{
remAttributes.push_back(DeserializeData((*iter1)->Id()));
++iter1;
}
}
while(!addAttributes.empty())
{
DeserializeData attributeData = addAttributes.back();
IAttribute *attribute = CreateAttribute(attributeData.type_, attributeData.id_);
if (attribute)
attribute->FromString(attributeData.value_.toStdString(), change);
addAttributes.pop_back();
}
while(!remAttributes.empty())
{
DeserializeData attributeData = remAttributes.back();
RemoveAttribute(attributeData.id_);
remAttributes.pop_back();
}
}
IAttribute *EC_DynamicComponent::CreateAttribute(const QString &typeName, const QString &id, AttributeChange::Type change)
{
if (ContainsAttribute(id))
return IComponent::AttributeById(id);
IAttribute *attribute = SceneAPI::CreateAttribute(typeName, id);
if (!attribute)
{
LogError("Failed to create new attribute of type \"" + typeName + "\" with ID \"" + id + "\" to dynamic component \"" + Name() + "\".");
return 0;
}
IComponent::AddAttribute(attribute);
Scene* scene = ParentScene();
if (scene)
scene->EmitAttributeAdded(this, attribute, change);
emit AttributeAdded(attribute);
EmitAttributeChanged(attribute, change);
return attribute;
}
void EC_DynamicComponent::RemoveAttribute(const QString &id, AttributeChange::Type change)
{
for(AttributeVector::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter)
if(*iter && (*iter)->Id().compare(id, Qt::CaseInsensitive) == 0)
{
IComponent::RemoveAttribute((*iter)->Index(), change);
break;
}
}
void EC_DynamicComponent::RemoveAllAttributes(AttributeChange::Type change)
{
for(AttributeVector::const_iterator iter = attributes.begin(); iter != attributes.end(); ++iter)
if (*iter)
IComponent::RemoveAttribute((*iter)->Index(), change);
attributes.clear();
}
int EC_DynamicComponent::GetInternalAttributeIndex(int index) const
{
if (index >= (int)attributes.size())
return -1; // Can be sure that is not found.
int cmp = 0;
for (unsigned i = 0; i < attributes.size(); ++i)
{
if (!attributes[i])
continue;
if (cmp == index)
return i;
++cmp;
}
return -1;
}
void EC_DynamicComponent::AddQVariantAttribute(const QString &id, AttributeChange::Type change)
{
LogWarning("EC_DynamicComponent::AddQVariantAttribute is deprecated and will be removed. Use CreateAttribute(\"QVariant\",...) instead.");
//Check if the attribute has already been created.
if(!ContainsAttribute(id))
{
Attribute<QVariant> *attribute = new Attribute<QVariant>(this, id.toStdString().c_str());
EmitAttributeChanged(attribute, change);
emit AttributeAdded(attribute);
}
else
LogWarning("Failed to add a new QVariant with ID " + id + ", because there already is an attribute with that ID.");
}
QVariant EC_DynamicComponent::GetAttribute(int index) const
{
// Do not count holes.
int attrIndex = GetInternalAttributeIndex(index);
if (attrIndex < 0)
return QVariant();
return attributes[attrIndex]->ToQVariant();
}
QVariant EC_DynamicComponent::GetAttribute(const QString &id) const
{
return IComponent::GetAttributeQVariant(id);
}
void EC_DynamicComponent::SetAttribute(int index, const QVariant &value, AttributeChange::Type change)
{
int attrIndex = GetInternalAttributeIndex(index);
if (attrIndex < 0)
{
LogWarning("Cannot set attribute, index out of bounds");
return;
}
attributes[attrIndex]->FromQVariant(value, change);
}
void EC_DynamicComponent::SetAttributeQScript(const QString &id, const QScriptValue &value, AttributeChange::Type change)
{
LogWarning("EC_DynamicComponent::SetAttributeQScript is deprecated and will be removed. Use SetAttribute instead.");
IAttribute* attr = AttributeById(id);
if (attr)
attr->FromScriptValue(value, change);
}
void EC_DynamicComponent::SetAttribute(const QString &id, const QVariant &value, AttributeChange::Type change)
{
IAttribute* attr = AttributeById(id);
if (attr)
attr->FromQVariant(value, change);
}
QString EC_DynamicComponent::GetAttributeName(int index) const
{
LogWarning("EC_DynamicComponent::GetAttributeName is deprecated and will be removed. For dynamic attributes ID is the same as name. Use GetAttributeId instead.");
// Do not count holes.
int attrIndex = GetInternalAttributeIndex(index);
if (attrIndex < 0)
{
LogWarning("Cannot get attribute name, index out of bounds");
return QString();
}
return attributes[index]->Name();
}
QString EC_DynamicComponent::GetAttributeId(int index) const
{
// Do not count holes.
int attrIndex = GetInternalAttributeIndex(index);
if (attrIndex < 0)
{
LogWarning("Cannot get attribute ID, index out of bounds");
return QString();
}
return attributes[index]->Id();
}
bool EC_DynamicComponent::ContainSameAttributes(const EC_DynamicComponent &comp) const
{
AttributeVector myAttributeVector = NonEmptyAttributes();
AttributeVector attributeVector = comp.NonEmptyAttributes();
if(attributeVector.size() != myAttributeVector.size())
return false;
if(attributeVector.empty() && myAttributeVector.empty())
return true;
std::sort(myAttributeVector.begin(), myAttributeVector.end(), &CmpAttributeById);
std::sort(attributeVector.begin(), attributeVector.end(), &CmpAttributeById);
AttributeVector::const_iterator iter1 = myAttributeVector.begin();
AttributeVector::const_iterator iter2 = attributeVector.begin();
while(iter1 != myAttributeVector.end() && iter2 != attributeVector.end())
{
// Compare attribute names and type and if they mach continue iteration if not components aren't exactly the same.
if (((*iter1)->Id().compare((*iter2)->Id(), Qt::CaseInsensitive) == 0) &&
(*iter1)->TypeName().compare((*iter2)->TypeName(), Qt::CaseInsensitive) == 0)
{
if(iter1 != myAttributeVector.end())
++iter1;
if(iter2 != attributeVector.end())
++iter2;
}
else
{
return false;
}
}
return true;
/*// Get both attributes and check if they are holding exact number of attributes.
AttributeVector myAttributeVector = Attributes();
AttributeVector attributeVector = comp.Attributes();
if(attributeVector.size() != myAttributeVector.size())
return false;
// Compare that every attribute is same in both components.
QSet<IAttribute*> myAttributeSet;
QSet<IAttribute*> attributeSet;
for(uint i = 0; i < myAttributeSet.size(); i++)
{
attributeSet.insert(myAttributeVector[i]);
myAttributeSet.insert(attributeVector[i]);
}
if(attributeSet != myAttributeSet)
return false;
return true;*/
}
bool EC_DynamicComponent::ContainsAttribute(const QString &id) const
{
return AttributeById(id) != 0;
}
void EC_DynamicComponent::SerializeToBinary(kNet::DataSerializer& dest) const
{
dest.Add<u8>((u8)attributes.size());
// For now, transmit all values as strings
AttributeVector::const_iterator iter = attributes.begin();
while(iter != attributes.end())
{
if (*iter)
{
dest.AddString((*iter)->Id().toStdString());
dest.AddString((*iter)->TypeName().toStdString());
dest.AddString((*iter)->ToString());
}
++iter;
}
}
void EC_DynamicComponent::DeserializeFromBinary(kNet::DataDeserializer& source, AttributeChange::Type change)
{
u8 num_attributes = source.Read<u8>();
std::vector<DeserializeData> deserializedAttributes;
for(uint i = 0; i < num_attributes; ++i)
{
std::string id = source.ReadString();
std::string typeName = source.ReadString();
std::string value = source.ReadString();
DeserializeData attrData(id.c_str(), typeName.c_str(), value.c_str());
deserializedAttributes.push_back(attrData);
}
DeserializeCommon(deserializedAttributes, change);
}
| {
"content_hash": "95b14f6e063ca0161f959d4e5ab373d1",
"timestamp": "",
"source": "github",
"line_count": 382,
"max_line_length": 166,
"avg_line_length": 33.56282722513089,
"alnum_prop": 0.6572810233211138,
"repo_name": "jesterKing/naali",
"id": "dbc92078161f8078ab18652f14ecf4effebe5dbd",
"size": "12821",
"binary": false,
"copies": "1",
"ref": "refs/heads/tundra2",
"path": "src/Core/TundraCore/Scene/EC_DynamicComponent.cpp",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "426656"
},
{
"name": "C#",
"bytes": "104929"
},
{
"name": "C++",
"bytes": "6854902"
},
{
"name": "CSS",
"bytes": "18579"
},
{
"name": "Java",
"bytes": "127224"
},
{
"name": "JavaScript",
"bytes": "317898"
},
{
"name": "Objective-C",
"bytes": "213945"
},
{
"name": "Shell",
"bytes": "17462"
},
{
"name": "TypeScript",
"bytes": "230019"
}
],
"symlink_target": ""
} |
using System;
using System.Threading;
using SevenDigital.Messaging.Infrastructure.SignalHandling.PrivateMonoDerived;
namespace SevenDigital.Messaging.Infrastructure.SignalHandling
{
/// <summary>
/// Wait for termination events on a background thread.
/// You should terminate soon after receiving a terminate event.
/// </summary>
public class CrossPlatformSignalDispatch
{
/// <summary>
/// Event triggered when SIGTERM or ^C occur
/// </summary>
public event TerminateEvent TerminateEvent;
/// <summary>
/// Singleton instance
/// </summary>
public static CrossPlatformSignalDispatch Instance
{
get
{
return instance ?? (instance = new CrossPlatformSignalDispatch());
}
}
static CrossPlatformSignalDispatch instance;
static bool RunningUnderPosix
{
get
{
var p = (int)Environment.OSVersion.Platform;
return (p == 4) || (p == 6) || (p == 128);
}
}
void TerminateEventSent(int signal)
{
var handler = TerminateEvent;
if (handler != null)
{
handler(this, new TerminateEventArgs(signal));
}
else
{
Environment.Exit(signal);
}
}
private CrossPlatformSignalDispatch()
{
if (RunningUnderPosix)
{
waitingThread = new Thread(UnixSignalLoop);
waitingThread.IsBackground = true;
waitingThread.Start();
}
else
{
Console.CancelKeyPress += ConsoleCancelKeyPress;
}
}
void UnixSignalLoop()
{
var signals = new[]{
new UnixSignal (Signum.SIGINT), // ^C
new UnixSignal (Signum.SIGTERM), // kill
new UnixSignal (Signum.SIGHUP) // background and drop
};
while (waitingThread.IsAlive)
{
var which = UnixSignal.WaitAny(signals, -1);
TerminateEventSent((int)signals[which].Signum);
}
}
void ConsoleCancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
e.Cancel = true;
TerminateEventSent((int)Signum.SIGINT);
}
readonly Thread waitingThread;
}
/// <summary>
/// Terminate signal event
/// </summary>
public delegate void TerminateEvent(object sender, TerminateEventArgs e);
/// <summary>
/// Terminate signal event arguments
/// </summary>
public class TerminateEventArgs : EventArgs
{
/// <summary>
/// UNIX signal number or equivalent
/// </summary>
public int Signal { get; set; }
/// <summary>
/// Create new event args with a given signal number
/// </summary>
public TerminateEventArgs(int signal)
{
Signal = signal;
}
}
}
| {
"content_hash": "b8850770a7a04c58abb6d3c4476ea728",
"timestamp": "",
"source": "github",
"line_count": 112,
"max_line_length": 78,
"avg_line_length": 23,
"alnum_prop": 0.6428571428571429,
"repo_name": "i-e-b/SevenDigital.Messaging",
"id": "1fe7f96d6b1edd53d78ab54c923def4ce5d3ba39",
"size": "2578",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/SevenDigital.Messaging/Infrastructure/SignalHandling/CrossPlatformSignalDispatch.cs",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C#",
"bytes": "272437"
}
],
"symlink_target": ""
} |
//! \file
//! This header includes core utilities from <tt><boost/move/utility_core.hpp></tt> and defines
//! some more advanced utilities such as:
#ifndef BOOST_MOVE_MOVE_UTILITY_HPP
#define BOOST_MOVE_MOVE_UTILITY_HPP
#ifndef BOOST_CONFIG_HPP
# include <boost/config.hpp>
#endif
#
#if defined(BOOST_HAS_PRAGMA_ONCE)
# pragma once
#endif
#include <boost/move/detail/config_begin.hpp>
#include <boost/move/utility_core.hpp>
#include <boost/move/traits.hpp>
#if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED)
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost {
//////////////////////////////////////////////////////////////////////////////
//
// move_if_noexcept()
//
//////////////////////////////////////////////////////////////////////////////
template <class T>
inline typename ::mars_boost::move_detail::enable_if_c
< enable_move_utility_emulation<T>::value && !has_move_emulation_enabled<T>::value
, typename ::mars_boost::move_detail::add_const<T>::type &
>::type
move_if_noexcept(T& x) BOOST_NOEXCEPT
{
return x;
}
template <class T>
inline typename ::mars_boost::move_detail::enable_if_c
< enable_move_utility_emulation<T>::value && has_move_emulation_enabled<T>::value
&& ::mars_boost::move_detail::is_nothrow_move_constructible_or_uncopyable<T>::value, rv<T>&>::type
move_if_noexcept(T& x) BOOST_NOEXCEPT
{
return *static_cast<rv<T>* >(::mars_boost::move_detail::addressof(x));
}
template <class T>
inline typename ::mars_boost::move_detail::enable_if_c
< enable_move_utility_emulation<T>::value && has_move_emulation_enabled<T>::value
&& ::mars_boost::move_detail::is_nothrow_move_constructible_or_uncopyable<T>::value
, rv<T>&
>::type
move_if_noexcept(rv<T>& x) BOOST_NOEXCEPT
{
return x;
}
template <class T>
inline typename ::mars_boost::move_detail::enable_if_c
< enable_move_utility_emulation<T>::value && has_move_emulation_enabled<T>::value
&& !::mars_boost::move_detail::is_nothrow_move_constructible_or_uncopyable<T>::value
, typename ::mars_boost::move_detail::add_const<T>::type &
>::type
move_if_noexcept(T& x) BOOST_NOEXCEPT
{
return x;
}
template <class T>
inline typename ::mars_boost::move_detail::enable_if_c
< enable_move_utility_emulation<T>::value && has_move_emulation_enabled<T>::value
&& !::mars_boost::move_detail::is_nothrow_move_constructible_or_uncopyable<T>::value
, typename ::mars_boost::move_detail::add_const<T>::type &
>::type
move_if_noexcept(rv<T>& x) BOOST_NOEXCEPT
{
return x;
}
} //namespace mars_boost
#else //#if defined(BOOST_NO_CXX11_RVALUE_REFERENCES) && !defined(BOOST_MOVE_DOXYGEN_INVOKED)
#if defined(BOOST_MOVE_USE_STANDARD_LIBRARY_MOVE)
#include <utility>
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost{
using ::std::move_if_noexcept;
} //namespace mars_boost
#else //!BOOST_MOVE_USE_STANDARD_LIBRARY_MOVE
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost {
//////////////////////////////////////////////////////////////////////////////
//
// move_if_noexcept()
//
//////////////////////////////////////////////////////////////////////////////
#if defined(BOOST_MOVE_DOXYGEN_INVOKED)
//! This function provides a way to convert a reference into a rvalue reference
//! in compilers with rvalue references. For other compilers converts T & into
//! <i>::mars_boost::rv<T> &</i> so that move emulation is activated. Reference
//! would be converted to rvalue reference only if input type is nothrow move
//! constructible or if it has no copy constructor. In all other cases const
//! reference would be returned
template <class T>
rvalue_reference_or_const_lvalue_reference move_if_noexcept(input_reference) noexcept;
#else //BOOST_MOVE_DOXYGEN_INVOKED
template <class T>
typename ::mars_boost::move_detail::enable_if_c
< ::mars_boost::move_detail::is_nothrow_move_constructible_or_uncopyable<T>::value, T&&>::type
move_if_noexcept(T& x) BOOST_NOEXCEPT
{ return ::mars_boost::move(x); }
template <class T>
typename ::mars_boost::move_detail::enable_if_c
< !::mars_boost::move_detail::is_nothrow_move_constructible_or_uncopyable<T>::value, const T&>::type
move_if_noexcept(T& x) BOOST_NOEXCEPT
{ return x; }
#endif //BOOST_MOVE_DOXYGEN_INVOKED
} //namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost {
#endif //#if defined(BOOST_MOVE_USE_STANDARD_LIBRARY_MOVE)
#endif //BOOST_NO_CXX11_RVALUE_REFERENCES
#include <boost/move/detail/config_end.hpp>
#endif //#ifndef BOOST_MOVE_MOVE_UTILITY_HPP
| {
"content_hash": "6cb6e3843fde7445a8cef6530333199a",
"timestamp": "",
"source": "github",
"line_count": 139,
"max_line_length": 112,
"avg_line_length": 37.97841726618705,
"alnum_prop": 0.5811706762644441,
"repo_name": "zhenyiyi/LearnDiary",
"id": "f727a9dc0188cfb110f6c7621893d59fcdfec339",
"size": "5711",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "mars/boost/move/utility.hpp",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Assembly",
"bytes": "425736"
},
{
"name": "Batchfile",
"bytes": "3122"
},
{
"name": "C",
"bytes": "1051854"
},
{
"name": "C#",
"bytes": "6481"
},
{
"name": "C++",
"bytes": "39195730"
},
{
"name": "M4",
"bytes": "19476"
},
{
"name": "Makefile",
"bytes": "4650"
},
{
"name": "Objective-C",
"bytes": "111719"
},
{
"name": "Objective-C++",
"bytes": "37672"
},
{
"name": "Perl",
"bytes": "2668"
},
{
"name": "Ruby",
"bytes": "279"
},
{
"name": "Shell",
"bytes": "1456"
}
],
"symlink_target": ""
} |
class InfraConversionJob < Job
#
# State-transition diagram:
# :poll_conversion :poll_post_stage
# * /-------------\ /---------------\
# | :initialize | | | |
# v :start v | v |
# waiting_to_start --------> running ------------------------------> post_conversion --/
# | | :start_post_stage |
# | :abort_job | :abort_job |
# \------------------------>| | :finish
# v |
# aborting --------------------------------->|
# :finish v
# finished
#
# TODO: Update this diagram after we've settled on the updated state transitions.
alias_method :initializing, :dispatch_start
alias_method :finish, :process_finished
alias_method :abort_job, :process_abort
alias_method :cancel, :process_cancel
alias_method :error, :process_error
def load_transitions
self.state ||= 'initialize'
{
:initializing => {'initialize' => 'waiting_to_start'},
:start => {'waiting_to_start' => 'started'},
:wait_for_ip_address => {
'started' => 'waiting_for_ip_address',
'powering_on_vm' => 'waiting_for_ip_address',
'waiting_for_ip_address' => 'waiting_for_ip_address'
},
:run_migration_playbook => {'waiting_for_ip_address' => 'running_migration_playbook'},
:poll_run_migration_playbook_complete => {'running_migration_playbook' => 'running_migration_playbook'},
:shutdown_vm => {'running_migration_playbook' => 'shutting_down_vm' },
:poll_shutdown_vm_complete => {'shutting_down_vm' => 'shutting_down_vm'},
:transform_vm => {'shutting_down_vm' => 'transforming_vm'},
:poll_transform_vm_complete => {'transforming_vm' => 'transforming_vm'},
:poll_inventory_refresh_complete => {
'transforming_vm' => 'waiting_for_inventory_refresh',
'waiting_for_inventory_refresh' => 'waiting_for_inventory_refresh'
},
:apply_right_sizing => {'waiting_for_inventory_refresh' => 'applying_right_sizing'},
:restore_vm_attributes => {'applying_right_sizing' => 'restoring_vm_attributes'},
:power_on_vm => {
'restoring_vm_attributes' => 'powering_on_vm',
'aborting_virtv2v' => 'powering_on_vm'
},
:poll_power_on_vm_complete => {'powering_on_vm' => 'powering_on_vm'},
:mark_vm_migrated => {'running_migration_playbook' => 'marking_vm_migrated'},
:poll_automate_state_machine => {
'powering_on_vm' => 'running_in_automate',
'marking_vm_migrated' => 'running_in_automate',
'running_in_automate' => 'running_in_automate'
},
:finish => {'*' => 'finished'},
:abort_job => {'*' => 'aborting'},
:cancel => {'*' => 'canceling'},
:abort_virtv2v => {
'canceling' => 'aborting_virtv2v',
'aborting_virtv2v' => 'aborting_virtv2v'
},
:error => {'*' => '*'}
}
end
# Example state:
# :state_name => {
# :description => 'State description',
# :weight => 30,
# :max_retries => 960
# }
def state_settings
@state_settings ||= {
:waiting_for_ip_address => {
:description => 'Waiting for VM IP address',
:weight => 2,
:max_retries => 1.hour / state_retry_interval
},
:running_migration_playbook => {
:description => "Running #{migration_phase}-migration playbook",
:weight => 15,
:max_retries => 6.hours / state_retry_interval
},
:shutting_down_vm => {
:description => "Shutting down virtual machine",
:weight => 2,
:max_retries => 15.minutes / state_retry_interval
},
:transforming_vm => {
:description => "Converting disks",
:weight => 60,
:max_retries => 1.day / state_retry_interval
},
:waiting_for_inventory_refresh => {
:description => "Identify destination VM",
:weight => 1,
:max_retries => 1.hour / state_retry_interval
},
:applying_right_sizing => {
:description => "Apply Right-Sizing Recommendation",
:weight => 1
},
:restoring_vm_attributes => {
:description => "Restore VM Attributes",
:weight => 1
},
:powering_on_vm => {
:description => "Power on virtual machine",
:weight => 2,
:max_retries => 15.minutes / state_retry_interval
},
:marking_vm_migrated => {
:description => "Mark source as migrated",
:weight => 1
},
:aborting_virtv2v => {
:description => "Abort virt-v2v operation",
:max_retries => 1.minute / state_retry_interval
},
:running_in_automate => {
:max_retries => 1.hour / state_retry_interval
}
}
end
# --- Override Job methods to handle cancelation properly --- #
def self.current_job_timeout(_timeout_adjustment = 1)
36.hours
end
def process_abort(*args)
message, status = args
_log.error("job aborting, #{message}")
set_status(message, status)
migration_task.canceling
queue_signal(:abort_virtv2v)
end
# --- Job relationships helper methods --- #
def state_retry_interval
@state_retry_interval ||= Settings.transformation.job.retry_interval || 15.seconds
end
def migration_task
@migration_task ||= target_entity
# valid states: %w(migrate pending finished active queued)
end
def migration_phase
migration_task.options[:migration_phase]
end
def source_vm
@source_vm ||= migration_task.source
end
def destination_vm
@destination_vm ||= migration_task.destination
end
def target_vm
return @target_vm = source_vm if migration_phase == 'pre' || migration_task.canceling?
return @target_vm = destination_vm if migration_phase == 'post'
end
# --- State transition helper methods --- #
def on_entry(state_hash, _)
state_hash || {
:state => 'active',
:status => 'Ok',
:description => state_settings[state.to_sym][:description],
:started_on => Time.now.utc,
:percent => 0.0
}.compact
end
def on_retry(state_hash, state_progress = nil)
if state_progress.nil?
state_hash[:percent] = context["retries_#{state}".to_sym].to_f / state_settings[state.to_sym][:max_retries].to_f * 100.0
else
state_hash.merge!(state_progress)
end
state_hash[:updated_on] = Time.now.utc
state_hash
end
def on_exit(state_hash, _)
state_hash[:state] = 'finished'
state_hash[:percent] = 100.0
state_hash[:updated_on] = Time.now.utc
state_hash
end
def on_error(state_hash, _)
state_hash[:state] = 'finished'
state_hash[:status] = 'Error'
state_hash[:updated_on] = Time.now.utc
state_hash
end
def update_migration_task_progress(state_phase, state_progress = nil)
progress = migration_task.options[:progress] || { :current_state => state, :percent => 0.0, :states => {} }
state_hash = send(state_phase, progress[:states][state.to_sym], state_progress)
progress[:states][state.to_sym] = state_hash
if state_phase == :on_entry
progress[:current_state] = state
progress[:current_description] = state_settings[state.to_sym][:description] if state_settings[state.to_sym][:description].present?
end
progress[:percent] = progress[:states].map { |k, v| v[:percent] * (state_settings[k.to_sym][:weight] || 0) / 100.0 }.inject(0) { |sum, x| sum + x }
migration_task.update_transformation_progress(progress)
abort_conversion('Migration cancelation requested', 'ok') if migration_task.cancel_requested?
end
# Temporary method to allow switching from InfraConversionJob to Automate.
# In Automate, another method waits for workflow_runner to be 'automate'.
def handover_to_automate
migration_task.update_options(:workflow_runner => 'automate')
end
def abort_conversion(message, status)
migration_task.cancel unless migration_task.cancel_requested?
queue_signal(:abort_job, message, status)
end
def polling_timeout
return false if state_settings[state.to_sym][:max_retries].nil?
retries = "retries_#{state}".to_sym
context[retries] = (context[retries] || 0) + 1
context[retries] > state_settings[state.to_sym][:max_retries]
end
def queue_signal(*args, deliver_on: nil)
MiqQueue.put(
:class_name => self.class.name,
:method_name => "signal",
:instance_id => id,
:role => "ems_operations",
:zone => zone,
:task_id => guid,
:args => args,
:deliver_on => deliver_on,
:server_guid => MiqServer.my_server.guid
)
end
def prep_message(contents)
"MiqRequestTask id=#{migration_task.id}, InfraConversionJob id=#{id}. #{contents}"
end
# --- Functional helper methods --- #
def apply_right_sizing_cpu(mode)
destination_vm.set_number_of_cpus(source_vm.send("#{mode}_recommended_vcpus"))
end
def apply_right_sizing_memory(mode)
destination_vm.set_memory(source_vm.send("#{mode}_recommended_mem"))
end
# --- Methods that implement the state machine transitions --- #
# This transition simply allows to officially mark the task as migrating.
# Temporarily, it also hands over to Automate.
def start
migration_task.update!(:state => 'migrate')
migration_task.update_options(:migration_phase => 'pre')
queue_signal(:wait_for_ip_address)
end
def wait_for_ip_address
update_migration_task_progress(:on_entry)
return abort_conversion('Waiting for IP address timed out', 'error') if polling_timeout
# If the target VM is powered off, we won't get an IP address, so no need to wait.
# We don't block powered off VMs, because the playbook could still be relevant.
if target_vm.power_state == 'on'
if target_vm.ipaddresses.empty?
update_migration_task_progress(:on_retry)
return queue_signal(:wait_for_ip_address)
end
end
update_migration_task_progress(:on_exit)
queue_signal(:run_migration_playbook)
rescue StandardError => error
update_migration_task_progress(:on_error)
abort_conversion(error.message, 'error')
end
def run_migration_playbook
update_migration_task_progress(:on_entry)
service_template = migration_task.send("#{migration_phase}_ansible_playbook_service_template")
unless service_template.nil?
service_dialog_options = {
:credentials => service_template.config_info[:provision][:credential_id],
:hosts => target_vm.ipaddresses.first || service_template.config_info[:provision][:hosts]
}
context["#{migration_phase}_migration_playbook_service_request_id".to_sym] = service_template.provision_request(migration_task.userid.to_i, service_dialog_options).id
update_migration_task_progress(:on_exit)
return queue_signal(:poll_run_migration_playbook_complete, :deliver_on => Time.now.utc + state_retry_interval)
end
update_migration_task_progress(:on_exit)
return queue_signal(:shutdown_vm) if migration_phase == 'pre'
queue_signal(:mark_vm_migrated)
rescue StandardError => error
update_migration_task_progress(:on_error)
return abort_conversion(error.message, 'error') if migration_phase == 'pre'
queue_signal(:mark_vm_migrated)
end
def poll_run_migration_playbook_complete
update_migration_task_progress(:on_entry)
return abort_conversion('Running migration playbook timed out', 'error') if polling_timeout
service_request = ServiceTemplateProvisionRequest.find(context["#{migration_phase}_migration_playbook_service_request_id".to_sym])
playbooks_status = migration_task.get_option(:playbooks) || {}
playbooks_status[migration_phase] = { :job_state => service_request.request_state }
migration_task.update_options(:playbooks => playbooks_status)
if service_request.request_state == 'finished'
playbooks_status[migration_phase][:job_status] = service_request.status
playbooks_status[migration_phase][:job_id] = service_request.miq_request_tasks.first.destination.service_resources.first.resource.id
migration_task.update_options(:playbooks => playbooks_status)
raise "Ansible playbook has failed (migration_phase=#{migration_phase})" if service_request.status == 'Error' && migration_phase == 'pre'
update_migration_task_progress(:on_exit)
return queue_signal(:shutdown_vm) if migration_phase == 'pre'
return queue_signal(:mark_vm_migrated)
end
update_migration_task_progress(:on_retry)
queue_signal(:poll_run_migration_playbook_complete, :deliver_on => Time.now.utc + state_retry_interval)
rescue StandardError => error
update_migration_task_progress(:on_error)
return abort_conversion(error.message, 'error') if migration_phase == 'pre'
queue_signal(:mark_vm_migrated)
end
def shutdown_vm
update_migration_task_progress(:on_entry)
unless target_vm.power_state == 'off'
if target_vm.supports_shutdown_guest?
target_vm.shutdown_guest
else
target_vm.stop
end
update_migration_task_progress(:on_exit)
return queue_signal(:poll_shutdown_vm_complete, :deliver_on => Time.now.utc + state_retry_interval)
end
update_migration_task_progress(:on_exit)
queue_signal(:transform_vm)
rescue StandardError => error
update_migration_task_progress(:on_error)
abort_conversion(error.message, 'error')
end
def poll_shutdown_vm_complete
update_migration_task_progress(:on_entry)
return abort_conversion('Shutting down VM timed out', 'error') if polling_timeout
if target_vm.power_state == 'off'
update_migration_task_progress(:on_exit)
return queue_signal(:transform_vm)
end
update_migration_task_progress(:on_retry)
queue_signal(:poll_shutdown_vm_complete, :deliver_on => Time.now.utc + state_retry_interval)
rescue StandardError => error
update_migration_task_progress(:on_error)
abort_conversion(error.message, 'error')
end
def transform_vm
update_migration_task_progress(:on_entry)
migration_task.run_conversion
update_migration_task_progress(:on_exit)
queue_signal(:poll_transform_vm_complete, :deliver_on => Time.now.utc + state_retry_interval)
rescue StandardError => error
update_migration_task_progress(:on_error)
abort_conversion(error.message, 'error')
end
def poll_transform_vm_complete
update_migration_task_progress(:on_entry)
return abort_conversion('Converting disks timed out', 'error') if polling_timeout
migration_task.get_conversion_state
case migration_task.options[:virtv2v_status]
when 'active'
virtv2v_disks = migration_task.options[:virtv2v_disks]
converted_disks = virtv2v_disks.reject { |disk| disk[:percent].zero? }
if converted_disks.empty?
message = 'Disk transformation is initializing.'
percent = 1
else
percent = 0
converted_disks.each { |disk| percent += (disk[:percent].to_f * disk[:weight].to_f / 100.0) }
message = "Converting disk #{converted_disks.length} / #{virtv2v_disks.length} [#{percent.round(2)}%]."
end
update_migration_task_progress(:on_retry, :message => message, :percent => percent)
queue_signal(:poll_transform_vm_complete, :deliver_on => Time.now.utc + state_retry_interval)
when 'failed'
raise migration_task.options[:virtv2v_message]
when 'succeeded'
update_migration_task_progress(:on_exit)
queue_signal(:poll_inventory_refresh_complete)
end
rescue StandardError => error
update_migration_task_progress(:on_error)
abort_conversion(error.message, 'error')
end
# This methods waits for the destination EMS inventory to refresh.
# It updates the migration_task.destination relationship with the create VM.
# We don't force the EMS refresh and rather allow 1 hour to get it.
def poll_inventory_refresh_complete
update_migration_task_progress(:on_entry)
return abort_conversion('Identify destination VM timed out', 'error') if polling_timeout
destination_vm = Vm.find_by(:name => migration_task.source.name, :ems_id => migration_task.destination_ems.id)
if destination_vm.nil?
update_migration_task_progress(:on_retry)
return queue_signal(:poll_inventory_refresh_complete, :deliver_on => Time.now.utc + state_retry_interval)
end
migration_task.update!(:destination => destination_vm)
migration_task.update_options(:migration_phase => 'post')
update_migration_task_progress(:on_exit)
queue_signal(:apply_right_sizing)
rescue StandardError => error
update_migration_task_progress(:on_error)
abort_conversion(error.message, 'error')
end
def apply_right_sizing
update_migration_task_progress(:on_entry)
%i[cpu memory].each do |item|
right_sizing_mode = migration_task.send("#{item}_right_sizing_mode")
send("apply_right_sizing_#{item}", right_sizing_mode) if right_sizing_mode.present?
end
update_migration_task_progress(:on_exit)
queue_signal(:restore_vm_attributes)
rescue StandardError
update_migration_task_progress(:on_error)
queue_signal(:restore_vm_attributes)
end
def restore_vm_attributes
update_migration_task_progress(:on_entry)
# Transfer service link to destination VM
if source_vm.service
destination_vm.add_to_service(source_vm.service)
source_vm.direct_service.try(:remove_resource, source_vm)
end
# Copy tags and custom attributes from source VM
source_vm.tags.each do |tag|
next if tag.name =~ /^\/managed\/folder_path_/
tag_as_array = tag.name.split('/')
namespace = tag_as_array.shift
value = tag_as_array.pop
category = tag_as_array.join('/')
destination_vm.tag_add("#{category}/#{value}", :ns => namespace)
end
source_vm.miq_custom_keys.each { |ca| destination_vm.miq_custom_set(ca, source_vm.miq_custom_get(ca)) }
# Copy ownership from source VM
destination_vm.evm_owner = source_vm.evm_owner if source_vm.present?
destination_vm.miq_group = source_vm.miq_group if source_vm.miq_group.present?
# Copy retirement settings from source VM
destination_vm.retires_on = source_vm.retires_on if source_vm.retires_on.present?
destination_vm.retirement_warn = source_vm.retirement_warn if source_vm.retirement_warn.present?
# Save destination_vm in VMDB
destination_vm.save
update_migration_task_progress(:on_exit)
queue_signal(:power_on_vm)
rescue StandardError
update_migration_task_progress(:on_error)
queue_signal(:power_on_vm)
end
def power_on_vm
update_migration_task_progress(:on_entry)
if migration_task.options[:source_vm_power_state] == 'on' && target_vm.power_state != 'on'
target_vm.start
update_migration_task_progress(:on_exit)
return queue_signal(:poll_power_on_vm_complete, :deliver_on => Time.now.utc + state_retry_interval)
end
update_migration_task_progress(:on_exit)
return queue_signal(:wait_for_ip_address) if target_vm.power_state == 'on' && !migration_task.canceling?
migration_task.canceled if migration_task.canceling?
handover_to_automate
queue_signal(:poll_automate_state_machine)
rescue StandardError
update_migration_task_progress(:on_error)
migration_task.canceled if migration_task.canceling?
handover_to_automate
queue_signal(:poll_automate_state_machine)
end
def poll_power_on_vm_complete
update_migration_task_progress(:on_entry)
raise 'Powering on VM timed out' if polling_timeout
if target_vm.power_state == 'on'
update_migration_task_progress(:on_exit)
return queue_signal(:wait_for_ip_address) unless migration_task.canceling?
migration_task.canceled
handover_to_automate
return queue_signal(:poll_automate_state_machine)
end
update_migration_task_progress(:on_retry)
queue_signal(:poll_power_on_vm_complete, :deliver_on => Time.now.utc + state_retry_interval)
rescue StandardError
update_migration_task_progress(:on_error)
migration_task.canceled if migration_task.canceling?
handover_to_automate
queue_signal(:poll_automate_state_machine)
end
def mark_vm_migrated
migration_task.mark_vm_migrated
handover_to_automate
queue_signal(:poll_automate_state_machine)
end
def abort_virtv2v
migration_task.get_conversion_state
virtv2v_runs = migration_task.options[:virtv2v_started_on].present? && migration_task.options[:virtv2v_finished_on].nil? && migration_task.options[:virtv2v_wrapper].present?
return queue_signal(:power_on_vm) unless virtv2v_runs
if polling_timeout
migration_task.kill_virtv2v('KILL')
return queue_signal(:power_on_vm)
end
migration_task.kill_virtv2v('TERM') if context["retries_#{state}".to_sym] == 1
queue_signal(:abort_virtv2v)
end
def poll_automate_state_machine
return abort_conversion('Polling Automate state machine timed out', 'error') if polling_timeout
message = "Migration Task vm=#{migration_task.source.name}, state=#{migration_task.state}, status=#{migration_task.status}"
_log.info(prep_message(message))
update(:message => message)
if migration_task.state == 'finished'
self.status = migration_task.status
queue_signal(:finish)
else
queue_signal(:poll_automate_state_machine, :deliver_on => Time.now.utc + state_retry_interval)
end
end
end
| {
"content_hash": "feaf9f4dfb1c27bf7c2fca0d55b9a127",
"timestamp": "",
"source": "github",
"line_count": 580,
"max_line_length": 177,
"avg_line_length": 39.206896551724135,
"alnum_prop": 0.6234828496042216,
"repo_name": "mkanoor/manageiq",
"id": "1323091c8a29a072656ae4513bd3c58ee54f91e9",
"size": "22740",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/models/infra_conversion_job.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "3042"
},
{
"name": "Dockerfile",
"bytes": "2925"
},
{
"name": "HTML",
"bytes": "2167"
},
{
"name": "JavaScript",
"bytes": "183"
},
{
"name": "Ruby",
"bytes": "7866558"
},
{
"name": "Shell",
"bytes": "22469"
}
],
"symlink_target": ""
} |
require 'spec_helper'
class HasManySchemaTestEntity
include Proper::Api::Entity
attr_accessor :x
schema do
float :x
end
end
describe Respect::HasManySchema::JSON do
context "representation" do
it "represents the array of values using :of option object" do
schema = Respect::HasManySchema.new(of: "HasManySchemaTestEntity")
e1 = HasManySchemaTestEntity.new
e1.x = 1.0
e2 = HasManySchemaTestEntity.new
e2.x = 2.0
expect( schema.represent(:json, [ e1, e2 ]) ).to eq( [{ x: 1.0 }, { x: 2.0 }] )
end
it "crashes on nil when options don't allow it" do
schema = Respect::HasManySchema.new(of: "HasManySchemaTestEntity")
expect(-> do
schema.represent( :json, nil )
end).to raise_error
end
it "works with nil when options allow it" do
schema = Respect::HasManySchema.new(allow_nil: true, of: "HasManySchemaTestEntity")
expect( schema.represent(:json, nil) ).to eq( nil )
end
end
context "parsing" do
it "parses the array of values using :of option object" do
schema = Respect::HasManySchema.new(of: "HasManySchemaTestEntity")
result = schema.parse(:json, [{ x: 1.0 }, { x: 2.0 }])
expect( result.size ).to eq(2)
expect( result[0] ).to be_instance_of(HasManySchemaTestEntity)
expect( result[0].x ).to eq(1.0)
expect( result[1] ).to be_instance_of(HasManySchemaTestEntity)
expect( result[1].x ).to eq(2.0)
end
it "crashes on nil when options don't allow it" do
schema = Respect::HasManySchema.new(of: "HasManySchemaTestEntity")
expect(-> do
schema.parse( :json, nil )
end).to raise_error
end
it "works with nil when options allow it" do
schema = Respect::HasManySchema.new(allow_nil: true, of: "HasManySchemaTestEntity")
expect( schema.parse(:json, nil) ).to eq( nil )
end
end
end | {
"content_hash": "2564c10fe1e0e8cd23f54ae7ca5d6f07",
"timestamp": "",
"source": "github",
"line_count": 77,
"max_line_length": 89,
"avg_line_length": 24.896103896103895,
"alnum_prop": 0.6421491914449661,
"repo_name": "yard/proper-api",
"id": "026ee447e978dd7b0729301f8facabec882622bf",
"size": "1917",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "spec/proper/api/entity/representations/json/has_many_schema_spec.rb",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "HTML",
"bytes": "4211"
},
{
"name": "Ruby",
"bytes": "104431"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.ObjectModel;
using System.Linq;
using System.Windows.Input;
using Moq;
using Ploeh.AutoFixture;
using Ploeh.SemanticComparison.Fluent;
using Xunit;
using Xunit.Extensions;
using Ploeh.AutoFixture.Xunit;
namespace Ploeh.Samples.ProductManagement.PresentationLogic.Wpf.UnitTest
{
public class MainWindowViewModelTest
{
[Theory, AutoMoqData]
public void CreateWithNullAgentWillThrow(IWindow dummyDialogService)
{
// Fixture setup
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(() =>
new MainWindowViewModel(null, dummyDialogService));
// Teardown
}
[Theory, AutoMoqData]
public void CreateWithNullDialogServiceWillThrow(IProductManagementAgent dummyAgent)
{
// Fixture setup
// Exercise system and verify outcome
Assert.Throws<ArgumentNullException>(() =>
new MainWindowViewModel(dummyAgent, null));
// Teardown
}
[Theory, AutoMoqData]
public void ProductsIsInstance(MainWindowViewModel sut)
{
// Fixture setup
// Exercise system
ObservableCollection<ProductViewModel> result = sut.Products;
// Verify outcome
Assert.NotNull(result);
// Teardown
}
[Theory, AutoMoqData]
public void CloseCommandIsInstance(MainWindowViewModel sut)
{
// Fixture setup
// Exercise system
ICommand result = sut.CloseCommand;
// Verify outcome
Assert.NotNull(result);
// Teardown
}
[Theory, AutoMoqData]
public void ExecuteCloseCommandWillCloseWindow([Frozen]Mock<IWindow> windowMock, MainWindowViewModel sut, object p)
{
// Fixture setup
// Exercise system
sut.CloseCommand.Execute(p);
// Verify outcome
windowMock.Verify(w => w.Close());
// Teardown
}
[Theory, AutoMoqData]
public void RefreshCommandIsInstance(MainWindowViewModel sut)
{
// Fixture setup
// Exercise system
ICommand result = sut.RefreshCommand;
// Verify outcome
Assert.NotNull(result);
// Teardown
}
[Fact]
public void ExecuteRefreshCommandWillCorrectlyPopulateProducts()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var products = fixture.CreateMany<ProductViewModel>().ToList();
fixture.Freeze<Mock<IProductManagementAgent>>().Setup(a => a.SelectAllProducts()).Returns(products);
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
fixture.AddManyTo(sut.Products);
// Exercise system
fixture.Do((object p) => sut.RefreshCommand.Execute(p));
// Verify outcome
Assert.True(products.SequenceEqual(sut.Products), "RefreshCommand");
// Teardown
}
[Theory, AutoMoqData]
public void InsertProductCommandIsInstance(MainWindowViewModel sut)
{
// Fixture setup
// Exercise system
ICommand result = sut.InsertProductCommand;
// Verify outcome
Assert.NotNull(result);
// Teardown
}
[Theory, AutoMoqData]
public void ExecuteInsertProductCommandWillShowCorrectDialog(Mock<IWindow> childWindowMock, [Frozen]Mock<IWindow> windowStub, MainWindowViewModel sut, object p)
{
// Fixture setup
var expectedVM = new ProductEditorViewModel(0)
{
Currency = "DKK",
Name = string.Empty,
Price = string.Empty,
Title = "Add Product"
}.AsSource().OfLikeness<ProductEditorViewModel>();
windowStub.Setup(w => w.CreateChild(expectedVM))
.Returns(childWindowMock.Object);
// Exercise system
sut.InsertProductCommand.Execute(p);
// Verify outcome
childWindowMock.Verify(w => w.ShowDialog());
// Teardown
}
[Fact]
public void ExecuteInsertProductCommandWillNotInsertIntoAgentWhenReturnValueIsNull()
{
// Fixture setup
var fixture = new AutoMoqFixture();
fixture.Freeze<Mock<IWindow>>().Setup(w => w.CreateChild(It.IsAny<object>())).Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns((bool?)null);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
// Exercise system
fixture.Do((object p) => sut.InsertProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.InsertProduct(It.IsAny<ProductEditorViewModel>()), Times.Never());
// Teardown
}
[Fact]
public void ExecuteInsertProductCommandWillNotInsertIntoAgentWhenReturnValueIsFalse()
{
// Fixture setup
var fixture = new AutoMoqFixture();
fixture.Freeze<Mock<IWindow>>().Setup(w => w.CreateChild(It.IsAny<object>())).Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns(false);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
// Exercise system
fixture.Do((object p) => sut.InsertProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.InsertProduct(It.IsAny<ProductEditorViewModel>()), Times.Never());
// Teardown
}
[Fact]
public void ExecuteInsertProductCommandWillInsertIntoAgentWhenReturnValueIsTrue()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var product = fixture.CreateAnonymous<ProductEditorViewModel>().AsSource().OfLikeness<ProductEditorViewModel>()
.Without(d => d.Title)
.Without(d => d.Error)
.Without(d => d.IsValid)
.Without(d => d.Id);
fixture.Freeze<Mock<IWindow>>()
.Setup(w => w.CreateChild(It.IsAny<object>()))
.Callback((object vm) =>
{
var pVM = (ProductEditorViewModel)vm;
pVM.Currency = product.Value.Currency;
pVM.Name = product.Value.Name;
pVM.Price = product.Value.Price;
})
.Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns(true);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
// Exercise system
fixture.Do((object p) => sut.InsertProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.InsertProduct(It.Is<ProductEditorViewModel>(pvm => product.Equals(pvm))));
// Teardown
}
[Fact]
public void ExecuteInsertProductCommandWillReloadProducts()
{
// Fixture setup
var fixture = new AutoMoqFixture();
fixture.Freeze<Mock<IWindow>>().Setup(w => w.CreateChild(It.IsAny<object>())).Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns(true);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
// Exercise system
fixture.Do((object p) => sut.InsertProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.SelectAllProducts());
// Teardown
}
[Theory, AutoMoqData]
public void EditProductCommandIsInstance(MainWindowViewModel sut)
{
// Fixture setup
// Exercise system
ICommand result = sut.EditProductCommand;
// Verify outcome
Assert.NotNull(result);
// Teardown
}
[Fact]
public void EditProductCommandCanExecuteWhenProductIsSelected()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous());
// Exercise system
var result = fixture.Get((object p) => sut.EditProductCommand.CanExecute(p));
// Verify outcome
Assert.True(result);
// Teardown
}
[Theory, AutoMoqData]
public void EditProductCommandCanNotExecuteWhenNoProductIsSelected(MainWindowViewModel sut, object p)
{
// Fixture setup
// Exercise system
var result = sut.EditProductCommand.CanExecute(p);
// Verify outcome
Assert.False(result);
// Teardown
}
[Fact]
public void ExecuteEditProductCommandWillShowCorrectDialog()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var product = fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous();
var expectedEditor = product.Edit().AsSource().OfLikeness<ProductEditorViewModel>()
.With(d => d.Title).EqualsWhen((s, d) => "Edit Product" == d.Title);
var childWindowMock = fixture.CreateAnonymous<Mock<IWindow>>();
var windowStub = fixture.Freeze<Mock<IWindow>>();
windowStub.Setup(w => w.CreateChild(expectedEditor))
.Returns(childWindowMock.Object);
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(product);
// Exercise system
fixture.Do((object p) => sut.EditProductCommand.Execute(p));
// Verify outcome
childWindowMock.Verify(w => w.ShowDialog());
// Teardown
}
[Fact]
public void ExecuteEditProductCommandWillNotUpdateOnAgentWhenReturnValueIsNull()
{
// Fixture setup
var fixture = new AutoMoqFixture();
fixture.Freeze<Mock<IWindow>>().Setup(w => w.CreateChild(It.IsAny<object>())).Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns((bool?)null);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous());
// Exercise system
fixture.Do((object p) => sut.EditProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.InsertProduct(It.IsAny<ProductEditorViewModel>()), Times.Never());
// Teardown
}
[Fact]
public void ExecuteEditProductCommandWillNotUpdateOnAgentWhenReturnValueIsFalse()
{
// Fixture setup
var fixture = new AutoMoqFixture();
fixture.Freeze<Mock<IWindow>>().Setup(w => w.CreateChild(It.IsAny<object>())).Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns(false);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous());
// Exercise system
fixture.Do((object p) => sut.EditProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.InsertProduct(It.IsAny<ProductEditorViewModel>()), Times.Never());
// Teardown
}
[Fact]
public void ExecuteEditProductCommandWillUpdateOnAgentWhenReturnValueIsTrue()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var product = fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous();
var editor = product.Edit().AsSource().OfLikeness<ProductEditorViewModel>()
.With(d => d.Title).EqualsWhen((s, d) => "Edit Product" == d.Title)
.Without(d => d.Error)
.Without(d => d.IsValid)
.Without(d => d.Title);
fixture.Freeze<Mock<IWindow>>()
.Setup(w => w.CreateChild(It.IsAny<object>()))
.Callback((object vm) =>
{
var pVM = (ProductEditorViewModel)vm;
pVM.Currency = editor.Value.Currency;
pVM.Name = editor.Value.Name;
pVM.Price = editor.Value.Price;
})
.Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns(true);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(product);
// Exercise system
fixture.Do((object p) => sut.EditProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.UpdateProduct(It.Is<ProductEditorViewModel>(pvm => editor.Equals(pvm))));
// Teardown
}
[Fact]
public void ExecuteEditProductCommandWillReloadProducts()
{
// Fixture setup
var fixture = new AutoMoqFixture();
fixture.Freeze<Mock<IWindow>>().Setup(w => w.CreateChild(It.IsAny<object>())).Returns(() =>
{
var childStub = fixture.CreateAnonymous<Mock<IWindow>>();
childStub.Setup(cw => cw.ShowDialog()).Returns(true);
return childStub.Object;
});
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous());
// Exercise system
fixture.Do((object p) => sut.EditProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.SelectAllProducts());
// Teardown
}
[Theory, AutoMoqData]
public void DeleteProductCommandIsInstance(MainWindowViewModel sut)
{
// Fixture setup
// Exercise system
ICommand result = sut.DeleteProductCommand;
// Verify outcome
Assert.NotNull(result);
// Teardown
}
[Fact]
public void DeleteProductCommandCanExecuteWhenProductIsSelected()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous());
// Exercise system
var result = fixture.Get((object p) => sut.DeleteProductCommand.CanExecute(p));
// Verify outcome
Assert.True(result, "DeleteProductCommand");
// Teardown
}
[Theory, AutoMoqData]
public void DeleteProductCommandCanNotExecuteWhenNoProductIsSelected(MainWindowViewModel sut, object p)
{
// Fixture setup
// Exercise system
var result = sut.DeleteProductCommand.CanExecute(p);
// Verify outcome
Assert.False(result);
// Teardown
}
[Fact]
public void ExecuteDeleteProductCommandWillDeleteFromAgent()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var product = fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous();
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(product);
// Exercise system
fixture.Do((object p) => sut.DeleteProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.DeleteProduct(product.Id));
// Teardown
}
[Fact]
public void ExecuteDeleteProductCommandWillReloadProducts()
{
// Fixture setup
var fixture = new AutoMoqFixture();
var product = fixture.Build<ProductViewModel>()
.With(x => x.IsSelected, true)
.CreateAnonymous();
var agentMock = fixture.Freeze<Mock<IProductManagementAgent>>();
var sut = fixture.CreateAnonymous<MainWindowViewModel>();
sut.Products.Add(product);
// Exercise system
fixture.Do((object p) => sut.DeleteProductCommand.Execute(p));
// Verify outcome
agentMock.Verify(a => a.SelectAllProducts());
// Teardown
}
}
}
| {
"content_hash": "daf021cd85cf11ef13cb9c04f695639b",
"timestamp": "",
"source": "github",
"line_count": 495,
"max_line_length": 168,
"avg_line_length": 38.38787878787879,
"alnum_prop": 0.55425744658457,
"repo_name": "owolp/Telerik-Academy",
"id": "7dd2e9231348e6942feae37aee6f127b2c9a818c",
"size": "19004",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "Module-2/Design-Patterns/Materials/DI.NET/WpfProductManagementClient/PresentationLogicUnitTest/MainWindowViewModelTest.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ASP",
"bytes": "41735"
},
{
"name": "Batchfile",
"bytes": "260"
},
{
"name": "C",
"bytes": "1487"
},
{
"name": "C#",
"bytes": "4599043"
},
{
"name": "CSS",
"bytes": "160410"
},
{
"name": "CoffeeScript",
"bytes": "3700"
},
{
"name": "HTML",
"bytes": "2086891"
},
{
"name": "JavaScript",
"bytes": "2891383"
},
{
"name": "PowerShell",
"bytes": "287"
},
{
"name": "XSLT",
"bytes": "2499"
}
],
"symlink_target": ""
} |
<?php
namespace User\Entity;
use Doctrine\ORM\Mapping as ORM;
/** @ORM\Entity
* @ORM\Table(name="acl_group")
* */
class AclGroup {
/**
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
* @ORM\Column(type="integer")
*/
protected $id;
/** @ORM\ManyToOne(targetEntity="UserRole",inversedBy="aclActions")
* @ORM\JoinColumn(name="roleId", referencedColumnName="id")
* */
protected $role;
/** @ORM\ManyToOne(targetEntity="AclAction")
* @ORM\JoinColumn(name="actionId", referencedColumnName="id")
* */
protected $action;
/**
* @return the $id
*/
public function getId()
{
return $this->id;
}
/**
* @param field_type $id
*/
public function setId($id)
{
$this->id = $id;
}
/**
* @return the $role
*/
public function getRole()
{
return $this->role;
}
/**
* @return the $action
*/
public function getAction()
{
return $this->action;
}
/**
* @param field_type $role
*/
public function setRole($role)
{
$this->role = $role;
}
/**
* @param field_type $action
*/
public function setAction($action)
{
$this->action = $action;
}
} | {
"content_hash": "9c5a25df66524edd9803754a5a57658e",
"timestamp": "",
"source": "github",
"line_count": 88,
"max_line_length": 71,
"avg_line_length": 15.965909090909092,
"alnum_prop": 0.4761565836298932,
"repo_name": "351784144/DhtvWeiXin",
"id": "4d3cf96011876797bc4ad2b4cd102de6d708d92f",
"size": "1405",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "module/User/src/User/Entity/AclGroup.php",
"mode": "33261",
"license": "bsd-3-clause",
"language": [
{
"name": "ApacheConf",
"bytes": "727"
},
{
"name": "Batchfile",
"bytes": "240"
},
{
"name": "CSS",
"bytes": "161365"
},
{
"name": "HTML",
"bytes": "199536"
},
{
"name": "JavaScript",
"bytes": "1935206"
},
{
"name": "PHP",
"bytes": "745960"
},
{
"name": "Shell",
"bytes": "1252"
}
],
"symlink_target": ""
} |
.multi-column-list {
margin: 1em;
padding: 0;
text-overflow: ellipsis;
overflow: auto;
}
.multi-column-list li {
box-sizing: border-box;
float: left;
list-style-type: none;
margin: 0 25px 2px 0;
width: 250px;
}
.file-pill {
display: block;
background: var(--color-blue);
color: var(--color-base2);
border-radius: 1em;
padding: 3px 7px;
text-overflow: ellipsis;
text-decoration: none;
overflow:hidden;
}
.framed-image {
border: solid 5px var(--color-base2);
border-radius: 10px;
}
| {
"content_hash": "bb0de779ddb172040ae63d70e63f27d4",
"timestamp": "",
"source": "github",
"line_count": 30,
"max_line_length": 39,
"avg_line_length": 17.366666666666667,
"alnum_prop": 0.6602687140115163,
"repo_name": "CGamesPlay/hterminal",
"id": "061968f7e3ce4057537d42c92859d1c80e30eb80",
"size": "521",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "client/ComponentLibrary.css",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "3059"
},
{
"name": "JavaScript",
"bytes": "73230"
},
{
"name": "Objective-C",
"bytes": "729"
},
{
"name": "Shell",
"bytes": "12419"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="@dimen/margin_quarter"
android:clipToPadding="false">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minHeight="@dimen/discovery_search_item_min_height"
android:orientation="vertical"
android:gravity="center_horizontal">
<ImageView
android:id="@+id/icon"
android:src="@drawable/ic_discovery_error"
android:layout_width="@dimen/margin_base_plus"
android:layout_height="@dimen/margin_base_plus"
android:layout_marginTop="@dimen/margin_double_plus"/>
<include layout="@layout/item_discovery_simple_message"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
</FrameLayout>
| {
"content_hash": "46257276faca7efc11f37232f595b89b",
"timestamp": "",
"source": "github",
"line_count": 26,
"max_line_length": 65,
"avg_line_length": 40.15384615384615,
"alnum_prop": 0.7049808429118773,
"repo_name": "matsprea/omim",
"id": "208c9d876b56008b0353369c9e110d93c9a0eef6",
"size": "1044",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "android/res/layout/item_discovery_simple_error.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "10112"
},
{
"name": "Awk",
"bytes": "3962"
},
{
"name": "Batchfile",
"bytes": "8661"
},
{
"name": "C",
"bytes": "11723363"
},
{
"name": "C++",
"bytes": "128909126"
},
{
"name": "CMake",
"bytes": "139770"
},
{
"name": "CSS",
"bytes": "19655"
},
{
"name": "Cucumber",
"bytes": "305230"
},
{
"name": "DIGITAL Command Language",
"bytes": "36710"
},
{
"name": "Emacs Lisp",
"bytes": "7798"
},
{
"name": "Groff",
"bytes": "78550"
},
{
"name": "HTML",
"bytes": "8640160"
},
{
"name": "Inno Setup",
"bytes": "4337"
},
{
"name": "Java",
"bytes": "2348959"
},
{
"name": "JavaScript",
"bytes": "3265"
},
{
"name": "Lua",
"bytes": "54431"
},
{
"name": "Makefile",
"bytes": "232821"
},
{
"name": "Module Management System",
"bytes": "2080"
},
{
"name": "Nginx",
"bytes": "1728"
},
{
"name": "Objective-C",
"bytes": "683316"
},
{
"name": "Objective-C++",
"bytes": "646372"
},
{
"name": "PHP",
"bytes": "2841"
},
{
"name": "Perl",
"bytes": "24354"
},
{
"name": "Protocol Buffer",
"bytes": "439653"
},
{
"name": "Python",
"bytes": "1366636"
},
{
"name": "QMake",
"bytes": "76672"
},
{
"name": "Ruby",
"bytes": "59753"
},
{
"name": "Shell",
"bytes": "2298307"
},
{
"name": "TeX",
"bytes": "311877"
},
{
"name": "VimL",
"bytes": "3744"
}
],
"symlink_target": ""
} |
typedef struct RD_Array RD_Array;
typedef struct RD_ByteArray RD_ByteArray;
RD_Array *array_new(RA_Array size);
RA_Array array_length(const RD_Array *array);
int array_get(const RD_Array *a, RA_Array idx, R_Word *value);
int array_put(RD_Array *a, RA_Array idx, R_Word value);
RD_ByteArray *bytearray_new(RA_Array size);
RD_ByteArray *bytearray_load(const void *source);
RA_Array bytearray_length(const RD_ByteArray *array);
int bytearray_get_byte(const RD_ByteArray *a, RA_Array idx, R_Word *value);
int bytearray_get_word(const RD_ByteArray *a, RA_Array idx, R_Word *value);
int bytearray_put_byte(RD_ByteArray *a, RA_Array idx, R_Byte value);
int bytearray_put_word(RD_ByteArray *a, RA_Array idx, R_Word value);
R_Byte *bytearray_data(RD_ByteArray *a);
const R_Byte *bytearray_data_c(const RD_ByteArray *a);
void bytearray_print(const RD_ByteArray *a);
#endif
| {
"content_hash": "032d05ce27ba7cb3fd05b74ebe1274da",
"timestamp": "",
"source": "github",
"line_count": 35,
"max_line_length": 75,
"avg_line_length": 25.17142857142857,
"alnum_prop": 0.7343927355278093,
"repo_name": "almk277/ROSE",
"id": "895cc4bb9e6968624952d126f519734da938bde1",
"size": "942",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "rose/array.h",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "70649"
},
{
"name": "C++",
"bytes": "25034"
},
{
"name": "Makefile",
"bytes": "1652"
},
{
"name": "Perl",
"bytes": "1401"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Rosita.Invoice.API.DtoMessages
{
public class Class1
{
public Class1()
{
}
}
}
| {
"content_hash": "2bc7b61a86a9f3f8285373cc728b532a",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 40,
"avg_line_length": 16,
"alnum_prop": 0.6473214285714286,
"repo_name": "jmanuelcorral/Rosita",
"id": "aee99ea8a919cfe2c64f1ee5f0d2c40d465bccf9",
"size": "226",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Rosita.Invoice.API.DtoMessages/Class1.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "60308"
}
],
"symlink_target": ""
} |
#include "cocos2d.h"
#include "FairyGUIMacros.h"
NS_FGUI_BEGIN
class UIConfig
{
public:
static std::string defaultFont;
static std::string buttonSound;
static float buttonSoundVolumeScale;
static int defaultScrollStep;
static float defaultScrollDecelerationRate;
static bool defaultScrollTouchEffect;
static bool defaultScrollBounceEffect;
static ScrollBarDisplayType defaultScrollBarDisplay;
static std::string verticalScrollBar;
static std::string horizontalScrollBar;
static int touchDragSensitivity;
static int clickDragSensitivity;
static int touchScrollSensitivity;
static int defaultComboBoxVisibleItemCount;
static std::string globalModalWaiting;
static cocos2d::Color4F modalLayerColor;
static std::string tooltipsWin;
static bool bringWindowToFrontOnClick;
static std::string windowModalWaiting;
static std::string popupMenu;
static std::string popupMenu_seperator;
static void registerFont(const std::string& aliasName, const std::string& realName);
static const std::string& getRealFontName(const std::string& aliasName, bool* isTTF = nullptr);
private:
struct FontNameItem
{
std::string name;
bool ttf;
};
static std::unordered_map<std::string, FontNameItem> _fontNames;
};
NS_FGUI_END
#endif
| {
"content_hash": "1bbfff78a34bfbf0ccbb84a03b308f80",
"timestamp": "",
"source": "github",
"line_count": 46,
"max_line_length": 99,
"avg_line_length": 30.065217391304348,
"alnum_prop": 0.7237888647866956,
"repo_name": "fairygui/FairyGUI-cocos",
"id": "27124fea964b4029e2be6ffb8a2fba6485ddefbe",
"size": "1431",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "libfairygui/Classes/UIConfig.h",
"mode": "33188",
"license": "mit",
"language": [],
"symlink_target": ""
} |
name 'cis_benchmark'
maintainer 'Joshua Timberman'
maintainer_email 'cookbooks@housepub.org'
license 'Apache 2.0'
description "Applies the Center for Internet Security's Benchmarks at\
configuration recommendations Level-I."
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version '0.0.17'
%w(redhat centos fedora scientific debian ubuntu).each do |os|
supports os
end
depends 'sysctl'
| {
"content_hash": "ebcd936c5c823102c41420acb08534bd",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 72,
"avg_line_length": 29.714285714285715,
"alnum_prop": 0.7740384615384616,
"repo_name": "WIU/cis_benchmark-cookbook",
"id": "dfc09506cb0ecf860b5fc5cb4f9fd1cd19e3c4e4",
"size": "416",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "metadata.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "HTML",
"bytes": "8256"
},
{
"name": "Ruby",
"bytes": "19981"
}
],
"symlink_target": ""
} |
package testsupport;
import com.jnape.loanshark.annotation.Todo;
import javax.lang.model.element.Element;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class ElementTestFactory {
public static Element elementWithTodo(Todo todo) {
Element element = mock(Element.class);
when(element.getAnnotation(Todo.class)).thenReturn(todo);
return element;
}
}
| {
"content_hash": "3fff28172bed0480626803a0ba27c7d4",
"timestamp": "",
"source": "github",
"line_count": 17,
"max_line_length": 65,
"avg_line_length": 25,
"alnum_prop": 0.7435294117647059,
"repo_name": "palatable/loan-shark",
"id": "e2acfeeec13f06d9f7ce20e5f8b5004508b54bac",
"size": "425",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/test/java/testsupport/ElementTestFactory.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "14873"
}
],
"symlink_target": ""
} |
"""
Routes Configuration File
Put Routing rules here
"""
from system.core.router import routes
routes['default_controller'] = 'Courses'
routes['GET']['/index'] = 'Courses#index'
routes['POST']['/courses/add'] = 'Courses#add'
routes['GET']['/courses/destroy/<course_id>'] = 'Courses#destroy'
routes['GET']['/courses/delete/<course_id>'] = 'Courses#delete'
| {
"content_hash": "6c5b80fbadd530a3db893884f899fc34",
"timestamp": "",
"source": "github",
"line_count": 14,
"max_line_length": 65,
"avg_line_length": 26.214285714285715,
"alnum_prop": 0.6757493188010899,
"repo_name": "authman/Python201609",
"id": "0e91d5f00152ab6513a7864e2496d49d8da49e8c",
"size": "367",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Guerrero_Melissa/Assignments/Pylot_Courses_app/config/routes.py",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Batchfile",
"bytes": "1231"
},
{
"name": "C",
"bytes": "430679"
},
{
"name": "C++",
"bytes": "21416"
},
{
"name": "CSS",
"bytes": "22689"
},
{
"name": "HTML",
"bytes": "168012"
},
{
"name": "JavaScript",
"bytes": "3734"
},
{
"name": "PowerShell",
"bytes": "8175"
},
{
"name": "Python",
"bytes": "590654"
},
{
"name": "Shell",
"bytes": "9350"
}
],
"symlink_target": ""
} |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Antlr4.Runtime;
namespace ImageQuery.Language
{
public class ParserErrorListener : BaseErrorListener
{
public static readonly ParserErrorListener Instance = new ParserErrorListener();
public override void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
{
throw new ParseException(string.Format("Syntax error at {0}:{1} - {2}", line, charPositionInLine, msg));
}
}
}
| {
"content_hash": "f3d2baf72ff06b1de961abe6842e2b7d",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 158,
"avg_line_length": 33.10526315789474,
"alnum_prop": 0.7313195548489666,
"repo_name": "redxdev/ImageQuery-CS",
"id": "1ba72b1330863469fcdc7a9bdb5efe56e7cb0896",
"size": "631",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "ImageQuery/Language/ParserErrorListener.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ANTLR",
"bytes": "12559"
},
{
"name": "C#",
"bytes": "112390"
}
],
"symlink_target": ""
} |
using Melanchall.DryWetMidi.Common;
namespace Melanchall.DryWetMidi.Standards
{
/// <summary>
/// The class which provides information about the General MIDI Level 1 standard.
/// </summary>
public static class GeneralMidi
{
#region Constants
/// <summary>
/// Channel reserved for percussion according to the General MIDI Level 1 standard.
/// </summary>
public static readonly FourBitNumber PercussionChannel = (FourBitNumber)9;
#endregion
}
}
| {
"content_hash": "37bc876c82dfe1375c90ee4e917138da",
"timestamp": "",
"source": "github",
"line_count": 19,
"max_line_length": 91,
"avg_line_length": 27.473684210526315,
"alnum_prop": 0.6609195402298851,
"repo_name": "melanchall/drywetmidi",
"id": "2dc169680166d7703714e5e1c7d3c0e8f646ebc6",
"size": "524",
"binary": false,
"copies": "2",
"ref": "refs/heads/develop",
"path": "DryWetMidi/Standards/GeneralMidi/GeneralMidi.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C",
"bytes": "79632"
},
{
"name": "C#",
"bytes": "6484646"
},
{
"name": "PowerShell",
"bytes": "8465"
}
],
"symlink_target": ""
} |
package org.loon.framework.android.game.action.sprite.effect;
import org.loon.framework.android.game.action.map.Config;
import org.loon.framework.android.game.action.map.Field2D;
import org.loon.framework.android.game.action.sprite.ISprite;
import org.loon.framework.android.game.core.LObject;
import org.loon.framework.android.game.core.LSystem;
import org.loon.framework.android.game.core.geom.RectBox;
import org.loon.framework.android.game.core.geom.Vector2D;
import org.loon.framework.android.game.core.graphics.LImage;
import org.loon.framework.android.game.core.graphics.device.LGraphics;
import org.loon.framework.android.game.core.timer.LTimer;
import android.graphics.Bitmap;
public class SplitEffect extends LObject implements ISprite {
/**
*
*/
private static final long serialVersionUID = 1L;
private Vector2D v1, v2;
private float alpha;
private int width, height, halfWidth, halfHeight, multiples, direction;
private boolean visible, complete, special;
private RectBox limit;
private LImage image;
private LTimer timer;
public SplitEffect(String fileName, int d) {
this(new LImage(fileName), d);
}
public SplitEffect(LImage t, int d) {
this(t, LSystem.screenRect, d);
}
public SplitEffect(LImage t, RectBox limit, int d) {
this.image = t;
this.width = image.getWidth();
this.height = image.getHeight();
this.halfWidth = width / 2;
this.halfHeight = height / 2;
this.multiples = 2;
this.direction = d;
this.limit = limit;
this.timer = new LTimer(10);
this.visible = true;
this.v1 = new Vector2D();
this.v2 = new Vector2D();
switch (direction) {
case Config.UP:
case Config.DOWN:
special = true;
case Config.TLEFT:
case Config.TRIGHT:
v1.set(0, 0);
v2.set(halfWidth, 0);
break;
case Config.LEFT:
case Config.RIGHT:
special = true;
case Config.TUP:
case Config.TDOWN:
v1.set(0, 0);
v2.set(0, halfHeight);
break;
}
}
public void setDelay(long delay) {
timer.setDelay(delay);
}
public long getDelay() {
return timer.getDelay();
}
public int getHeight() {
return height;
}
public int getWidth() {
return width;
}
public void update(long elapsedTime) {
if (!complete) {
if (timer.action(elapsedTime)) {
switch (direction) {
case Config.LEFT:
case Config.RIGHT:
case Config.TLEFT:
case Config.TRIGHT:
v1.move_multiples(Field2D.TLEFT, multiples);
v2.move_multiples(Field2D.TRIGHT, multiples);
break;
case Config.UP:
case Config.DOWN:
case Config.TUP:
case Config.TDOWN:
v1.move_multiples(Field2D.TUP, multiples);
v2.move_multiples(Field2D.TDOWN, multiples);
break;
}
if (special) {
if (!limit.intersects((int) v1.x, (int) v1.y, halfHeight,
halfWidth)
&& !limit.intersects((int) v2.x, (int) v2.y,
halfHeight, halfWidth)) {
this.complete = true;
}
} else if (!limit.intersects((int) v1.x, (int) v1.y, halfWidth,
halfHeight)
&& !limit.intersects((int) v2.x, (int) v2.y, halfWidth,
halfHeight)) {
this.complete = true;
}
}
}
}
public void createUI(LGraphics g) {
if (!visible) {
return;
}
if (!complete) {
if (alpha > 0 && alpha < 1) {
g.setAlpha(alpha);
}
final int x1 = (int) (v1.x + getX());
final int y1 = (int) (v1.y + getY());
final int x2 = (int) (v2.x + getX());
final int y2 = (int) (v2.y + getY());
switch (direction) {
case Config.LEFT:
case Config.RIGHT:
case Config.TUP:
case Config.TDOWN:
g.drawImage(image, x1, y1, width, halfHeight, 0, 0, width,
halfHeight);
g.drawImage(image, x2, y2, width, halfHeight, 0, halfHeight,
width, height);
break;
case Config.UP:
case Config.DOWN:
case Config.TLEFT:
case Config.TRIGHT:
g.drawImage(image, x1, y1, halfWidth, height, 0, 0,
halfWidth, height);
g.drawImage(image, x2, y2, halfWidth, height, halfWidth, 0,
width, height);
break;
}
if (alpha > 0 && alpha < 1) {
g.setAlpha(1f);
}
}
}
public boolean isComplete() {
return complete;
}
public float getAlpha() {
return alpha;
}
public void setAlpha(float a) {
this.alpha = a;
}
public Bitmap getBitmap() {
return image.getBitmap();
}
public RectBox getCollisionBox() {
return getRect(x(), y(), width, height);
}
public int getMultiples() {
return multiples;
}
public void setMultiples(int multiples) {
this.multiples = multiples;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
public void dispose() {
if (image != null) {
image.dispose();
image = null;
}
}
}
| {
"content_hash": "10dcf5ccca9257e4de00d456955f4338",
"timestamp": "",
"source": "github",
"line_count": 217,
"max_line_length": 72,
"avg_line_length": 21.70046082949309,
"alnum_prop": 0.6568273518793799,
"repo_name": "cping/LGame",
"id": "1974dda9dabe8259aa21ec80c339703b912e678c",
"size": "5399",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Java/old/Canvas_ver/src/org/loon/framework/android/game/action/sprite/effect/SplitEffect.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "1472"
},
{
"name": "C",
"bytes": "3901"
},
{
"name": "C#",
"bytes": "3682953"
},
{
"name": "C++",
"bytes": "24221"
},
{
"name": "CSS",
"bytes": "115312"
},
{
"name": "HTML",
"bytes": "1782"
},
{
"name": "Java",
"bytes": "26857190"
},
{
"name": "JavaScript",
"bytes": "177232"
},
{
"name": "Shell",
"bytes": "236"
}
],
"symlink_target": ""
} |
package com.google.gerrit.server.plugins;
import com.google.gerrit.extensions.registration.DynamicSet;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.jgit.internal.storage.file.FileSnapshot;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Singleton
class UniversalServerPluginProvider implements ServerPluginProvider {
private static final Logger log = LoggerFactory.getLogger(UniversalServerPluginProvider.class);
private final DynamicSet<ServerPluginProvider> serverPluginProviders;
@Inject
UniversalServerPluginProvider(DynamicSet<ServerPluginProvider> sf) {
this.serverPluginProviders = sf;
}
@Override
public ServerPlugin get(Path srcPath, FileSnapshot snapshot, PluginDescription pluginDescription)
throws InvalidPluginException {
return providerOf(srcPath).get(srcPath, snapshot, pluginDescription);
}
@Override
public String getPluginName(Path srcPath) {
return providerOf(srcPath).getPluginName(srcPath);
}
@Override
public boolean handles(Path srcPath) {
List<ServerPluginProvider> providers = providersForHandlingPlugin(srcPath);
switch (providers.size()) {
case 1:
return true;
case 0:
return false;
default:
throw new MultipleProvidersForPluginException(srcPath, providers);
}
}
@Override
public String getProviderPluginName() {
return "gerrit";
}
private ServerPluginProvider providerOf(Path srcPath) {
List<ServerPluginProvider> providers = providersForHandlingPlugin(srcPath);
switch (providers.size()) {
case 1:
return providers.get(0);
case 0:
throw new IllegalArgumentException(
"No ServerPluginProvider found/loaded to handle plugin file "
+ srcPath.toAbsolutePath());
default:
throw new MultipleProvidersForPluginException(srcPath, providers);
}
}
private List<ServerPluginProvider> providersForHandlingPlugin(Path srcPath) {
List<ServerPluginProvider> providers = new ArrayList<>();
for (ServerPluginProvider serverPluginProvider : serverPluginProviders) {
boolean handles = serverPluginProvider.handles(srcPath);
log.debug(
"File {} handled by {} ? => {}",
srcPath,
serverPluginProvider.getProviderPluginName(),
handles);
if (handles) {
providers.add(serverPluginProvider);
}
}
return providers;
}
}
| {
"content_hash": "cb06cf076535f091b83219d346fb3716",
"timestamp": "",
"source": "github",
"line_count": 82,
"max_line_length": 99,
"avg_line_length": 31.097560975609756,
"alnum_prop": 0.7247058823529412,
"repo_name": "gerrit-review/gerrit",
"id": "50b8752150ca3a4fafdb7ce8ee16939ec99fb6c5",
"size": "3159",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "java/com/google/gerrit/server/plugins/UniversalServerPluginProvider.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "47547"
},
{
"name": "GAP",
"bytes": "4124"
},
{
"name": "Go",
"bytes": "8041"
},
{
"name": "HTML",
"bytes": "1695553"
},
{
"name": "Java",
"bytes": "14114142"
},
{
"name": "JavaScript",
"bytes": "821208"
},
{
"name": "PLpgSQL",
"bytes": "2616"
},
{
"name": "Perl",
"bytes": "9943"
},
{
"name": "Prolog",
"bytes": "18454"
},
{
"name": "Python",
"bytes": "187604"
},
{
"name": "Roff",
"bytes": "32749"
},
{
"name": "Shell",
"bytes": "58865"
}
],
"symlink_target": ""
} |
package com.ihgoo.calendar.adapter;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import com.ihgoo.calendar.view.CalendarMonthView;
/**
* Created by ihgoo on 2015/3/20.
*/
public class CalendarMonthAdapter extends BaseAdapter {
private Context mContext;
public CalendarMonthAdapter(Context mContext) {
this.mContext = mContext;
}
@Override
public int getCount() {
return 12;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = new CalendarMonthView(mContext, position);
return view;
}
}
| {
"content_hash": "ab772be5b786dd56dae955fdd5bdf8a9",
"timestamp": "",
"source": "github",
"line_count": 42,
"max_line_length": 75,
"avg_line_length": 20.285714285714285,
"alnum_prop": 0.6784037558685446,
"repo_name": "ihgoo/SimpleCalendar",
"id": "0c00610f6ee37a2d34174df312bf93ddda683489",
"size": "852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "calendar/app/src/main/java/com/ihgoo/calendar/adapter/CalendarMonthAdapter.java",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "Java",
"bytes": "6798"
}
],
"symlink_target": ""
} |
<?xml version="1.0" encoding="utf-8"?>
<org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject plugin="workflow-multibranch">
<properties/>
<views>
<hudson.model.AllView>
<name>All</name>
<filterExecutors>false</filterExecutors>
<filterQueue>false</filterQueue>
<properties class="hudson.model.View$PropertyList"/>
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../../.."/>
</hudson.model.AllView>
</views>
<viewsTabBar class="hudson.views.DefaultViewsTabBar"/>
<folderViews class="jenkins.branch.MultiBranchProjectViewHolder" plugin="branch-api">
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../.."/>
</folderViews>
<healthMetrics>
<com.cloudbees.hudson.plugins.folder.health.WorstChildHealthMetric plugin="cloudbees-folder">
<nonRecursive>false</nonRecursive>
</com.cloudbees.hudson.plugins.folder.health.WorstChildHealthMetric>
</healthMetrics>
<icon class="jenkins.branch.MetadataActionFolderIcon" plugin="branch-api">
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../.."/>
</icon>
<orphanedItemStrategy class="com.cloudbees.hudson.plugins.folder.computed.DefaultOrphanedItemStrategy" plugin="cloudbees-folder">
<pruneDeadBranches>true</pruneDeadBranches>
<daysToKeep>-1</daysToKeep>
<numToKeep>-1</numToKeep>
</orphanedItemStrategy>
<triggers/>
<sources class="jenkins.branch.MultiBranchProject$BranchSourceList" plugin="branch-api">
<data>
<jenkins.branch.BranchSource>
<source class="org.jenkinsci.plugins.github_branch_source.GitHubSCMSource" plugin="github-branch-source">
<id>gh-johndoe-foo</id>
<repoOwner>johndoe</repoOwner>
<repository>foo</repository>
<traits>
<org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait>
<strategyId>1</strategyId>
</org.jenkinsci.plugins.github__branch__source.BranchDiscoveryTrait>
<org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait>
<strategyId>1</strategyId>
<trust class="org.jenkinsci.plugins.github_branch_source.ForkPullRequestDiscoveryTrait$TrustContributors"/>
</org.jenkinsci.plugins.github__branch__source.ForkPullRequestDiscoveryTrait>
<org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait>
<strategyId>1</strategyId>
</org.jenkinsci.plugins.github__branch__source.OriginPullRequestDiscoveryTrait>
<jenkins.plugins.git.traits.WipeWorkspaceTrait>
<extension class="hudson.plugins.git.extensions.impl.WipeWorkspace"/>
</jenkins.plugins.git.traits.WipeWorkspaceTrait>
</traits>
</source>
<strategy class="jenkins.branch.NamedExceptionsBranchPropertyStrategy">
<defaultProperties class="java.util.Arrays$ArrayList">
<a class="jenkins.branch.BranchProperty-array">
<org.jenkinsci.plugins.workflow.multibranch.DurabilityHintBranchProperty plugin="workflow-multibranch">
<hint>MAX_SURVIVABILITY</hint>
</org.jenkinsci.plugins.workflow.multibranch.DurabilityHintBranchProperty>
</a>
</defaultProperties>
<namedExceptions class="java.util.Arrays$ArrayList">
<a class="jenkins.branch.NamedExceptionsBranchPropertyStrategy$Named-array">
<jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
<name>master</name>
<props class="java.util.Arrays$ArrayList">
<a class="jenkins.branch.BranchProperty-array">
<jenkins.branch.NoTriggerBranchProperty/>
<org.jenkinsci.plugins.workflow.multibranch.DurabilityHintBranchProperty plugin="workflow-multibranch">
<hint>SURVIVABLE_NONATOMIC</hint>
</org.jenkinsci.plugins.workflow.multibranch.DurabilityHintBranchProperty>
</a>
</props>
</jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
<jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
<name>staging</name>
<props class="java.util.Arrays$ArrayList">
<a class="jenkins.branch.BranchProperty-array">
<jenkins.branch.NoTriggerBranchProperty/>
</a>
</props>
</jenkins.branch.NamedExceptionsBranchPropertyStrategy_-Named>
</a>
</namedExceptions>
</strategy>
</jenkins.branch.BranchSource>
</data>
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../.."/>
</sources>
<factory class="org.jenkinsci.plugins.workflow.multibranch.WorkflowBranchProjectFactory">
<owner class="org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject" reference="../.."/>
<scriptPath>Jenkinsfile</scriptPath>
</factory>
</org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject>
| {
"content_hash": "1b8fb4ba44ab778bf4fcb3bbd5adc459",
"timestamp": "",
"source": "github",
"line_count": 94,
"max_line_length": 131,
"avg_line_length": 55.92553191489362,
"alnum_prop": 0.6859425527867605,
"repo_name": "gforcada/jenkins-job-builder",
"id": "07818a90fccd4726b2256cce8bbbd56f2fc824b9",
"size": "5257",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "tests/multibranch/fixtures/scm_github_named_branch_props.xml",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "465"
},
{
"name": "C++",
"bytes": "737"
},
{
"name": "HTML",
"bytes": "144"
},
{
"name": "PHP",
"bytes": "334"
},
{
"name": "Pawn",
"bytes": "57"
},
{
"name": "Python",
"bytes": "1335234"
},
{
"name": "Shell",
"bytes": "7552"
},
{
"name": "SourcePawn",
"bytes": "63"
}
],
"symlink_target": ""
} |
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Reflection;
namespace ExRam.Gremlinq.Core
{
internal abstract class GremlinQueryBase
{
private delegate IGremlinQueryBase QueryContinuation(
GremlinQueryBase existingQuery,
Traversal? maybeNewTraversal,
IImmutableDictionary<StepLabel, LabelProjections>? maybeNewLabelProjections,
QueryFlags? maybeNewQueryFlags);
private static readonly ConcurrentDictionary<Type, QueryContinuation?> QueryTypes = new();
private static readonly MethodInfo CreateFuncMethod = typeof(GremlinQueryBase).GetMethod(nameof(CreateFunc), BindingFlags.NonPublic | BindingFlags.Static)!;
protected GremlinQueryBase(
IGremlinQueryEnvironment environment,
Traversal steps,
IImmutableDictionary<StepLabel, LabelProjections> labelProjections,
QueryFlags flags)
{
Steps = steps;
Flags = flags;
Environment = environment;
LabelProjections = labelProjections;
}
public override string ToString() => $"GremlinQuery(Steps.Count: {Steps.Count})";
protected internal TTargetQuery CloneAs<TTargetQuery>(
Traversal? maybeNewTraversal = null,
IImmutableDictionary<StepLabel, LabelProjections>? maybeNewLabelProjections = null,
QueryFlags? maybeNewQueryFlags = null)
{
var targetQueryType = typeof(TTargetQuery);
var maybeConstructor = QueryTypes.GetOrAdd(
targetQueryType,
static closureType =>
{
if (closureType.IsGenericType && closureType.GetGenericTypeDefinition() == typeof(GremlinQuery<,,,,,>))
{
return (QueryContinuation?)CreateFuncMethod
.MakeGenericMethod(
closureType.GetGenericArguments())
.Invoke(null, new object?[] { closureType })!;
}
var elementType = GetMatchingType(closureType, "TElement", "TVertex", "TEdge", "TProperty", "TArray") ?? typeof(object);
var outVertexType = GetMatchingType(closureType, "TOutVertex", "TAdjacentVertex") ?? typeof(object);
var inVertexType = GetMatchingType(closureType, "TInVertex") ?? typeof(object);
var scalarType = GetMatchingType(closureType, "TValue", "TArrayItem");
var metaType = GetMatchingType(closureType, "TMeta") ?? typeof(object);
var queryType = GetMatchingType(closureType, "TOriginalQuery") ?? typeof(object);
return (QueryContinuation?)CreateFuncMethod
.MakeGenericMethod(
elementType,
outVertexType,
inVertexType,
scalarType ?? (elementType.IsArray
? elementType.GetElementType()!
: typeof(object)),
metaType,
queryType)
.Invoke(null, new object?[] { closureType })!;
});
return (maybeConstructor is { } constructor)
? (TTargetQuery)constructor(this, maybeNewTraversal, maybeNewLabelProjections, maybeNewQueryFlags)
: throw new NotSupportedException($"Cannot change the query type to {targetQueryType}.");
}
private static QueryContinuation? CreateFunc<TElement, TOutVertex, TInVertex, TScalar, TMeta, TFoldedQuery>(Type targetQueryType)
{
if (!targetQueryType.IsAssignableFrom(typeof(GremlinQuery<TElement, TOutVertex, TInVertex, TScalar, TMeta, TFoldedQuery>)))
return null;
return (existingQuery, maybeNewTraversal, maybeNewLabelProjections, maybeNewQueryFlags) =>
{
var newTraversal = maybeNewTraversal ?? existingQuery.Steps;
var newQueryFlags = maybeNewQueryFlags ?? existingQuery.Flags;
var newLabelProjections = maybeNewLabelProjections ?? existingQuery.LabelProjections;
if (targetQueryType.IsInstanceOfType(existingQuery) && newQueryFlags == existingQuery.Flags && maybeNewTraversal == null && newLabelProjections == existingQuery.LabelProjections)
return (IGremlinQueryBase)existingQuery;
return new GremlinQuery<TElement, TOutVertex, TInVertex, TScalar, TMeta, TFoldedQuery>(
existingQuery.Environment,
newTraversal,
newLabelProjections,
newQueryFlags);
};
}
private static Type? GetMatchingType(Type interfaceType, params string[] argumentNames)
{
if (interfaceType.IsGenericType)
{
var genericArguments = interfaceType.GetGenericArguments();
var genericTypeDefinitionArguments = interfaceType.GetGenericTypeDefinition().GetGenericArguments();
foreach (var argumentName in argumentNames)
{
for (var i = 0; i < genericTypeDefinitionArguments.Length; i++)
{
if (genericTypeDefinitionArguments[i].ToString() == argumentName)
return genericArguments[i];
}
}
}
return default;
}
protected internal Traversal Steps { get; }
protected internal QueryFlags Flags { get; }
protected internal IGremlinQueryEnvironment Environment { get; }
protected internal IImmutableDictionary<StepLabel, LabelProjections> LabelProjections { get; }
}
}
| {
"content_hash": "ca81ada86319d3bb063433ba81bd89a0",
"timestamp": "",
"source": "github",
"line_count": 123,
"max_line_length": 194,
"avg_line_length": 48.235772357723576,
"alnum_prop": 0.5961570874768245,
"repo_name": "ExRam/ExRam.Gremlinq",
"id": "a3727227534ca3f556dbb307781802d463d3f7c8",
"size": "5935",
"binary": false,
"copies": "1",
"ref": "refs/heads/main",
"path": "src/ExRam.Gremlinq.Core/Queries/GremlinQueryBase.cs",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "C#",
"bytes": "1459609"
}
],
"symlink_target": ""
} |
class FileAPI{
public:
FileAPI(const std::string& directory);
ObjectBd createObject(pcl::PointCloud<pcl::VFHSignature308>::Ptr object_signature,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_pointcloud,
std::vector<tf::Transform> relative_arm_pose,
std::vector<tf::Transform> object_pose);
ObjectBd createObject(pcl::PointCloud<pcl::VFHSignature308>::Ptr object_signature,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_pointcloud,
std::vector<tf::Transform> relative_arm_pose,
std::vector<tf::Transform> object_pose,
std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > p_tf);
void save(pcl::PointCloud<pcl::VFHSignature308>::Ptr object_signature,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_pointCloud,
std::vector<tf::Transform> relative_arm_pose,
std::vector<tf::Transform> object_pose);
void save(pcl::PointCloud<pcl::VFHSignature308>::Ptr object_signature,
pcl::PointCloud<pcl::PointXYZRGB>::Ptr object_pointCloud,
std::vector<tf::Transform> relative_arm_pose,
std::vector<tf::Transform> object_pose,
std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > p_tf);
void saveObject(ObjectBd obj);
ObjectBd loadFile(const std::string& p_fileName);
std::vector<ObjectBd> getAllObjects() const;
ObjectBd getObjectByIndex(int index) const;
pcl::PointCloud<pcl::VFHSignature308>::Ptr getAllHistograms() const;
pcl::VFHSignature308 getHistogramByIndex (int p_index) const;
ObjectBd retrieveObjectFromHistogram(int p_positionHisto) const;
std::vector<ObjectBd> retrieveObjectFromHistogram(std::vector<int> indices) const;
std::vector<int> retrieveHistogramFromObject(int p_indice) const;
int fileAlreadyLoad(const std::string& p_filename);
void clearDatabase();
private:
std::string findDefaultName();
void saveCvgh(ObjectBd p_obj, const std::string& p_fileName);
void savePointCloud(ObjectBd p_obj, const std::string& p_fileName);
void savePoseArm(ObjectBd p_obj, const std::string& p_fileName);
void savePoseObject(ObjectBd p_obj, const std::string& p_fileName);
void saveTranform(ObjectBd p_obj, const std::string& p_fileName);
void failSaveUndo(const std::string& p_fileName);
pcl::PointCloud<pcl::VFHSignature308>::Ptr loadSignature(const std::string& p_filename);
pcl::PointCloud<pcl::PointXYZRGB>::Ptr loadPointCloud(const std::string& p_filename);
std::vector<tf::Transform> loadPoseArm(const std::string& p_filename);
std::vector<tf::Transform> loadPoseObject(const std::string& p_filename);
std::vector<Eigen::Matrix4f,Eigen::aligned_allocator<Eigen::Matrix4f> > loadTransform(const std::string& p_filename);
bool validationObj(ObjectBd p_obj);
bool fileExist(const std::string& p_fileName);
void parseDirectory();
int m_highest_index;
std::string m_pathToBd;
std::string m_pathcvfh;
std::string m_pathPointCloud;
std::string m_pathPoseObject;
std::string m_pathPoseArm;
std::string m_pathTransform;
std::vector<ObjectBd> m_bdObjectVector;
pcl::PointCloud<pcl::VFHSignature308>::Ptr m_pcvfh;
};
#endif
| {
"content_hash": "1ece7e16d25ceeb564478bdc9095b3b9",
"timestamp": "",
"source": "github",
"line_count": 87,
"max_line_length": 121,
"avg_line_length": 39.229885057471265,
"alnum_prop": 0.676530911221799,
"repo_name": "jpmerc/perception3d",
"id": "2c61c6b461e6662ce7796a0ea4a37dd05f235ed6",
"size": "3847",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "include/fileAPI.h",
"mode": "33188",
"license": "bsd-3-clause",
"language": [
{
"name": "C++",
"bytes": "432439"
},
{
"name": "CMake",
"bytes": "6109"
},
{
"name": "Shell",
"bytes": "200"
}
],
"symlink_target": ""
} |
#pragma once
#include <aws/quicksight/QuickSight_EXPORTS.h>
#include <aws/quicksight/QuickSightRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/quicksight/model/ResourcePermission.h>
#include <utility>
namespace Aws
{
namespace QuickSight
{
namespace Model
{
/**
*/
class AWS_QUICKSIGHT_API UpdateFolderPermissionsRequest : public QuickSightRequest
{
public:
UpdateFolderPermissionsRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateFolderPermissions"; }
Aws::String SerializePayload() const override;
/**
* <p>The AWS account ID.</p>
*/
inline const Aws::String& GetAwsAccountId() const{ return m_awsAccountId; }
/**
* <p>The AWS account ID.</p>
*/
inline bool AwsAccountIdHasBeenSet() const { return m_awsAccountIdHasBeenSet; }
/**
* <p>The AWS account ID.</p>
*/
inline void SetAwsAccountId(const Aws::String& value) { m_awsAccountIdHasBeenSet = true; m_awsAccountId = value; }
/**
* <p>The AWS account ID.</p>
*/
inline void SetAwsAccountId(Aws::String&& value) { m_awsAccountIdHasBeenSet = true; m_awsAccountId = std::move(value); }
/**
* <p>The AWS account ID.</p>
*/
inline void SetAwsAccountId(const char* value) { m_awsAccountIdHasBeenSet = true; m_awsAccountId.assign(value); }
/**
* <p>The AWS account ID.</p>
*/
inline UpdateFolderPermissionsRequest& WithAwsAccountId(const Aws::String& value) { SetAwsAccountId(value); return *this;}
/**
* <p>The AWS account ID.</p>
*/
inline UpdateFolderPermissionsRequest& WithAwsAccountId(Aws::String&& value) { SetAwsAccountId(std::move(value)); return *this;}
/**
* <p>The AWS account ID.</p>
*/
inline UpdateFolderPermissionsRequest& WithAwsAccountId(const char* value) { SetAwsAccountId(value); return *this;}
/**
* <p>The folder ID.</p>
*/
inline const Aws::String& GetFolderId() const{ return m_folderId; }
/**
* <p>The folder ID.</p>
*/
inline bool FolderIdHasBeenSet() const { return m_folderIdHasBeenSet; }
/**
* <p>The folder ID.</p>
*/
inline void SetFolderId(const Aws::String& value) { m_folderIdHasBeenSet = true; m_folderId = value; }
/**
* <p>The folder ID.</p>
*/
inline void SetFolderId(Aws::String&& value) { m_folderIdHasBeenSet = true; m_folderId = std::move(value); }
/**
* <p>The folder ID.</p>
*/
inline void SetFolderId(const char* value) { m_folderIdHasBeenSet = true; m_folderId.assign(value); }
/**
* <p>The folder ID.</p>
*/
inline UpdateFolderPermissionsRequest& WithFolderId(const Aws::String& value) { SetFolderId(value); return *this;}
/**
* <p>The folder ID.</p>
*/
inline UpdateFolderPermissionsRequest& WithFolderId(Aws::String&& value) { SetFolderId(std::move(value)); return *this;}
/**
* <p>The folder ID.</p>
*/
inline UpdateFolderPermissionsRequest& WithFolderId(const char* value) { SetFolderId(value); return *this;}
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline const Aws::Vector<ResourcePermission>& GetGrantPermissions() const{ return m_grantPermissions; }
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline bool GrantPermissionsHasBeenSet() const { return m_grantPermissionsHasBeenSet; }
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline void SetGrantPermissions(const Aws::Vector<ResourcePermission>& value) { m_grantPermissionsHasBeenSet = true; m_grantPermissions = value; }
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline void SetGrantPermissions(Aws::Vector<ResourcePermission>&& value) { m_grantPermissionsHasBeenSet = true; m_grantPermissions = std::move(value); }
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline UpdateFolderPermissionsRequest& WithGrantPermissions(const Aws::Vector<ResourcePermission>& value) { SetGrantPermissions(value); return *this;}
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline UpdateFolderPermissionsRequest& WithGrantPermissions(Aws::Vector<ResourcePermission>&& value) { SetGrantPermissions(std::move(value)); return *this;}
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline UpdateFolderPermissionsRequest& AddGrantPermissions(const ResourcePermission& value) { m_grantPermissionsHasBeenSet = true; m_grantPermissions.push_back(value); return *this; }
/**
* <p>The permissions that you want to grant on a resource.</p>
*/
inline UpdateFolderPermissionsRequest& AddGrantPermissions(ResourcePermission&& value) { m_grantPermissionsHasBeenSet = true; m_grantPermissions.push_back(std::move(value)); return *this; }
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline const Aws::Vector<ResourcePermission>& GetRevokePermissions() const{ return m_revokePermissions; }
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline bool RevokePermissionsHasBeenSet() const { return m_revokePermissionsHasBeenSet; }
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline void SetRevokePermissions(const Aws::Vector<ResourcePermission>& value) { m_revokePermissionsHasBeenSet = true; m_revokePermissions = value; }
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline void SetRevokePermissions(Aws::Vector<ResourcePermission>&& value) { m_revokePermissionsHasBeenSet = true; m_revokePermissions = std::move(value); }
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline UpdateFolderPermissionsRequest& WithRevokePermissions(const Aws::Vector<ResourcePermission>& value) { SetRevokePermissions(value); return *this;}
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline UpdateFolderPermissionsRequest& WithRevokePermissions(Aws::Vector<ResourcePermission>&& value) { SetRevokePermissions(std::move(value)); return *this;}
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline UpdateFolderPermissionsRequest& AddRevokePermissions(const ResourcePermission& value) { m_revokePermissionsHasBeenSet = true; m_revokePermissions.push_back(value); return *this; }
/**
* <p>The permissions that you want to revoke from a resource.</p>
*/
inline UpdateFolderPermissionsRequest& AddRevokePermissions(ResourcePermission&& value) { m_revokePermissionsHasBeenSet = true; m_revokePermissions.push_back(std::move(value)); return *this; }
private:
Aws::String m_awsAccountId;
bool m_awsAccountIdHasBeenSet;
Aws::String m_folderId;
bool m_folderIdHasBeenSet;
Aws::Vector<ResourcePermission> m_grantPermissions;
bool m_grantPermissionsHasBeenSet;
Aws::Vector<ResourcePermission> m_revokePermissions;
bool m_revokePermissionsHasBeenSet;
};
} // namespace Model
} // namespace QuickSight
} // namespace Aws
| {
"content_hash": "6533592c2ea6a8fc7b62b4647ddb446c",
"timestamp": "",
"source": "github",
"line_count": 214,
"max_line_length": 196,
"avg_line_length": 36.13551401869159,
"alnum_prop": 0.6848571059097375,
"repo_name": "awslabs/aws-sdk-cpp",
"id": "eac503806be1acc76d0054b93ce5496ce77b556f",
"size": "7852",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "aws-cpp-sdk-quicksight/include/aws/quicksight/model/UpdateFolderPermissionsRequest.h",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "C",
"bytes": "7596"
},
{
"name": "C++",
"bytes": "61740540"
},
{
"name": "CMake",
"bytes": "337520"
},
{
"name": "Java",
"bytes": "223122"
},
{
"name": "Python",
"bytes": "47357"
}
],
"symlink_target": ""
} |
<?php
/**
* @author Honza Cerny (http://honzacerny.com)
*/
namespace App\Model;
use Aprila\Model\BaseRepository;
class TagRepository extends BaseRepository
{
public $table = 'tag';
public function findAll()
{
return $this->table()->where('type', 'normal');
}
public function getByName($tag, $type = 'normal')
{
return $this->table()->where('name', $tag)->where('type', $type)->fetch();
}
} | {
"content_hash": "43784b87a875269cabf1501e05f4c320",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 76,
"avg_line_length": 15.222222222222221,
"alnum_prop": 0.6472019464720195,
"repo_name": "Aprila/app-blog",
"id": "33aa90bd4a9af9acea91b91b1247dacb117c3717",
"size": "411",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "app/model/Repository/TagRepository.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "894"
},
{
"name": "CSS",
"bytes": "586923"
},
{
"name": "CoffeeScript",
"bytes": "3072"
},
{
"name": "HTML",
"bytes": "43816"
},
{
"name": "JavaScript",
"bytes": "192976"
},
{
"name": "PHP",
"bytes": "87419"
},
{
"name": "Shell",
"bytes": "424"
}
],
"symlink_target": ""
} |
<?php
/**
* Fired during plugin activation
*
* @link http://socialsquare.dk
* @since 1.0.0
*
* @package Dac_Content_Hub
* @subpackage Dac_Content_Hub/includes
*/
/**
* Fired during plugin activation.
*
* This class defines all code necessary to run during the plugin's activation.
*
* @since 1.0.0
* @package Dac_Content_Hub
* @subpackage Dac_Content_Hub/includes
* @author Kræn Hansen <kraen@socialsquare.dk>
*/
class Dac_Content_Hub_Activator {
/**
* Short Description. (use period)
*
* Long Description.
*
* @since 1.0.0
*/
public static function activate() {
}
}
| {
"content_hash": "160b5528570fbc5b232180dd1efa491a",
"timestamp": "",
"source": "github",
"line_count": 36,
"max_line_length": 79,
"avg_line_length": 17.583333333333332,
"alnum_prop": 0.6287519747235387,
"repo_name": "Socialsquare/wp-dac-content-hub",
"id": "286f48fa866ad2f88cf05553c4fa53f9ee99386c",
"size": "634",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "includes/class-dac-content-hub-activator.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "1322"
},
{
"name": "HTML",
"bytes": "521"
},
{
"name": "JavaScript",
"bytes": "10837"
},
{
"name": "PHP",
"bytes": "35499"
}
],
"symlink_target": ""
} |
ACCEPTED
#### According to
International Plant Names Index
#### Published in
null
#### Original name
null
### Remarks
null | {
"content_hash": "89bf0f59a8e5bc1d5393d7000b84664d",
"timestamp": "",
"source": "github",
"line_count": 13,
"max_line_length": 31,
"avg_line_length": 9.692307692307692,
"alnum_prop": 0.7063492063492064,
"repo_name": "mdoering/backbone",
"id": "c98783b0f27fbff953a5c86c4fb12c7c4d379a4a",
"size": "183",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "life/Plantae/Magnoliophyta/Magnoliopsida/Lamiales/Linderniaceae/Lindernia/Lindernia grossidentata/README.md",
"mode": "33188",
"license": "apache-2.0",
"language": [],
"symlink_target": ""
} |
require 'forwardable'
require 'cucumber/core/platform'
module Cucumber
module Core
module Ast
IncompatibleLocations = Class.new(StandardError)
module Location
def self.of_caller(additional_depth = 0)
from_file_colon_line(*caller[1 + additional_depth])
end
def self.from_file_colon_line(file_colon_line)
file, raw_line = file_colon_line.match(/(.*):(\d+)/)[1..2]
from_source_location(file, raw_line.to_i)
end
def self.from_source_location(file, line)
file = File.expand_path(file)
pwd = File.expand_path(Dir.pwd)
pwd.force_encoding(file.encoding)
if file.index(pwd)
file = file[pwd.length+1..-1]
elsif file =~ /.*\/gems\/(.*\.rb)$/
file = $1
end
new(file, line)
end
def self.new(file, raw_lines=nil)
file || raise(ArgumentError, "file is mandatory")
if raw_lines
Precise.new(file, Lines.new(raw_lines))
else
Wildcard.new(file)
end
end
def self.merge(*locations)
locations.reduce do |a, b|
a + b
end
end
class Wildcard < Struct.new(:file)
def to_s
file
end
def match?(other)
other.file == file
end
def include?(lines)
true
end
end
class Precise < Struct.new(:file, :lines)
def include?(other_lines)
lines.include?(other_lines)
end
def line
lines.first
end
def match?(other)
return false unless other.file == file
other.include?(lines)
end
def to_s
[file, lines.to_s].join(":")
end
def hash
self.class.hash ^ to_s.hash
end
def to_str
to_s
end
def on_line(new_line)
Location.new(file, new_line)
end
def +(other)
raise IncompatibleLocations if file != other.file
Precise.new(file, lines + other.lines)
end
def inspect
"<#{self.class}: #{to_s}>"
end
end
require 'set'
class Lines < Struct.new(:data)
protected :data
def initialize(raw_data)
super Array(raw_data).to_set
end
def first
data.first
end
def include?(other)
other.data.subset?(data) || data.subset?(other.data)
end
def +(more_lines)
new_data = data + more_lines.data
self.class.new(new_data)
end
def to_s
return first.to_s if data.length == 1
return "#{data.min}..#{data.max}" if range?
data.to_a.join(":")
end
def inspect
"<#{self.class}: #{to_s}>"
end
protected
def range?
data.size == (data.max - data.min + 1)
end
end
end
module HasLocation
def file_colon_line
location.to_s
end
def file
location.file
end
def line
location.line
end
def location
raise('Please set @location in the constructor') unless defined?(@location)
@location
end
def all_locations
@all_locations ||= Location.merge([location] + attributes.map { |node| node.all_locations }.flatten)
end
def attributes
[tags, comments, multiline_arg].flatten
end
def tags
# will be overriden by nodes that actually have tags
[]
end
def comments
# will be overriden by nodes that actually have comments
[]
end
def multiline_arg
# will be overriden by nodes that actually have a multiline_argument
EmptyMultilineArgument.new
end
end
end
end
end
| {
"content_hash": "2ff22fca6a00d645d07e6a38aabbed1a",
"timestamp": "",
"source": "github",
"line_count": 183,
"max_line_length": 110,
"avg_line_length": 22.69945355191257,
"alnum_prop": 0.49061145883485796,
"repo_name": "Jeff-Tian/mybnb",
"id": "59c75fecf41afd76eaa39fcd20ec45a4b0fafb7e",
"size": "4154",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Ruby200/lib/ruby/gems/2.0.0/gems/cucumber-core-1.5.0/lib/cucumber/core/ast/location.rb",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Assembly",
"bytes": "455330"
},
{
"name": "Batchfile",
"bytes": "6263"
},
{
"name": "C",
"bytes": "2304983"
},
{
"name": "C#",
"bytes": "8440"
},
{
"name": "C++",
"bytes": "31815"
},
{
"name": "CSS",
"bytes": "30628"
},
{
"name": "Cucumber",
"bytes": "248616"
},
{
"name": "F#",
"bytes": "2310"
},
{
"name": "Forth",
"bytes": "506"
},
{
"name": "GLSL",
"bytes": "1040"
},
{
"name": "Groff",
"bytes": "31983"
},
{
"name": "HTML",
"bytes": "376863"
},
{
"name": "JavaScript",
"bytes": "20239"
},
{
"name": "M4",
"bytes": "67848"
},
{
"name": "Makefile",
"bytes": "142926"
},
{
"name": "Mask",
"bytes": "969"
},
{
"name": "PLSQL",
"bytes": "22886"
},
{
"name": "Python",
"bytes": "19913027"
},
{
"name": "REXX",
"bytes": "3862"
},
{
"name": "Ruby",
"bytes": "14954382"
},
{
"name": "Shell",
"bytes": "366205"
},
{
"name": "Tcl",
"bytes": "2150972"
},
{
"name": "TeX",
"bytes": "230259"
},
{
"name": "Visual Basic",
"bytes": "494"
},
{
"name": "XSLT",
"bytes": "3736"
},
{
"name": "Yacc",
"bytes": "14342"
}
],
"symlink_target": ""
} |
using UnityEngine;
using System.Collections;
public class ClimableController : MonoBehaviour {
LayerMask whatIsClimbable;
ClimberCharacterController controller;
void Awake() {
controller = GetComponentInParent<ClimberCharacterController>();
whatIsClimbable = controller.whatIsClimbable;
}
void OnTriggerEnter2D(Collider2D col)
{
if ((1 << col.gameObject.layer & whatIsClimbable.value) != 0) {
controller.walled = true;
}
}
void OnTriggerExit2D(Collider2D col)
{
if ((1 << col.gameObject.layer & whatIsClimbable.value) != 0) {
controller.walled = false;
}
}
}
| {
"content_hash": "6605bc872a63c30ef5736867a342dec4",
"timestamp": "",
"source": "github",
"line_count": 27,
"max_line_length": 66,
"avg_line_length": 22.074074074074073,
"alnum_prop": 0.7298657718120806,
"repo_name": "derpawe/GameChainGraz",
"id": "5d1fed5c5036dd34e53360c6612c3aace8429ad3",
"size": "598",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "Assets/Scripts/ClimableController.cs",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "ASP",
"bytes": "118649"
},
{
"name": "C#",
"bytes": "21375"
}
],
"symlink_target": ""
} |
.class Lcom/android/server/net/NetworkPolicyManagerService$14;
.super Landroid/content/BroadcastReceiver;
.source "NetworkPolicyManagerService.java"
# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
value = Lcom/android/server/net/NetworkPolicyManagerService;
.end annotation
.annotation system Ldalvik/annotation/InnerClass;
accessFlags = 0x0
name = null
.end annotation
# instance fields
.field final synthetic this$0:Lcom/android/server/net/NetworkPolicyManagerService;
# direct methods
.method constructor <init>(Lcom/android/server/net/NetworkPolicyManagerService;)V
.locals 0
iput-object p1, p0, Lcom/android/server/net/NetworkPolicyManagerService$14;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;
invoke-direct {p0}, Landroid/content/BroadcastReceiver;-><init>()V
return-void
.end method
# virtual methods
.method public onReceive(Landroid/content/Context;Landroid/content/Intent;)V
.locals 8
const-string/jumbo v5, "networkInfo"
invoke-virtual {p2, v5}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;
move-result-object v2
check-cast v2, Landroid/net/NetworkInfo;
invoke-virtual {v2}, Landroid/net/NetworkInfo;->isConnected()Z
move-result v5
if-nez v5, :cond_0
return-void
:cond_0
const-string/jumbo v5, "wifiInfo"
invoke-virtual {p2, v5}, Landroid/content/Intent;->getParcelableExtra(Ljava/lang/String;)Landroid/os/Parcelable;
move-result-object v0
check-cast v0, Landroid/net/wifi/WifiInfo;
invoke-virtual {v0}, Landroid/net/wifi/WifiInfo;->getMeteredHint()Z
move-result v1
invoke-virtual {v0}, Landroid/net/wifi/WifiInfo;->getSSID()Ljava/lang/String;
move-result-object v5
invoke-static {v5}, Landroid/net/NetworkTemplate;->buildTemplateWifi(Ljava/lang/String;)Landroid/net/NetworkTemplate;
move-result-object v4
iget-object v5, p0, Lcom/android/server/net/NetworkPolicyManagerService$14;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;
iget-object v6, v5, Lcom/android/server/net/NetworkPolicyManagerService;->mUidRulesFirstLock:Ljava/lang/Object;
monitor-enter v6
:try_start_0
iget-object v5, p0, Lcom/android/server/net/NetworkPolicyManagerService$14;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;
iget-object v7, v5, Lcom/android/server/net/NetworkPolicyManagerService;->mNetworkPoliciesSecondLock:Ljava/lang/Object;
monitor-enter v7
:try_end_0
.catchall {:try_start_0 .. :try_end_0} :catchall_1
:try_start_1
iget-object v5, p0, Lcom/android/server/net/NetworkPolicyManagerService$14;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;
iget-object v5, v5, Lcom/android/server/net/NetworkPolicyManagerService;->mNetworkPolicy:Landroid/util/ArrayMap;
invoke-virtual {v5, v4}, Landroid/util/ArrayMap;->get(Ljava/lang/Object;)Ljava/lang/Object;
move-result-object v3
check-cast v3, Landroid/net/NetworkPolicy;
if-nez v3, :cond_2
if-eqz v1, :cond_2
invoke-static {v4, v1}, Lcom/android/server/net/NetworkPolicyManagerService;->newWifiPolicy(Landroid/net/NetworkTemplate;Z)Landroid/net/NetworkPolicy;
move-result-object v3
iget-object v5, p0, Lcom/android/server/net/NetworkPolicyManagerService$14;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;
invoke-virtual {v5, v3}, Lcom/android/server/net/NetworkPolicyManagerService;->addNetworkPolicyAL(Landroid/net/NetworkPolicy;)V
:try_end_1
.catchall {:try_start_1 .. :try_end_1} :catchall_0
:cond_1
:goto_0
:try_start_2
monitor-exit v7
:try_end_2
.catchall {:try_start_2 .. :try_end_2} :catchall_1
monitor-exit v6
return-void
:cond_2
if-eqz v3, :cond_1
:try_start_3
iget-boolean v5, v3, Landroid/net/NetworkPolicy;->inferred:Z
if-eqz v5, :cond_1
iput-boolean v1, v3, Landroid/net/NetworkPolicy;->metered:Z
iget-object v5, p0, Lcom/android/server/net/NetworkPolicyManagerService$14;->this$0:Lcom/android/server/net/NetworkPolicyManagerService;
invoke-virtual {v5}, Lcom/android/server/net/NetworkPolicyManagerService;->updateNetworkRulesNL()V
:try_end_3
.catchall {:try_start_3 .. :try_end_3} :catchall_0
goto :goto_0
:catchall_0
move-exception v5
:try_start_4
monitor-exit v7
throw v5
:try_end_4
.catchall {:try_start_4 .. :try_end_4} :catchall_1
:catchall_1
move-exception v5
monitor-exit v6
throw v5
.end method
| {
"content_hash": "7be76248e2af9f1a24f03aa319eb821f",
"timestamp": "",
"source": "github",
"line_count": 159,
"max_line_length": 154,
"avg_line_length": 28.78616352201258,
"alnum_prop": 0.7336683417085427,
"repo_name": "BatMan-Rom/ModdedFiles",
"id": "5e07445caf2888227e5ee8ee510c19d1df132c23",
"size": "4577",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "services.jar.out/smali/com/android/server/net/NetworkPolicyManagerService$14.smali",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "GLSL",
"bytes": "15069"
},
{
"name": "HTML",
"bytes": "139176"
},
{
"name": "Smali",
"bytes": "541934400"
}
],
"symlink_target": ""
} |
<?php
namespace FRM\ShBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormView;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\PropertyAccess\PropertyAccess;
class ImageType extends AbstractType
{
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setOptional(array(
'image_url',
'width',
'height',
'lightbox',
));
}
public function buildView(FormView $view, FormInterface $form, array $options)
{
if (array_key_exists('image_url', $options)) {
$parentData = $form->getParent()->getData();
if (null !== $parentData) {
$accessor = PropertyAccess::createPropertyAccessor();
$imageUrl = $accessor->getValue($parentData, $options['image_url']);
} else {
$imageUrl = null;
}
// set an "image_url" variable that will be available when rendering this field
$view->vars['image_url'] = $imageUrl;
$view->vars['width'] = isset($options['width']) ? $options['width'] : null;
$view->vars['height'] = isset($options['height']) ? $options['height'] : null;
$view->vars['lightbox'] = (isset($options['lightbox']) && $options['lightbox'])
? $options['lightbox']
: null;
}
}
public function getParent()
{
return 'file';
}
public function getName()
{
return 'image';
}
} | {
"content_hash": "419f2ccf18279dee80756ccef48d762d",
"timestamp": "",
"source": "github",
"line_count": 54,
"max_line_length": 91,
"avg_line_length": 30.425925925925927,
"alnum_prop": 0.5788192331101644,
"repo_name": "FRM81/sh2",
"id": "63da4eeb46eafcfb6bc705bd85a32657624d105b",
"size": "1643",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/FRM/ShBundle/Form/Type/ImageType.php",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "CSS",
"bytes": "41048"
},
{
"name": "JavaScript",
"bytes": "335249"
},
{
"name": "PHP",
"bytes": "227332"
},
{
"name": "Perl",
"bytes": "2647"
}
],
"symlink_target": ""
} |
/* global colorbrewer */
var layer = {
// Default values
palette: 'YlGn',
selectedNum: '3',
type: 'continuous',
min: '0',
max: '300',
name: 'usgs:ned',
sld: '',
projection: 'EPSG:3785'
};
var baseUrl = 'https://demo.boundlessgeo.com/geoserver/ows';
var layerViewer = {
renderPalettes: function () {
var paletteArray = Object.keys(colorbrewer);
utility.populateDropdown('#palette', paletteArray);
},
renderWidget: function (layer) {
// Populates the number of colors dropdown
$('#color-count').empty();
var numberArray = Object.keys(colorbrewer[layer.palette]);
utility.populateDropdown('#color-count', numberArray);
// Sets the count
$('#color-count').val(layer.selectedNum);
// Sets the type
$('#palette-type').val(layer.type);
// Sets the min and max values
$('#min').val(layer.min);
$('#max').val(layer.max);
$('#name').val(layer.name);
$('#projection').val(layer.projection);
$('#baseurl').val(baseUrl);
}
};
var layerController = {
syncLayer: function (layer) {
// Sync the model with UI
layer.palette = $('#palette').val();
var items = Object.keys(colorbrewer[layer.palette]);
var maxNumber = parseInt(items[items.length - 1]);
if (parseInt($('#color-count').val()) <= maxNumber) {
layer.selectedNum = $('#color-count').val();
} else {
layer.selectedNum = String(maxNumber);
}
layer.type = $('#palette-type').val();
layer.min = $('#min').val();
layer.max = $('#max').val();
layer.sld = this.generateSld(layer);
layer.name = $('#name').val();
layer.projection = $('#projection').val();
baseUrl = $('#baseurl').val();
},
generateSld: function (layer) {
// Orchestrates the sld generation
var sequence = utility.generateSequence(layer.min, layer.max, layer.selectedNum);
var palette_array = utility.getPalette(layer.palette, layer.selectedNum);
var xml = utility.generateXml(
layer.name, layer.selectedNum, sequence, palette_array, layer.type);
return xml;
}
};
// Run after the DOM loads
$(function () {
'use strict';
// Create a map object
var map = geo.map({
node: '#map',
zoom: 9,
center: {
x: -77.0,
y: 39
}
});
// Add an OSM layer
map.createLayer('osm');
// Populate the palette dropdown
layerViewer.renderPalettes();
// Render the widget
layerViewer.renderWidget(layer);
// Generate sld
layer.sld = layerController.generateSld(layer);
// Add the wms layer
var wms = utility.createWMSLayer(map, layer.sld, layer.projection, layer.name);
// If any of the input boxes changes regenerate sld again
$('#palette, #color-count, #min, #max, #palette-type, #baseurl, #projection, #name')
.change(function () {
layerController.syncLayer(layer);
layerViewer.renderWidget(layer);
map.deleteLayer(wms);
wms = utility.createWMSLayer(map, layer.sld, layer.projection, layer.name);
});
});
var utility = {
// Some utility functions
populateDropdown: function (dropdown, array) {
// Populates the dropdown based on the array given
$.each(array, function () {
var option = document.createElement('option');
$(dropdown)
.append($(option)
.attr('value', this)
.html(this));
});
},
generateSequence: function (start, stop, count) {
// Generates a sequence of numbers with the given start,
// stop and count variables
var sequence = [];
var step = (stop - start) / (count - 1.0);
for (var i = 0; i < count; i++) {
sequence.push(parseFloat(start + i * step));
}
return sequence;
},
getPalette: function (name, count) {
// Gets the palette array with the given name and count parameters
return colorbrewer[name][count];
},
createMapEntry: function (xml, color, value, opacity) {
// Adds a color-quantity-opacity entry to the sld
$(xml)
.find('ColorMap')
.append($('<ColorMapEntry>', xml)
.attr({
color: color,
quantity: value,
opacity: opacity
}));
},
generateXml: function (name, count, values, palette, type) {
// Generates the xml (sld) file with the given parameters
var xml = $($.parseXML(
'<?xml version="1.0" encoding="utf-8" ?><StyledLayerDescriptor />'
));
$('StyledLayerDescriptor', xml)
.attr({
version: '1.0.0',
'xsi:schemaLocation': 'http://www.opengis.net/sld StyledLayerDescriptor.xsd',
xmlns: 'http://www.opengis.net/sld',
'xmlns:ogc': 'http://www.opengis.net/ogc',
'xmlns:xlink': 'http://www.w3.org/1999/xlink',
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance'
});
$('StyledLayerDescriptor', xml)
.append($('<NamedLayer>', xml));
$(xml)
.find('NamedLayer')
.append($('<Name>', xml))
.append($(
'<UserStyle>', xml));
$(xml)
.find('Name')
.text(name);
$(xml)
.find('UserStyle')
.append($('<Title>', xml))
.append($(
'<IsDefault>', xml))
.append($('<FeatureTypeStyle>', xml));
$(xml)
.find('Title')
.text('Custom Visualization');
$(xml)
.find('IsDefault')
.text(1);
$(xml)
.find('FeatureTypeStyle')
.append($('<Rule>', xml));
$(xml)
.find('Rule')
.append($('<RasterSymbolizer>', xml));
$(xml)
.find('RasterSymbolizer')
.append($('<ColorMap>', xml));
if (type === 'discrete') {
$(xml)
.find('ColorMap')
.attr({
type: 'intervals'
});
}
for (var i = 0; i < count; i++) {
this.createMapEntry(xml, palette[i], values[i], 1);
}
var xmlString = new XMLSerializer().serializeToString(xml[0]);
return xmlString;
},
createWMSLayer: function (map, sld, projection, layer_name) {
// Add an OSM layer with a WMS server as the source of its titles
var wms = map.createLayer('osm', {
keepLower: false,
attribution: null
});
wms.url(function (x, y, zoom) {
// Compute the bounding box
var bb = wms.gcsTileBounds({
x: x,
y: y,
level: zoom
}, projection);
var bbox_mercator = bb.left + ',' + bb.bottom + ',' +
bb.right + ',' + bb.top;
// Set the WMS server parameters
var params = {
SERVICE: 'WMS',
VERSION: '1.3.0',
REQUEST: 'GetMap',
LAYERS: layer_name, // US Elevation
STYLES: '',
BBOX: bbox_mercator,
WIDTH: 256, //Use 256x256 tiles
HEIGHT: 256,
FORMAT: 'image/png',
TRANSPARENT: true,
SRS: projection,
TILED: true,
SLD_BODY: sld
};
// OpenGeo Demo Web Map Service
return baseUrl + (baseUrl.indexOf('?') >= 0 ? '&' : '?') + $.param(params);
});
return wms;
}
};
| {
"content_hash": "a61319cdf352130b45bc2c31cff082ad",
"timestamp": "",
"source": "github",
"line_count": 253,
"max_line_length": 86,
"avg_line_length": 27.284584980237153,
"alnum_prop": 0.5758365927857453,
"repo_name": "OpenGeoscience/geojs",
"id": "16d80b98659dc43ed2925af3ed036df3bd554c0a",
"size": "6903",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "examples/sld/main.js",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "CSS",
"bytes": "25110"
},
{
"name": "EJS",
"bytes": "12943"
},
{
"name": "GLSL",
"bytes": "39018"
},
{
"name": "HTML",
"bytes": "7969"
},
{
"name": "JavaScript",
"bytes": "2426705"
},
{
"name": "Pug",
"bytes": "102783"
},
{
"name": "Python",
"bytes": "17103"
},
{
"name": "SCSS",
"bytes": "7521"
},
{
"name": "Stylus",
"bytes": "3235"
}
],
"symlink_target": ""
} |

This Grav theme is a port of the [Free Bootstrap 3.0 Template](http://livedemo00.template-help.com/wt_bootstrap_free_sample/index.html) by [Template Help](http://template-help.com/).
# Features
* Bootstrap 3.0
* Photo Slider
* Photo Gallery
* Various templates for presenting your content
* Modular template included
* Simple Form Support
* 2 Level custom menu
* Social Icons
## Basic Setup for a new Grav site
The simplest way to install Photographer theme for Grav is to download and install the Photographer Skeleton package:
1. [Download Photographer Skeleton](http://getgrav.org/downloads/skeletons#extras)
2. Simply unzip the package into your web root folder.
3. Point your browser at the folder, job done!
**TIP:** Check out the [general Grav installation instructions](http://learn.getgrav.org/basics/installation) for more details on this process.
---
## Existing Grav site
It is possible to install just the theme, but page content will need to reference the [Photographer theme](https://github.com/getgrav/grav-theme-photographer)'s supported templates. It is strongly advised to at least install the Photographer Skeleton package to see the theme's capabilities in action.
To install **just** the theme:
```
$ bin/gpm install photographer
```
| {
"content_hash": "48a3d220bcf9f324d1be34afd1b0c102",
"timestamp": "",
"source": "github",
"line_count": 39,
"max_line_length": 302,
"avg_line_length": 33.58974358974359,
"alnum_prop": 0.7687022900763358,
"repo_name": "ulilu/grav-toctoc",
"id": "b615b68c050dc27516eae177b0b6ffdc51f9186b",
"size": "1344",
"binary": false,
"copies": "2",
"ref": "refs/heads/master",
"path": "user/README.md",
"mode": "33188",
"license": "mit",
"language": [
{
"name": "ApacheConf",
"bytes": "2701"
},
{
"name": "CSS",
"bytes": "627624"
},
{
"name": "HTML",
"bytes": "219797"
},
{
"name": "JavaScript",
"bytes": "329663"
},
{
"name": "Nginx",
"bytes": "1485"
},
{
"name": "PHP",
"bytes": "1043894"
},
{
"name": "Shell",
"bytes": "263"
}
],
"symlink_target": ""
} |
package co.yiiu.pybbs.directive;
import co.yiiu.pybbs.service.INotificationService;
import freemarker.core.Environment;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.List;
import java.util.Map;
@Component
public class NotificationsDirective implements TemplateDirectiveModel {
@Autowired
private INotificationService notificationService;
@Override
public void execute(Environment environment, Map map, TemplateModel[] templateModels, TemplateDirectiveBody
templateDirectiveBody) throws TemplateException, IOException {
Integer userId = Integer.parseInt(map.get("userId").toString());
Boolean read = Integer.parseInt(map.get("read").toString()) == 1;
// 如果想查询所有的消息,limit 传一个负数就可以了 比如 -1
Integer limit = Integer.parseInt(map.get("limit").toString());
List<Map<String, Object>> notifications = notificationService.selectByUserId(userId, read, limit);
DefaultObjectWrapperBuilder builder = new DefaultObjectWrapperBuilder(Configuration.VERSION_2_3_28);
environment.setVariable("notifications", builder.build().wrap(notifications));
templateDirectiveBody.render(environment.getOut());
}
}
| {
"content_hash": "e739d59b2999108771a0a397c8632198",
"timestamp": "",
"source": "github",
"line_count": 32,
"max_line_length": 111,
"avg_line_length": 41.46875,
"alnum_prop": 0.760361718161266,
"repo_name": "liygheart/jfinalbbs",
"id": "dc809d463090e68118e05118960c1669fa560949",
"size": "1463",
"binary": false,
"copies": "1",
"ref": "refs/heads/master",
"path": "src/main/java/co/yiiu/pybbs/directive/NotificationsDirective.java",
"mode": "33188",
"license": "apache-2.0",
"language": [
{
"name": "Batchfile",
"bytes": "163"
},
{
"name": "CSS",
"bytes": "1085981"
},
{
"name": "FreeMarker",
"bytes": "190553"
},
{
"name": "HTML",
"bytes": "5070196"
},
{
"name": "Java",
"bytes": "168222"
},
{
"name": "JavaScript",
"bytes": "3149203"
},
{
"name": "PHP",
"bytes": "1684"
},
{
"name": "Python",
"bytes": "32324"
},
{
"name": "Ruby",
"bytes": "1282"
},
{
"name": "Shell",
"bytes": "355"
}
],
"symlink_target": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.