code stringlengths 3 1.05M | repo_name stringlengths 4 116 | path stringlengths 4 991 | language stringclasses 9 values | license stringclasses 15 values | size int32 3 1.05M |
|---|---|---|---|---|---|
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributesLocation. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ThreeCs")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ThreeCs")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[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)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0fe3836c-5a46-4702-a6e1-94c0961e99f1")]
// 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 Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("69.0.*")]
[assembly: AssemblyFileVersion("69.0.0.0")]
| lathoub/three.cs | ThreeCs/Properties/AssemblyInfo.cs | C# | mit | 1,360 |
<?php
namespace Enigmatic\CRMBundle\Form;
use Enigmatic\CRMBundle\Entity\ContactPhone;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class ContactPhoneType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('type', 'genemu_jqueryselect2_choice', array(
'choices' => array(
ContactPhone::WORK => 'enigmatic.crm.contact.form.field.phones.type.work.label',
ContactPhone::MOBILE => 'enigmatic.crm.contact.form.field.phones.type.mobile.label',
ContactPhone::FAX => 'enigmatic.crm.contact.form.field.phones.type.fax.label',
ContactPhone::OTHER => 'enigmatic.crm.contact.form.field.phones.type.other.label',
),
'required' => true,
'multiple' => false,
'expanded' => false,
'label' => null,
))
->add('phone', 'text', array (
'label' => null,
'required' => false,
'attr' => array(
'pattern' => '^([+]{1}[0-9]{1})?[0-9]{10}$',
'placeholder' => 'enigmatic.crm.contact.form.field.phones.phone.label',
)
))
;
}
/**
* @param OptionsResolverInterface $resolver
*/
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Enigmatic\CRMBundle\Entity\ContactPhone'
));
}
/**
* @return string
*/
public function getName()
{
return 'enigmatic_crm_contact_phone';
}
}
| chadyred/crm | src/Enigmatic/CRMBundle/Form/ContactPhoneType.php | PHP | mit | 1,987 |
namespace EarTrumpet.Interop
{
internal enum AppBarEdge : uint
{
Left = 0,
Top = 1,
Right = 2,
Bottom = 3
}
}
| File-New-Project/EarTrumpet | EarTrumpet/Interop/AppBarEdge.cs | C# | mit | 157 |
require'rails_helper'
feature 'Admin edits site setting' do
let!(:admin) { create :admin_user }
before :each do
SiteSettings.instance.destroy
end
background do
login_as admin, scope: :user
end
scenario 'checks settings' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
expect(page).to have_content 'Day starts'
expect(page).to have_content 'Day ends'
expect(page).to have_content 'Site title'
expect(page).to have_content 'Schedule time zone'
expect(page).to have_content 'Block reservation cancellation'
expect(page).to have_content 'Email'
end
scenario 'edits site title' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
fill_in 'Site title', with: 'My Awesome Site'
click_button 'Save'
visit root_path
within 'nav' do
expect(page).to have_content 'My Awesome Site'
end
end
context 'with a schedule item' do
before :all do
Timecop.freeze(Time.now.utc.beginning_of_day)
end
after :all do
Timecop.return
end
let!(:schedule_item) { create :schedule_item, start: Time.now.utc.beginning_of_day + 12.hours }
scenario 'edits schedule time zone' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
select '0', from: 'Day starts'
select '23', from: 'Day ends'
select 'UTC', from: 'Schedule time zone'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).to have_content '12:00'
end
click_link 'Admin Panel'
click_link 'Site Settings'
select 'Hawaii', from: 'Schedule time zone'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).to have_content '02:00'
end
end
scenario 'edits day start so that it\'s later than day end' do
visit root_path
click_link 'Admin Panel'
click_link 'Site Settings'
select '0', from: 'Day starts'
select '23', from: 'Day ends'
select 'UTC', from: 'Schedule time zone'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).to have_content '12:00'
end
click_link 'Admin Panel'
click_link 'Site Settings'
select '23', from: 'Day starts'
select '15', from: 'Day ends'
click_button 'Save'
visit root_path
within '.schedule' do
expect(page).not_to have_content '12:00'
end
end
end
end | angelikatyborska/fitness-class-schedule | spec/features/admin/site_settings/admin_edits_site_settings_spec.rb | Ruby | mit | 2,527 |
########
"""
This code is open source under the MIT license.
Its purpose is to help create special motion graphics
with effector controls inspired by Cinema 4D.
Example usage:
https://www.youtube.com/watch?v=BYXmV7fObOc
Notes to self:
Create a simialr, lower poly contorl handle and
perhaps auto enable x-ray/bounding.
Long term, might become an entire panel with tools
of all types of effectors, with secitons like
convinience tools (different split faces/loose buttons)
next to the actual different effector types
e.g. transform effector (as it is)
time effector (..?) etc. Research it more.
another scripting ref:
http://wiki.blender.org/index.php/Dev:2.5/Py/Scripts/Cookbook/Code_snippets/Interface#A_popup_dialog
plans:
- Make checkboxes for fields to have effector affect (loc, rot, scale)
- Name the constraints consistent to effector name, e.g. effector.L.001 for easy removal
- add falloff types (and update-able in driver setting)
- custome driver equation field ('advanced' tweaking, changes drivers for all in that effector group)
- Empty vertex objects for location which AREN'T transformed, so that there is no limit to
how much the location can do (now limited to be between object and base bone)
- create list panel that shows effectors added, and with each selected can do things:
- all more effector objects
- select current objects (and rig)
- change falloff/equation
- remove selected from effector
- remove effector (drivers & rig)
- apply effector in position (removes rig)
Source code available on github:
https://github.com/TheDuckCow/Blender_Effectors
"""
########
bl_info = {
"name": "Blender Effectors",
"author": "Patrick W. Crawford",
"version": (1, 0, 3),
"blender": (2, 71, 0),
"location": "3D window toolshelf",
"category": "Object",
"description": "Effector special motion graphics",
"wiki_url": "https://github.com/TheDuckCow/Blender_Effectors"
}
import bpy
## just in case
from bpy.props import *
from bpy_extras.io_utils import ExportHelper
from bpy.types import Operator
from os.path import dirname, join
""" needed? """
"""
class SceneButtonsPanel():
bl_space_type = 'PROPERTIES'
bl_region_type = 'WINDOW'
bl_context = "scene"
@classmethod
def poll(cls, context):
rd = context.scene.render
return context.scene and (rd.engine in cls.COMPAT_ENGINES)
"""
""" original """
def createEffectorRig(bones,loc=None):
[bone_base,bone_control] = bones
if (loc==None):
loc = bpy.context.scene.cursor_location
bpy.ops.object.armature_add(location=loc)
rig = bpy.context.active_object
rig.name = "effector"
bpy.types.Object.one = bpy.props.FloatProperty(name="does this setting do anything at all?", description="one hundred million", default=1.000, min=0.000, max=1.000)
rig.one = 0.6
#bpy.ops.wm.properties_add(data_path="object")
"""
bpy.ops.object.mode_set(mode='EDIT')
control = rig.data.edit_bones.new('control')
#bpy.ops.armature.bone_primitive_add() #control
# eventually add property as additional factor
rig.data.bones[0].name = 'base'
rig.data.bones[0].show_wire = True
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.mode_set(mode='EDIT')
# SCENE REFRESH OR SOMETHING???
rig.data.bones[1].name = 'control'
control = obj.pose.bones[bones['base']]
#rig.data.bones[1].parent = rig.data.[bones['base']] #need other path to bone data
bpy.ops.object.mode_set(mode='OBJECT')
rig.pose.bones[0].custom_shape = bone_base
rig.pose.bones[1].custom_shape = bone_control
# turn of inherent rotation for control??
# property setup
#bpy.ops.wm.properties_edit(data_path='object', property='Effector Scale',
# value='1.0', min=0, max=100, description='Falloff scale of effector')
#scene property='Effector.001'
"""
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.armature.select_all(action='SELECT')
bpy.ops.armature.delete()
arm = rig.data
bones = {}
bone = arm.edit_bones.new('base')
bone.head[:] = 0.0000, 0.0000, 0.0000
bone.tail[:] = 0.0000, 0.0000, 1.0000
bone.roll = 0.0000
bone.use_connect = False
bone.show_wire = True
bones['base'] = bone.name
bone = arm.edit_bones.new('control')
bone.head[:] = 0.0000, 0.0000, 0.0000
bone.tail[:] = 0.0000, 1.0000, 0.0000
bone.roll = 0.0000
bone.use_connect = False
bone.parent = arm.edit_bones[bones['base']]
bones['control'] = bone.name
bpy.ops.object.mode_set(mode='OBJECT')
pbone = rig.pose.bones[bones['base']]
#pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
pbone.bone.layers = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False]
pbone = rig.pose.bones[bones['control']]
#pbone.rigify_type = ''
pbone.lock_location = (False, False, False)
pbone.lock_rotation = (False, False, False)
pbone.lock_rotation_w = False
pbone.lock_scale = (False, False, False)
pbone.rotation_mode = 'QUATERNION'
#pbone.bone.layers = [True, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True]
bpy.ops.object.mode_set(mode='EDIT')
for bone in arm.edit_bones:
bone.select = False
bone.select_head = False
bone.select_tail = False
for b in bones:
bone = arm.edit_bones[bones[b]]
bone.select = True
bone.select_head = True
bone.select_tail = True
arm.edit_bones.active = bone
arm.layers = [(x in [0]) for x in range(32)]
bpy.ops.object.mode_set(mode='OBJECT')
rig.pose.bones[0].custom_shape = bone_base
rig.pose.bones[1].custom_shape = bone_control
return rig
def createBoneShapes():
if (bpy.data.objects.get("effectorBone1") is None) or (bpy.data.objects.get("effectorBone2") is None):
bpy.ops.mesh.primitive_uv_sphere_add(segments=8, ring_count=8, enter_editmode=True)
bpy.ops.mesh.delete(type='ONLY_FACE')
bpy.ops.object.editmode_toggle()
effectorBone1 = bpy.context.active_object
effectorBone1.name = "effectorBone1"
bpy.ops.mesh.primitive_ico_sphere_add(subdivisions=1, enter_editmode=False, size=0.5)
effectorBone2 = bpy.context.active_object
effectorBone2.name = "effectorBone2"
#move to last layer and hide
[False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, True]
effectorBone1.hide = True
effectorBone2.hide = True
effectorBone1.hide_render = True
effectorBone2.hide_render = True
return [bpy.data.objects["effectorBone1"],bpy.data.objects["effectorBone2"]]
def addEffectorObj(objList, rig):
# store previous selections/active etc
prevActive = bpy.context.scene.objects.active
#default expression, change later with different falloff etc
default_expression = "1/(.000001+objDist)*scale"
#empty list versus obj list?
emptyList = []
# explicit state set
bpy.ops.object.mode_set(mode='OBJECT')
# iterate over all objects passed in
for obj in objList:
if obj.type=="EMPTY": continue
##############################################
# Add the empty intermediate object/parent
bpy.ops.object.empty_add(type='PLAIN_AXES', view_align=False, location=obj.location)
empty = bpy.context.active_object
empty.name = "effr.empty"
obj.select = True
preParent = obj.parent
bpy.ops.object.parent_set(type='OBJECT', keep_transform=True)
bpy.context.object.empty_draw_size = 0.1
if (preParent):
bpy.ops.object.select_all(action='DESELECT')
# need to keep transform!
preParent.select = True
empty.select = True
bpy.context.scene.objects.active = preParent
bpy.ops.object.parent_set(type='OBJECT', keep_transform=True)
#empty.parent = preParent
bpy.context.scene.objects.active = obj
preConts = len(obj.constraints) # starting number of constraints
###############################################
# LOCATION
bpy.ops.object.constraint_add(type='COPY_LOCATION')
obj.constraints[preConts].use_offset = True
obj.constraints[preConts].target_space = 'LOCAL'
obj.constraints[preConts].owner_space = 'LOCAL'
obj.constraints[preConts].target = rig
obj.constraints[preConts].subtarget = "control"
driverLoc = obj.constraints[preConts].driver_add("influence").driver
driverLoc.type = 'SCRIPTED'
# var for objDist two targets, 1st is "base" second is "distanceRef"
varL_dist = driverLoc.variables.new()
varL_dist.type = 'LOC_DIFF'
varL_dist.name = "objDist"
varL_dist.targets[0].id = rig
varL_dist.targets[0].bone_target = 'base'
varL_dist.targets[1].id = empty
varL_scale = driverLoc.variables.new()
varL_scale.type = 'TRANSFORMS'
varL_scale.name = 'scale'
varL_scale.targets[0].id = rig
varL_scale.targets[0].transform_type = 'SCALE_Z'
varL_scale.targets[0].bone_target = 'base'
driverLoc.expression = default_expression
###############################################
# ROTATION
bpy.ops.object.constraint_add(type='COPY_ROTATION')
preConts+=1
obj.constraints[preConts].target_space = 'LOCAL'
obj.constraints[preConts].owner_space = 'LOCAL'
obj.constraints[preConts].target = rig
obj.constraints[preConts].subtarget = "control"
driverRot = obj.constraints[preConts].driver_add("influence").driver
driverRot.type = 'SCRIPTED'
# var for objDist two targets, 1st is "base" second is "distanceRef"
varR_dist = driverRot.variables.new()
varR_dist.type = 'LOC_DIFF'
varR_dist.name = "objDist"
varR_dist.targets[0].id = rig
varR_dist.targets[0].bone_target = 'base'
varR_dist.targets[1].id = obj
varR_scale = driverRot.variables.new()
varR_scale.type = 'TRANSFORMS'
varR_scale.name = 'scale'
varR_scale.targets[0].id = rig
varR_scale.targets[0].transform_type = 'SCALE_Z'
varR_scale.targets[0].bone_target = 'base'
driverRot.expression = default_expression
###############################################
# SCALE
bpy.ops.object.constraint_add(type='COPY_SCALE')
preConts+=1
obj.constraints[preConts].target_space = 'LOCAL'
obj.constraints[preConts].owner_space = 'LOCAL'
obj.constraints[preConts].target = rig
obj.constraints[preConts].subtarget = "control"
driverScale = obj.constraints[preConts].driver_add("influence").driver
driverScale.type = 'SCRIPTED'
# var for objDist two targets, 1st is "base" second is "distanceRef"
varS_dist = driverScale.variables.new()
varS_dist.type = 'LOC_DIFF'
varS_dist.name = "objDist"
varS_dist.targets[0].id = rig
varS_dist.targets[0].bone_target = 'base'
varS_dist.targets[1].id = obj
varS_scale = driverScale.variables.new()
varS_scale.type = 'TRANSFORMS'
varS_scale.name = 'scale'
varS_scale.targets[0].id = rig
varS_scale.targets[0].transform_type = 'SCALE_Z'
varS_scale.targets[0].bone_target = 'base'
driverScale.expression = default_expression
########################################################################################
# Above for precursor functions
# Below for the class functions
########################################################################################
class addEffector(bpy.types.Operator):
"""Create the effector object and setup"""
bl_idname = "object.add_effector"
bl_label = "Add Effector"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
objList = bpy.context.selected_objects
[effectorBone1,effectorBone2] = createBoneShapes()
rig = createEffectorRig([effectorBone1,effectorBone2])
addEffectorObj(objList, rig)
bpy.context.scene.objects.active = rig
return {'FINISHED'}
class updateEffector(bpy.types.Operator):
bl_idname = "object.update_effector"
bl_label = "Update Effector"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
print("Update Effector: NOT CREATED YET!")
# use the popup window??
return {'FINISHED'}
class selectEmpties(bpy.types.Operator):
bl_idname = "object.select_empties"
bl_label = "Select Effector Empties"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
print("Selecting effector empties: NOT COMPLETELY CORRECT YET!")
# just selects all empties, lol.
bpy.ops.object.select_by_type(type='EMPTY')
return {'FINISHED'}
class separateFaces(bpy.types.Operator):
"""Separate all faces into new meshes"""
bl_idname = "object.separate_faces"
bl_label = "Separate Faces to Objects"
bl_options = {'REGISTER', 'UNDO'}
def execute(self, context):
# make sure it's currently in object mode for sanity
bpy.ops.object.mode_set(mode='OBJECT')
for obj in bpy.context.selected_objects:
bpy.context.scene.objects.active = obj
if obj.type != "MESH": continue
#set scale to 1
try:
bpy.ops.object.transform_apply(location=False, rotation=True, scale=True)
except:
print("couodn't transform")
print("working?")
#mark all edges sharp
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.select_all(action='SELECT')
bpy.ops.mesh.mark_sharp()
bpy.ops.object.mode_set(mode='OBJECT')
#apply modifier to split faces
bpy.ops.object.modifier_add(type='EDGE_SPLIT')
obj.modifiers[-1].split_angle = 0
bpy.ops.object.modifier_apply(apply_as='DATA', modifier=obj.modifiers[-1].name)
#clear sharp
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.mesh.mark_sharp(clear=True)
bpy.ops.object.mode_set(mode='OBJECT')
#separate to meshes
bpy.ops.mesh.separate(type="LOOSE")
bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')
return {'FINISHED'}
# SceneButtonsPanel
# ^^ above for attempt to make in scenes panel
class effectorPanel(bpy.types.Panel):
"""Effector Tools"""
bl_label = "Effector Tools"
bl_space_type = 'VIEW_3D'
bl_region_type = 'TOOLS'
bl_category = "Tools"
"""
bl_label = "Effector Tools"
bl_space_type = 'VIEW_3D'#"PROPERTIES" #or 'VIEW_3D' ?
bl_region_type = "WINDOW"
bl_context = "scene"
"""
def draw(self, context):
view = context.space_data
scene = context.scene
layout = self.layout
split = layout.split()
col = split.column(align=True)
col.operator("object.separate_faces", text="Separate Faces")
split = layout.split() # uncomment to make vertical
#col = split.column(align=True) # uncomment to make horizontal
col.operator("object.add_effector", text="Add Effector")
split = layout.split()
col.operator("wm.mouse_position", text="Update Effector alt")
col.operator("object.select_empties", text="Select Empties")
split = layout.split()
col = split.column(align=True)
#col = layout.column()
layout.label("Disable Recommended:")
col.prop(view, "show_relationship_lines")
# shameless copy from vertex group pa
# funcitons to implement:
# add new (change from current, where it creates just the armature
# and later need to assign objects to it
# need to figure out data structure for it! I think properties
# for each of the objects, either unique per group or over+1 unique per group
# Assign
# Remove
# Select
# Deselect
# select Effector Control
"""
ob = context.object
group = ob.vertex_groups.active
rows = 1
if group:
rows = 3
row = layout.row()
row.template_list("MESH_UL_vgroups", "", ob, "vertex_groups", ob.vertex_groups, "active_index", rows=rows)
col = row.column(align=True)
col.operator("object.vertex_group_add", icon='ZOOMIN', text="")
col.operator("object.vertex_group_remove", icon='ZOOMOUT', text="").all = False
if ob.vertex_groups and (ob.mode == 'OBJECT'):
row = layout.row()
sub = row.row(align=True)
sub.operator("object.vertex_group_assign", text="Assign")
sub.operator("object.vertex_group_remove_from", text="Remove")
row = layout.row()
sub = row.row(align=True)
sub.operator("object.vertex_group_select", text="Select")
sub.operator("object.vertex_group_deselect", text="Deselect")
"""
########################################################################################
# Above for the class functions
# Below for extra classes/registration stuff
########################################################################################
#### WIP popup
class WIPpopup(bpy.types.Operator):
bl_idname = "error.message"
bl_label = "WIP popup"
type = StringProperty()
message = StringProperty()
def execute(self, context):
self.report({'INFO'}, self.message)
print(self.message)
return {'FINISHED'}
def invoke(self, context, event):
wm = context.window_manager
return wm.invoke_popup(self, width=350, height=40)
return self.execute(context)
def draw(self, context):
self.layout.label("This addon is a work in progress, feature not yet implemented")
row = self.layout.split(0.80)
row.label("")
row.operator("error.ok")
# shows in header when run
class notificationWIP(bpy.types.Operator):
bl_idname = "wm.mouse_position"
bl_label = "Mouse location"
def execute(self, context):
# rather then printing, use the report function,
# this way the message appears in the header,
self.report({'INFO'}, "Not Implemented")
return {'FINISHED'}
def invoke(self, context, event):
return self.execute(context)
# WIP OK button general purpose
class OkOperator(bpy.types.Operator):
bl_idname = "error.ok"
bl_label = "OK"
def execute(self, context):
#eventually another one for url lib
return {'FINISHED'}
# This allows you to right click on a button and link to the manual
# auto-generated code, not fully changed
def add_object_manual_map():
url_manual_prefix = "https://github.com/TheDuckCow"
url_manual_mapping = (
("bpy.ops.mesh.add_object", "Modeling/Objects"),
)
return url_manual_prefix, url_manual_mapping
def register():
bpy.utils.register_class(addEffector)
bpy.utils.register_class(updateEffector)
bpy.utils.register_class(effectorPanel)
bpy.utils.register_class(separateFaces)
bpy.utils.register_class(selectEmpties)
bpy.utils.register_class(WIPpopup)
bpy.utils.register_class(notificationWIP)
bpy.utils.register_class(OkOperator)
#bpy.utils.register_manual_map(add_object_manual_map)
def unregister():
bpy.utils.unregister_class(addEffector)
bpy.utils.unregister_class(updateEffector)
bpy.utils.unregister_class(effectorPanel)
bpy.utils.unregister_class(separateFaces)
bpy.utils.unregister_class(selectEmpties)
bpy.utils.unregister_class(WIPpopup)
bpy.utils.unregister_class(notificationWIP)
bpy.utils.unregister_class(OkOperator)
#bpy.utils.unregister_manual_map(add_object_manual_map)
if __name__ == "__main__":
register()
| kmeirlaen/Blender_Effectors | effector.py | Python | mit | 18,791 |
var indexSectionsWithContent =
{
0: "acdefhilmnoprtw",
1: "w",
2: "aehilmoprw",
3: "w",
4: "acdefhlnrt",
5: "w",
6: "w",
7: "w"
};
var indexSectionNames =
{
0: "all",
1: "classes",
2: "files",
3: "functions",
4: "variables",
5: "typedefs",
6: "enums",
7: "defines"
};
var indexSectionLabels =
{
0: "All",
1: "Data Structures",
2: "Files",
3: "Functions",
4: "Variables",
5: "Typedefs",
6: "Enumerations",
7: "Macros"
};
| niho/libwave | doc/private/html/search/searchdata.js | JavaScript | mit | 471 |
<?php
namespace Nwidart\Modules\Commands;
use Illuminate\Console\Command;
use Nwidart\Modules\Module;
use Symfony\Component\Console\Input\InputArgument;
class DisableCommand extends Command
{
/**
* The console command name.
*
* @var string
*/
protected $name = 'module:disable';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Disable the specified module.';
/**
* Execute the console command.
*/
public function handle() : int
{
/**
* check if user entred an argument
*/
if ($this->argument('module') === null) {
$this->disableAll();
}
/** @var Module $module */
$module = $this->laravel['modules']->findOrFail($this->argument('module'));
if ($module->isEnabled()) {
$module->disable();
$this->info("Module [{$module}] disabled successful.");
} else {
$this->comment("Module [{$module}] has already disabled.");
}
return 0;
}
/**
* disableAll
*
* @return void
*/
public function disableAll()
{
/** @var Modules $modules */
$modules = $this->laravel['modules']->all();
foreach ($modules as $module) {
if ($module->isEnabled()) {
$module->disable();
$this->info("Module [{$module}] disabled successful.");
} else {
$this->comment("Module [{$module}] has already disabled.");
}
}
}
/**
* Get the console command arguments.
*
* @return array
*/
protected function getArguments()
{
return [
['module', InputArgument::OPTIONAL, 'Module name.'],
];
}
}
| nWidart/laravel-modules | src/Commands/DisableCommand.php | PHP | mit | 1,832 |
#! /usr/bin/env python
import flickr_api, pprint, os, sys,argparse,json,csv
flickr_api.set_keys(api_key = '52182e4e29c243689f8a8f45ee2939ae', api_secret = 'a6238b15052797dc')
def DownloadSource(SourceList, PhotosetTitle):
for url in SourceList:
os.system("wget --append-output=download.log --no-verbose --no-clobber -P '%s' -i %s" % (PhotosetTitle,'downloadstack'))
#print url
pass
def GetSource(PhotoList,SizeToDownload):
SourceList = []
f = open('downloadstack', 'wb')
for PhotoId in PhotoList:
r = flickr_api.method_call.call_api(
method = "flickr.photos.getSizes",
photo_id = PhotoId
)
for Size in r['sizes']['size']:
if Size['label'] == SizeToDownload:
SourceList.append(Size['source'])
f.write('%s \n' % Size['source'])
f.close()
return SourceList
def GetInfo(PhotoList,userid):
for PhotoId in PhotoList:
g = open('/home/chandrasg/Desktop/%s/%s_Info.json'%(userid,PhotoId),'wb')
g=convert(g)
h = open('/home/chandrasg/Desktop/%s/%s_Exif.json'%(userid,PhotoId),'wb')
h=convert(h)
#print g
q= flickr_api.method_call.call_api(
method = "flickr.photos.getInfo",
photo_id = PhotoId,
format='xml'
)
q=convert(q)
g.write(str(q))
g.close()
r=flickr_api.method_call.call_api(
method = "flickr.photos.getExif",
photo_id = PhotoId,
format='xml'
)
r=convert(r)
h.write(str(r))
h.close()
def GetFavorites(userid):
PhotoList=[]
r = flickr_api.method_call.call_api(
method = "flickr.favorites.getPublicList",
user_id = userid,
per_page=200
)
for r in r['photos']['photo']:
PhotoList.append(r['id'])
return PhotoList
def convert(input):
if isinstance(input, dict):
return {convert(key): convert(value) for key, value in input.iteritems()}
elif isinstance(input, list):
return [convert(element) for element in input]
elif isinstance(input, unicode):
return input.encode('utf-8')
else:
return input
def GetUserid(userid):
userid= "http://www.flickr.com/photos/"+userid+"/"
r = flickr_api.method_call.call_api(
method = "flickr.urls.lookupUser",
url=userid
)
return r['user']['id']
def GetUserfriends(userid):
h = open('/home/chandrasg/Desktop/%s_friends.json'%userid,'wb')
h=convert(h)
q= flickr_api.method_call.call_api(
method = "flickr.contacts.getPublicList",
user_id = userid,
format='xml'
)
q=convert(q)
g.write(str(q))
g.close()
with open('users.txt','rb') as infile:
reader=csv.reader(infile)
for user in reader:
userid=user[0]
if userid[0].isdigit():
print userid
SizeToDownload = 'Large'
PhotoList = GetFavorites(userid)
print "Found %s Photos..." % (len(PhotoList))
SourceList = GetSource(PhotoList,SizeToDownload)
print "Downloading %s Photos..." % (len(SourceList))
DownloadSource(SourceList,userid)
GetInfo(PhotoList,userid)
GetUserfriends(userid)
os.remove('./downloadstack')
else:
print userid
userid=GetUserid(userid)
userid=convert(userid)
print userid
SizeToDownload = 'Large'
PhotoList = GetFavorites(userid)
print "Found %s Photos..." % (len(PhotoList))
SourceList = GetSource(PhotoList,SizeToDownload)
print "Downloading %s Photos..." % (len(SourceList))
DownloadSource(SourceList,userid)
GetInfo(PhotoList,userid)
GetUserfriends(userid)
os.remove('./downloadstack')
| sharathchandra92/flickrapi_downloadfavorites | flickrdownload.py | Python | mit | 3,886 |
/**
* This deadlock is missed if the transitive closure of the
* `X is held by this thread while locking Y' relation is not computed when
* building the lock graph because the B lock causes the (A, B)(B, C)(C, A)
* cycle to have two edges (A, B)(B, C) within the same thread (t0). If the
* transitive closure is computed, the cycle we find is (A, C)(C, A) instead,
* which is valid. Thus, the transitive closure allows us to "jump" over the
* B lock because there is a DIRECT edge from A to C.
*/
#include <d2mock.hpp>
int main(int argc, char const* argv[]) {
d2mock::mutex A, B, C;
d2mock::thread t0([&] {
A.lock();
B.lock();
C.lock();
C.unlock();
B.unlock();
A.unlock();
});
d2mock::thread t1([&] {
C.lock();
A.lock();
A.unlock();
C.unlock();
});
auto test_main = [&] {
t0.start();
t1.start();
t1.join();
t0.join();
};
return d2mock::check_scenario(test_main, argc, argv, {
{
{t0, A, B, C},
{t1, C, A}
}
});
}
| ldionne/d2 | test/scenarios/miss_unless_transitive_closure.cpp | C++ | mit | 1,188 |
class Parent < ActiveRecord::Base
wikify
has_many :children
end | Arcath/Wikify | spec/models/parent.rb | Ruby | mit | 70 |
namespace IrbisUI.Pft
{
partial class PftDebuggerForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.SuspendLayout();
//
// PftDebuggerForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(584, 326);
this.Name = "PftDebuggerForm";
this.Text = "PftDebuggerForm";
this.ResumeLayout(false);
}
#endregion
}
} | amironov73/ManagedIrbis | Source/Classic/Libs/IrbisUI/Source/Pft/PftDebuggerForm.Designer.cs | C# | mit | 1,403 |
import {Glyphicon, Table} from 'react-bootstrap';
let defaultActions = ['Download', 'Bookmark'];
const actions = {
link : defaultActions,
image: defaultActions,
text : [...defaultActions, 'Edit'],
web : [...defaultActions, 'Preview', 'Edit']
};
export default class ActionView extends React.Component {
makeBookmark(activeId) {
this.getActiveModel(activeId).toggleBookmark();
}
makeAction(action, activeId) {
switch (action){
case 'Bookmark':
this.makeBookmark(activeId);
break;
}
}
getActiveModel(activeId) {
return this.props.collection.get(activeId);
}
fileActions(activeId){
let fileType = this.getActiveModel(activeId).toJSON().format || 'link';
return _.map(actions[fileType], (action, index)=> {
return (
<tr key={index}>
<td onClick={this.makeAction.bind(this, action, activeId)}>
{ action === 'Download' ? <Glyphicon glyph="download-alt"/> :
action === 'Bookmark' ? <Glyphicon glyph="bookmark"/> :
action === 'Preview' ? <Glyphicon glyph="eye-open"/> :
action === 'Edit' ? <Glyphicon glyph="pencil"/> : null
}
<strong> {action} </strong>
</td>
</tr>
)
});
}
showActiveFile(activeId){
return (
<tr>
<td>File selected:
<strong>{this.getActiveModel(activeId).toJSON().name}</strong>
</td>
</tr>
);
}
render() {
let selectFile = (
<tr>
<td>Select file at the left side by clicking on it</td>
</tr>
);
let activeId = this.props.activeId;
return (
<Table responsive hover bordered className="action-view">
<thead>
<tr>
<th><strong>Action</strong></th>
</tr>
</thead>
<tbody>
{ !activeId ? selectFile : this.fileActions.bind(this, activeId)()}
{ !activeId ? null : this.showActiveFile.bind(this, activeId)()}
</tbody>
</Table>
);
}
} | andrey-ponamarev/file-manager | app/components/ActionView.js | JavaScript | mit | 1,844 |
<?php
include_once 'session.inc.php';
include_once 'check_login.php';
include_once 'connect.inc.php';
if(!empty($_GET['category']) && (!empty($_GET['usn']) || !empty($_GET['email']) ) && !empty($_GET['passkey']))
{
$category=mysql_real_escape_string($_GET['category']);
$usn=mysql_real_escape_string($_GET['usn']);
$passkey=mysql_real_escape_string($_GET['passkey']);
$email=mysql_real_escape_string($_GET['email']);
if($category=="student")
{
$query1=mysql_query("SELECT activated FROM users WHERE usn='$usn' AND confirmation='$passkey'") or die('Cannot execute query1');
$row1=mysql_fetch_assoc($query1);
if($row1['activated']==1)
$_SESSION['msg1']="<div style=\"color:red\"><b>Your account has already been activated.</b></div><br><br>";
else if(mysql_num_rows($query1)==1)
{
$query2=mysql_query("UPDATE users SET activated=1 WHERE usn='$usn' AND confirmation='$passkey'") or die('Cannot execute query2');
$_SESSION['msg1']="<div style=\"color:green\"><b>Your account has been activated successfully.</b></div><br><br>";
}
else
$_SESSION['msg1']="<div style=\"color:red\"><b>Invalid operations.</b></div><br><br>";
}
else if($category=="teacher")
{
$query3=mysql_query("SELECT activated FROM staff WHERE email='$usn' AND confirmation='$passkey'") or die('Cannot execute query3');
$row3=mysql_fetch_assoc($query3);
if($row3['activated']==1)
$_SESSION['msg1']="<div style=\"color:red\"><b>Your account has already been activated.</b></div><br><br>";
else if(mysql_num_rows($query3)==1)
{
$query4=mysql_query("UPDATE users SET activated=1 WHERE email='$usn' AND confirmation='$passkey'") or die('Cannot execute query4');
$_SESSION['msg1']="<div style=\"color:green\"><b>Your account has been activated successfully.</b></div><br><br>";
}
else
$_SESSION['msg1']="<div style=\"color:red\"><b>Invalid operations.</b></div><br><br>";
}else if($category=="HOD")
{
$query3=mysql_query("SELECT activated FROM hod WHERE email='$email' AND confirmation='$passkey'") or die('Cannot execute query3');
$row3=mysql_fetch_assoc($query3);
if($row3['activated']==1)
$_SESSION['msg1']="<div style=\"color:red\"><b>Your account has already been activated.</b></div><br><br>";
else if(mysql_num_rows($query3)==1)
{
$query4=mysql_query("UPDATE hod SET activated=1 WHERE email='$email' AND confirmation='$passkey'") or die('Cannot execute query4');
$_SESSION['msg1']="<div style=\"color:green\"><b>Your account has been activated successfully.</b></div><br><br>";
}
else
$_SESSION['msg1']="<div style=\"color:red\"><b>Invalid operations.</b></div><br><br>";
}
}
header("location:index.php");
?> | ajhalthor/signup-login-form | confirm.php | PHP | mit | 2,717 |
<style type="text/css">
.cart-coupon-code-show{display:none;}
a.tooltip{ width: 23px;
height: 23px;
background: #9c9c9c;
display: block;
color: #fff;
position: absolute;
top: 10px;
right: 7px;
border-radius: 20px;
text-align: center;
line-height: 23px;
font-family: trade-gotich-medium, Helvetica, Arial, sans-serif;
font-weight: bold;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var bagCount = $('.bag-count').find('a').length ? $('.bag-count a').html() : $('.bag-count').html();
$('#cartpage').addClass('cartpage')
$('#cartpage').addClass('my-bag-selected');
if(bagCount>0){
$('#cartpage').find('.header-mini-cart').removeClass('empty-red-bag').removeClass('empty-black-bag').addClass('filled-white-bag');
}else{
$('#cartpage').find('.header-mini-cart').removeClass('empty-red-bag').removeClass('empty-black-bag').addClass('empty-white-bag');
}
$('.mini-cart-holder').find('.bag-count').css('color','#fff');
$('.mini-cart-holder').find('.bag-count a').css('color','#fff');
});
</script>
<div id="main" role="main" class="primary-focus clearfix">
<div class="cart-header">
<h2>My Bag</h2>
</div>
<div class="breadcrumb-container cart-breadcrumb-container">
<ol class="breadcrumb cart-breadcrumb">
<li>
<h4>
<a href="<?=base_url();?>" title="Home" >Home</a>
</h4>
<span class="divider">/</span>
</li>
<li>
<h4>
<a href="<?=base_url('cart');?>" title="Your Shopping Bag" class="breadcrumb-last" >Your Shopping Bag</a>
</h4>
</li>
</ol>
</div>
<div class="cart-wrapper container-fluid cnc-redesign " data-purchase-limit="{'lineItem' :5.0, 'totalItem': 50.0}">
<?php if(isset($cart_data) && isset($cart_data['cart_detail']) && !empty($cart_data['cart_detail'])) { ?>
<div id="primary" class="primary-content pageName col-md-9" data-pagename="Cart">
<form action="<?=base_url('cart'); ?>" method="post" name="dwfrm_cart" class="cart-items-form" novalidate="novalidate">
<fieldset>
<button class="visually-hidden hide" type="submit" value="dwfrm_cart_updateCart" name="dwfrm_cart_updateCart"></button>
<div id="js-continue-shoping" class="continue-shopping primary-button">
Back to Shopping
</div>
<div id="js-checkout-button" class="checkout-button primary-button checkout-button-duplicate" style="display:none;">
Proceed with checkout
</div>
<div class="cart-footer visually-hidden">
<div class="cart-order-totals">
<button type="submit" value="dwfrm_cart_updateCart" name="dwfrm_cart_updateCart" id="update-cart">
Update Cart </button>
</div>
</div>
<div class="tabling-data col-md-12">
<div class="thead-data row mobile-hide">
<div class="col-md-6 section-header first-child">
Shopping Bag<span> -You have
<?php if(!empty($cart_data)) {
echo count($cart_data['cart_detail']);
} else {
echo '0';
} ?> products in your bag</span>
</div>
<h3 class="col-md-2 section-header qty">Quantity</h3>
<h3 class="col-md-2 section-header price">Price</h3>
<h3 class="col-md-2 section-header last-child">Total Price</h3>
</div>
<hr class="mobile-hide">
<?php if(!empty($cart_data)) { ?>
<?php foreach ($cart_data['cart_detail'] as $row) { ?>
<div class="tbody-data row " id="cart_box_<?=$row['cart_id']; ?>">
<div class="primary-product-detail global.product col-sm-12 col-md-6">
<div class="item-image col-sm-4 col-md-5">
<a href="<?=$row['link']; ?>" title="<?=$row['name']; ?>">
<img itemprop="image" class="primary-image" src="<?=$row['image']; ?>" >
</a>
</div>
<div class="item-details col-sm-8 col-md-7">
<div class="product-list-item">
<div class="name">
<a href="<?=$row['link']; ?>" title="<?=$row['name']; ?>">Diesel <?=$row['name']; ?></a>
</div>
<div class="product-group">
<?=$row['category'];?>
</div>
<?php if($row['color_name'] != '') { ?>
<div class="attribute">
<span class="label">Colour:</span>
<span class="value"><?=$row['color_name'];?></span>
</div>
<?php } ?>
<?php if($row['size'] != '') { ?>
<div class="attribute">
<span class="label">Size:</span>
<span class="value"><?=$row['size'];?></span>
</div>
<?php } ?>
<?php if($row['length'] != '') { ?>
<div class="attribute">
<span class="label">Length:</span>
<span class="value"><?=$row['length'];?></span>
</div>
<?php } ?>
</div>
<div class="diesel-sr-eligible-cart" name="sr_cartProductDiv"></div>
</div>
<div class="item-link">
<ul class="item-user-actions row ">
<li class="remove-bag-item col-sm-4 col-md-4 col-lg-3">
<input type="hidden" name="qty-<?=$row['barcode'].'-'.$row['cart_id']; ?>" id="qty-<?=$row['barcode'].'-'.$row['cart_id']; ?>" value="<?=$row['qty']; ?>">
<button data-pname="<?=$row['name']; ?>" class="remove-product button-text" title="Remove product from cart" type="submit" value="REMOVE" name="remove-item" id="remove-<?=$row['barcode'].'-'.$row['cart_id']; ?>"><span>REMOVE</span></button>
<script type="text/javascript">
$("#remove-<?php echo $row['barcode'].'-'.$row['cart_id']; ?>").click(function(){
$("#qty-<?php echo $row['barcode'].'-'.$row['cart_id']; ?>").val('0');
});
</script>
</li>
<li class="col-sm-4 col-lg-2 col-md-4 sprite-icon">
<a href="<?=$row['edit_link']; ?>" title="<?=$row['name']; ?>" style="text-decoration:underline;">Edit </a>
</li>
<li class=" wish-list-txt col-sm-4 col-md-4 col-lg-7 ">
<?php if($user_type == "Member") { ?>
<a data-pname="<?=$row['name']; ?>" class="add-to-wishlist" href="javascript:void(0);" name="dwfrm_cart_shipments_i0_items_i0_addToWishList" title="Move to Wishlist" onclick="move_to_wishlist('<?=$row['barcode']?>','<?=$row['cart_id']; ?>');" >
Add to Wishlist </a>
<?php } else { ?>
<a data-pname="<?=$row['name']; ?>" class="add-to-wishlist" title="Add to Wishlist" href="<?php echo base_url();?>wishlist/wishlist_login?source=productdetail">Add to Wishlist</a>
<?php } ?>
</li>
<li class="in-wishlist-wrapper" style="display: none;">
<div class="in-wishlist"></div>
</li>
</ul>
</div>
</div>
<div class="secondary-product-detail col-md-6 equal-width-five-sec">
<div class="product-details-template row" data-hbs-template="productiondetails">
<div class="item-quantity col-sm-6 col-md-4 equal-width-two">
<input type="hidden" id="barcode_qty" name="barcode_qty" value="<?=$row['barcode']; ?>">
<input type="hidden" id="cart_id_qty" name="cart_id_qty" value="<?=$row['cart_id']; ?>">
<h3 class="section-header">Quantity</h3>
<span class="decrease-quantity icons disabled " data-product-name="<?=$row['name']; ?>"></span>
<input type="text" name="dwfrm_cart_shipments_i0_items_i0_quantity" size="2" maxlength="2" value="<?= isset($row['qty']) ? $row['qty'] : 1; ?>" class="input-text" disabled="disabled">
<span class="increase-quantity icons " data-product-name="<?=$row['name']; ?>"></span>
</div>
<?php
$actual_discount = $row['discount_price'] / $row['qty'];
$price_sale = (!empty($row['price_sale']) && $row['price_sale'] != $row['unit_price'] && $row['price_sale'] != 0)? $row['price_sale'] : $row['unit_price'];
?>
<div class="item-price col-sm-6 col-md-4 equal-width-four">
<h3 class="section-header">Price</h3>
<p class="price-sales">$<?php
if($price_sale != $row['unit_price'] && !empty($price_sale) && $price_sale != 0){
echo "<span style='padding-right:3px; text-decoration: line-through; color:red;'><span style='color:grey'>".number_format($row['unit_price'], 2)."</span></span>".number_format($price_sale, 2);
}elseif($row['original_price'] != $row['unit_price'] && !empty($row['original_price']) && $row['original_price'] != 0){
echo "<span style='padding-right:3px; text-decoration: line-through; color:red;'><span style='color:grey'>".number_format($row['original_price'], 2)."</span></span>".number_format($row['unit_price'], 2);
}else{
echo number_format($row['unit_price'], 2);
}
?>
<br class="mobile-only"/>
<? if(!empty($row['discount_percent']) || $row['discount_percent'] != '0'):?> <span class="discount_percent" style="background: #e6e6e6;padding: 1px 4px;font-size: 10px;"><?php echo $row['discount_percent'];?>% OFF </span><? endif;?>
</p>
</div>
<div class="item-total col-sm-12 col-md-4 equal-width-four-sec">
<h3 class="section-header">Total Price</h3>
<p class="price-total">
<?php
if($row['discount_price'] < ($price_sale * $row['qty'])){
$total = $row['discount_price'];
} else {
$total = $row['qty'] * $price_sale;
}?>
$<?=number_format($total,2); ?>
</p>
</div>
<!-- Ecommerce tracking code -->
<?php if(ENVIRONMENT == 'production'){?>
<script type="text/javascript">
ga('ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
ga('dieselitaly.ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
ga('syg.ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
</script>
<?}else{?>
<script type="text/javascript">
ga('ec:addProduct', {
'id': '<?php echo $row['sku'] ?>' ,
'name': '<?php echo $row['name'];?>',
'category': '<?php echo check_product_brand($row['category'],$row['gender']);?>',
'brand': '<?php echo $row['style'];?>',
'variant': '<?php echo $row['color'];?>',
'price': '<?php echo $total;?>',
'quantity': '<?php echo $row['qty'];?>'
});
</script>
<?php } ?>
<!-- Ecommerce tracking code-->
</div>
<ul class="product-availability-list"></ul>
</div>
</div>
<div class="item-seperator"></div>
<?php } ?>
<?php } ?>
<!--<textarea rows="50" cols="100"><? print_r($cart_data['cart_api']);?></textarea>-->
</div>
<!-- Ecommerce tracking code -->
<?php if(!empty($cart_data)): ?>
<?php if(ENVIRONMENT == 'production'){?>
<script type="text/javascript">
ga('ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('dieselitaly.ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('syg.ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('send', 'pageview'); // Pageview for payment.html
ga('dieselitaly.send', 'pageview');
ga('syg.send', 'pageview');
</script>
<? }else{?>
<script type="text/javascript">
ga('ec:setAction','checkout', {
'step': 1, // A value of 1 indicates this action is first checkout step.
'option': 'Checkout' // Used to specify additional info about a checkout stage, e.g. payment method.
});
ga('send', 'pageview'); // Pageview for payment.html
</script>
<? }?>
<!--End of Ecommerce tracking code -->
<?php endif; ?>
</fieldset>
</form>
</div>
<div id="secondary" class="nav cart col-md-3" data-bonuseligibleorder="false">
<div class="cart-secondary">
<div class="order-totals-table">
<div style="display:none;">
<div class="content-asset">
<!-- dwMarker="content" dwContentID="bc8OsiaaiM5pEaaadqYUJ3Rq88" -->
<div id="cart-shipping-helptext">
The shipping cost will be a flat fee that is guaranteed based on the service level selected during checkout.
</div>
<div id="cart-tax-helptext">
Sales Tax is applied to your order in accordance with individual State and local regulations. Exact charges will be calculated automatically after your order is shipped, depending on the Zip Code of the shipping address.
</div>
</div>
<!-- End content-asset -->
</div>
<div class="order-subtotal">
<span class="label">
Order Subtotal </span>
<span class="value">$<?=isset($cart_data) ? number_format($cart_data['cart_total'],2) : '0.00'; ?></span>
</div>
<div class="order-shipping">
<span class="label">
<!-- Display Shipping Method -->
Shipping</span>
<span class="value">Free</span>
</div>
<div class="cart-secondary cart-coupon-code">
<label for="dwfrm_cart_couponCode" class="promotional-code-new">
Have a promotional code?</label>
<div class="cart-coupon" style="display:none;">
<input type="text" class="coupon-code" name="dwfrm_cart_couponCode" id="dwfrm_cart_couponCode" placeholder="Enter Coupon Code" onkeyup="checkVisibility()" >
<span class="error coupon-error"></span>
<div class="confirm-coupon"></div>
<div id="email_container" style="position:relative;display:none;">
<? if(!$this->session->userdata('s_uid') || $this->session->userdata('s_uid')==''){ ?>
<input type="text" class="coupon-code coupon-email" name="dwfrm_customer_email" id="dwfrm_customer_email" placeholder="Enter Your Email id"">
<? }else{
$user_email = $this->session->userdata('s_email');?>
<input type="text" class="coupon-code coupon-email" name="dwfrm_customer_email" id="dwfrm_customer_email" value="<?php echo $user_email;?>" readonly>
<? }?>
<span class="error email-error"></span>
<a class="tooltip">?
<div class="tooltip-content"><strong>Promotional Code</strong>
<p style="margin:10px 0">The promotion discount will only be applied to items that are not discounted already.</p>
<p>We require your email address to check if you are a member of the DIESEL TRIBE. If you're not, just click on login/register.</p>
</div>
</a>
</div>
<button type="submit" value="dwfrm_cart_addCoupon" name="dwfrm_cart_addCoupon" id="add-coupon" onclick="checkCodeStatus()">
Apply </button>
</div>
</div>
<div class="cart-secondary cart-coupon-code-show">
<div id="cartCouponRemove">
<span class="value" style="width: 53%;text-align: right;"></span>
<!--<form action="<?php echo site_url('cart/removecoupon'); ?>" method="post" name="dwfrm_cart_d0qpakcnxejy" id="ajaxremovecoupon" novalidate="novalidate">-->
<fieldset>
<label for="dwfrm_cart_couponCode">
Coupon code</label>
<?php if(!empty($coupon_code)){
$promo_code = $coupon_code['promo_code'];?>
<span class="value" style="width: 53%;text-align: right;"><? echo $coupon_code['promo_string'];?>
<a href="<?=base_url()?>cart/removecoupon/<?=$promo_code; ?>" class="remove_coupon" style="display: block;float: right;margin-left: 7px;">
<img src="<?=base_url()?>images/close-icon.png" width="24" height="24" id="remove_code_btn">
</a>
</span>
<?} ?>
<input type="hidden" name="cart_mast_id" value="<?=(!empty($coupon_code))? $coupon_code['cart_mast_id'] :''?>">
<input type="hidden" class="coupon-code" name="dwfrm_cart_couponCode" id="dwfrm_cart_couponCode" value="<?=(!empty($coupon_code))? $coupon_code['promo_code']:''?>">
<div class="confirm-coupon"></div>
</fieldset>
<!--</form>-->
</div>
</div>
<script type="text/javascript">
function checkVisibility() {
var pass1 = document.getElementById('dwfrm_cart_couponCode');
var pass2 = document.getElementById('dwfrm_customer_email');
if (pass1.value=='DLSIGNUP') {
$("#email_container").fadeIn();
//pass2.style.visibility = 'visible';
} else {
$("#email_container").fadeOut();
// pass2.style.visibility = 'hidden';
}
}
function checkCodeStatus(){
var promo_code = $(".cart-secondary .cart-coupon-code .coupon-code").val();
var email_id = $(".cart-secondary .cart-coupon-code .coupon-email").val();
var error=0;
if(promo_code == ''){
$('input[name="dwfrm_cart_couponCode"]').next('span').text('Please Enter the Promotion Code');
error=1;
}else {
if(promo_code == 'DLSIGNUP'){
if(email_id == ''){
$('input[name="dwfrm_customer_email"]').next('span').text('Please Enter a Email Id');
console.log('Email in if');
error=1;
}
}
}
if(error>0){
return false;
}else{
$.ajax(
{
url : "<?php echo base_url('cart/couponvalidate/'); ?>",
type : "POST",
data : {promo_code: promo_code,email_id:email_id} ,
cache : false,
dataType:'json',
statusCode: {
404: function() {
alert( "page not found" );
}
},
success:function(data, textStatus, jqXHR)
{
//console.log('hi in success');return false;
if(data.result == 'success'){
console.log('hi in success success');
//$(".cart-secondary .cart-coupon-code-show").val(promo_code);
$('input[name=dwfrm_cart_couponCode]').val(promo_code);
$('.cart-secondary .cart-coupon-code-show span').html(promo_code);
//$(".remove_coupon").fadeIn();
$(".cart-coupon-code").fadeOut();
$(".cart-coupon-code-show").fadeIn();
if(data.redirect){
window.location.reload();
}
}else{
if(data.msg_type == 'promo_code'){
$(".coupon-error").html(data.msg);
}else{
$(".email-error").html(data.msg);
}
}
},
error: function(jqXHR, textStatus, errorThrown) {
//if fails
console.log(errorThrown);
}
});
}
}
//$(document).ready(function() {
$('.cart-coupon-code-show').hide();
var coupon_code = $("#cartCouponRemove #dwfrm_cart_couponCode").val();
if(coupon_code != ''){
$(".cart-coupon-code").fadeOut();
$(".cart-coupon-code-show").fadeIn();
}
// });
$(document).ready(function(){
$(".promotional-code-new").click(function(){
$(".cart-coupon").slideToggle();
});
});
</script>
<hr>
<div class="order-total">
<span class="label">Total(<span style="text-transform: lowercase;font-size:17px;">inc</span> GST)</span>
<span class="value">$<?=isset($cart_data) ? number_format($cart_data['cart_total'],2) : '0.00'; ?></span>
</div>
</div>
<div class="cart-action-checkout">
<?php if($user_type == "Member") { ?>
<form action="<?=base_url();?>order/checkout" method="post" name="dwfrm_cart_d0eqfxckhikc" novalidate="novalidate">
<fieldset>
<button class="btn-oswald red continue-checkout-button" type="submit" value="Proceed with checkout" name="dwfrm_cart_checkoutCart">
Proceed with checkout </button>
</fieldset>
</form>
<?php } else { ?>
<form class="mobile-only" action="<?=base_url();?>cart/checkout_signin" method="post" name="dwfrm_cart_d0eqfxckhikc" id="checkout-form" novalidate="novalidate">
<fieldset>
<button class="btn-oswald red continue-checkout-button" type="submit" value="Proceed with checkout" name="dwfrm_cart_checkoutCart" id="js-continue-checkout">
Proceed with checkout </button>
</fieldset>
</form>
<form class="no-mobile" action="<?=base_url();?>cart/proceed_checkout" method="post" name="dwfrm_cart_d0eqfxckhikc" id="checkout-form" novalidate="novalidate">
<fieldset>
<button class="btn-oswald red continue-checkout-button" type="submit" value="Proceed with checkout" name="dwfrm_cart_checkoutCart" id="js-continue-checkout">
Proceed with checkout </button>
</fieldset>
</form>
<?php } ?>
<form class="cart-action-continue-shopping" action="<?=base_url();?>" method="post" name="dwfrm_cart_d0ihllxcbhbi" id="continue-shopping" novalidate="novalidate">
<fieldset>
<button class="button-text" type="submit" value="Back to Shopping" name="dwfrm_cart_continueShopping" id="cart-continue-shoping">
Back to Shopping </button>
</fieldset>
</form>
</div>
</div>
<div class="appendPromo-message" style="display:none;"></div>
<div class="cart-secondary last-child hide"></div>
</div>
<?php } else { ?>
<div id="primary" class="primary-content pageName col-md-9" data-pagename="Cart">
<div class="cart-empty">
<h2 class="empty-bag-title">FEED ME I'M HUNGRY</h2>
<hr>
<div class="empty-header">
Your Shopping Bag is empty
</div>
<div class="cont-shopping">
<a href="<?=base_url();?>" class="continue button primary-button">
Back To Shopping </a>
</div>
</div>
</div>
<?php } ?>
</div>
</div>
<script type="text/javascript">
function move_to_wishlist(barcode,cart_id){
var url = '<?=base_url("Cart/move_product_to_wishlist");?>';
$.ajax({
type: "POST",
url: url,
async: false,
data: {barcode:barcode , cart_id:cart_id},
dataType: 'json',
success: function(result) {
/*console.log("hi"+result.res);
return false;*/
if(result){
if(result.res == 'success'){
$('#cart_box_'+cart_id).find('.in-wishlist').html('This item has been added to your Wish List.');
$('#cart_box_'+cart_id).find('.in-wishlist-wrapper').show();
$('.rgt-content .wishlist-header-count').find('span.favourite_count_red').html(result.count);
} else if(result.res == 'product_exist'){
$('#cart_box_'+cart_id).find('.in-wishlist').html('This item already in your Wish List.');
$('#cart_box_'+cart_id).find('.in-wishlist-wrapper').show();
} else {
$('#cart_box_'+cart_id).find('.in-wishlist-wrapper').hide();
}
}
},
error: function() {}
});
return false;
}
</script> | sygcom/diesel_2016 | application/views/cart_view_20161202.php | PHP | mit | 28,392 |
(function () {
'use strict';
describe('Inventories Controller Tests', function () {
// Initialize global variables
var InventoriesController,
$scope,
$httpBackend,
$state,
Authentication,
InventoriesService,
mockInventory;
// The $resource service augments the response object with methods for updating and deleting the resource.
// If we were to use the standard toEqual matcher, our tests would fail because the test values would not match
// the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher.
// When the toEqualData matcher compares two objects, it takes only object properties into
// account and ignores methods.
beforeEach(function () {
jasmine.addMatchers({
toEqualData: function (util, customEqualityTesters) {
return {
compare: function (actual, expected) {
return {
pass: angular.equals(actual, expected)
};
}
};
}
});
});
// Then we can start by loading the main application module
beforeEach(module(ApplicationConfiguration.applicationModuleName));
// The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
// This allows us to inject a service but then attach it to a variable
// with the same name as the service.
beforeEach(inject(function ($controller, $rootScope, _$state_, _$httpBackend_, _Authentication_, _InventoriesService_) {
// Set a new global scope
$scope = $rootScope.$new();
// Point global variables to injected services
$httpBackend = _$httpBackend_;
$state = _$state_;
Authentication = _Authentication_;
InventoriesService = _InventoriesService_;
// create mock Inventory
mockInventory = new InventoriesService({
_id: '525a8422f6d0f87f0e407a33',
name: 'Inventory Name'
});
// Mock logged in user
Authentication.user = {
roles: ['user']
};
// Initialize the Inventories controller.
InventoriesController = $controller('InventoriesController as vm', {
$scope: $scope,
inventoryResolve: {}
});
//Spy on state go
spyOn($state, 'go');
}));
describe('vm.save() as create', function () {
var sampleInventoryPostData;
beforeEach(function () {
// Create a sample Inventory object
sampleInventoryPostData = new InventoriesService({
name: 'Inventory Name'
});
$scope.vm.inventory = sampleInventoryPostData;
});
it('should send a POST request with the form input values and then locate to new object URL', inject(function (InventoriesService) {
// Set POST response
$httpBackend.expectPOST('api/inventories', sampleInventoryPostData).respond(mockInventory);
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL redirection after the Inventory was created
expect($state.go).toHaveBeenCalledWith('inventories.view', {
inventoryId: mockInventory._id
});
}));
it('should set $scope.vm.error if error', function () {
var errorMessage = 'this is an error message';
$httpBackend.expectPOST('api/inventories', sampleInventoryPostData).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
});
});
describe('vm.save() as update', function () {
beforeEach(function () {
// Mock Inventory in $scope
$scope.vm.inventory = mockInventory;
});
it('should update a valid Inventory', inject(function (InventoriesService) {
// Set PUT response
$httpBackend.expectPUT(/api\/inventories\/([0-9a-fA-F]{24})$/).respond();
// Run controller functionality
$scope.vm.save(true);
$httpBackend.flush();
// Test URL location to new object
expect($state.go).toHaveBeenCalledWith('inventories.view', {
inventoryId: mockInventory._id
});
}));
it('should set $scope.vm.error if error', inject(function (InventoriesService) {
var errorMessage = 'error';
$httpBackend.expectPUT(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(400, {
message: errorMessage
});
$scope.vm.save(true);
$httpBackend.flush();
expect($scope.vm.error).toBe(errorMessage);
}));
});
describe('vm.remove()', function () {
beforeEach(function () {
//Setup Inventories
$scope.vm.inventory = mockInventory;
});
it('should delete the Inventory and redirect to Inventories', function () {
//Return true on confirm message
spyOn(window, 'confirm').and.returnValue(true);
$httpBackend.expectDELETE(/api\/inventories\/([0-9a-fA-F]{24})$/).respond(204);
$scope.vm.remove();
$httpBackend.flush();
expect($state.go).toHaveBeenCalledWith('inventories.list');
});
it('should should not delete the Inventory and not redirect', function () {
//Return false on confirm message
spyOn(window, 'confirm').and.returnValue(false);
$scope.vm.remove();
expect($state.go).not.toHaveBeenCalled();
});
});
});
})();
| ebonertz/mean-blog | modules/inventories/tests/client/inventories.client.controller.tests.js | JavaScript | mit | 5,483 |
version https://git-lfs.github.com/spec/v1
oid sha256:ff952c4ac029ba9d378d24581d9a56937e7dc731986397dc47c3c42c56fd0729
size 132398
| yogeshsaroya/new-cdnjs | ajax/libs/soundmanager2/2.97a.20120318/script/soundmanager2.js | JavaScript | mit | 131 |
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper')
describe PayloadProcessor do
describe "process!" do
context "with a payload containing 3 commits" do
before(:each) do
@project = Project.make
@content = {"commits"=>
[
{"author_email" => "developer_one@example.com",
"author_name" => "Developer One",
"committed_at" => "Wed May 20 09:09:06 -0500 2009",
"short_message" => "Last commit",
"authored_at" => "Wed May 20 09:09:06 -0500 2009",
"identifier" => "f3badd5624dfbc35176f0471261731e1b92ce957",
"message" => "Last commit\n- 2nd line of commit message",
"committer_email" => "developer_one@example.com",
"committer_name" => "Developer One",
"line_additions" => "15",
"line_deletions" => "25",
"line_total" => "34",
"affected_file_count" => "2"
},
{"author_email" => "developer_one@example.com",
"author_name" => "Developer One",
"committed_at" => "Wed May 13 22:40:46 -0500 2009",
"short_message" => "Second commit",
"authored_at" => "Wed May 13 22:40:46 -0500 2009",
"identifier" => "2debe9d1b2591d1face99fd49246fc952df38666",
"message" => "Second commit",
"committer_email" => "developer_one@example.com",
"committer_name" => "Developer One",
"line_additions" => "5",
"line_deletions" => "15",
"line_total" => "43",
"affected_file_count" => "3"
},
{"author_email" => "developer_one@example.com",
"author_name" => "Developer One",
"committed_at" => "Wed May 13 22:26:13 -0500 2009",
"short_message" => "Initial commit",
"authored_at" => "Wed May 13 22:26:13 -0500 2009",
"identifier" => "9aedb043a88b1e2e8c165a3791b9da4961d1dfa3",
"message" => "Initial commit",
"committer_email" => "developer_one@example.com",
"committer_name" => "Developer One",
"line_additions" => "25",
"line_deletions" => "5",
"line_total" => "33",
"affected_file_count" => "7"
}
]
}
end
context "when all commits are processed successfully" do
it "creates a new commit for each entry in the payload" do
lambda {
# Kicks off PayloadProcessor.process! in after_create hook
Payload.make(:project => @project, :content => @content)
}.should change(Commit, :count).by(3)
end
it "assigns the commits created to the same project the payload was associated with" do
lambda {
# Kicks off PayloadProcessor.process! in after_create hook
Payload.make(:project => @project, :content => @content)
}.should change(@project.commits, :count).by(3)
end
it "marks the 'outcome' as 'Successful'"
end
context "when all commits are not processed successfully" do
it "marks the 'outcome' as 'Unsuccessful'"
end
end
end
end
| tomkersten/codefumes-site | spec/models/payload_processor_spec.rb | Ruby | mit | 3,979 |
using ClosedXML.Excel;
using System;
namespace ClosedXML_Examples.Misc
{
public class RightToLeft : IXLExample
{
public void Create(String filePath)
{
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("RightToLeftSheet");
ws.Cell("A1").Value = "A1";
ws.Cell("B1").Value = "B1";
ws.Cell("C1").Value = "C1";
ws.RightToLeft = true;
wb.SaveAs(filePath);
}
}
}
| vbjay/ClosedXML | ClosedXML_Examples/Misc/RightToLeft.cs | C# | mit | 486 |
/*
* Copyright (c) 2009 Roy Wellington IV
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "json.h"
json::Array::Array(const json::Array &a) : Value(TYPE_ARRAY)
{
try
{
for(std::vector<Value *>::const_iterator i = a.m_values.begin();
i != a.m_values.end();
++i)
{
Value *v = NULL;
try
{
v = (*i)->clone();
m_values.push_back(v);
}
catch(...)
{
delete v;
throw;
}
}
}
catch(...)
{
for(std::vector<Value *>::const_iterator i = m_values.begin();
i != m_values.end();
++i)
{
delete *i;
}
throw;
}
}
json::Array::~Array()
{
for(std::vector<Value *>::iterator i = m_values.begin();
i != m_values.end();
++i)
{
delete *i;
}
}
void json::Array::swap(json::Array &a)
{
m_values.swap(a.m_values);
}
json::Array &json::Array::operator = (const json::Array &a)
{
if(this == &a)
return *this;
json::Array temp(a);
swap(temp);
return *this;
}
void json::Array::pushBack(const json::Value *v)
{
Value *c = NULL;
try
{
c = v->clone();
m_values.push_back(c);
}
catch(...)
{
delete c;
throw;
}
}
| thanatos/libjson | src/array.cpp | C++ | mit | 2,141 |
import { JKFPlayer } from "json-kifu-format";
import { observer } from "mobx-react";
import * as React from "react";
import Piece from "./Piece";
import KifuStore from "./stores/KifuStore";
export interface IProps {
kifuStore: KifuStore;
}
@observer
export default class Board extends React.Component<IProps, any> {
public render() {
const { reversed, player } = this.props.kifuStore;
const board = player.getState().board;
const lastMove = player.getMove();
const nineY = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const nineX = nineY.slice().reverse();
const ths = nineX.map((logicalX) => {
const x = reversed ? 10 - logicalX : logicalX;
return <th key={x}>{x}</th>;
});
const trs = nineY.map((logicalY) => {
const y = reversed ? 10 - logicalY : logicalY;
const pieces = nineX.map((logicalX) => {
const x = reversed ? 10 - logicalX : logicalX;
return (
<Piece
key={x}
data={board[x - 1][y - 1]}
x={x}
y={y}
lastMove={lastMove}
kifuStore={this.props.kifuStore}
/>
);
});
return (
<tr key={y}>
{pieces}
<th>{JKFPlayer.numToKan(y)}</th>
</tr>
);
});
return (
<table className="kifuforjs-board">
<tbody>
<tr>{ths}</tr>
{trs}
</tbody>
</table>
);
}
}
| na2hiro/Kifu-for-JS | src/Board.tsx | TypeScript | mit | 1,723 |
import java.util.*;
public class WeightedGraph<T> implements WeightedGraphInterface<T>
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
{
if(numVertices == 0)
return true;
return false;
}
public boolean isFull()
{
if(numVertices == maxVertices)
return true;
return false;
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
{
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
}
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special "null-edge" value.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
return edges[row][column];
}
public Queue<T> getToVertices(T vertex)
// Returns a queue of the vertices that are adjacent from vertex.
{
Queue<T> adjVertices = new LinkedList<>();
int fromIndex;
int toIndex;
fromIndex = indexIs(vertex);
for (toIndex = 0; toIndex < numVertices; toIndex++)
if (edges[fromIndex][toIndex] != NULL_EDGE)
adjVertices.add(vertices[toIndex]);
return adjVertices;
}
public void markVertex(T vertex)
// Sets mark for vertex to true.
{
int index;
index = indexIs(vertex);
marks[index] = true;
}
public boolean isMarked(T vertex) {
int index;
index = indexIs(vertex);
return (marks[index]);
}
public void clearMarks() {
for (int i = 0; i < this.numVertices; i++) {
marks[i] = false;
}
}
public static boolean isPath(WeightedGraph<String> graph, String startVertex, String endVertex) {
Deque<String> stack = new ArrayDeque<String>();
Queue<String> vertexQueue = new LinkedList<String>();
boolean found = false;
String vertex;
String item;
graph.clearMarks();
stack.push(startVertex);
do {
vertex = stack.peek();
stack.pop();
if (vertex == endVertex)
found = true;
else {
if (!graph.isMarked(vertex)) {
graph.markVertex(vertex);
vertexQueue = graph.getToVertices(vertex);
while (!vertexQueue.isEmpty()) {
item = vertexQueue.poll();
if (!graph.isMarked(item))
stack.push(item);
}
}
}
} while (!stack.isEmpty() && !found);
return found;
}
public static void shortestPaths(WeightedGraph<String> graph, String startVertex){
Flight flight;
Flight saveFlight; // for saving on priority queue
int minDistance;
int newDistance;
PriorityQueue<Flight> pq = new PriorityQueue<Flight>(20); // Assume at most 20 vertices
String vertex;
Queue<String> vertexQueue = new LinkedList<>();
graph.clearMarks();
saveFlight = new Flight(startVertex, startVertex, 0);
pq.add(saveFlight);
System.out.println("Last Vertex Destination Distance");
System.out.println("------------------------------------");
do {
flight = pq.remove();
if (!graph.isMarked(flight.getToVertex())) {
graph.markVertex(flight.getToVertex());
System.out.println(flight);
flight.setFromVertex(flight.getToVertex());
minDistance = flight.getDistance();
vertexQueue = graph.getToVertices(flight.getFromVertex());
while (!vertexQueue.isEmpty()) {
vertex = vertexQueue.poll();
if (!graph.isMarked(vertex)) {
newDistance = minDistance
+ graph.weightIs(flight.getFromVertex(), vertex);
saveFlight = new Flight(flight.getFromVertex(), vertex, newDistance);
pq.add(saveFlight);
}
}
}
} while (!pq.isEmpty());
}
}
| Josecc/CSC202 | 5-assignment/Graph/WeightedGraph.java | Java | mit | 5,724 |
// Copyright (c) 2014-2019 Daniel Kraft
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <names/main.h>
#include <chainparams.h>
#include <coins.h>
#include <consensus/validation.h>
#include <dbwrapper.h>
#include <hash.h>
#include <names/encoding.h>
#include <script/interpreter.h>
#include <script/names.h>
#include <txmempool.h>
#include <uint256.h>
#include <undo.h>
#include <util/system.h>
#include <util/strencodings.h>
#include <validation.h>
#include <string>
#include <vector>
namespace
{
/**
* Check whether a name at nPrevHeight is expired at nHeight. Also
* heights of MEMPOOL_HEIGHT are supported. For nHeight == MEMPOOL_HEIGHT,
* we check at the current best tip's height.
* @param nPrevHeight The name's output.
* @param nHeight The height at which it should be updated.
* @return True iff the name is expired.
*/
bool
isExpired (unsigned nPrevHeight, unsigned nHeight)
{
assert (nHeight != MEMPOOL_HEIGHT);
if (nPrevHeight == MEMPOOL_HEIGHT)
return false;
const Consensus::Params& params = Params ().GetConsensus ();
return nPrevHeight + params.rules->NameExpirationDepth (nHeight) <= nHeight;
}
} // anonymous namespace
/* ************************************************************************** */
/* CNameData. */
bool
CNameData::isExpired () const
{
return isExpired (::ChainActive ().Height ());
}
bool
CNameData::isExpired (unsigned h) const
{
return ::isExpired (nHeight, h);
}
/* ************************************************************************** */
/* CNameTxUndo. */
void
CNameTxUndo::fromOldState (const valtype& nm, const CCoinsView& view)
{
name = nm;
isNew = !view.GetName (name, oldData);
}
void
CNameTxUndo::apply (CCoinsViewCache& view) const
{
if (isNew)
view.DeleteName (name);
else
view.SetName (name, oldData, true);
}
/* ************************************************************************** */
bool
CheckNameTransaction (const CTransaction& tx, unsigned nHeight,
const CCoinsView& view,
TxValidationState& state, unsigned flags)
{
const bool fMempool = (flags & SCRIPT_VERIFY_NAMES_MEMPOOL);
/* Ignore historic bugs. */
CChainParams::BugType type;
if (Params ().IsHistoricBug (tx.GetHash (), nHeight, type))
return true;
/* As a first step, try to locate inputs and outputs of the transaction
that are name scripts. At most one input and output should be
a name operation. */
int nameIn = -1;
CNameScript nameOpIn;
Coin coinIn;
for (unsigned i = 0; i < tx.vin.size (); ++i)
{
const COutPoint& prevout = tx.vin[i].prevout;
Coin coin;
if (!view.GetCoin (prevout, coin))
return state.Invalid (TxValidationResult::TX_MISSING_INPUTS,
"bad-txns-inputs-missingorspent",
"Failed to fetch name input coin");
const CNameScript op(coin.out.scriptPubKey);
if (op.isNameOp ())
{
if (nameIn != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-multiple-name-inputs",
"Multiple name inputs");
nameIn = i;
nameOpIn = op;
coinIn = coin;
}
}
int nameOut = -1;
CNameScript nameOpOut;
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp ())
{
if (nameOut != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-multiple-name-outputs",
"Multiple name outputs");
nameOut = i;
nameOpOut = op;
}
}
/* Check that no name inputs/outputs are present for a non-Namecoin tx.
If that's the case, all is fine. For a Namecoin tx instead, there
should be at least an output (for NAME_NEW, no inputs are expected). */
if (!tx.IsNamecoin ())
{
if (nameIn != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nonname-with-name-input",
"Non-name transaction has name input");
if (nameOut != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nonname-with-name-output",
"Non-name transaction has name output");
return true;
}
assert (tx.IsNamecoin ());
if (nameOut == -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-name-without-name-output",
"Name transaction has no name output");
/* Reject "greedy names". */
const Consensus::Params& params = Params ().GetConsensus ();
if (tx.vout[nameOut].nValue < params.rules->MinNameCoinAmount(nHeight))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-name-greedy",
"Greedy name operation");
/* Handle NAME_NEW now, since this is easy and different from the other
operations. */
if (nameOpOut.getNameOp () == OP_NAME_NEW)
{
if (nameIn != -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-namenew-with-name-input",
"NAME_NEW with previous name input");
if (nameOpOut.getOpHash ().size () != 20)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-namenew-wrong-size",
"NAME_NEW's hash has the wrong size");
return true;
}
/* Now that we have ruled out NAME_NEW, check that we have a previous
name input that is being updated. */
assert (nameOpOut.isAnyUpdate ());
if (nameIn == -1)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-without-name-input",
"Name update has no previous name input");
const valtype& name = nameOpOut.getOpName ();
if (name.size () > MAX_NAME_LENGTH)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-name-invalid",
"Invalid name");
if (nameOpOut.getOpValue ().size () > MAX_VALUE_LENGTH)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-value-invalid",
"Invalid value");
/* Process NAME_UPDATE next. */
if (nameOpOut.getNameOp () == OP_NAME_UPDATE)
{
if (!nameOpIn.isAnyUpdate ())
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-invalid-prev",
"Name input for NAME_UPDATE is not an update");
if (name != nameOpIn.getOpName ())
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-name-mismatch",
"NAME_UPDATE name mismatch to name input");
/* If the name input is pending, then no further checks with respect
to the name input in the name database are done. Otherwise, we verify
that the name input matches the name database; this is redundant
as UTXO handling takes care of it anyway, but we do it for
an extra safety layer. */
const unsigned inHeight = coinIn.nHeight;
if (inHeight == MEMPOOL_HEIGHT)
return true;
CNameData oldName;
if (!view.GetName (name, oldName))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-nonexistant",
"NAME_UPDATE name does not exist");
if (oldName.isExpired (nHeight))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-nameupdate-expired",
"NAME_UPDATE on an expired name");
assert (inHeight == oldName.getHeight ());
assert (tx.vin[nameIn].prevout == oldName.getUpdateOutpoint ());
return true;
}
/* Finally, NAME_FIRSTUPDATE. */
assert (nameOpOut.getNameOp () == OP_NAME_FIRSTUPDATE);
if (nameOpIn.getNameOp () != OP_NAME_NEW)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-nonnew-input",
"NAME_FIRSTUPDATE input is not a NAME_NEW");
/* Maturity of NAME_NEW is checked only if we're not adding
to the mempool. */
if (!fMempool)
{
assert (static_cast<unsigned> (coinIn.nHeight) != MEMPOOL_HEIGHT);
if (coinIn.nHeight + MIN_FIRSTUPDATE_DEPTH > nHeight)
return state.Invalid (TxValidationResult::TX_PREMATURE_SPEND,
"tx-firstupdate-immature",
"NAME_FIRSTUPDATE on immature NAME_NEW");
}
if (nameOpOut.getOpRand ().size () > 20)
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-invalid-rand",
"NAME_FIRSTUPDATE rand value is too large");
{
valtype toHash(nameOpOut.getOpRand ());
toHash.insert (toHash.end (), name.begin (), name.end ());
const uint160 hash = Hash160 (toHash);
if (hash != uint160 (nameOpIn.getOpHash ()))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-hash-mismatch",
"NAME_FIRSTUPDATE mismatch in hash / rand value");
}
CNameData oldName;
if (view.GetName (name, oldName) && !oldName.isExpired (nHeight))
return state.Invalid (TxValidationResult::TX_CONSENSUS,
"tx-firstupdate-existing-name",
"NAME_FIRSTUPDATE on existing name");
/* We don't have to specifically check that miners don't create blocks with
conflicting NAME_FIRSTUPDATE's, since the mining's CCoinsViewCache
takes care of this with the check above already. */
return true;
}
void
ApplyNameTransaction (const CTransaction& tx, unsigned nHeight,
CCoinsViewCache& view, CBlockUndo& undo)
{
assert (nHeight != MEMPOOL_HEIGHT);
/* Handle historic bugs that should *not* be applied. Names that are
outputs should be marked as unspendable in this case. Otherwise,
we get an inconsistency between the UTXO set and the name database. */
CChainParams::BugType type;
const uint256 txHash = tx.GetHash ();
if (Params ().IsHistoricBug (txHash, nHeight, type)
&& type != CChainParams::BUG_FULLY_APPLY)
{
if (type == CChainParams::BUG_FULLY_IGNORE)
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp () && op.isAnyUpdate ())
view.SpendCoin (COutPoint (txHash, i));
}
return;
}
/* This check must be done *after* the historic bug fixing above! Some
of the names that must be handled above are actually produced by
transactions *not* marked as Namecoin tx. */
if (!tx.IsNamecoin ())
return;
/* Changes are encoded in the outputs. We don't have to do any checks,
so simply apply all these. */
for (unsigned i = 0; i < tx.vout.size (); ++i)
{
const CNameScript op(tx.vout[i].scriptPubKey);
if (op.isNameOp () && op.isAnyUpdate ())
{
const valtype& name = op.getOpName ();
LogPrint (BCLog::NAMES, "Updating name at height %d: %s\n",
nHeight, EncodeNameForMessage (name));
CNameTxUndo opUndo;
opUndo.fromOldState (name, view);
undo.vnameundo.push_back (opUndo);
CNameData data;
data.fromScript (nHeight, COutPoint (tx.GetHash (), i), op);
view.SetName (name, data, false);
}
}
}
bool
ExpireNames (unsigned nHeight, CCoinsViewCache& view, CBlockUndo& undo,
std::set<valtype>& names)
{
names.clear ();
/* The genesis block contains no name expirations. */
if (nHeight == 0)
return true;
/* Otherwise, find out at which update heights names have expired
since the last block. If the expiration depth changes, this could
be multiple heights at once. */
const Consensus::Params& params = Params ().GetConsensus ();
const unsigned expDepthOld = params.rules->NameExpirationDepth (nHeight - 1);
const unsigned expDepthNow = params.rules->NameExpirationDepth (nHeight);
if (expDepthNow > nHeight)
return true;
/* Both are inclusive! The last expireTo was nHeight - 1 - expDepthOld,
now we start at this value + 1. */
const unsigned expireFrom = nHeight - expDepthOld;
const unsigned expireTo = nHeight - expDepthNow;
/* It is possible that expireFrom = expireTo + 1, in case that the
expiration period is raised together with the block height. In this
case, no names expire in the current step. This case means that
the absolute expiration height "n - expirationDepth(n)" is
flat -- which is fine. */
assert (expireFrom <= expireTo + 1);
/* Find all names that expire at those depths. Note that GetNamesForHeight
clears the output set, to we union all sets here. */
for (unsigned h = expireFrom; h <= expireTo; ++h)
{
std::set<valtype> newNames;
view.GetNamesForHeight (h, newNames);
names.insert (newNames.begin (), newNames.end ());
}
/* Expire all those names. */
for (std::set<valtype>::const_iterator i = names.begin ();
i != names.end (); ++i)
{
const std::string nameStr = EncodeNameForMessage (*i);
CNameData data;
if (!view.GetName (*i, data))
return error ("%s : name %s not found in the database",
__func__, nameStr);
if (!data.isExpired (nHeight))
return error ("%s : name %s is not actually expired",
__func__, nameStr);
/* Special rule: When d/postmortem expires (the name used by
libcoin in the name-stealing demonstration), it's coin
is already spent. Ignore. */
if (nHeight == 175868
&& EncodeName (*i, NameEncoding::ASCII) == "d/postmortem")
continue;
const COutPoint& out = data.getUpdateOutpoint ();
Coin coin;
if (!view.GetCoin(out, coin))
return error ("%s : name coin for %s is not available",
__func__, nameStr);
const CNameScript nameOp(coin.out.scriptPubKey);
if (!nameOp.isNameOp () || !nameOp.isAnyUpdate ()
|| nameOp.getOpName () != *i)
return error ("%s : name coin to be expired is wrong script", __func__);
if (!view.SpendCoin (out, &coin))
return error ("%s : spending name coin failed", __func__);
undo.vexpired.push_back (coin);
}
return true;
}
bool
UnexpireNames (unsigned nHeight, CBlockUndo& undo, CCoinsViewCache& view,
std::set<valtype>& names)
{
names.clear ();
/* The genesis block contains no name expirations. */
if (nHeight == 0)
return true;
std::vector<Coin>::reverse_iterator i;
for (i = undo.vexpired.rbegin (); i != undo.vexpired.rend (); ++i)
{
const CNameScript nameOp(i->out.scriptPubKey);
if (!nameOp.isNameOp () || !nameOp.isAnyUpdate ())
return error ("%s : wrong script to be unexpired", __func__);
const valtype& name = nameOp.getOpName ();
if (names.count (name) > 0)
return error ("%s : name %s unexpired twice",
__func__, EncodeNameForMessage (name));
names.insert (name);
CNameData data;
if (!view.GetName (nameOp.getOpName (), data))
return error ("%s : no data for name '%s' to be unexpired",
__func__, EncodeNameForMessage (name));
if (!data.isExpired (nHeight) || data.isExpired (nHeight - 1))
return error ("%s : name '%s' to be unexpired is not expired in the DB"
" or it was already expired before the current height",
__func__, EncodeNameForMessage (name));
if (ApplyTxInUndo (std::move(*i), view,
data.getUpdateOutpoint ()) != DISCONNECT_OK)
return error ("%s : failed to undo name coin spending", __func__);
}
return true;
}
void
CheckNameDB (bool disconnect)
{
const int option
= gArgs.GetArg ("-checknamedb", Params ().DefaultCheckNameDB ());
if (option == -1)
return;
assert (option >= 0);
if (option != 0)
{
if (disconnect || ::ChainActive ().Height () % option != 0)
return;
}
auto& coinsTip = ::ChainstateActive ().CoinsTip ();
coinsTip.Flush ();
const bool ok = coinsTip.ValidateNameDB ();
/* The DB is inconsistent (mismatch between UTXO set and names DB) between
(roughly) blocks 139,000 and 180,000. This is caused by libcoin's
"name stealing" bug. For instance, d/postmortem is removed from
the UTXO set shortly after registration (when it is used to steal
names), but it remains in the name DB until it expires. */
if (!ok)
{
const unsigned nHeight = ::ChainActive ().Height ();
LogPrintf ("ERROR: %s : name database is inconsistent\n", __func__);
if (nHeight >= 139000 && nHeight <= 180000)
LogPrintf ("This is expected due to 'name stealing'.\n");
else
assert (false);
}
}
| namecoin/namecore | src/names/main.cpp | C++ | mit | 17,522 |
/**
*/
package geometry.impl;
import geometry.GeometryPackage;
import geometry.Point;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Point</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link geometry.impl.PointImpl#getXLocation <em>XLocation</em>}</li>
* <li>{@link geometry.impl.PointImpl#getYLocation <em>YLocation</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class PointImpl extends GObjectImpl implements Point {
/**
* The default value of the '{@link #getXLocation() <em>XLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getXLocation()
* @generated
* @ordered
*/
protected static final int XLOCATION_EDEFAULT = 0;
/**
* The cached value of the '{@link #getXLocation() <em>XLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getXLocation()
* @generated
* @ordered
*/
protected int xLocation = XLOCATION_EDEFAULT;
/**
* The default value of the '{@link #getYLocation() <em>YLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getYLocation()
* @generated
* @ordered
*/
protected static final int YLOCATION_EDEFAULT = 0;
/**
* The cached value of the '{@link #getYLocation() <em>YLocation</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getYLocation()
* @generated
* @ordered
*/
protected int yLocation = YLOCATION_EDEFAULT;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PointImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return GeometryPackage.Literals.POINT;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getXLocation() {
return xLocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setXLocation(int newXLocation) {
int oldXLocation = xLocation;
xLocation = newXLocation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GeometryPackage.POINT__XLOCATION, oldXLocation, xLocation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public int getYLocation() {
return yLocation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setYLocation(int newYLocation) {
int oldYLocation = yLocation;
yLocation = newYLocation;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, GeometryPackage.POINT__YLOCATION, oldYLocation, yLocation));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
return getXLocation();
case GeometryPackage.POINT__YLOCATION:
return getYLocation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
setXLocation((Integer)newValue);
return;
case GeometryPackage.POINT__YLOCATION:
setYLocation((Integer)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
setXLocation(XLOCATION_EDEFAULT);
return;
case GeometryPackage.POINT__YLOCATION:
setYLocation(YLOCATION_EDEFAULT);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case GeometryPackage.POINT__XLOCATION:
return xLocation != XLOCATION_EDEFAULT;
case GeometryPackage.POINT__YLOCATION:
return yLocation != YLOCATION_EDEFAULT;
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (xLocation: ");
result.append(xLocation);
result.append(", yLocation: ");
result.append(yLocation);
result.append(')');
return result.toString();
}
} //PointImpl
| albertfdp/petrinet | src/dk.dtu.se2.geometry/src/geometry/impl/PointImpl.java | Java | mit | 5,044 |
'use strict';
angular.module('eklabs.angularStarterPack.offer')
.directive('removeOffer',function($log, $location, Offers){
return {
templateUrl : 'eklabs.angularStarterPack/modules/offers/views/MyRemoveOfferView.html',
scope : {
offer : '=?',
callback : '=?',
listOffer : '='
},link : function(scope, attr, $http) {
// Initialisation du constructeur
var offersCreation = new Offers();
// Supprimer une offre de stage
scope.deleteOffer = function(idOfferToDelete) {
offersCreation.deleteOffer(idOfferToDelete).then(idOfferToDelete);
alert("L\'annonce a bien été supprimer. Vous allez être redirigé sur la page d'accueil. ");
};
}
}
})
| julienbnr/InternMe | src/modules/offers/directives/my-offer/MyRemoveOfferDirective.js | JavaScript | mit | 883 |
<?php
$registration_notice = '';
$success = false;
if ( isset($_POST['submit_registration']) ) { // process registration
$username = isset($_POST['username']) ? trim($_POST['username']) : '';
$email = isset($_POST['email']) ? trim($_POST['email']) : '';
$password = isset($_POST['password']) ? trim($_POST['password']) : '';
$password2 = isset($_POST['password2']) ? trim($_POST['password2']) : '';
if ( !empty($username) &&
!empty($email) &&
!empty($password) &&
$password == $password2 ) {
$registration = $db->prepare("INSERT INTO users (`login`, `email`, `password`, `created_at`) VALUES (?, ?, PASSWORD(?), ?)");
$success = $registration->execute(
array(
$username,
$email,
$password,
date(MYSQL_DATETIME)
)
);
if ($success) {
$registration_notice = "Registrazione eseguita correttamente. Ti è stata inviata un'email di conferma.";
$success = true;
} else { // fail
$registration_notice = "Registrazione fallita. Per favore riprova.";
}
} else { // invalid data
$registration_notice = "Campi non validi. Per favore aggiorna la pagina e riprova.";
}
echo $registration_notice;
if (!$success) { include_once INC . 'forms/register.php'; }
} else { // show registration form
include_once INC . 'forms/register.php';
}
| simonewebdesign/Fushi | application/accounts/register.php | PHP | mit | 1,329 |
'use strict';
var angular = require('angular');
module.exports = angular.module('services.notifications', [])
.factory('notifications', ['$rootScope', function ($rootScope) {
var notifications = {
'STICKY' : [],
'ROUTE_CURRENT' : [],
'ROUTE_NEXT' : []
};
var notificationsService = {};
var addNotification = function (notificationsArray, notificationObj) {
if (!angular.isObject(notificationObj)) {
throw new Error("Only object can be added to the notification service");
}
notificationsArray.push(notificationObj);
return notificationObj;
};
$rootScope.$on('$routeChangeSuccess', function () {
notifications.ROUTE_CURRENT.length = 0;
notifications.ROUTE_CURRENT = angular.copy(notifications.ROUTE_NEXT);
notifications.ROUTE_NEXT.length = 0;
});
notificationsService.getCurrent = function(){
return [].concat(notifications.STICKY, notifications.ROUTE_CURRENT);
};
notificationsService.pushSticky = function(notification) {
return addNotification(notifications.STICKY, notification);
};
notificationsService.pushForCurrentRoute = function(notification) {
return addNotification(notifications.ROUTE_CURRENT, notification);
};
notificationsService.pushForNextRoute = function(notification) {
return addNotification(notifications.ROUTE_NEXT, notification);
};
notificationsService.remove = function(notification){
angular.forEach(notifications, function (notificationsByType) {
var idx = notificationsByType.indexOf(notification);
if (idx>-1){
notificationsByType.splice(idx,1);
}
});
};
notificationsService.removeAll = function(){
angular.forEach(notifications, function (notificationsByType) {
notificationsByType.length = 0;
});
};
return notificationsService;
}]);
| evangalen/webpack-angular-app | client/src/common/services/notifications.js | JavaScript | mit | 1,830 |
import KolibriModule from 'kolibri_module';
import { getCurrentSession } from 'kolibri.coreVue.vuex.actions';
import router from 'kolibri.coreVue.router';
import Vue from 'kolibri.lib.vue';
import store from 'kolibri.coreVue.vuex.store';
import heartbeat from 'kolibri.heartbeat';
/*
* A class for single page apps that control routing and vuex state.
* Override the routes, mutations, initialState, and RootVue getters.
*/
export default class KolibriApp extends KolibriModule {
/*
* @return {Array[Object]} Array of objects that define vue-router route configurations.
* These will get passed to our internal router, so the handlers should
* be functions that invoke vuex actions.
*/
get routes() {
return [];
}
/*
* @return {Object} An object of vuex mutations, with keys as the mutation name, and
* values that are methods that perform the store mutation.
*/
get mutations() {
return {};
}
/*
* @return {Object} The initial state of the vuex store for this app, this will be merged with
* the core app initial state to instantiate the store.
*/
get initialState() {
return {};
}
/*
* @return {Object} A component definition for the root component of this single page app.
*/
get RootVue() {
return {};
}
/*
* @return {Store} A convenience getter to return the vuex store.
*/
get store() {
return store;
}
/*
* @return {Array[Function]} Array of vuex actions that will do initial state setting before the
* routes are handled. Use this to do initial state setup that needs to
* be dynamically determined, and done before every route in the app.
* Each function should return a promise that resolves when the state
* has been set. These will be invoked after the current session has
* been set in the vuex store, in order to allow these actions to
* reference getters that return data set by the getCurrentSession
* action. As this has always been bootstrapped into the base template
* this should not cause any real slow down in page loading.
*/
get stateSetters() {
return [];
}
ready() {
this.store.registerModule({
state: this.initialState,
mutations: this.mutations,
});
getCurrentSession(store).then(() => {
Promise.all([
// Invoke each of the state setters before initializing the app.
...this.stateSetters.map(setter => setter(this.store)),
]).then(() => {
heartbeat.start();
this.rootvue = new Vue(
Object.assign(
{
el: 'rootvue',
store: store,
router: router.init(this.routes),
},
this.RootVue
)
);
});
});
}
}
| christianmemije/kolibri | kolibri/core/assets/src/kolibri_app.js | JavaScript | mit | 3,037 |
module.exports = require('./lib/tapioca'); | salomaosnff/tapioca-load | index.js | JavaScript | mit | 42 |
package com.thedreamsanctuary.main.java.dreamplus.commands;
import com.thedreamsanctuary.main.java.dreamplus.DreamPlus;
import com.thedreamsanctuary.main.java.dreamplus.executors.DPFood;
import java.util.Random;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
* @author Ajcool1050
*/
public class GetOtherDrunkCommand implements CommandExecutor
{
final DreamPlus dp;
public GetOtherDrunkCommand(DreamPlus dp)
{
this.dp = dp;
}
@Override
public boolean onCommand(CommandSender sender, Command command, String string, String[] args)
{
if (sender instanceof Player)
{
Player player = (Player) sender;
if (player.hasPermission("dreamplus.command.getotherdrunk"))
{
if (args.length == 2)
{
Player receiver = player.getServer().getPlayer(args[0]);
if (receiver != null)
{
if (isInt(args[1]))
{
int seconds = Integer.parseInt(args[1]);
DPFood.drinkLager(receiver, seconds);
Random random = new Random();
int number = random.nextInt(50) + 1;
if (number == 1)
{
receiver.sendMessage(ChatColor.DARK_GRAY + "["
+ ChatColor.DARK_AQUA + "Kesaro"
+ ChatColor.DARK_GRAY + " -> "
+ ChatColor.GRAY + "You"
+ ChatColor.DARK_GRAY + "]"
+ ChatColor.AQUA + " u fukin wot m8 ill bash ur fkin hed in i swer on me mum");
}
player.sendMessage(ChatColor.GOLD + receiver.getName() + " sure did enjoy their VoxelLager");
}
else player.sendMessage(ChatColor.GOLD + "Usage: /getotherdrunk [player] [seconds]");
}
else player.sendMessage(ChatColor.GOLD + "That player could not be found.");
}
else player.sendMessage(ChatColor.GOLD + "Usage: /getotherdrunk [player] [seconds]");
}
else player.sendMessage("You are not able to execute that command.");
}
else sender.sendMessage("Must be and ingame player to execute command.");
return false;
}
private static boolean isInt(String s)
{
try
{
Integer.parseInt(s);
}
catch (NumberFormatException nfe)
{
return false;
}
return true;
}
}
| TheDreamSanctuary/DreamPlus | main/java/com/thedreamsanctuary/main/java/dreamplus/commands/GetOtherDrunkCommand.java | Java | mit | 3,041 |
module.exports = function(server){
return {
login: require('./login')(server),
logout: require('./logout')(server)
}
}
| julien-sarazin/learning-nodejs | actions/auth/index.js | JavaScript | mit | 135 |
namespace SubsetSums
{
using System.Collections.Generic;
using System.Linq;
public static class SubsetsSumEvaluator
{
/// <summary>
/// Evaluates all possible subset sums. Negative numbers not allowed.
/// </summary>
/// <param name="numbers"></param>
/// <returns></returns>
public static IList<int> FindPossibleSums(int[] numbers)
{
int maxPossibleSum = numbers.Sum();
bool[] possibleSums = new bool[maxPossibleSum + 1];
possibleSums[0] = true;
bool hasZero = false;
int minSum = 0;
int maxSum = 0;
int tempMaxSum = 0;
foreach (var number in numbers)
{
if (!hasZero && number == 0)
{
hasZero = true;
}
for (int i = maxSum; i >= minSum; i--)
{
if (possibleSums[i])
{
var currentNumber = i + number;
if (tempMaxSum < currentNumber)
{
tempMaxSum = currentNumber;
}
possibleSums[currentNumber] = true;
}
}
maxSum = tempMaxSum;
}
var sums = new List<int>();
if (hasZero)
{
sums.Add(0);
}
for (int i = 1; i < possibleSums.Length; i++)
{
if (possibleSums[i])
{
sums.Add(i);
}
}
return sums;
}
/// <summary>
/// Evaluates all possible subset sums. Negative numbers allowed.
/// </summary>
/// <param name="numbers"></param>
/// <returns></returns>
public static IList<int> FindPossibleSumsWithNegative(int[] numbers)
{
// var possitiveNumbers = new List<int>();
// var negativeNumbers = new List<int>();
int minPossibleSum = 0;
int maxPossibleSum = 0;
foreach (var number in numbers)
{
if (number >= 0)
{
// possitiveNumbers.Add(number);
maxPossibleSum += number;
}
else
{
// negativeNumbers.Add(number);
minPossibleSum += number;
}
}
int offset = -1 * minPossibleSum;
bool[] possibleSums = new bool[maxPossibleSum + offset + 1];
possibleSums[offset] = true;
bool hasZero = false;
int minSum = offset;
int maxSum = offset;
int tempMinSum = offset;
int tempMaxSum = offset;
foreach (var number in numbers.Where(n => n >= 0))
{
if (!hasZero && number == 0)
{
hasZero = true;
}
tempMaxSum = maxSum;
for (int i = maxSum; i >= minSum; i--)
{
if (possibleSums[i])
{
var currentNumber = i + number;
if (tempMaxSum < currentNumber)
{
tempMaxSum = currentNumber;
}
possibleSums[currentNumber] = true;
}
}
maxSum = tempMaxSum;
}
foreach (var number in numbers.Where(n => n < 0))
{
tempMinSum = minSum;
for (int i = minSum; i <= maxSum; i++)
{
if (possibleSums[i])
{
var currentNumber = i + number;
if (!hasZero && currentNumber == offset)
{
hasZero = true;
}
if (tempMinSum > currentNumber)
{
tempMinSum = currentNumber;
}
possibleSums[currentNumber] = true;
}
}
minSum = tempMinSum;
}
var sums = new List<int>();
for (int i = 0; i < offset; i++)
{
if (possibleSums[i])
{
sums.Add(i - offset);
}
}
if (hasZero)
{
sums.Add(0);
}
for (int i = offset + 1; i < possibleSums.Length; i++)
{
if (possibleSums[i])
{
sums.Add(i - offset);
}
}
return sums;
}
}
}
| bstaykov/Telerik-DSA | 2015/DynamicProgramming/SubsetSums/SubsetsSumEvaluator.cs | C# | mit | 5,009 |
import { Model } from 'type-r';
import { RestfulFetchOptions, RestfulEndpoint, RestfulIOOptions, HttpMethod } from './restful';
export declare type ConstructUrl = (params: {
[key: string]: any;
}, model?: Model) => string;
export declare function fetchModelIO(method: HttpMethod, url: ConstructUrl, options?: RestfulFetchOptions): ModelFetchEndpoint;
declare class ModelFetchEndpoint extends RestfulEndpoint {
method: HttpMethod;
constructUrl: ConstructUrl;
constructor(method: HttpMethod, constructUrl: ConstructUrl, { mockData, ...options }?: RestfulFetchOptions);
list(): Promise<void>;
destroy(): Promise<void>;
create(): Promise<void>;
update(): Promise<void>;
read(id: any, options: RestfulIOOptions, model: Model): Promise<any>;
}
export {};
| Volicon/Type-R | endpoints/restful/lib/fetchModel.d.ts | TypeScript | mit | 785 |
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.integer :user_id
t.string :title
t.text :content
t.timestamps null: false
end
end
end
| Bulldogse45/website_on_rails | db/migrate/20151116004951_create_posts.rb | Ruby | mit | 207 |
<?php
// /var/www/symfony2.0/alf/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/views/Exception/error.atom.twig
return array (
);
| radzikowski/alf | app/cache/dev/assetic/config/e/e3d82803dd71bab66d782bbf081c9e4b.php | PHP | mit | 144 |
using Qwack.Core.Basic;
using Qwack.Core.Instruments;
namespace Qwack.Core.Models
{
public interface IAssetPathPayoff
{
IAssetInstrument AssetInstrument { get; }
double AverageResult { get; }
bool IsComplete { get; }
double ResultStdError { get; }
CashFlowSchedule ExpectedFlows(IAssetFxModel model);
CashFlowSchedule[] ExpectedFlowsByPath(IAssetFxModel model);
void Finish(IFeatureCollection collection);
void Process(IPathBlock block);
void SetupFeatures(IFeatureCollection pathProcessFeaturesCollection);
string RegressionKey { get; }
}
}
| cetusfinance/qwack | src/Qwack.Core/Models/IAssetPathPayoff.cs | C# | mit | 658 |
package org.scenarioo.pizza.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import static org.junit.jupiter.api.Assertions.*;
public class SummaryPage extends BasePage {
public static void assertPizzaVerduraAndRedWineAreListed() {
WebDriver webDriver = getWebDriver();
String pizza = webDriver.findElement(By.id("summary_pizza")).getText();
String drinks = webDriver.findElement(By.id("summary_drinks")).getText();
assertEquals("Pizza Verdura", pizza);
assertEquals("Vino Rosso", drinks);
}
public static void clickOrderButton() {
getStepElement().findElement(By.className("next")).click();
}
private static WebElement getStepElement() {
return getWebDriver().findElement(By.id("step-summary"));
}
}
| scenarioo/pizza-delivery | src/test/java/org/scenarioo/pizza/pageObjects/SummaryPage.java | Java | mit | 861 |
namespace ConsoleTestApp.Features.C
{
using System;
using Miruken.Mvc.Console;
using Buffer = Miruken.Mvc.Console.Buffer;
public class CView : View<CController>
{
private readonly Menu menu;
public CView()
{
var output = new Buffer();
Content = output;
output.Header("C View");
output.WriteLine("C Feature");
output.Block("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?");
menu = new Menu(new MenuItem("Back", ConsoleKey.B, () => Controller.Back()));
output.WriteLine(menu.ToString());
}
public override void KeyPressed(ConsoleKeyInfo keyInfo)
{
menu.Listen(keyInfo);
}
}
} | Miruken-DotNet/Miruken.Mvc | Test/ConsoleTestApp/Features/C/CView.cs | C# | mit | 1,574 |
/*
* Copyright (c) 2015 Phoenix Scholars Co. (http://dpq.co.ir)
*
* 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.
*/
'use strict';
angular.module('pluf')
/**
* @memberof pluf
* @ngdoc service
* @name $monitor
* @description مدیریت تمام مانیتورها را ایجاد میکند
*
* مانیتورها در واحد زمان باید به روز شوند. این سرویس نه تنها مانیتورها را ایجاد
* بلکه آنها را در واحد زمان به روز میکند.
*
* در صورتی که استفاده از یک مانیتور تمام شود،این سرویس مانیتورهای ایجاد شده را
* حذف میکند تا میزان انتقال اطلاعات را کم کند.
*
* @see PMonitor
*
*/
.service('$collection', function($pluf, PCollection, PObjectFactory) {
var _cache = new PObjectFactory(function(data) {
return new PCollection(data);
});
/**
* Creates new collection
*
* @memberof $collection
* @return Promise<PCollection>
* createdreceipt
*
*/
this.newCollection = $pluf.createNew({
method : 'POST',
url : '/api/collection/new'
}, _cache);
/**
* Gets collection detail. Input could be id or name of collection.
*
* @memberof $collection
* @return Promise<PCollection>
* createdreceipt
*
*/
this.collection = $pluf.createGet({
method : 'GET',
url : '/api/collection/{id}',
}, _cache);
/**
* Lists all collections
*
* @memberof $collection
* @return Promise<PaginatorPage<PCollection>>
* createdreceipt
*
*/
this.collections = $pluf.createFind({
method : 'GET',
url : '/api/collection/find',
}, _cache);
});
| phoenix-scholars/angular-pluf | src/collection/services/collection.js | JavaScript | mit | 2,721 |
package com.nestedworld.nestedworld.data.database.entities;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import com.nestedworld.nestedworld.data.database.entities.base.BaseEntity;
import org.greenrobot.greendao.annotation.Entity;
import org.greenrobot.greendao.annotation.Generated;
import org.greenrobot.greendao.annotation.Id;
import org.greenrobot.greendao.annotation.Unique;
@Entity()
public class ShopItem extends BaseEntity {
@Expose
@SerializedName("id")
@Unique
public long shopItemId;
@Expose
public String name;
@Expose
public String kind;
@Expose
public String power;
@Expose
public Boolean premium;
@Expose
public String description;
@Expose
public long price;
@Expose
public String image;
@Id(autoincrement = true)
@Unique
private Long id;
@Generated(hash = 33734647)
public ShopItem(long shopItemId, String name, String kind, String power,
Boolean premium, String description, long price, String image,
Long id) {
this.shopItemId = shopItemId;
this.name = name;
this.kind = kind;
this.power = power;
this.premium = premium;
this.description = description;
this.price = price;
this.image = image;
this.id = id;
}
@Generated(hash = 872247774)
public ShopItem() {
}
public long getShopItemId() {
return this.shopItemId;
}
public void setShopItemId(long shopItemId) {
this.shopItemId = shopItemId;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getKind() {
return this.kind;
}
public void setKind(String kind) {
this.kind = kind;
}
public String getPower() {
return this.power;
}
public void setPower(String power) {
this.power = power;
}
public Boolean getPremium() {
return this.premium;
}
public void setPremium(Boolean premium) {
this.premium = premium;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public long getPrice() {
return this.price;
}
public void setPrice(long price) {
this.price = price;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
}
| NestedWorld/NestedWorld-Android | app/src/main/java/com/nestedworld/nestedworld/data/database/entities/ShopItem.java | Java | mit | 2,768 |
package fi.guagua.pixrayandroid.models;
import java.io.Serializable;
import java.util.ArrayList;
public class ScoreTypes implements Serializable {
private ArrayList<Integer> mIds;
private ArrayList<String> mNames;
private ArrayList<String> mColors;
public ScoreTypes(ArrayList<Integer> ids, ArrayList<String> names, ArrayList<String> colors) {
mIds = ids;
mNames = names;
mColors = colors;
}
public ArrayList<Integer> getIds() {
return mIds;
}
public ArrayList<String> getNames() {
return mNames;
}
public ArrayList<String> getColors() {
return mColors;
}
}
| huiningd/PixrayAndroid | app/src/main/java/fi/guagua/pixrayandroid/models/ScoreTypes.java | Java | mit | 657 |
'use strict'
// ensure endpoint starts w/ http:// or https://
module.exports = function normalizeEndpoint (endpoint, version) {
if (endpoint == null) throw new Error('endpoint is required')
if (typeof endpoint !== 'string') throw new Error('endpoint must be a string')
if (endpoint === '') throw new Error('endpoint must not be empty string')
if (version == null || version === 1) {
version = 'v1'
}
if (version !== 'v1') {
throw new Error('Only v1 of the API is currently supported')
}
// if doesn't match http:// or https://, use https://
endpoint = endpoint.trim() + '/api/' + version + '/'
if (!endpoint.match(/^https?:\/\//)) {
endpoint = 'https://' + endpoint
}
return endpoint
}
| nodesource/nsolid-statsd | node_modules/nsolid-apiclient/lib/normalize-endpoint.js | JavaScript | mit | 726 |
"""
Tahmatassu Web Server
~~~~~~~~~~~~~~~~~~~~~
HTTP-status codes containing module
:copyright: (c) 2014 by Teemu Puukko.
:license: MIT, see LICENSE for more details.
"""
from werkzeug.wsgi import LimitedStream
class StreamConsumingMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
content_length = environ.get('CONTENT_LENGTH',0)
content_length = 0 if content_length is '' else content_length
stream = LimitedStream(environ.get('wsgi.input'),
int(content_length))
environ['wsgi.input'] = stream
app_iter = self.app(environ, start_response)
try:
stream.exhaust()
for event in app_iter:
yield event
finally:
if hasattr(app_iter, 'close'):
app_iter.close() | puumuki/tahmatassu-api | tahmatassu-server/middlewares.py | Python | mit | 813 |
import React, { Component } from 'react'
import cx from 'classnames'
import Collapse from 'react-collapse'
import {
MdAutorenew as IconChecking,
MdNote as IconSimple,
MdViewDay as IconSeparated,
} from 'react-icons/md'
import fetchGallery from 'helpers/fetchGallery'
import Tabbable from 'components/Tabbable'
class TemplateChooser extends Component {
state = {
// can be basic | gallery
source: 'basic',
isFetching: false,
isError: false,
gallery: [],
}
handleChangeSource = async source => {
this.setState({ source })
if (source === 'gallery') {
if (this.state.isFetching) {
return
}
this.setState({ isFetching: true })
try {
const gallery = await fetchGallery()
this.setState({
isFetching: false,
isError: false,
gallery,
})
this.handleSelectGalleryTemplate(0)
} catch (err) {
this.setState({
isFetching: false,
isError: true,
})
}
} else {
this.props.onSelect('singleBasic')
}
}
handleSelectGalleryTemplate = i => {
this.props.onSelect(this.state.gallery[i])
}
render() {
const { template, onSelect } = this.props
const { source, isFetching, isError, gallery } = this.state
return (
<div className="flow-v-20">
<div className="d-f TemplateChooserTabs">
<Tabbable
onClick={() => this.handleChangeSource('basic')}
className={cx('TemplateChooserTabs--tab f-1 cu-d', {
isActive: source === 'basic',
})}
>
{'Basic'}
</Tabbable>
<Tabbable
onClick={() => this.handleChangeSource('gallery')}
className={cx('TemplateChooserTabs--tab f-1 cu-d', {
isActive: source === 'gallery',
})}
>
{'Gallery'}
</Tabbable>
</div>
<Collapse isOpened springConfig={{ stiffness: 300, damping: 30 }}>
{source === 'basic' ? (
<div className="d-f">
<TabItem
onClick={() => onSelect('singleBasic')}
isSelected={template === 'singleBasic'}
label="Single file, basic layout"
>
<IconSimple size={80} />
</TabItem>
<TabItem
onClick={() => onSelect('headerFooter')}
isSelected={template === 'headerFooter'}
label="Header & Footer"
>
<IconSeparated size={80} />
</TabItem>
</div>
) : source === 'gallery' ? (
<div>
{isFetching ? (
<div className="z" style={{ height: 250 }}>
<IconChecking className="rotating mb-20" size={30} />
{'Fetching templates...'}
</div>
) : isError ? (
<div>{'Error'}</div>
) : (
<div className="r" style={{ height: 450 }}>
<div className="sticky o-y-a Gallery">
{gallery.map((tpl, i) => (
<Tabbable
key={tpl.name}
onClick={() => this.handleSelectGalleryTemplate(i)}
className={cx('Gallery-Item-wrapper', {
isSelected: template.name === tpl.name,
})}
>
<div
className="Gallery-Item"
style={{
backgroundImage: `url(${tpl.thumbnail})`,
}}
>
<div className="Gallery-item-label small">{tpl.name}</div>
</div>
</Tabbable>
))}
</div>
</div>
)}
</div>
) : null}
</Collapse>
</div>
)
}
}
function TabItem({ onClick, isSelected, thumbnail, children, label }) {
return (
<Tabbable
onClick={onClick}
className={cx('Gallery-Item-wrapper', {
isSelected,
})}
>
<div
className="Gallery-Item"
style={{
backgroundImage: thumbnail ? `url(${thumbnail})` : undefined,
}}
>
{children}
<div className="Gallery-item-label small">{label}</div>
</div>
</Tabbable>
)
}
export default TemplateChooser
| mjmlio/mjml-app | src/components/NewProjectModal/TemplateChooser.js | JavaScript | mit | 4,575 |
$(document).ready(function () {
$('.eacc-change-photo-btn').bind('click', function () {
$('#eacc-change-photo-file').click();
return false;
});
$('.icon-menu').on('click', function () {
var is_active = $('#main-menu').hasClass('active');
if (is_active) {
$('#main-menu').slideUp();
$('#main-menu').removeClass('active');
} else {
$('#main-menu').slideDown();
$('#main-menu').addClass('active');
}
});
$('#name-field').blur(function () {
var value = $('#name-field').val();
if (value) {
$('.hello').html('miło Cię poznać!');
} else {
$('.hello').empty();
}
});
$('.login').on('click', function () {
var is_open = $('.auth-form-wrapper').hasClass('open');
if (!is_open) {
$('.auth-login-wrapper').addClass('open');
fullscreenlogin('.auth-login-wrapper');
}
});
$('.close-login').on('click', function () {
$('.auth-login-wrapper').removeClass('open');
})
});
function fullscreenlogin(element) {
var windowheight = $(window).height();
$(element).css('height', windowheight);
$(element).css('height', "touch");
var loginwrapperheight = $('.login-form-wrapper').outerHeight();
if (windowheight > loginwrapperheight) {
$('.login-form-wrapper').css('margin-top', (windowheight - loginwrapperheight) / 2);
}
} | wzywno/tescopl_ng | js/test.js | JavaScript | mit | 1,483 |
import { Component, Input, OnInit } from '@angular/core';
import { LangChangeEvent, TranslateService } from '@ngx-translate/core';
import { Observable } from 'rxjs/Observable';
import { ImagesService } from '../../shared/shared.module';
import { ISkill } from '../../models/skill.model';
import { ITranslation, IWork } from '../../models/work.model';
import { WorksService } from '../../shared/shared.module';
@Component({
selector: 'app-skill',
templateUrl: './skill.component.html',
styleUrls: [ './skill.component.scss' ]
})
export class SkillComponent implements OnInit {
@Input() skill: ISkill;
view: any[] = [ 200, 100 ];
years = '';
proficiency = '';
$worksRelated: Observable<IWork[]>;
imagesService = ImagesService;
constructor(private translate: TranslateService,
private worksService: WorksService) {
}
ngOnInit() {
this.$worksRelated = this.worksService.findWorksBySkill(this.skill.slug);
this.translate.getTranslation(this.translate.currentLang)
.subscribe(translation => this.translateChartsUnits(translation));
this.translate.onLangChange
.switchMap((e: LangChangeEvent) => this.translate.getTranslation(e.lang))
.subscribe(translation => this.translateChartsUnits(translation));
}
formatProficiency(proficiency) {
return `${proficiency}%`;
}
translateChartsUnits(translation) {
this.proficiency = translation.WHO.proficiency;
this.years = translation.WHO.years;
}
getRemoteTranslation(item: ITranslation): string {
return item[ this.translate.currentLang ];
}
}
| plastikaweb/plastikaweb2017 | src/app/who-module/skill/skill.component.ts | TypeScript | mit | 1,587 |
import Route from '@ember/routing/route';
import { inject as service } from '@ember/service';
export default class AttributeRoute extends Route {
@service cognito;
async model({ name }) {
if (name) {
const attrs = await this.cognito.user.getUserAttributesHash();
const value = attrs[name];
return { name, value };
}
return { isNew: true };
}
}
| paulcwatts/ember-cognito | tests/dummy/app/routes/attribute.js | JavaScript | mit | 382 |
import React from 'react';
import clsx from 'clsx';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core/styles';
import NoSsr from '@material-ui/core/NoSsr';
import Divider from '@material-ui/core/Divider';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
const users = [
{
logo: 'nasa.svg',
logoWidth: 49,
logoHeight: 40,
caption: 'NASA',
},
{
logo: 'walmart-labs.svg',
logoWidth: 205,
logoHeight: 39,
caption: 'Walmart Labs',
class: 'walmart',
},
{
logo: 'capgemini.svg',
logoWidth: 180,
logoHeight: 40,
caption: 'Capgemini',
},
{
logo: 'uniqlo.svg',
logoWidth: 40,
logoHeight: 40,
caption: 'Uniqlo',
},
{
logo: 'bethesda.svg',
logoWidth: 196,
logoHeight: 29,
caption: 'Bethesda',
},
{
logo: 'jpmorgan.svg',
logoWidth: 198,
logoHeight: 40,
caption: 'J.P. Morgan',
},
{
logo: 'shutterstock.svg',
caption: 'Shutterstock',
logoWidth: 205,
logoHeight: 29,
},
{
logo: 'netflix.svg',
logoWidth: 111,
logoHeight: 29,
caption: 'Netflix',
},
{
logo: 'amazon.svg',
logoWidth: 119,
logoHeight: 36,
caption: 'Amazon',
class: 'amazon',
},
{
logo: 'unity.svg',
logoWidth: 138,
logoHeight: 50,
caption: 'Unity',
class: 'unity',
},
{
logo: 'spotify.svg',
logoWidth: 180,
logoHeight: 54,
caption: 'Spotify',
class: 'spotify',
},
];
const useStyles = makeStyles(
(theme) => ({
root: {
padding: theme.spacing(2),
minHeight: 160,
paddingTop: theme.spacing(5),
},
container: {
marginBottom: theme.spacing(4),
},
users: {
padding: theme.spacing(10, 6, 0),
},
grid: {
marginTop: theme.spacing(5),
marginBottom: theme.spacing(5),
},
img: {
margin: theme.spacing(1.5, 3),
},
amazon: {
margin: theme.spacing(2.4, 3, 1.5),
},
unity: {
margin: theme.spacing(0.5, 3, 1.5),
},
spotify: {
margin: theme.spacing(0, 3, 1.5),
},
walmart: {
margin: '13px 4px 12px',
},
button: {
margin: theme.spacing(2, 0, 0),
},
}),
{ name: 'Users' },
);
export default function Users() {
const classes = useStyles();
const t = useSelector((state) => state.options.t);
return (
<div className={classes.root}>
<NoSsr defer>
<Container maxWidth="md" className={classes.container} disableGutters>
<Divider />
<div className={classes.users}>
<Typography variant="h4" component="h2" align="center" gutterBottom>
{t('whosUsing')}
</Typography>
<Typography variant="body1" align="center" gutterBottom>
{t('joinThese')}
</Typography>
<Grid container justify="center" className={classes.grid}>
{users.map((user) => (
<img
key={user.caption}
src={`/static/images/users/${user.logo}`}
alt={user.caption}
className={clsx(classes.img, classes[user.class])}
loading="lazy"
width={user.logoWidth}
height={user.logoHeight}
/>
))}
</Grid>
<Typography variant="body1" align="center" gutterBottom>
{t('usingMui')}
</Typography>
<Grid container justify="center">
<Button
variant="outlined"
href="https://github.com/mui-org/material-ui/issues/22426"
rel="noopener nofollow"
target="_blank"
className={classes.button}
>
{t('letUsKnow')}
</Button>
</Grid>
</div>
</Container>
</NoSsr>
</div>
);
}
| lgollut/material-ui | docs/src/pages/landing/Users.js | JavaScript | mit | 4,076 |
import { LavaJsOptions } from "./types";
export const DefaultOptions: LavaJsOptions = {
autodraw: false,
autoloadGoogle: true,
debug: false,
language: "en",
mapsApiKey: "",
responsive: true,
// datetimeFormat: "",
debounceTimeout: 250,
chartPackages: ["corechart"],
timezone: "America/Los_Angeles"
};
| lavacharts/lava.js | src/DefaultOptions.ts | TypeScript | mit | 322 |
/*
Dorm Room Control Server
July 28, 2014
notify.js
Sends notifications through Pushover's notification API
Copyright (c) 2014 by Tristan Honscheid
<MIT License>
*/
var req = require("request");
var app_token = "abwQbZzfMK7v2GvJcnFy8h1bNYHrTj";
/* Send a POST request to the Pushover
* msgData object:
* {
* "title" : string, message title (opt),
* "priority" : int, -2 = no alert, -1 = quiet, 1 = high priority, 2 = emergency (opt),
* "timestamp" : int, unix timestamp (opt),
* "sound" : string, a supported sound name to play (opt),
* "url" : string, a URL to bundle with the message (opt),
* "url_title" : string, the URL's title (opt)
* }
*/
exports.SendNotification = function(userKey, message, msgData, callback) {
if(typeof userKey !== "string" || typeof message !== "string") {
return false;
}
var postData = {
"token" : app_token,
"user" : userKey,
"message" : message,
"title" : msgData.title,
"url" : msgData.url,
"url_title" : msgData.url_title,
"priority" : msgData.priority,
"timestamp" : msgData.timestamp,
"sound" : msgData.sound
};
var post_options = {
uri : "https://api.pushover.net/1/messages.json",
method : "POST",
form : postData,
headers : {
"User-Agent" : "nodejs"
}
};
req(post_options, function(error, response, body) {
if(!error && response.statusCode==200) {
var data = JSON.parse(body);
if(data.status == 1) {
callback({"error" : false, "error_msg" : "", "code" : data.request});
} else {
callback({"error" : true, "error_msg" : ("Pushover error, status " + response.statusCode + ", " + body)});
}
} else {
callback({"error" : true, "error_msg" : ("HTTP error, status " + response.statusCode + ", " + body)});
}
});
};
| tristantech/Dorm-Room-Automation | NodeServer/lib/notify.js | JavaScript | mit | 1,918 |
// you can use includes, for example:
#include <algorithm>
#include <vector>
using namespace std;
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A);
int solution(vector<int> &A) {
// write your code in C++14 (g++ 6.2.0)
sort(A.begin(), A.end());
int n = A.size()-1;
return max(A[0] * A[1] * A[n], A[n] * A[n-1] * A[n-2]);
}
| gonini/Codility-Lesson | Lesson6/MaxProductOfThree/maxProductOfThree.cpp | C++ | mit | 424 |
require 'chef_runner'
require_relative '../../../lib/chef_runner/windows/bootstrap'
require_relative '../../../lib/chef_runner/windows/solo'
require_relative 'spec_helper'
describe ChefRunner::Windows::Solo do
it 'should provision machine using chef-solo' do
ChefRunner.bootstrap(params)
ChefRunner.solo(params)
end
end
def params
{
platform: :windows,
user: 'vagrant',
password: 'vagrant',
chef: {
version: '12.4.1',
repo: 'spec/integration/test-files/repository.tar.gz',
json_file: 'spec/integration/test-files/node.json',
secret_file: 'spec/integration/test-files/secret_file'
},
server: {
host: '10.0.10.253',
port: 5985
},
show_output: false
}
end
| MYOB-Technology/chef_runner | spec/integration/windows/windows_solo_spec.rb | Ruby | mit | 754 |
//..............................................................................
//
// This file is part of the Jancy toolkit.
//
// Jancy is distributed under the MIT license.
// For details see accompanying license.txt file,
// the public copy of which is also available at:
// http://tibbo.com/downloads/archive/jancy/license.txt
//
//..............................................................................
#include "pch.h"
#include "jnc_ct_Closure.h"
#include "jnc_ct_DeclTypeCalc.h"
#include "jnc_ct_ArrayType.h"
#include "jnc_ct_UnionType.h"
#include "jnc_ct_DynamicLibClassType.h"
#include "jnc_ct_DynamicLibNamespace.h"
#include "jnc_ct_ExtensionNamespace.h"
#include "jnc_ct_AsyncLauncherFunction.h"
#include "jnc_ct_ReactorClassType.h"
#include "jnc_ct_Parser.llk.h"
#include "jnc_ct_Parser.llk.cpp"
namespace jnc {
namespace ct {
//..............................................................................
Parser::Parser(
Module* module,
const PragmaSettings* pragmaSettings,
Mode mode
):
m_doxyParser(&module->m_doxyModule) {
m_module = module;
m_mode = mode;
if (pragmaSettings)
m_pragmaSettings = *pragmaSettings;
m_cachedPragmaSettings = pragmaSettings;
m_storageKind = StorageKind_Undefined;
m_accessKind = AccessKind_Undefined;
m_attributeBlock = NULL;
m_lastDeclaredItem = NULL;
m_lastNamedType = NULL;
m_lastPropertyGetterType = NULL;
m_lastPropertyTypeModifiers = 0;
m_reactorType = NULL;
m_reactionIdx = 0;
m_constructorType = NULL;
m_constructorProperty = NULL;
m_topDeclarator = NULL;
}
bool Parser::checkUnusedAttributeBlock() {
if (m_attributeBlock) {
err::setFormatStringError("unused attribute block in declaration");
return false;
}
return true;
}
bool
Parser::tokenizeBody(
sl::BoxList<Token>* tokenList,
const lex::LineColOffset& pos,
const sl::StringRef& body
) {
Unit* unit = m_module->m_unitMgr.getCurrentUnit();
ASSERT(unit);
Lexer lexer(m_mode == Mode_Parse ? LexerMode_Parse : LexerMode_Compile);
if ((m_module->getCompileFlags() & ModuleCompileFlag_Documentation) && !unit->getLib())
lexer.m_channelMask = TokenChannelMask_All; // also include doxy-comments (but not for libs!)
lexer.create(unit->getFilePath(), body);
lexer.setLineColOffset(pos);
char buffer[256];
sl::Array<Token*> scopeAnchorTokenStack(rc::BufKind_Stack, buffer, sizeof(buffer));
bool isScopeFlagMarkupRequired = m_mode != Mode_Parse;
for (;;) {
const Token* token = lexer.getToken();
switch (token->m_token) {
case TokenKind_Eof: // don't add EOF token (parseTokenList adds one automatically)
return true;
case TokenKind_Error:
err::setFormatStringError("invalid character '\\x%02x'", (uchar_t) token->m_data.m_integer);
lex::pushSrcPosError(unit->getFilePath(), token->m_pos);
return false;
}
tokenList->insertTail(*token);
lexer.nextToken();
Token* anchorToken;
if (isScopeFlagMarkupRequired)
switch (token->m_token) {
case '{':
anchorToken = tokenList->getTail().p();
anchorToken->m_data.m_integer = 0; // tokens can be reused, ensure 0
scopeAnchorTokenStack.append(anchorToken);
break;
case '}':
scopeAnchorTokenStack.pop();
break;
case TokenKind_NestedScope:
case TokenKind_Case:
case TokenKind_Default:
if (!scopeAnchorTokenStack.isEmpty()) {
anchorToken = tokenList->getTail().p();
anchorToken->m_data.m_integer = 0; // tokens can be reused, ensure 0
scopeAnchorTokenStack.getBack() = anchorToken;
}
break;
case TokenKind_Catch:
if (!scopeAnchorTokenStack.isEmpty())
scopeAnchorTokenStack.getBack()->m_data.m_integer |= ScopeFlag_CatchAhead | ScopeFlag_HasCatch;
break;
case TokenKind_Finally:
if (!scopeAnchorTokenStack.isEmpty())
scopeAnchorTokenStack.getBack()->m_data.m_integer |= ScopeFlag_FinallyAhead | ScopeFlag_Finalizable;
break;
}
}
}
bool
Parser::pragma(
const sl::StringRef& name,
int value
) {
Pragma pragmaKind = PragmaMap::findValue(name, Pragma_Undefined);
switch (pragmaKind) {
case Pragma_Alignment:
if (value < 0)
m_pragmaSettings.m_fieldAlignment = PragmaDefault_Alignment;
else if (sl::isPowerOf2(value) && value <= 16)
m_pragmaSettings.m_fieldAlignment = value;
else {
err::setFormatStringError("invalid alignment %d", value);
return false;
}
break;
case Pragma_ThinPointers:
m_pragmaSettings.m_pointerModifiers = value > 0 ? (uint_t)TypeModifier_Thin : PragmaDefault_PointerModifiers;
break;
case Pragma_ExposedEnums:
m_pragmaSettings.m_enumFlags = value > 0 ? (uint_t)EnumTypeFlag_Exposed : PragmaDefault_EnumFlags;
break;
default:
err::setFormatStringError("unknown pragma '%s'", name.sz());
return false;
}
m_cachedPragmaSettings = NULL;
return true;
}
void
Parser::addDoxyComment(const Token& token) {
uint_t compileFlags = m_module->getCompileFlags();
if (compileFlags & (ModuleCompileFlag_DisableDoxyComment1 << (token.m_token - TokenKind_DoxyComment1)))
return;
sl::StringRef comment = token.m_data.m_string;
ModuleItem* lastDeclaredItem = NULL;
lex::LineCol pos = token.m_pos;
pos.m_col += 3; // doxygen comments always start with 3 characters: ///, //!, /** /*!
if (!comment.isEmpty() && comment[0] == '<') {
lastDeclaredItem = m_lastDeclaredItem;
comment = comment.getSubString(1);
pos.m_col++;
}
m_doxyParser.addComment(
comment,
pos,
token.m_token <= TokenKind_DoxyComment2, // only concat single-line comments
lastDeclaredItem
);
}
bool
Parser::parseBody(
SymbolKind symbol,
const lex::LineColOffset& pos,
const sl::StringRef& body
) {
sl::BoxList<Token> tokenList;
bool result = tokenizeBody(&tokenList, pos, body);
if (!result)
return false;
return !tokenList.isEmpty() ?
parseTokenList(symbol, tokenList) :
create(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), symbol) &&
parseEofToken(pos, body.getLength());
}
bool
Parser::parseTokenList(
SymbolKind symbol,
const sl::ConstBoxList<Token>& tokenList
) {
ASSERT(!tokenList.isEmpty());
Unit* unit = m_module->m_unitMgr.getCurrentUnit();
create(unit->getFilePath(), symbol);
Token::Pos lastTokenPos = tokenList.getTail()->m_pos;
if (!m_module->m_codeAssistMgr.getCodeAssistKind() ||
!unit->isRootUnit() ||
!isOffsetInsideTokenList(tokenList, m_module->m_codeAssistMgr.getOffset())) {
sl::ConstBoxIterator<Token> token = tokenList.getHead();
for (; token; token++) {
bool result = parseToken(&*token);
if (!result) {
lex::ensureSrcPosError(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), token->m_pos);
return false;
}
}
return parseEofToken(lastTokenPos, lastTokenPos.m_length); // might trigger actions
} else {
size_t offset = m_module->m_codeAssistMgr.getOffset();
size_t autoCompleteFallbackOffset = offset;
bool result = true;
sl::ConstBoxIterator<Token> token = tokenList.getHead();
for (; token; token++) {
bool isCodeAssist = markCodeAssistToken((Token*)token.p(), offset);
if (isCodeAssist) {
if (token->m_tokenKind == TokenKind_Identifier && (token->m_flags & TokenFlag_CodeAssist))
autoCompleteFallbackOffset = token->m_pos.m_offset;
if (token->m_flags & TokenFlag_PostCodeAssist) {
m_module->m_codeAssistMgr.prepareAutoCompleteFallback(autoCompleteFallbackOffset);
if (m_mode == Mode_Compile) {
lastTokenPos = token->m_pos;
break;
}
offset = -1; // not needed anymore
}
}
result = parseToken(&*token);
if (!result)
break;
}
if (result)
parseEofToken(lastTokenPos, lastTokenPos.m_length); // might trigger actions
if (!m_module->m_codeAssistMgr.getCodeAssist() &&
m_module->m_codeAssistMgr.hasArgumentTipStack())
m_module->m_codeAssistMgr.createArgumentTipFromStack();
return true;
}
}
bool
Parser::parseEofToken(
const lex::LineColOffset& pos,
size_t length
) {
Token eofToken;
eofToken.m_token = 0;
eofToken.m_pos.m_line = pos.m_line;
eofToken.m_pos.m_col = pos.m_col + length;
eofToken.m_pos.m_offset = pos.m_offset + length;
bool result = parseToken(&eofToken);
if (!result) {
lex::ensureSrcPosError(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), pos);
return false;
}
return true;
}
bool
Parser::isTypeSpecified() {
if (m_typeSpecifierStack.isEmpty())
return false;
// if we've seen 'unsigned', assume 'int' is implied.
// checking for 'property' is required for full property syntax e.g.:
// property foo { int get (); }
// here 'foo' should be a declarator, not import-type-specifier
// the same logic applies to 'reactor'
TypeSpecifier* typeSpecifier = m_typeSpecifierStack.getBack();
return
typeSpecifier->getType() != NULL ||
typeSpecifier->getTypeModifiers() & (TypeModifier_Unsigned | TypeModifier_Property | TypeModifier_Reactor);
}
NamedImportType*
Parser::getNamedImportType(
const QualifiedName& name,
const lex::LineCol& pos
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamedImportType* type = m_module->m_typeMgr.getNamedImportType(name, nspace);
if (!type->m_parentUnit) {
type->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
type->m_pos = pos;
}
return type;
}
Type*
Parser::findType(
size_t baseTypeIdx,
const QualifiedName& name,
const lex::LineCol& pos
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ModuleItem* item;
if (m_mode == Mode_Parse) {
if (baseTypeIdx != -1)
return NULL;
if (!name.isSimple())
return getNamedImportType(name, pos);
sl::String shortName = name.getShortName();
FindModuleItemResult findResult = nspace->findDirectChildItem(shortName);
if (!findResult.m_result)
return NULL;
if (!findResult.m_item)
return getNamedImportType(name, pos);
item = findResult.m_item;
} else {
if (baseTypeIdx != -1) {
DerivableType* baseType = findBaseType(baseTypeIdx);
if (!baseType)
return NULL;
nspace = baseType;
if (name.isEmpty())
return baseType;
}
FindModuleItemResult findResult = nspace->findItemTraverse(name);
if (!findResult.m_item)
return NULL;
item = findResult.m_item;
}
ModuleItemKind itemKind = item->getItemKind();
switch (itemKind) {
case ModuleItemKind_Type:
return (Type*)item;
case ModuleItemKind_Typedef:
return (m_module->getCompileFlags() & ModuleCompileFlag_KeepTypedefShadow) ?
((Typedef*)item)->getShadowType() :
((Typedef*)item)->getType();
default:
return NULL;
}
}
Type*
Parser::getType(
size_t baseTypeIdx,
const QualifiedName& name,
const lex::LineCol& pos
) {
Type* type = findType(baseTypeIdx, name, pos);
if (!type) {
if (baseTypeIdx == -1)
err::setFormatStringError("'%s' is not found or not a type", name.getFullName ().sz());
else if (name.isEmpty())
err::setFormatStringError("'basetype%d' is not found", baseTypeIdx + 1);
else
err::setFormatStringError("'basetype%d.%s' is not found or not a type", baseTypeIdx + 1, name.getFullName ().sz());
return NULL;
}
return type;
}
bool
Parser::setSetAsType(Type* type) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
if (nspace->getNamespaceKind() != NamespaceKind_Type) {
err::setFormatStringError("invalid setas in '%s'", nspace->getQualifiedName().sz());
return false;
}
DerivableType* derivableType = (DerivableType*)(NamedType*)nspace;
if (derivableType->m_setAsType) {
err::setFormatStringError("setas redefinition for '%s'", derivableType->getTypeString().sz());
return false;
}
derivableType->m_setAsType = type;
if (type->getTypeKindFlags() & TypeKindFlag_Import)
((ImportType*)type)->addFixup(&derivableType->m_setAsType);
return true;
}
bool
Parser::createAttributeBlock(const lex::LineCol& pos) {
ASSERT(!m_attributeBlock);
m_attributeBlock = m_module->m_attributeMgr.createAttributeBlock();
m_attributeBlock->m_parentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
m_attributeBlock->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
m_attributeBlock->m_pos = pos;
return true;
}
bool
Parser::createAttribute(
const lex::LineCol& pos,
const sl::StringRef& name,
sl::BoxList<Token>* initializer
) {
ASSERT(m_attributeBlock);
Attribute* attribute = m_attributeBlock->createAttribute(name, initializer);
if (!attribute)
return false;
attribute->m_parentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
attribute->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
attribute->m_pos = pos;
return true;
}
void
Parser::preDeclaration() {
m_storageKind = StorageKind_Undefined;
m_accessKind = AccessKind_Undefined;
m_lastDeclaredItem = NULL;
}
bool
Parser::bodylessDeclaration() {
if (m_mode == Mode_Reaction)
return true; // reactor declarations are already processed at this stage
ASSERT(m_lastDeclaredItem);
ModuleItemKind itemKind = m_lastDeclaredItem->getItemKind();
switch (itemKind) {
case ModuleItemKind_Property:
return finalizeLastProperty(false);
case ModuleItemKind_Orphan:
err::setFormatStringError(
"orphan '%s' without a body",
m_lastDeclaredItem->getDecl()->getQualifiedName().sz()
);
return false;
}
return true;
}
bool
Parser::setDeclarationBody(const Token& bodyToken) {
if (!m_lastDeclaredItem) {
err::setFormatStringError("declaration without declarator cannot have a body");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
Function* function;
Orphan* orphan;
Type* type;
ModuleItemKind itemKind = m_lastDeclaredItem->getItemKind();
switch (itemKind) {
case ModuleItemKind_Function:
if (nspace->getNamespaceKind() == NamespaceKind_DynamicLib) {
err::setFormatStringError("dynamiclib function cannot have a body");
return false;
}
function = (Function*)m_lastDeclaredItem;
function->addUsingSet(nspace);
return setBody(function, bodyToken);
case ModuleItemKind_Property:
return parseLastPropertyBody(bodyToken);
case ModuleItemKind_Typedef:
type = ((Typedef*)m_lastDeclaredItem)->getType();
break;
case ModuleItemKind_Type:
type = (Type*)m_lastDeclaredItem;
break;
case ModuleItemKind_Variable:
type = ((Variable*)m_lastDeclaredItem)->getType();
break;
case ModuleItemKind_Field:
type = ((Field*)m_lastDeclaredItem)->getType();
break;
case ModuleItemKind_Orphan:
orphan = (Orphan*)m_lastDeclaredItem;
orphan->addUsingSet(nspace);
return setBody(orphan, bodyToken);
default:
err::setFormatStringError("'%s' cannot have a body", getModuleItemKindString(m_lastDeclaredItem->getItemKind ()));
return false;
}
if (!isClassType(type, ClassTypeKind_Reactor)) {
err::setFormatStringError("only functions and reactors can have bodies, not '%s'", type->getTypeString().sz());
return false;
}
return setBody((ReactorClassType*)type, bodyToken);
}
bool
Parser::setStorageKind(StorageKind storageKind) {
if (m_storageKind) {
err::setFormatStringError(
"more than one storage specifier specifiers ('%s' and '%s')",
getStorageKindString(m_storageKind),
getStorageKindString(storageKind)
);
return false;
}
m_storageKind = storageKind;
return true;
}
bool
Parser::setAccessKind(AccessKind accessKind) {
if (m_accessKind) {
err::setFormatStringError(
"more than one access specifiers ('%s' and '%s')",
getAccessKindString(m_accessKind),
getAccessKindString(accessKind)
);
return false;
}
m_accessKind = accessKind;
return true;
}
void
Parser::postDeclaratorName(Declarator* declarator) {
if (!m_topDeclarator)
m_topDeclarator = declarator;
if (!m_topDeclarator->isQualified() || declarator->m_baseType->getTypeKind() != TypeKind_NamedImport)
return;
// need to re-anchor the import, e.g.:
// A C.foo(); <-- here 'A' should be searched for starting with 'C'
QualifiedName anchorName = m_topDeclarator->m_name;
if (m_topDeclarator->getDeclaratorKind() == DeclaratorKind_Name)
anchorName.removeLastName();
ASSERT(!anchorName.isEmpty());
NamedImportType* importType = m_module->m_typeMgr.getNamedImportType(
((NamedImportType*)declarator->m_baseType)->m_name,
m_module->m_namespaceMgr.getCurrentNamespace(),
anchorName
);
importType->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
importType->m_pos = declarator->getPos();
declarator->m_baseType = importType;
}
void
Parser::postDeclarator(Declarator* declarator) {
if (declarator == m_topDeclarator)
m_topDeclarator = NULL;
}
GlobalNamespace*
Parser::getGlobalNamespace(
GlobalNamespace* parentNamespace,
const sl::StringRef& name,
const lex::LineCol& pos
) {
GlobalNamespace* nspace;
FindModuleItemResult findResult = parentNamespace->findItem(name);
if (!findResult.m_result)
return NULL;
if (!findResult.m_item) {
nspace = m_module->m_namespaceMgr.createGlobalNamespace(name, parentNamespace);
nspace->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
nspace->m_pos = pos;
parentNamespace->addItem(nspace);
} else {
if (findResult.m_item->getItemKind() != ModuleItemKind_Namespace) {
err::setFormatStringError("'%s' exists and is not a namespace", parentNamespace->createQualifiedName(name).sz());
return NULL;
}
nspace = (GlobalNamespace*)findResult.m_item;
}
return nspace;
}
GlobalNamespace*
Parser::declareGlobalNamespace(
const lex::LineCol& pos,
const QualifiedName& name,
const Token& bodyToken
) {
Namespace* currentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
if (currentNamespace->getNamespaceKind() != NamespaceKind_Global) {
err::setFormatStringError("cannot open global namespace in '%s'", getNamespaceKindString(currentNamespace->getNamespaceKind ()));
return NULL;
}
GlobalNamespace* nspace = getGlobalNamespace((GlobalNamespace*)currentNamespace, name.getFirstName(), pos);
if (!nspace)
return NULL;
sl::ConstBoxIterator<sl::StringRef> it = name.getNameList().getHead();
for (; it; it++) {
nspace = getGlobalNamespace(nspace, *it, pos);
if (!nspace)
return NULL;
}
nspace->addBody(
m_module->m_unitMgr.getCurrentUnit(),
getCachedPragmaSettings(),
bodyToken.m_pos,
bodyToken.m_data.m_string
);
if (bodyToken.m_flags & TokenFlag_CodeAssist)
m_module->m_codeAssistMgr.m_containerItem = nspace;
return nspace;
}
ExtensionNamespace*
Parser::declareExtensionNamespace(
const lex::LineCol& pos,
const sl::StringRef& name,
Type* type,
const Token& bodyToken
) {
Namespace* currentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
ExtensionNamespace* nspace = m_module->m_namespaceMgr.createGlobalNamespace<ExtensionNamespace>(
name,
currentNamespace
);
nspace->m_type = (DerivableType*)type; // force-cast
if (type->getTypeKindFlags() & TypeKindFlag_Import)
((ImportType*)type)->addFixup(&nspace->m_type);
assignDeclarationAttributes(nspace, nspace, pos);
bool result = currentNamespace->addItem(nspace);
if (!result)
return NULL;
result = nspace->setBody(
getCachedPragmaSettings(),
bodyToken.m_pos,
bodyToken.m_data.m_string
);
ASSERT(result);
if (bodyToken.m_flags & TokenFlag_CodeAssist)
m_module->m_codeAssistMgr.m_containerItem = nspace;
return nspace;
}
bool
Parser::useNamespace(
const sl::BoxList<QualifiedName>& nameList,
NamespaceKind namespaceKind,
const lex::LineCol& pos
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
sl::ConstBoxIterator<QualifiedName> it = nameList.getHead();
for (; it; it++) {
result = nspace->m_usingSet.addNamespace(nspace, namespaceKind, *it);
if (!result)
return false;
}
return true;
}
AttributeBlock*
Parser::popAttributeBlock() {
AttributeBlock* attributeBlock = m_attributeBlock;
m_attributeBlock = NULL;
return attributeBlock;
}
bool
Parser::declareInReaction(Declarator* declarator) {
ASSERT(m_mode == Mode_Reaction && m_reactorType);
if (!declarator->isSimple()) {
err::setFormatStringError("invalid declarator in reactor");
return false;
}
const sl::StringRef& name = declarator->getName().getShortName();
FindModuleItemResult findResult = m_reactorType->findItem(name);
if (!findResult.m_result)
return false;
if (!findResult.m_item) {
err::setFormatStringError("member '%s' not found in reactor '%s'", name.sz(), m_reactorType->getQualifiedName().sz());
return false;
}
m_lastDeclaredItem = findResult.m_item;
if (declarator->m_initializer.isEmpty())
return true;
// modify initializer so it looks like an assignment expression: name = <initializer>
Token token;
token.m_pos = declarator->m_initializer.getHead()->m_pos;
token.m_tokenKind = (TokenKind) '=';
declarator->m_initializer.insertHead(token);
token.m_tokenKind = TokenKind_Identifier;
token.m_data.m_string = name;
declarator->m_initializer.insertHead(token);
Parser parser(m_module, getCachedPragmaSettings(), Mode_Reaction);
parser.m_reactorType = m_reactorType;
parser.m_reactionIdx = m_reactionIdx;
return parser.parseTokenList(SymbolKind_expression, declarator->m_initializer);
}
bool
Parser::declare(Declarator* declarator) {
if (m_mode == Mode_Reaction)
return declareInReaction(declarator);
m_lastDeclaredItem = NULL;
bool isLibrary = m_module->m_namespaceMgr.getCurrentNamespace()->getNamespaceKind() == NamespaceKind_DynamicLib;
if ((declarator->getTypeModifiers() & TypeModifier_Property) && m_storageKind != StorageKind_Typedef) {
if (isLibrary) {
err::setFormatStringError("only functions can be part of library");
return false;
}
// too early to calctype cause maybe this property has a body
// declare a typeless property for now
return declareProperty(declarator, NULL, 0);
}
uint_t declFlags;
Type* type = declarator->calcType(&declFlags);
if (!type)
return false;
DeclaratorKind declaratorKind = declarator->getDeclaratorKind();
uint_t postModifiers = declarator->getPostDeclaratorModifiers();
TypeKind typeKind = type->getTypeKind();
if (isLibrary && typeKind != TypeKind_Function) {
err::setFormatStringError("only functions can be part of library");
return false;
}
if (postModifiers != 0 && typeKind != TypeKind_Function) {
err::setFormatStringError("unused post-declarator modifier '%s'", getPostDeclaratorModifierString(postModifiers).sz());
return false;
}
switch (m_storageKind) {
case StorageKind_Typedef:
return declareTypedef(declarator, type);
case StorageKind_Alias:
return declareAlias(declarator, type, declFlags);
default:
switch (typeKind) {
case TypeKind_Void:
err::setFormatStringError("illegal use of type 'void'");
return false;
case TypeKind_Function:
return declareFunction(declarator, (FunctionType*)type);
case TypeKind_Property:
return declareProperty(declarator, (PropertyType*)type, declFlags);
default:
return type->getStdType() == StdType_ReactorBase ?
declareReactor(declarator, declFlags) :
declareData(declarator, type, declFlags);
}
}
}
void
Parser::assignDeclarationAttributes(
ModuleItem* item,
ModuleItemDecl* decl,
const lex::LineCol& pos,
AttributeBlock* attributeBlock,
dox::Block* doxyBlock
) {
decl->m_accessKind = m_accessKind ?
m_accessKind :
m_module->m_namespaceMgr.getCurrentAccessKind();
// don't overwrite storage unless explicit
if (m_storageKind)
decl->m_storageKind = m_storageKind;
decl->m_pos = pos;
decl->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
decl->m_parentNamespace = m_module->m_namespaceMgr.getCurrentNamespace();
decl->m_pragmaSettings = getCachedPragmaSettings();
decl->m_attributeBlock = attributeBlock ? attributeBlock : popAttributeBlock();
if (m_module->getCompileFlags() & ModuleCompileFlag_Documentation)
m_module->m_doxyHost.setItemBlock(item, decl, doxyBlock ? doxyBlock : m_doxyParser.popBlock());
item->m_flags |= ModuleItemFlag_User;
m_lastDeclaredItem = item;
}
bool
Parser::declareTypedef(
Declarator* declarator,
Type* type
) {
ASSERT(m_storageKind == StorageKind_Typedef);
if (!declarator->isSimple()) {
err::setFormatStringError("invalid typedef declarator");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
const sl::StringRef& name = declarator->getName().getShortName();
FindModuleItemResult findResult = nspace->findItem(name);
if (!findResult.m_result)
return false;
if (findResult.m_item) {
ModuleItem* prevItem = findResult.m_item;
if (prevItem->getItemKind() != ModuleItemKind_Typedef ||
((Typedef*)prevItem)->getType()->cmp(type) != 0) {
setRedefinitionError(name);
return false;
}
m_attributeBlock = NULL;
m_lastDeclaredItem = prevItem;
m_doxyParser.popBlock();
return true;
}
sl::String qualifiedName = nspace->createQualifiedName(name);
ModuleItem* item;
ModuleItemDecl* decl;
Typedef* tdef = m_module->m_typeMgr.createTypedef(name, qualifiedName, type);
item = tdef;
decl = tdef;
assignDeclarationAttributes(item, decl, declarator);
return nspace->addItem(name, item);
}
bool
Parser::declareAlias(
Declarator* declarator,
Type* type,
uint_t ptrTypeFlags
) {
bool result;
if (!declarator->m_constructor.isEmpty()) {
err::setFormatStringError("alias cannot have constructor");
return false;
}
if (declarator->m_initializer.isEmpty()) {
err::setFormatStringError("missing alias initializer");
return false;
}
if (!declarator->isSimple()) {
err::setFormatStringError("invalid alias declarator");
return false;
}
if (type->getTypeKind() != TypeKind_Void) {
err::setFormatStringError("alias doesn't need a type");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
const sl::StringRef& name = declarator->getName().getShortName();
sl::String qualifiedName = nspace->createQualifiedName(name);
sl::BoxList<Token>* initializer = &declarator->m_initializer;
Alias* alias = m_module->m_namespaceMgr.createAlias(name, qualifiedName, initializer);
assignDeclarationAttributes(alias, alias, declarator);
if (nspace->getNamespaceKind() == NamespaceKind_Property) {
Property* prop = (Property*)nspace;
if (ptrTypeFlags & PtrTypeFlag_Bindable) {
result = prop->setOnChanged(alias);
if (!result)
return false;
} else if (ptrTypeFlags & PtrTypeFlag_AutoGet) {
result = prop->setAutoGetValue(alias);
if (!result)
return false;
}
}
return nspace->addItem(alias);
}
bool
Parser::declareFunction(
Declarator* declarator,
FunctionType* type
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
DeclaratorKind declaratorKind = declarator->getDeclaratorKind();
uint_t postModifiers = declarator->getPostDeclaratorModifiers();
FunctionKind functionKind = declarator->getFunctionKind();
bool hasArgs = !type->getArgArray().isEmpty();
if (declaratorKind == DeclaratorKind_UnaryBinaryOperator) {
ASSERT(functionKind == FunctionKind_UnaryOperator || functionKind == FunctionKind_BinaryOperator);
functionKind = hasArgs ? FunctionKind_BinaryOperator : FunctionKind_UnaryOperator;
}
ASSERT(functionKind);
uint_t functionKindFlags = getFunctionKindFlags(functionKind);
if ((functionKindFlags & FunctionKindFlag_NoStorage) && m_storageKind) {
err::setFormatStringError("'%s' cannot have storage specifier", getFunctionKindString(functionKind));
return false;
}
if ((functionKindFlags & FunctionKindFlag_NoArgs) && hasArgs) {
err::setFormatStringError("'%s' cannot have arguments", getFunctionKindString(functionKind));
return false;
}
if (!m_storageKind) {
m_storageKind =
functionKind == FunctionKind_StaticConstructor ? StorageKind_Static :
namespaceKind == NamespaceKind_Property ? ((Property*)nspace)->getStorageKind() : StorageKind_Undefined;
}
if (namespaceKind == NamespaceKind_PropertyTemplate) {
if (m_storageKind) {
err::setFormatStringError("invalid storage '%s' in property template", getStorageKindString(m_storageKind));
return false;
}
if (postModifiers) {
err::setFormatStringError("unused post-declarator modifier '%s'", getPostDeclaratorModifierString(postModifiers).sz());
return false;
}
bool result = ((PropertyTemplate*)nspace)->addMethod(functionKind, type);
if (!result)
return false;
m_lastDeclaredItem = type;
return true;
}
ModuleItem* functionItem;
ModuleItemDecl* functionItemDecl;
FunctionName* functionName;
if (declarator->isQualified()) {
Orphan* orphan = m_module->m_namespaceMgr.createOrphan(OrphanKind_Function, type);
orphan->m_functionKind = functionKind;
orphan->m_declaratorName = declarator->getName();
functionItem = orphan;
functionItemDecl = orphan;
functionName = orphan;
nspace->addOrphan(orphan);
} else {
Function* function;
if (type->getFlags() & FunctionTypeFlag_Async) {
function = m_module->m_functionMgr.createFunction<AsyncLauncherFunction>(
sl::StringRef(),
sl::StringRef(),
type
);
} else {
function = m_module->m_functionMgr.createFunction(type);
function->m_functionKind = functionKind;
}
functionItem = function;
functionItemDecl = function;
functionName = function;
if (!declarator->m_initializer.isEmpty())
sl::takeOver(&function->m_initializer, &declarator->m_initializer);
}
assignDeclarationAttributes(functionItem, functionItemDecl, declarator);
if (postModifiers & PostDeclaratorModifier_Const)
functionName->m_thisArgTypeFlags = PtrTypeFlag_Const;
switch (functionKind) {
case FunctionKind_Normal:
functionItemDecl->m_name = declarator->getName().getShortName();
functionItemDecl->m_qualifiedName = nspace->createQualifiedName(functionItemDecl->m_name);
break;
case FunctionKind_UnaryOperator:
functionName->m_unOpKind = declarator->getUnOpKind();
functionItemDecl->m_qualifiedName.format(
"%s.unary operator %s",
nspace->getQualifiedName().sz(),
getUnOpKindString(functionName->m_unOpKind)
);
break;
case FunctionKind_BinaryOperator:
functionName->m_binOpKind = declarator->getBinOpKind();
functionItemDecl->m_qualifiedName.format(
"%s.binary operator %s",
nspace->getQualifiedName().sz(),
getBinOpKindString(functionName->m_binOpKind)
);
break;
case FunctionKind_CastOperator:
functionName->m_castOpType = declarator->getCastOpType();
functionItemDecl->m_qualifiedName.format(
"%s.cast operator %s",
nspace->getQualifiedName().sz(),
functionName->m_castOpType->getTypeString().sz()
);
break;
default:
functionItemDecl->m_qualifiedName.format(
"%s.%s",
nspace->getQualifiedName().sz(),
getFunctionKindString(functionKind)
);
}
if (functionItem->getItemKind() == ModuleItemKind_Orphan) {
if (namespaceKind == NamespaceKind_DynamicLib) {
err::setFormatStringError("illegal orphan in dynamiclib '%s'", nspace->getQualifiedName().sz());
return false;
}
return true;
}
ASSERT(functionItem->getItemKind() == ModuleItemKind_Function);
Function* function = (Function*)functionItem;
TypeKind typeKind;
switch (namespaceKind) {
case NamespaceKind_Extension:
return ((ExtensionNamespace*)nspace)->addMethod(function);
case NamespaceKind_Type:
typeKind = ((NamedType*)nspace)->getTypeKind();
switch (typeKind) {
case TypeKind_Struct:
return ((StructType*)nspace)->addMethod(function);
case TypeKind_Union:
return ((UnionType*)nspace)->addMethod(function);
case TypeKind_Class:
return ((ClassType*)nspace)->addMethod(function);
default:
err::setFormatStringError("method members are not allowed in '%s'", ((NamedType*)nspace)->getTypeString().sz());
return false;
}
case NamespaceKind_Property:
return ((Property*)nspace)->addMethod(function);
case NamespaceKind_DynamicLib:
function->m_libraryTableIndex = ((DynamicLibNamespace*)nspace)->m_functionCount++;
// and fall through
default:
if (postModifiers) {
err::setFormatStringError("unused post-declarator modifier '%s'", getPostDeclaratorModifierString(postModifiers).sz());
return false;
}
if (!m_storageKind) {
function->m_storageKind = StorageKind_Static;
} else if (m_storageKind != StorageKind_Static) {
err::setFormatStringError("invalid storage specifier '%s' for a global function", getStorageKindString(m_storageKind));
return false;
}
}
if (!nspace->getParentNamespace()) // module constructor / destructor
switch (functionKind) {
case FunctionKind_Constructor:
case FunctionKind_StaticConstructor:
return m_module->m_functionMgr.addGlobalCtorDtor(GlobalCtorDtorKind_Constructor, function);
case FunctionKind_Destructor:
return m_module->m_functionMgr.addGlobalCtorDtor(GlobalCtorDtorKind_Destructor, function);
}
if (functionKind != FunctionKind_Normal) {
err::setFormatStringError(
"invalid '%s' at '%s' namespace",
getFunctionKindString(functionKind),
getNamespaceKindString(namespaceKind)
);
return false;
}
size_t result = nspace->addFunction(function);
return result != -1 || m_module->m_codeAssistMgr.getCodeAssistKind(); // when doing code-assist, ignore redefinition errors
}
bool
Parser::declareProperty(
Declarator* declarator,
PropertyType* type,
uint_t flags
) {
if (!declarator->isSimple()) {
err::setFormatStringError("invalid property declarator");
return false;
}
Property* prop = createProperty(declarator);
if (!prop)
return false;
if (type) {
prop->m_flags |= flags;
return prop->create(type);
}
m_lastPropertyTypeModifiers = declarator->getTypeModifiers();
if (m_lastPropertyTypeModifiers & TypeModifier_Const)
prop->m_flags |= PropertyFlag_Const;
if (declarator->getBaseType()->getTypeKind() != TypeKind_Void ||
!declarator->getPointerPrefixList().isEmpty() ||
!declarator->getSuffixList().isEmpty()) {
DeclTypeCalc typeCalc;
m_lastPropertyGetterType = typeCalc.calcPropertyGetterType(declarator);
if (!m_lastPropertyGetterType)
return false;
} else {
m_lastPropertyGetterType = NULL;
}
return true;
}
PropertyTemplate*
Parser::createPropertyTemplate() {
PropertyTemplate* propertyTemplate = m_module->m_functionMgr.createPropertyTemplate();
uint_t modifiers = getTypeSpecifier()->clearTypeModifiers(TypeModifier_Property | TypeModifier_Bindable);
if (modifiers & TypeModifier_Bindable)
propertyTemplate->m_typeFlags = PropertyTypeFlag_Bindable;
return propertyTemplate;
}
Property*
Parser::createProperty(Declarator* declarator) {
bool result;
m_lastDeclaredItem = NULL;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
if (namespaceKind == NamespaceKind_PropertyTemplate) {
err::setFormatStringError("property templates cannot have property members");
return NULL;
}
const sl::StringRef& name = declarator->getName().getShortName();
sl::String qualifiedName = nspace->createQualifiedName(name);
Property* prop = m_module->m_functionMgr.createProperty(name, qualifiedName);
assignDeclarationAttributes(prop, prop, declarator);
TypeKind typeKind;
switch (namespaceKind) {
case NamespaceKind_Extension:
result = ((ExtensionNamespace*)nspace)->addProperty(prop);
if (!result)
return NULL;
break;
case NamespaceKind_Type:
typeKind = ((NamedType*)nspace)->getTypeKind();
switch (typeKind) {
case TypeKind_Struct:
result = ((StructType*)nspace)->addProperty(prop);
break;
case TypeKind_Union:
result = ((UnionType*)nspace)->addProperty(prop);
break;
case TypeKind_Class:
result = ((ClassType*)nspace)->addProperty(prop);
break;
default:
err::setFormatStringError("property members are not allowed in '%s'", ((NamedType*) nspace)->getTypeString().sz());
return NULL;
}
if (!result)
return NULL;
break;
case NamespaceKind_Property:
result = ((Property*)nspace)->addProperty(prop);
if (!result)
return NULL;
break;
default:
if (m_storageKind && m_storageKind != StorageKind_Static) {
err::setFormatStringError("invalid storage specifier '%s' for a global property", getStorageKindString(m_storageKind));
return NULL;
}
result = nspace->addItem(prop);
if (!result)
return NULL;
prop->m_storageKind = StorageKind_Static;
}
return prop;
}
bool
Parser::parseLastPropertyBody(const Token& bodyToken) {
size_t length = bodyToken.m_data.m_string.getLength();
sl::BoxList<Token> tokenList;
return
tokenizeBody(
&tokenList,
lex::LineColOffset(
bodyToken.m_pos.m_line,
bodyToken.m_pos.m_col + 1,
bodyToken.m_pos.m_offset + 1
),
bodyToken.m_data.m_string.getSubString(1, length - 2)
) &&
parseLastPropertyBody(tokenList);
}
bool
Parser::parseLastPropertyBody(const sl::ConstBoxList<Token>& body) {
ASSERT(m_lastDeclaredItem && m_lastDeclaredItem->getItemKind() == ModuleItemKind_Property);
Parser parser(m_module, getCachedPragmaSettings(), Mode_Parse);
m_module->m_namespaceMgr.openNamespace((Property*)m_lastDeclaredItem);
bool result = parser.parseTokenList(SymbolKind_member_block_declaration_list, body);
if (!result)
return false;
m_module->m_namespaceMgr.closeNamespace();
return finalizeLastProperty(true);
}
bool
Parser::finalizeLastProperty(bool hasBody) {
ASSERT(m_lastDeclaredItem && m_lastDeclaredItem->getItemKind() == ModuleItemKind_Property);
bool result;
Property* prop = (Property*)m_lastDeclaredItem;
if (prop->getType())
return true;
// finalize getter
if (prop->m_getter) {
if (m_lastPropertyGetterType && m_lastPropertyGetterType->cmp(prop->m_getter->getType()) != 0) {
err::setFormatStringError("getter type '%s' does not match property declaration", prop->m_getter->getType ()->getTypeString().sz());
return false;
}
} else if (prop->m_autoGetValue) {
ASSERT(prop->m_autoGetValue->getItemKind() == ModuleItemKind_Alias); // otherwise, getter would have been created
} else {
if (!m_lastPropertyGetterType) {
err::setFormatStringError("incomplete property: no 'get' method or 'autoget' field");
return false;
}
Function* getter = (m_lastPropertyTypeModifiers & TypeModifier_AutoGet) ?
m_module->m_functionMgr.createFunction<Property::AutoGetter>(m_lastPropertyGetterType) :
m_module->m_functionMgr.createFunction(m_lastPropertyGetterType);
getter->m_functionKind = FunctionKind_Getter;
getter->m_flags |= ModuleItemFlag_User;
result = prop->addMethod(getter);
if (!result)
return false;
}
// finalize setter
if (!(m_lastPropertyTypeModifiers & TypeModifier_Const) && !hasBody) {
FunctionType* getterType = prop->m_getter->getType()->getShortType();
sl::Array<FunctionArg*> argArray = getterType->getArgArray();
Type* setterArgType = getterType->getReturnType();
if (setterArgType->getTypeKindFlags() & TypeKindFlag_Derivable) {
Type* setAsType = ((DerivableType*)setterArgType)->getSetAsType();
if (setAsType)
setterArgType = setAsType;
}
argArray.append(setterArgType->getSimpleFunctionArg());
FunctionType* setterType = m_module->m_typeMgr.getFunctionType(argArray);
Function* setter = m_module->m_functionMgr.createFunction(setterType);
setter->m_functionKind = FunctionKind_Setter;
setter->m_flags |= ModuleItemFlag_User;
result = prop->addMethod(setter);
if (!result)
return false;
}
// finalize binder
if (m_lastPropertyTypeModifiers & TypeModifier_Bindable) {
if (!prop->m_onChanged) {
result = prop->createOnChanged();
if (!result)
return false;
}
}
// finalize auto-get value
if (m_lastPropertyTypeModifiers & TypeModifier_AutoGet) {
if (!prop->m_autoGetValue) {
result = prop->createAutoGetValue(prop->m_getter->getType()->getReturnType());
if (!result)
return false;
}
}
if (prop->m_getter)
prop->createType();
return true;
}
bool
Parser::declareReactor(
Declarator* declarator,
uint_t ptrTypeFlags
) {
bool result;
if (declarator->getDeclaratorKind() != DeclaratorKind_Name) {
err::setFormatStringError("invalid reactor declarator");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
NamedType* parentType = NULL;
switch (namespaceKind) {
case NamespaceKind_Property:
parentType = ((Property*)nspace)->getParentType();
break;
case NamespaceKind_Type:
parentType = (NamedType*)nspace;
break;
}
if (parentType && parentType->getTypeKind() != TypeKind_Class) {
err::setFormatStringError("'%s' cannot contain reactor members", parentType->getTypeString().sz());
return false;
}
const sl::StringRef& name = declarator->getName().getShortName();
sl::String qualifiedName = nspace->createQualifiedName(name);
if (declarator->isQualified()) {
Orphan* orphan = m_module->m_namespaceMgr.createOrphan(OrphanKind_Reactor, NULL);
orphan->m_functionKind = FunctionKind_Normal;
orphan->m_declaratorName = declarator->getName();
assignDeclarationAttributes(orphan, orphan, declarator);
nspace->addOrphan(orphan);
} else {
ReactorClassType* type = m_module->m_typeMgr.createReactorType(name, qualifiedName, (ClassType*)parentType);
assignDeclarationAttributes(type, type, declarator);
result = declareData(declarator, type, ptrTypeFlags);
if (!result)
return false;
}
return true;
}
bool
Parser::declareData(
Declarator* declarator,
Type* type,
uint_t ptrTypeFlags
) {
bool result;
if (!declarator->isSimple()) {
err::setFormatStringError("invalid data declarator");
return false;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
NamespaceKind namespaceKind = nspace->getNamespaceKind();
switch (namespaceKind) {
case NamespaceKind_PropertyTemplate:
case NamespaceKind_Extension:
err::setFormatStringError("'%s' cannot have data fields", getNamespaceKindString(namespaceKind));
return false;
}
const sl::StringRef& name = declarator->getName().getShortName();
size_t bitCount = declarator->getBitCount();
sl::BoxList<Token>* constructor = &declarator->m_constructor;
sl::BoxList<Token>* initializer = &declarator->m_initializer;
if (isAutoSizeArrayType(type)) {
if (initializer->isEmpty()) {
err::setFormatStringError("auto-size array '%s' should have initializer", type->getTypeString().sz());
return false;
}
ArrayType* arrayType = (ArrayType*)type;
arrayType->m_elementCount = m_module->m_operatorMgr.parseAutoSizeArrayInitializer(arrayType, *initializer);
if (arrayType->m_elementCount == -1)
return false;
if (m_mode == Mode_Compile) {
result = arrayType->ensureLayout();
if (!result)
return false;
}
}
bool isDisposable = false;
if (namespaceKind != NamespaceKind_Property && (ptrTypeFlags & (PtrTypeFlag_AutoGet | PtrTypeFlag_Bindable))) {
err::setFormatStringError("'%s' can only be used on property field", getPtrTypeFlagString(ptrTypeFlags & (PtrTypeFlag_AutoGet | PtrTypeFlag_Bindable)).sz());
return false;
}
Scope* scope = m_module->m_namespaceMgr.getCurrentScope();
StorageKind storageKind = m_storageKind;
switch (storageKind) {
case StorageKind_Undefined:
switch (namespaceKind) {
case NamespaceKind_Scope:
storageKind = (type->getFlags() & TypeFlag_NoStack) ? StorageKind_Heap : StorageKind_Stack;
break;
case NamespaceKind_Type:
storageKind = StorageKind_Member;
break;
case NamespaceKind_Property:
storageKind = ((Property*)nspace)->getParentType() ? StorageKind_Member : StorageKind_Static;
break;
default:
storageKind = StorageKind_Static;
}
break;
case StorageKind_Static:
break;
case StorageKind_Tls:
if (!scope && (!constructor->isEmpty() || !initializer->isEmpty())) {
err::setFormatStringError("global 'threadlocal' variables cannot have initializers");
return false;
}
break;
case StorageKind_Mutable:
switch (namespaceKind) {
case NamespaceKind_Type:
break;
case NamespaceKind_Property:
if (((Property*)nspace)->getParentType())
break;
default:
err::setFormatStringError("'mutable' can only be applied to member fields");
return false;
}
break;
case StorageKind_Disposable:
if (namespaceKind != NamespaceKind_Scope) {
err::setFormatStringError("'disposable' can only be applied to local variables");
return false;
}
if (!isDisposableType(type)) {
err::setFormatStringError("'%s' is not a disposable type", type->getTypeString().sz());
return false;
}
ASSERT(scope);
if (!(scope->getFlags() & ScopeFlag_Disposable))
scope = m_module->m_namespaceMgr.openScope(
declarator->getPos(),
ScopeFlag_Disposable | ScopeFlag_FinallyAhead | ScopeFlag_Finalizable | ScopeFlag_Nested
);
storageKind = (type->getFlags() & TypeFlag_NoStack) ? StorageKind_Heap : StorageKind_Stack;
m_storageKind = StorageKind_Undefined; // don't overwrite
isDisposable = true;
break;
default:
err::setFormatStringError("invalid storage specifier '%s' for variable", getStorageKindString(storageKind));
return false;
}
if (namespaceKind == NamespaceKind_Property) {
Property* prop = (Property*)nspace;
ModuleItem* dataItem = NULL;
if (storageKind == StorageKind_Member) {
Field* field = prop->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
if (!field)
return false;
assignDeclarationAttributes(field, field, declarator);
dataItem = field;
} else {
Variable* variable = m_module->m_variableMgr.createVariable(
storageKind,
name,
nspace->createQualifiedName(name),
type,
ptrTypeFlags,
constructor,
initializer
);
assignDeclarationAttributes(variable, variable, declarator);
result = nspace->addItem(variable);
if (!result)
return false;
prop->m_staticVariableArray.append(variable);
dataItem = variable;
}
if (ptrTypeFlags & PtrTypeFlag_Bindable) {
result = prop->setOnChanged(dataItem);
if (!result)
return false;
} else if (ptrTypeFlags & PtrTypeFlag_AutoGet) {
result = prop->setAutoGetValue(dataItem);
if (!result)
return false;
}
} else if (storageKind != StorageKind_Member && storageKind != StorageKind_Mutable) {
Variable* variable = m_module->m_variableMgr.createVariable(
storageKind,
name,
nspace->createQualifiedName(name),
type,
ptrTypeFlags,
constructor,
initializer
);
assignDeclarationAttributes(variable, variable, declarator);
result = nspace->addItem(variable);
if (!result)
return false;
if (nspace->getNamespaceKind() == NamespaceKind_Type) {
NamedType* namedType = (NamedType*)nspace;
TypeKind namedTypeKind = namedType->getTypeKind();
switch (namedTypeKind) {
case TypeKind_Class:
case TypeKind_Struct:
case TypeKind_Union:
((DerivableType*)namedType)->m_staticVariableArray.append(variable);
break;
default:
err::setFormatStringError("field members are not allowed in '%s'", namedType->getTypeString().sz());
return false;
}
} else if (scope) {
result = m_module->m_variableMgr.allocateVariable(variable);
if (!result)
return false;
if (isDisposable) {
result = m_module->m_variableMgr.finalizeDisposableVariable(variable);
if (!result)
return false;
}
switch (storageKind) {
case StorageKind_Stack:
case StorageKind_Heap:
result = m_module->m_variableMgr.initializeVariable(variable);
if (!result)
return false;
break;
case StorageKind_Static:
case StorageKind_Tls:
if (variable->m_initializer.isEmpty() &&
variable->m_type->getTypeKind() != TypeKind_Class &&
!isConstructibleType(variable->m_type))
break;
OnceStmt stmt;
m_module->m_controlFlowMgr.onceStmt_Create(&stmt, variable->m_pos, storageKind);
result = m_module->m_controlFlowMgr.onceStmt_PreBody(&stmt, variable->m_pos);
if (!result)
return false;
result = m_module->m_variableMgr.initializeVariable(variable);
if (!result)
return false;
m_module->m_controlFlowMgr.onceStmt_PostBody(
&stmt,
!variable->m_initializer.isEmpty() ? variable->m_initializer.getTail()->m_pos :
!variable->m_constructor.isEmpty() ? variable->m_constructor.getTail()->m_pos :
variable->m_pos
);
break;
default:
ASSERT(false);
}
}
} else {
ASSERT(nspace->getNamespaceKind() == NamespaceKind_Type);
NamedType* namedType = (NamedType*)nspace;
TypeKind namedTypeKind = namedType->getTypeKind();
Field* field;
switch (namedTypeKind) {
case TypeKind_Class:
field = ((ClassType*)namedType)->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
break;
case TypeKind_Struct:
field = ((StructType*)namedType)->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
break;
case TypeKind_Union:
field = ((UnionType*)namedType)->createField(name, type, bitCount, ptrTypeFlags, constructor, initializer);
break;
default:
err::setFormatStringError("field members are not allowed in '%s'", namedType->getTypeString().sz());
return false;
}
if (!field)
return false;
assignDeclarationAttributes(field, field, declarator);
}
return true;
}
bool
Parser::declareUnnamedStructOrUnion(DerivableType* type) {
m_storageKind = StorageKind_Undefined;
m_accessKind = AccessKind_Undefined;
Declarator declarator;
declarator.m_declaratorKind = DeclaratorKind_Name;
declarator.m_pos = type->getPos();
return declareData(&declarator, type, 0);
}
FunctionArg*
Parser::createFormalArg(
DeclFunctionSuffix* argSuffix,
Declarator* declarator
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
uint_t ptrTypeFlags = 0;
Type* type = declarator->calcType(&ptrTypeFlags);
if (!type)
return NULL;
TypeKind typeKind = type->getTypeKind();
switch (typeKind) {
case TypeKind_Void:
case TypeKind_Class:
case TypeKind_Function:
case TypeKind_Property:
err::setFormatStringError(
"function cannot accept '%s' as an argument",
type->getTypeString().sz()
);
return NULL;
}
if (m_storageKind) {
err::setFormatStringError("invalid storage '%s' for argument", getStorageKindString(m_storageKind));
return NULL;
}
m_storageKind = StorageKind_Stack;
sl::String name;
if (declarator->isSimple()) {
name = declarator->getName().getShortName();
} else if (declarator->getDeclaratorKind() != DeclaratorKind_Undefined) {
err::setFormatStringError("invalid formal argument declarator");
return NULL;
}
FunctionArg* arg = m_module->m_typeMgr.createFunctionArg(
name,
type,
ptrTypeFlags,
&declarator->m_initializer
);
assignDeclarationAttributes(arg, arg, declarator);
argSuffix->m_argArray.append(arg);
return arg;
}
bool
Parser::addEnumFlag(
uint_t* flags,
EnumTypeFlag flag
) {
if (*flags & flag) {
err::setFormatStringError("modifier '%s' used more than once", getEnumTypeFlagString(flag));
return false;
}
*flags |= flag;
return true;
}
EnumType*
Parser::createEnumType(
const sl::StringRef& name,
Type* baseType,
uint_t flags
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
EnumType* enumType = NULL;
if (name.isEmpty()) {
flags |= EnumTypeFlag_Exposed;
enumType = m_module->m_typeMgr.createUnnamedEnumType(baseType, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
enumType = m_module->m_typeMgr.createEnumType(name, qualifiedName, baseType, flags);
if (!enumType)
return NULL;
bool result = nspace->addItem(enumType);
if (!result)
return NULL;
}
assignDeclarationAttributes(enumType, enumType, m_lastMatchedToken.m_pos);
return enumType;
}
EnumConst*
Parser::createEnumConst(
const sl::StringRef& name,
const lex::LineCol& pos,
sl::BoxList<Token>* initializer
) {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ASSERT(nspace->getNamespaceKind() == NamespaceKind_Type);
ASSERT(((NamedType*)nspace)->getTypeKind() == TypeKind_Enum);
EnumType* type = (EnumType*)m_module->m_namespaceMgr.getCurrentNamespace();
EnumConst* enumConst = type->createConst(name, initializer);
if (!enumConst)
return NULL;
assignDeclarationAttributes(enumConst, enumConst, pos);
return enumConst;
}
StructType*
Parser::createStructType(
const sl::StringRef& name,
sl::BoxList<Type*>* baseTypeList,
size_t fieldAlignment,
uint_t flags
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
StructType* structType = NULL;
if (name.isEmpty()) {
structType = m_module->m_typeMgr.createUnnamedStructType(fieldAlignment, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
structType = m_module->m_typeMgr.createStructType(name, qualifiedName, fieldAlignment, flags);
if (!structType)
return NULL;
}
if (baseTypeList) {
sl::BoxIterator<Type*> baseType = baseTypeList->getHead();
for (; baseType; baseType++) {
result = structType->addBaseType(*baseType) != NULL;
if (!result)
return NULL;
}
}
if (!name.isEmpty()) {
result = nspace->addItem(structType);
if (!result)
return NULL;
}
assignDeclarationAttributes(structType, structType, m_lastMatchedToken.m_pos);
return structType;
}
UnionType*
Parser::createUnionType(
const sl::StringRef& name,
size_t fieldAlignment,
uint_t flags
) {
bool result;
if (flags & TypeFlag_Dynamic) {
err::setError("dynamic unions are not supported yet");
return NULL;
}
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
UnionType* unionType = NULL;
if (name.isEmpty()) {
unionType = m_module->m_typeMgr.createUnnamedUnionType(fieldAlignment, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
unionType = m_module->m_typeMgr.createUnionType(name, qualifiedName, fieldAlignment, flags);
if (!unionType)
return NULL;
result = nspace->addItem(unionType);
if (!result)
return NULL;
}
assignDeclarationAttributes(unionType, unionType, m_lastMatchedToken.m_pos);
return unionType;
}
ClassType*
Parser::createClassType(
const sl::StringRef& name,
sl::BoxList<Type*>* baseTypeList,
size_t fieldAlignment,
uint_t flags
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ClassType* classType;
if (name.isEmpty()) {
classType = m_module->m_typeMgr.createUnnamedClassType(fieldAlignment, flags);
} else {
sl::String qualifiedName = nspace->createQualifiedName(name);
classType = m_module->m_typeMgr.createClassType(name, qualifiedName, fieldAlignment, flags);
}
if (baseTypeList) {
sl::BoxIterator<Type*> baseType = baseTypeList->getHead();
for (; baseType; baseType++) {
result = classType->addBaseType(*baseType) != NULL;
if (!result)
return NULL;
}
}
if (!name.isEmpty()) {
result = nspace->addItem(classType);
if (!result)
return NULL;
}
assignDeclarationAttributes(classType, classType, m_lastMatchedToken.m_pos);
return classType;
}
DynamicLibClassType*
Parser::createDynamicLibType(const sl::StringRef& name) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
sl::String qualifiedName = nspace->createQualifiedName(name);
DynamicLibClassType* classType = m_module->m_typeMgr.createClassType<DynamicLibClassType>(name, qualifiedName);
Type* baseType = m_module->m_typeMgr.getStdType(StdType_DynamicLib);
result =
classType->addBaseType(baseType) != NULL &&
nspace->addItem(classType);
if (!result)
return NULL;
assignDeclarationAttributes(classType, classType, m_lastMatchedToken.m_pos);
DynamicLibNamespace* dynamicLibNamespace = classType->createLibNamespace();
dynamicLibNamespace->m_parentUnit = classType->getParentUnit();
return classType;
}
bool
Parser::finalizeDynamicLibType() {
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
ASSERT(nspace->getNamespaceKind() == NamespaceKind_DynamicLib);
DynamicLibNamespace* dynamicLibNamespace = (DynamicLibNamespace*)nspace;
DynamicLibClassType* dynamicLibType = dynamicLibNamespace->getLibraryType();
bool result = dynamicLibType->ensureFunctionTable();
if (!result)
return false;
m_module->m_namespaceMgr.closeNamespace();
return true;
}
bool
Parser::addReactionBinding(const Value& value) {
ASSERT(m_mode == Mode_Reaction && m_reactorType);
Function* addBindingFunc = getReactorMethod(m_module, ReactorMethod_AddOnChangedBinding);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
Value onChangedValue;
return
m_module->m_operatorMgr.getPropertyOnChanged(value, &onChangedValue) &&
m_module->m_operatorMgr.callOperator(addBindingFunc, thisValue, onChangedValue);
}
bool
Parser::resetReactionBindings() {
Function* resetBindingsFunc = getReactorMethod(m_module, ReactorMethod_ResetOnChangedBindings);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
return m_module->m_operatorMgr.callOperator(resetBindingsFunc, thisValue);
}
bool
Parser::reactorOnEventStmt(
const sl::ConstBoxList<Value>& valueList,
Declarator* declarator,
sl::BoxList<Token>* tokenList
) {
ASSERT(m_mode == Mode_Reaction && m_reactorType);
DeclFunctionSuffix* suffix = declarator->getFunctionSuffix();
ASSERT(suffix);
FunctionType* functionType = m_module->m_typeMgr.getFunctionType(suffix->getArgArray());
Function* handler = m_reactorType->createOnEventHandler(m_reactionIdx, functionType);
handler->m_parentUnit = m_module->m_unitMgr.getCurrentUnit();
handler->setBody(tokenList);
Function* addBindingFunc = getReactorMethod(m_module, ReactorMethod_AddOnEventBinding);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
sl::ConstBoxIterator<Value> it = valueList.getHead();
for (; it; it++) {
bool result = m_module->m_operatorMgr.callOperator(addBindingFunc, thisValue, *it);
if (!result)
return false;
}
return true;
}
bool
Parser::callBaseTypeMemberConstructor(
const QualifiedName& name,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
Namespace* nspace = m_module->m_functionMgr.getCurrentFunction()->getParentNamespace();
FindModuleItemResult findResult = nspace->findItemTraverse(name);
if (!findResult.m_result)
return false;
if (!findResult.m_item) {
err::setFormatStringError("name '%s' is not found", name.getFullName ().sz());
return false;
}
Type* type = NULL;
ModuleItem* item = findResult.m_item;
ModuleItemKind itemKind = item->getItemKind();
switch (itemKind) {
case ModuleItemKind_Type:
return callBaseTypeConstructor((Type*)item, argList);
case ModuleItemKind_Typedef:
return callBaseTypeConstructor(((Typedef*)item)->getType(), argList);
case ModuleItemKind_Property:
err::setFormatStringError("property construction is not yet implemented");
return false;
case ModuleItemKind_Field:
return callFieldConstructor((Field*)item, argList);
case ModuleItemKind_Variable:
err::setFormatStringError("static field construction is not yet implemented");
return false;
default:
err::setFormatStringError("'%s' cannot be used in base-type-member construct list");
return false;
}
}
DerivableType*
Parser::findBaseType(size_t baseTypeIdx) {
Function* function = m_module->m_functionMgr.getCurrentFunction();
ASSERT(function); // should not be called at pass
DerivableType* parentType = function->getParentType();
if (!parentType)
return NULL;
BaseTypeSlot* slot = parentType->getBaseTypeByIndex(baseTypeIdx);
if (!slot)
return NULL;
return slot->getType();
}
DerivableType*
Parser::getBaseType(size_t baseTypeIdx) {
DerivableType* type = findBaseType(baseTypeIdx);
if (!type) {
err::setFormatStringError("'basetype%d' is not found", baseTypeIdx + 1);
return NULL;
}
return type;
}
bool
Parser::getBaseType(
size_t baseTypeIdx,
Value* resultValue
) {
DerivableType* type = getBaseType(baseTypeIdx);
if (!type)
return false;
resultValue->setNamespace(type);
return true;
}
bool
Parser::callBaseTypeConstructor(
size_t baseTypeIdx,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
if (m_constructorProperty) {
err::setFormatStringError("'%s.construct' cannot have base-type constructor calls", m_constructorProperty->getQualifiedName().sz());
return false;
}
BaseTypeSlot* baseTypeSlot = m_constructorType->getBaseTypeByIndex(baseTypeIdx);
if (!baseTypeSlot)
return false;
return callBaseTypeConstructorImpl(baseTypeSlot, argList);
}
bool
Parser::callBaseTypeConstructor(
Type* type,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
if (m_constructorProperty) {
err::setFormatStringError("'%s.construct' cannot have base-type constructor calls", m_constructorProperty->getQualifiedName().sz());
return false;
}
BaseTypeSlot* baseTypeSlot = m_constructorType->findBaseType(type);
if (!baseTypeSlot) {
err::setFormatStringError(
"'%s' is not a base type of '%s'",
type->getTypeString().sz(),
m_constructorType->getTypeString().sz()
);
return false;
}
return callBaseTypeConstructorImpl(baseTypeSlot, argList);
}
bool
Parser::callBaseTypeConstructorImpl(
BaseTypeSlot* baseTypeSlot,
sl::BoxList<Value>* argList
) {
DerivableType* type = baseTypeSlot->getType();
if (baseTypeSlot->m_flags & ModuleItemFlag_Constructed) {
err::setFormatStringError("'%s' is already constructed", type->getTypeString().sz());
return false;
}
OverloadableFunction constructor = type->getConstructor();
if (!constructor) {
err::setFormatStringError("'%s' has no constructor", type->getTypeString().sz());
return false;
}
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
argList->insertHead(thisValue);
bool result = m_module->m_operatorMgr.callOperator(constructor, argList);
if (!result)
return false;
baseTypeSlot->m_flags |= ModuleItemFlag_Constructed;
return true;
}
bool
Parser::callFieldConstructor(
Field* field,
sl::BoxList<Value>* argList
) {
ASSERT(m_constructorType || m_constructorProperty);
Value thisValue = m_module->m_functionMgr.getThisValue();
ASSERT(thisValue);
bool result;
if (m_constructorProperty) {
err::setFormatStringError("property field construction is not yet implemented");
return false;
}
if (field->getParentNamespace() != m_constructorType) {
err::setFormatStringError(
"'%s' is not an immediate field of '%s'",
field->getName().sz(),
m_constructorType->getTypeString().sz()
);
return false;
}
if (field->getFlags() & ModuleItemFlag_Constructed) {
err::setFormatStringError("'%s' is already constructed", field->getName().sz());
return false;
}
if (!(field->getType()->getTypeKindFlags() & TypeKindFlag_Derivable) ||
!((DerivableType*)field->getType())->getConstructor()) {
err::setFormatStringError("'%s' has no constructor", field->getName().sz());
return false;
}
OverloadableFunction constructor = ((DerivableType*)field->getType())->getConstructor();
Value fieldValue;
result =
m_module->m_operatorMgr.getField(thisValue, field, NULL, &fieldValue) &&
m_module->m_operatorMgr.unaryOperator(UnOpKind_Addr, &fieldValue);
if (!result)
return false;
argList->insertHead(fieldValue);
result = m_module->m_operatorMgr.callOperator(constructor, argList);
if (!result)
return false;
field->m_flags |= ModuleItemFlag_Constructed;
return true;
}
bool
Parser::finalizeBaseTypeMemberConstructBlock() {
ASSERT(m_constructorType || m_constructorProperty);
Function* constructor = m_module->m_functionMgr.getCurrentFunction();
FunctionKind functionKind = constructor->getFunctionKind();
ASSERT(functionKind == FunctionKind_Constructor || functionKind == FunctionKind_StaticConstructor);
if (functionKind == FunctionKind_StaticConstructor) {
MemberBlock* memberBlock = m_constructorProperty ?
(MemberBlock*)m_constructorProperty :
(MemberBlock*)m_constructorType;
memberBlock->primeStaticVariables();
return
memberBlock->initializeStaticVariables() &&
memberBlock->callPropertyStaticConstructors();
} else {
Value thisValue = m_module->m_functionMgr.getThisValue();
if (m_constructorProperty)
return
m_constructorProperty->initializeFields(thisValue) &&
m_constructorProperty->callPropertyConstructors(thisValue);
else
return
m_constructorType->callBaseTypeConstructors(thisValue) &&
m_constructorType->callStaticConstructor() &&
m_constructorType->initializeFields(thisValue) &&
m_constructorType->callPropertyConstructors(thisValue);
}
}
bool
Parser::lookupIdentifier(
const Token& token,
Value* value
) {
bool result;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
MemberCoord coord;
FindModuleItemResult findResult = nspace->findDirectChildItemTraverse(token.m_data.m_string, &coord);
if (!findResult.m_result)
return false;
if (!findResult.m_item) {
err::setFormatStringError("undeclared identifier '%s'", token.m_data.m_string.sz());
lex::pushSrcPosError(m_module->m_unitMgr.getCurrentUnit()->getFilePath(), token.m_pos);
return false;
}
Value thisValue;
ModuleItem* item = findResult.m_item;
ModuleItemKind itemKind = item->getItemKind();
switch (itemKind) {
case ModuleItemKind_Namespace:
value->setNamespace((GlobalNamespace*)item);
break;
case ModuleItemKind_Typedef:
item = ((Typedef*)item)->getType();
// and fall through
case ModuleItemKind_Type:
if (!(((Type*)item)->getTypeKindFlags() & TypeKindFlag_Named)) {
err::setFormatStringError("'%s' cannot be used as expression", ((Type*)item)->getTypeString().sz());
return false;
}
value->setNamespace((NamedType*)item);
break;
case ModuleItemKind_Const:
*value = ((Const*)item)->getValue();
break;
case ModuleItemKind_Variable:
value->setVariable((Variable*)item);
break;
case ModuleItemKind_Function:
result = value->trySetFunction((Function*)item);
if (!result)
return false;
if (((Function*)item)->isMember()) {
result = m_module->m_operatorMgr.createMemberClosure(value, (Function*)item);
if (!result)
return false;
}
break;
case ModuleItemKind_FunctionOverload:
value->setFunctionOverload((FunctionOverload*)item);
if (((FunctionOverload*)item)->getFlags() & FunctionOverloadFlag_HasMembers) {
result = m_module->m_operatorMgr.createMemberClosure(value, (FunctionOverload*)item);
if (!result)
return false;
}
break;
case ModuleItemKind_Property:
value->setProperty((Property*)item);
if (((Property*)item)->isMember()) {
result = m_module->m_operatorMgr.createMemberClosure(value, (Property*)item);
if (!result)
return false;
}
break;
case ModuleItemKind_EnumConst:
result = value->trySetEnumConst((EnumConst*)item);
if (!result)
return false;
break;
case ModuleItemKind_Field:
result =
m_module->m_operatorMgr.getThisValue(&thisValue, (Field*)item) &&
m_module->m_operatorMgr.getField(thisValue, (Field*)item, &coord, value);
if (!result)
return false;
m_module->m_operatorMgr.finalizeDualType(thisValue, (Field*)item, value);
break;
default:
err::setFormatStringError(
"%s '%s' cannot be used as expression",
getModuleItemKindString(item->getItemKind()),
token.m_data.m_string.sz()
);
return false;
};
if (m_module->m_codeAssistMgr.getCodeAssistKind() == CodeAssistKind_QuickInfoTip &&
(token.m_flags & TokenFlag_CodeAssist))
m_module->m_codeAssistMgr.createQuickInfoTip(token.m_pos.m_offset, item);
return true;
}
bool
Parser::prepareCurlyInitializerNamedItem(
CurlyInitializer* initializer,
const sl::StringRef& name
) {
Value memberValue;
bool result = m_module->m_operatorMgr.memberOperator(
initializer->m_targetValue,
name,
&initializer->m_memberValue
);
if (!result)
return false;
initializer->m_index = -1;
m_curlyInitializerTargetValue = initializer->m_memberValue;
return true;
}
bool
Parser::prepareCurlyInitializerIndexedItem(CurlyInitializer* initializer) {
if (initializer->m_index == -1) {
err::setFormatStringError("indexed-based initializer cannot be used after named-based initializer");
return false;
}
bool result = m_module->m_operatorMgr.memberOperator(
initializer->m_targetValue,
initializer->m_index,
&initializer->m_memberValue
);
if (!result)
return false;
m_curlyInitializerTargetValue = initializer->m_memberValue;
return true;
}
bool
Parser::skipCurlyInitializerItem(CurlyInitializer* initializer) {
if (initializer->m_index == -1)
return true; // allow finishing comma(s)
initializer->m_index++;
return true;
}
bool
Parser::assignCurlyInitializerItem(
CurlyInitializer* initializer,
const Value& value
) {
if (initializer->m_index == -1 ||
value.getValueKind() != ValueKind_Const ||
!isCharArrayType(value.getType()) ||
!isCharArrayRefType(initializer->m_targetValue.getType())) {
if (initializer->m_index != -1)
initializer->m_index++;
initializer->m_count++;
return m_module->m_operatorMgr.binaryOperator(BinOpKind_Assign, initializer->m_memberValue, value);
}
ArrayType* srcType = (ArrayType*)value.getType();
ArrayType* dstType = (ArrayType*)((DataPtrType*)initializer->m_targetValue.getType())->getTargetType();
size_t length = srcType->getElementCount();
if (dstType->getElementCount() < initializer->m_index + length) {
err::setFormatStringError("literal initializer is too big to fit inside the target array");
return false;
}
initializer->m_index += length;
initializer->m_count++;
Value memberPtrValue;
return
m_module->m_operatorMgr.unaryOperator(UnOpKind_Addr, initializer->m_memberValue, &memberPtrValue) &&
m_module->m_operatorMgr.memCpy(memberPtrValue, value, length);
}
bool
Parser::addFmtSite(
Literal* literal,
const sl::StringRef& string,
const Value& value,
bool isIndex,
const sl::StringRef& fmtSpecifierString
) {
literal->m_binData.append(string.cp(), string.getLength());
FmtSite* site = AXL_MEM_NEW(FmtSite);
site->m_offset = literal->m_binData.getCount();
site->m_fmtSpecifierString = fmtSpecifierString;
literal->m_fmtSiteList.insertTail(site);
literal->m_isZeroTerminated = true;
if (!isIndex) {
site->m_value = value;
return true;
}
if (value.getValueKind() != ValueKind_Const ||
!(value.getType()->getTypeKindFlags() & TypeKindFlag_Integer)) {
err::setFormatStringError("expression is not integer constant");
return false;
}
site->m_index = 0;
memcpy(&site->m_index, value.getConstData(), value.getType()->getSize());
literal->m_lastIndex = site->m_index;
return true;
}
void
Parser::addFmtSite(
Literal* literal,
const sl::StringRef& string,
size_t index
) {
literal->m_binData.append(string.cp(), string.getLength());
FmtSite* site = AXL_MEM_NEW(FmtSite);
site->m_offset = literal->m_binData.getCount();
site->m_index = index;
literal->m_fmtSiteList.insertTail(site);
literal->m_lastIndex = index;
literal->m_isZeroTerminated = true;
}
void
Parser::addFmtSite(
Literal* literal,
const sl::StringRef& string,
const sl::StringRef& fmtSpecifierString
) {
literal->m_binData.append(string.cp(), string.getLength());
FmtSite* site = AXL_MEM_NEW(FmtSite);
site->m_offset = literal->m_binData.getCount();
site->m_index = ++literal->m_lastIndex;
site->m_fmtSpecifierString = fmtSpecifierString;
literal->m_fmtSiteList.insertTail(site);
literal->m_isZeroTerminated = true;
}
bool
Parser::finalizeLiteral(
Literal* literal,
sl::BoxList<Value>* argValueList,
Value* resultValue
) {
bool result;
if (literal->m_fmtSiteList.isEmpty()) {
if (literal->m_isZeroTerminated)
literal->m_binData.append(0);
resultValue->setCharArray(literal->m_binData, literal->m_binData.getCount(), m_module);
return true;
}
char buffer[256];
sl::Array<Value*> argValueArray(rc::BufKind_Stack, buffer, sizeof(buffer));
size_t argCount = 0;
if (argValueList) {
argCount = argValueList->getCount();
argValueArray.setCount(argCount);
sl::BoxIterator<Value> it = argValueList->getHead();
for (size_t i = 0; i < argCount; i++, it++) {
ASSERT(it);
argValueArray[i] = it.p();
}
}
Type* type = m_module->m_typeMgr.getStdType(StdType_FmtLiteral);
Variable* fmtLiteral = m_module->m_variableMgr.createSimpleStackVariable("fmtLiteral", type);
result = m_module->m_variableMgr.initializeVariable(fmtLiteral);
ASSERT(result);
Value fmtLiteralValue = fmtLiteral;
size_t offset = 0;
sl::BitMap argUsageMap;
argUsageMap.setBitCount(argCount);
sl::Iterator<FmtSite> siteIt = literal->m_fmtSiteList.getHead();
for (; siteIt; siteIt++) {
FmtSite* site = *siteIt;
Value* value;
if (site->m_index == -1) {
value = &site->m_value;
} else {
size_t i = site->m_index - 1;
if (i >= argCount) {
err::setFormatStringError("formatting literal doesn't have argument %%%d", site->m_index);
return false;
}
value = argValueArray[i];
argUsageMap.setBit(i);
}
if (site->m_offset > offset) {
size_t length = site->m_offset - offset;
appendFmtLiteralRawData(
fmtLiteralValue,
literal->m_binData + offset,
length
);
offset += length;
}
if (value->isEmpty()) {
err::setFormatStringError("formatting literals arguments cannot be skipped");
return false;
}
result = appendFmtLiteralValue(fmtLiteralValue, *value, site->m_fmtSpecifierString);
if (!result)
return false;
}
size_t unusedArgIdx = argUsageMap.findBit(0, false);
if (unusedArgIdx < argCount) {
err::setFormatStringError("formatting literal argument %%%d is not used", unusedArgIdx + 1);
return false;
}
size_t endOffset = literal->m_binData.getCount();
if (endOffset > offset) {
size_t length = endOffset - offset;
appendFmtLiteralRawData(
fmtLiteralValue,
literal->m_binData + offset,
length
);
}
DataPtrType* resultType = m_module->m_typeMgr.getPrimitiveType(TypeKind_Char)->getDataPtrType(DataPtrTypeKind_Lean);
if (!m_module->hasCodeGen()) {
resultValue->setType(resultType);
return true;
}
Value fatPtrValue;
Value thinPtrValue;
Value validatorValue;
Type* validatorType = m_module->m_typeMgr.getStdType(StdType_DataPtrValidatorPtr);
m_module->m_llvmIrBuilder.createGep2(fmtLiteralValue, 0, NULL, &fatPtrValue);
m_module->m_llvmIrBuilder.createLoad(fatPtrValue, NULL, &fatPtrValue);
m_module->m_llvmIrBuilder.createExtractValue(fatPtrValue, 0, NULL, &thinPtrValue);
m_module->m_llvmIrBuilder.createExtractValue(fatPtrValue, 1, validatorType, &validatorValue);
resultValue->setLeanDataPtr(thinPtrValue.getLlvmValue(), resultType, validatorValue);
return true;
}
void
Parser::appendFmtLiteralRawData(
const Value& fmtLiteralValue,
const void* p,
size_t length
) {
if (!m_module->hasCodeGen())
return;
Function* append = m_module->m_functionMgr.getStdFunction(StdFunc_AppendFmtLiteral_a);
Value literalValue;
literalValue.setCharArray(p, length, m_module);
bool result = m_module->m_operatorMgr.castOperator(&literalValue, m_module->m_typeMgr.getStdType(StdType_CharConstPtr));
ASSERT(result);
Value lengthValue;
lengthValue.setConstSizeT(length, m_module);
Value resultValue;
m_module->m_llvmIrBuilder.createCall3(
append,
append->getType(),
fmtLiteralValue,
literalValue,
lengthValue,
&resultValue
);
}
bool
Parser::appendFmtLiteralValue(
const Value& fmtLiteralValue,
const Value& rawSrcValue,
const sl::StringRef& fmtSpecifierString
) {
if (fmtSpecifierString == "B") // binary format
return appendFmtLiteralBinValue(fmtLiteralValue, rawSrcValue);
Value srcValue;
bool result = m_module->m_operatorMgr.prepareOperand(rawSrcValue, &srcValue);
if (!result)
return false;
StdFunc appendFunc;
Type* type = srcValue.getType();
TypeKind typeKind = type->getTypeKind();
uint_t typeKindFlags = type->getTypeKindFlags();
if (typeKindFlags & TypeKindFlag_Integer) {
static StdFunc funcTable[2][2] = {
{ StdFunc_AppendFmtLiteral_i32, StdFunc_AppendFmtLiteral_ui32 },
{ StdFunc_AppendFmtLiteral_i64, StdFunc_AppendFmtLiteral_ui64 },
};
size_t i1 = type->getSize() > 4;
size_t i2 = (typeKindFlags & TypeKindFlag_Unsigned) != 0;
appendFunc = funcTable[i1][i2];
} else if (typeKindFlags & TypeKindFlag_Fp) {
appendFunc = StdFunc_AppendFmtLiteral_f;
} else if (typeKind == TypeKind_Variant) {
appendFunc = StdFunc_AppendFmtLiteral_v;
} else if (isCharArrayType(type) || isCharArrayRefType(type) || isCharPtrType(type)) {
appendFunc = StdFunc_AppendFmtLiteral_p;
} else {
err::setFormatStringError("don't know how to format '%s'", type->getTypeString().sz());
return false;
}
Function* append = m_module->m_functionMgr.getStdFunction(appendFunc);
Type* argType = append->getType()->getArgArray() [2]->getType();
Value argValue;
result = m_module->m_operatorMgr.castOperator(srcValue, argType, &argValue);
if (!result)
return false;
Value fmtSpecifierValue;
if (!fmtSpecifierString.isEmpty()) {
fmtSpecifierValue.setCharArray(fmtSpecifierString, m_module);
m_module->m_operatorMgr.castOperator(&fmtSpecifierValue, m_module->m_typeMgr.getStdType(StdType_CharConstPtr));
} else {
fmtSpecifierValue = m_module->m_typeMgr.getStdType(StdType_CharConstPtr)->getZeroValue();
}
return m_module->m_operatorMgr.callOperator(
append,
fmtLiteralValue,
fmtSpecifierValue,
argValue
);
}
bool
Parser::appendFmtLiteralBinValue(
const Value& fmtLiteralValue,
const Value& rawSrcValue
) {
Value srcValue;
bool result = m_module->m_operatorMgr.prepareOperand(rawSrcValue, &srcValue);
if (!result)
return false;
if (!m_module->hasCodeGen())
return true;
Type* type = srcValue.getType();
Function* append = m_module->m_functionMgr.getStdFunction(StdFunc_AppendFmtLiteral_a);
Type* argType = m_module->m_typeMgr.getStdType(StdType_BytePtr);
Value sizeValue(
type->getSize(),
m_module->m_typeMgr.getPrimitiveType(TypeKind_SizeT)
);
Value tmpValue;
Value resultValue;
m_module->m_llvmIrBuilder.createAlloca(type, "tmpFmtValue", NULL, &tmpValue);
m_module->m_llvmIrBuilder.createStore(srcValue, tmpValue);
m_module->m_llvmIrBuilder.createBitCast(tmpValue, argType, &tmpValue);
m_module->m_llvmIrBuilder.createCall3(
append,
append->getType(),
fmtLiteralValue,
tmpValue,
sizeValue,
&resultValue
);
return true;
}
bool
Parser::finalizeReSwitchCaseLiteral(
sl::StringRef* data,
const Value& value,
bool isZeroTerminated
) {
if (value.getValueKind() != ValueKind_Const) {
err::setFormatStringError("not a constant literal expression");
return false;
}
size_t length = value.m_type->getSize();
if (isZeroTerminated) {
ASSERT(length);
length--;
}
*data = sl::StringRef(value.m_constData.getHdr(), value.m_constData.cp(), length);
return true;
}
BasicBlock*
Parser::assertCondition(const sl::BoxList<Token>& tokenList) {
bool result;
Value conditionValue;
result = m_module->m_operatorMgr.parseExpression(tokenList, &conditionValue);
if (!result)
return NULL;
BasicBlock* failBlock = m_module->m_controlFlowMgr.createBlock("assert_fail");
BasicBlock* continueBlock = m_module->m_controlFlowMgr.createBlock("assert_continue");
result = m_module->m_controlFlowMgr.conditionalJump(conditionValue, continueBlock, failBlock, failBlock);
if (!result)
return NULL;
return continueBlock;
}
bool
Parser::finalizeAssertStmt(
const sl::BoxList<Token>& conditionTokenList,
const Value& messageValue,
BasicBlock* continueBlock
) {
ASSERT(!conditionTokenList.isEmpty());
sl::String fileName = m_module->m_unitMgr.getCurrentUnit()->getFilePath();
sl::String conditionString = Token::getTokenListString(conditionTokenList);
Token::Pos pos = conditionTokenList.getHead()->m_pos;
Value fileNameValue;
Value lineValue;
Value conditionValue;
fileNameValue.setCharArray(fileName, m_module);
lineValue.setConstInt32(pos.m_line, m_module);
conditionValue.setCharArray(conditionString, m_module);
Function* assertionFailure = m_module->m_functionMgr.getStdFunction(StdFunc_AssertionFailure);
sl::BoxList<Value> argValueList;
argValueList.insertTail(fileNameValue);
argValueList.insertTail(lineValue);
argValueList.insertTail(conditionValue);
if (messageValue) {
argValueList.insertTail(messageValue);
} else {
Value nullValue;
nullValue.setNull(m_module);
argValueList.insertTail(nullValue);
}
bool result = m_module->m_operatorMgr.callOperator(assertionFailure, &argValueList);
if (!result)
return false;
m_module->m_controlFlowMgr.follow(continueBlock);
return true;
}
void
Parser::addScopeAnchorToken(
StmtPass1* stmt,
const Token& token
) {
sl::BoxIterator<Token> it = stmt->m_tokenList.insertTail(token);
stmt->m_scopeAnchorToken = &*it;
stmt->m_scopeAnchorToken->m_data.m_integer = 0; // tokens can be reused, ensure 0
}
void
Parser::generateAutoComplete(
const Token& token,
const Value& value
) {
Namespace* nspace = m_module->m_operatorMgr.getValueNamespace(value);
if (nspace)
generateAutoComplete(token, nspace);
else
m_module->m_codeAssistMgr.createEmptyCodeAssist(token.m_pos.m_offset);
}
void
Parser::generateMemberInfo(
const Token& token,
const Value& value,
const sl::StringRef& name
) {
Namespace* nspace = m_module->m_operatorMgr.getValueNamespace(value);
if (nspace) {
FindModuleItemResult result = nspace->findDirectChildItemTraverse(name, NULL, TraverseFlag_NoParentNamespace);
if (result.m_item)
m_module->m_codeAssistMgr.createQuickInfoTip(token.m_pos.m_offset, result.m_item);
}
}
void
Parser::generateAutoComplete(
const Token& token,
Namespace* nspace,
uint_t flags
) {
size_t offset = token.m_pos.m_offset;
if (token.m_tokenKind != TokenKind_Identifier)
if (token.m_flags & TokenFlag_CodeAssistRight)
offset += token.m_pos.m_length;
else
return;
m_module->m_codeAssistMgr.createAutoComplete(offset, nspace, flags);
}
void
Parser::prepareAutoCompleteFallback(
const Token& token,
const QualifiedName& prefix,
uint_t flags
) {
size_t offset = token.m_pos.m_offset;
if (token.m_tokenKind != TokenKind_Identifier)
if (token.m_flags & TokenFlag_CodeAssistRight)
offset += token.m_pos.m_length;
else
return;
Namespace* nspace = m_module->m_namespaceMgr.getCurrentNamespace();
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_offset = offset;
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_namespace = nspace;
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_prefix = prefix;
m_module->m_codeAssistMgr.m_autoCompleteFallback.m_flags = flags;
}
//..............................................................................
} // namespace ct
} // namespace jnc
| vovkos/jancy | src/jnc_ct/jnc_ct_Parser/jnc_ct_Parser.cpp | C++ | mit | 82,212 |
/********************************************************************
The Multiverse Platform is made available under the MIT License.
Copyright (c) 2012 The Multiverse Foundation
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.
*********************************************************************/
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:2.0.50727.42
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TerrainAssembler.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "2.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("TerrainAssembler.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
| longde123/MultiversePlatform | tools/TerrainAssembler/TerrainAssembler/Properties/Resources.Designer.cs | C# | mit | 4,084 |
import { DataView } from '@antv/data-set';
import { Chart } from '@antv/g2';
const data = [
{
State: 'AL',
'Under 5 Years': 310504,
'5 to 13 Years': 552339,
'14 to 17 Years': 259034,
'18 to 24 Years': 450818,
'25 to 44 Years': 1231572,
'45 to 64 Years': 1215966,
'65 Years and Over': 641667,
},
{
State: 'AK',
'Under 5 Years': 52083,
'5 to 13 Years': 85640,
'14 to 17 Years': 42153,
'18 to 24 Years': 74257,
'25 to 44 Years': 198724,
'45 to 64 Years': 183159,
'65 Years and Over': 50277,
},
{
State: 'AZ',
'Under 5 Years': 515910,
'5 to 13 Years': 828669,
'14 to 17 Years': 362642,
'18 to 24 Years': 601943,
'25 to 44 Years': 1804762,
'45 to 64 Years': 1523681,
'65 Years and Over': 862573,
},
{
State: 'AR',
'Under 5 Years': 202070,
'5 to 13 Years': 343207,
'14 to 17 Years': 157204,
'18 to 24 Years': 264160,
'25 to 44 Years': 754420,
'45 to 64 Years': 727124,
'65 Years and Over': 407205,
},
{
State: 'CA',
'Under 5 Years': 2704659,
'5 to 13 Years': 4499890,
'14 to 17 Years': 2159981,
'18 to 24 Years': 3853788,
'25 to 44 Years': 10604510,
'45 to 64 Years': 8819342,
'65 Years and Over': 4114496,
},
{
State: 'CO',
'Under 5 Years': 358280,
'5 to 13 Years': 587154,
'14 to 17 Years': 261701,
'18 to 24 Years': 466194,
'25 to 44 Years': 1464939,
'45 to 64 Years': 1290094,
'65 Years and Over': 511094,
},
{
State: 'CT',
'Under 5 Years': 211637,
'5 to 13 Years': 403658,
'14 to 17 Years': 196918,
'18 to 24 Years': 325110,
'25 to 44 Years': 916955,
'45 to 64 Years': 968967,
'65 Years and Over': 478007,
},
];
const ages = [
'Under 5 Years',
'5 to 13 Years',
'14 to 17 Years',
'18 to 24 Years',
'25 to 44 Years',
'45 to 64 Years',
'65 Years and Over',
];
const dv = new DataView();
dv.source(data)
.transform({
type: 'fold',
fields: ages,
key: 'age',
value: 'population',
retains: ['State'],
})
.transform({
type: 'map',
callback: (obj) => {
const key = obj.age;
let type;
if (key === 'Under 5 Years' || key === '5 to 13 Years' || key === '14 to 17 Years') {
type = 'a';
} else if (key === '18 to 24 Years') {
type = 'b';
} else if (key === '25 to 44 Years') {
type = 'c';
} else {
type = 'd';
}
obj.type = type;
return obj;
},
});
const colorMap = {
'Under 5 Years': '#E3F4BF',
'5 to 13 Years': '#BEF7C8',
'14 to 17 Years': '#86E6C8',
'18 to 24 Years': '#36CFC9',
'25 to 44 Years': '#209BDD',
'45 to 64 Years': '#1581E6',
'65 Years and Over': '#0860BF',
};
const chart = new Chart({
container: 'container',
autoFit: true,
height: 500,
});
chart.coordinate('polar', {
innerRadius: 0.5,
});
chart.data(dv.rows);
chart.scale({
population: {
tickInterval: 5000000,
nice: true,
},
});
chart.axis('population', {
label: {
formatter: (val) => {
return +val / 1000000 + 'M';
},
},
line: null
});
chart.axis('State', {
tickLine: null,
grid: {
alignTick: false,
line: {
style: {
stroke: '#BFBFBF',
lineWidth: 1,
lineDash: [3, 3],
}
}
}
});
chart.legend({
position: 'right',
});
chart.tooltip({
showMarkers: false,
shared: true,
});
chart
.interval()
.position('State*population')
.color('age', (age) => colorMap[age])
.tooltip('age*population', (age, population) => {
return {
name: age,
value: population,
};
})
.adjust([
{
type: 'dodge',
dodgeBy: 'type', // 按照 type 字段进行分组
marginRatio: 1, // 分组中各个柱子之间不留空隙
},
{
type: 'stack',
},
]);
chart.interaction('active-region');
chart.render();
| antvis/g2 | examples/column/dodge-stack/demo/circular-stacked.ts | TypeScript | mit | 3,914 |
#include "VulkanDebug.h"
#include <windows.h>
#include <math.h>
#include <stdlib.h>
#include <string>
#include <cstring>
#include <fstream>
#include <assert.h>
#include <stdio.h>
#include <vector>
#include <fcntl.h>
#include <io.h>
#include <iostream>
#include <vulkan.h>
namespace VKDebug
{
int validationLayerCount = 1;
const char *validationLayerNames[] =
{
// This is a meta layer that enables all of the standard
// validation layers in the correct order :
// threading, parameter_validation, device_limits, object_tracker, image, core_validation, swapchain, and unique_objects
"VK_LAYER_LUNARG_standard_validation"
};
PFN_vkCreateDebugReportCallbackEXT CreateDebugReportCallback;
PFN_vkDestroyDebugReportCallbackEXT DestroyDebugReportCallback;
PFN_vkDebugReportMessageEXT dbgBreakCallback;
VkDebugReportCallbackEXT msgCallback;
VkBool32 MessageCallback(
VkDebugReportFlagsEXT flags,
VkDebugReportObjectTypeEXT objType,
uint64_t srcObject,
size_t location,
int32_t msgCode,
const char* pLayerPrefix,
const char* pMsg,
void* pUserData)
{
char *message = (char *)malloc(strlen(pMsg) + 100);
assert(message);
if (flags & VK_DEBUG_REPORT_ERROR_BIT_EXT)
{
std::cout << "ERROR: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n";
}
else
if (flags & VK_DEBUG_REPORT_WARNING_BIT_EXT)
{
// Uncomment to see warnings
std::cout << "WARNING: " << "[" << pLayerPrefix << "] Code " << msgCode << " : " << pMsg << "\n";
}
else
{
return false;
}
fflush(stdout);
free(message);
return false;
}
void SetupDebugging(VkInstance instance, VkDebugReportFlagsEXT flags, VkDebugReportCallbackEXT callBack)
{
CreateDebugReportCallback = (PFN_vkCreateDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugReportCallbackEXT");
DestroyDebugReportCallback = (PFN_vkDestroyDebugReportCallbackEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugReportCallbackEXT");
dbgBreakCallback = (PFN_vkDebugReportMessageEXT)vkGetInstanceProcAddr(instance, "vkDebugReportMessageEXT");
VkDebugReportCallbackCreateInfoEXT dbgCreateInfo = {};
dbgCreateInfo.sType = VK_STRUCTURE_TYPE_DEBUG_REPORT_CREATE_INFO_EXT;
dbgCreateInfo.pfnCallback = (PFN_vkDebugReportCallbackEXT)MessageCallback;
dbgCreateInfo.flags = flags;
VkResult err = CreateDebugReportCallback(
instance,
&dbgCreateInfo,
nullptr,
(callBack != nullptr) ? &callBack : &msgCallback);
assert(!err);
}
void freeDebugCallback(VkInstance instance)
{
if (msgCallback != VK_NULL_HANDLE)
{
DestroyDebugReportCallback(instance, msgCallback, nullptr);
}
}
/*PFN_vkDebugMarkerSetObjectNameEXT DebugMarkerSetObjectName = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerBeginEXT CmdDebugMarkerBegin = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerEndEXT CmdDebugMarkerEnd = VK_NULL_HANDLE;
PFN_vkCmdDebugMarkerInsertEXT CmdDebugMarkerInsert = VK_NULL_HANDLE;
// Set up the debug marker function pointers
void SetupDebugMarkers(VkDevice device)
{
DebugMarkerSetObjectName = (PFN_vkDebugMarkerSetObjectNameEXT)vkGetDeviceProcAddr(device, "vkDebugMarkerSetObjectNameEXT");
CmdDebugMarkerBegin = (PFN_vkCmdDebugMarkerBeginEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerBeginEXT");
CmdDebugMarkerEnd = (PFN_vkCmdDebugMarkerEndEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerEndEXT");
CmdDebugMarkerInsert = (PFN_vkCmdDebugMarkerInsertEXT)vkGetDeviceProcAddr(device, "vkCmdDebugMarkerInsertEXT");
}*/
} | yunyinghu/CVCT_Vulkan | source/VulkanDebug.cpp | C++ | mit | 3,485 |
<?php
use ElasticSearcher\Parsers\FragmentParser;
use ElasticSearcher\Fragments\Queries\TermQuery;
use ElasticSearcher\Fragments\Analyzers\StandardAnalyzer;
use ElasticSearcher\Dummy\Fragments\Filters\IDFilter;
class FragmentParserTest extends ElasticSearcherTestCase
{
public function testParsingRootLevel()
{
$parser = new FragmentParser();
$body = [
'query' => new TermQuery('name', 'John'),
];
$expectedBody = [
'query' => [
'term' => [
'name' => 'John',
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingChildLevel()
{
$parser = new FragmentParser();
$body = [
'query' => [
'bool' => [
'and' => [
new TermQuery('name', 'John'),
new TermQuery('category', 'authors'),
]
]
]
];
$expectedBody = [
'query' => [
'bool' => [
'and' => [
[
'term' => [
'name' => 'John'
]
],
[
'term' => [
'category' => 'authors'
]
],
]
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingNestedFragments()
{
$parser = new FragmentParser();
$body = [
'query' => [
'bool' => [
'and' => [
new TermQuery('name', new TermQuery('category', 'authors')),
]
]
]
];
$expectedBody = [
'query' => [
'bool' => [
'and' => [
[
'term' => [
'name' => [
'term' => [
'category' => 'authors'
]
]
]
],
]
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingAndMergingWithParent()
{
$parser = new FragmentParser();
$body = [
'settings' => [
new StandardAnalyzer('myAnalyzer')
]
];
$expectedBody = [
'settings' => [
'myAnalyzer' => [
'type' => 'standard'
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingAndMergingMultipleFragmentsWithParent()
{
$parser = new FragmentParser();
$body = [
'settings' => [
new StandardAnalyzer('myAnalyzer1'),
new StandardAnalyzer('myAnalyzer2'),
new StandardAnalyzer('myAnalyzer3'),
]
];
$expectedBody = [
'settings' => [
'myAnalyzer1' => [
'type' => 'standard'
],
'myAnalyzer2' => [
'type' => 'standard'
],
'myAnalyzer3' => [
'type' => 'standard'
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
public function testParsingCustomFragments()
{
$parser = new FragmentParser();
$body = [
'query' => [
new IDFilter(123),
]
];
$expectedBody = [
'query' => [
[
'term' => [
'id' => 123
]
]
]
];
$this->assertEquals($expectedBody, $parser->parse($body));
}
}
| madewithlove/elasticsearcher | tests/Parsers/FragmentParserTest.php | PHP | mit | 2,850 |
using System.Data;
using System.Net;
using OhioTrackStats.API.ServiceModel;
using OhioTrackStats.API.ServiceModel.Types;
using ServiceStack;
using ServiceStack.OrmLite;
namespace OhioTrackStats.API.ServiceInterface
{
public class EventService : Service
{
public IAutoQueryDb AutoQuery { get; set; }
public object Get(QueryEvents query)
{
return AutoQuery.Execute(query, AutoQuery.CreateQuery(query, this.Request));
}
public object Delete(DeleteEvent request)
{
Db.DeleteById<Event>(request.Id);
return new HttpResult(HttpStatusCode.OK);
}
public object Post(CreateEvent request)
{
Db.Insert(request.Event);
return new HttpResult(HttpStatusCode.Created);
}
public static void SeedData(IDbConnection db)
{
db.Insert(new Event { Name = "100M", ShortName = "100m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false});
db.Insert(new Event { Name = "200M", ShortName = "200m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "400M", ShortName = "400m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "800M", ShortName = "800m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "1600M", ShortName = "1600m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "3200M", ShortName = "3200m", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "100M Hurdles", ShortName = "100m-hurdles", IsMale = false, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "110M Hurdles", ShortName = "110m-hurdles", IsMale = true, IsFemale = false, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "300M Hurdles", ShortName = "300m-hurdles", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = false });
db.Insert(new Event { Name = "4x100M Relay", ShortName = "4x100m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "4x200M Relay", ShortName = "4x200m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "4x400M Relay", ShortName = "4x400m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "4x800M Relay", ShortName = "4x800m-relay", IsMale = true, IsFemale = true, IsRunning = true, IsField = false, IsRelay = true });
db.Insert(new Event { Name = "Shot Put", ShortName = "shot-put", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "Discus", ShortName = "discus", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "Long Jump", ShortName = "long-jump", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "High Jump", ShortName = "high-jump", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
db.Insert(new Event { Name = "Pole Vault", ShortName = "pole-vault", IsMale = true, IsFemale = true, IsRunning = false, IsField = true, IsRelay = false });
}
}
}
| OhioTrackStats/OhioTrackStats.API | src/OhioTrackStats.API.ServiceInterface/EventService.cs | C# | mit | 3,859 |
require 'open3'
Given(/^that a queue parent directory exists$/) do
td = TestDir.new('features/fixtures/setup/queue')
td.nuke
td.create_root
end
When(/^I setup the queue$/) do
_, e, s = Open3.capture3('rake git_transactor:setup:queue QUEUE_ROOT=features/fixtures/setup/queue/work')
raise RuntimeError.new(e)unless s == 0
end
Then(/^I should be able to use the queue$/) do
GitTransactor::QueueManager.open('features/fixtures/setup/queue/work')
end
| NYULibraries/git_transactor | features/step_definitions/setup_queue_steps.rb | Ruby | mit | 461 |
class CreateRooms < ActiveRecord::Migration[5.0]
def change
create_table :rooms do |t|
t.string :code
t.string :name
t.integer :capacity
t.boolean :active
t.integer :time_grid_id
t.references :department, foreign_key: true
t.belongs_to :building, index: true
t.timestamps
end
end
end
| fga-gpp-mds/2017.1-SIGS | SIGS/db/migrate/20170414134440_create_rooms.rb | Ruby | mit | 345 |
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
var token = readCookie("_xsrf")
// console.log("ajaxPrefilter: _xsrf = ", token)
jqXHR.setRequestHeader('X-Csrftoken', token);
});
//auth_signup.html
//注册发送验证码
$( "#get-authcode-bt" ).bind("click", function() {
// event.preventDefault();
// $(this).attr('disabled', 'true')
$(this).unbind("click");
var email = $("#email")[0].value
var query_string = `mutation MyMutation {
auth {
signup_identifier(type:"email", data: "${email}") {
id
}
}
}`
$.ajax({
url: "/api/graphql",
method: "POST",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({"query": query_string }),
contentType: "application/json; charset=utf-8",
dataType: "json",
// dataType:'jsonp',
success: function(data){
// console.log("data",data.errors)
if (data.errors) {
var s = data.errors.map(function(v)
{
$(".error-append").append('<span class="error-message">'+v.message +'</span>');
})
// alert(s)
} else {
$("#auth_key")[0].value = data.data.auth.signup_identifier.id
// console.log('22222=>',$("#auth_key")[0].value)
}
},
failure: function(errMsg) {
alert(errMsg);
}
});
})
//忘记密码发送验证码
$( "#forgetpassord-authcode-bt" ).bind("click", function() {
// event.preventDefault();
// $(this).attr('disabled', 'true')
$(this).unbind("click");
var email = $("#email")[0].value
var query_string = `mutation MyMutation {
auth {
forget_password_identifier(type:"email", data: "${email}") {
id
}
}
}`
$.ajax({
url: "/api/graphql",
method: "POST",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({"query": query_string }),
contentType: "application/json; charset=utf-8",
dataType: "json",
// dataType:'jsonp',
success: function(data){
// console.log('1111=>',data)
if (data.errors) {
var s = data.errors.map(function(v)
{
$(".error-append").append('<span class="error-message">'+v.message +'</span>');
})
// alert(s)
} else {
$("#auth_key")[0].value = data.data.auth.forget_password_identifier.id
}
// console.log('22222=>',$("#auth_key")[0].value)
},
failure: function(errMsg) {
alert(errMsg);
}
});
})
$('input').on("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
});
window.blog_menu_init = function blog_menu_init() {
// var $selector = $(".submenu a[href='" + window.location.pathname + "']")
// console.log($selector)
if (window.location.pathname.startsWith("/console/blog")) {
var p_url = window.location.pathname.split("/").slice(0,4).join('/')
var selector = ".submenu a[href='" + p_url + "']"
$(selector).parent().addClass("active")
} else {
var selector = ".submenu a[href='" + window.location.pathname + "']"
$(selector).parent().addClass("active")
}
// $selector.parent().addClass("active")
var s=window.location.pathname
if (!s.startsWith("/console/account")) {
$(selector).closest(".panel-default").find(".panel-title a").first().click()
}
// var $s = $selector.closest(".panel-default").find(".panel-title a").first()
// $s.click()
// $s.removeClass("collapsed")
// console.log($(selector).closest(".panel-default").find(".panel-title a").text())
// console.log($(selector).closest(".panel-default").find("a.collapsed").first())
}
//创建目录
import { success_catalog_change, create_catalog, success_blog_catalog_change } from './catalog'
window.create_catalog = create_catalog
window.success_catalog_change = success_catalog_change
window.success_blog_catalog_change = success_blog_catalog_change
// Tag操作
import { success_tag_change, create_tag, blog_add_tag, set_hidden_input, success_blog_tag_change, delete_tag } from './tag'
window.create_tag = create_tag
window.success_tag_change = success_tag_change
window.success_blog_tag_change = success_blog_tag_change
window.blog_add_tag = blog_add_tag
window.set_hidden_input = set_hidden_input
window.delete_tag = delete_tag
| nuanri/hiblog | src/js-dev/src/blog-home.js | JavaScript | mit | 5,466 |
import {CommonGraphAPI} from '../common/CommonGraphAPI'
import {CommonGraphBuilders} from '../common/CommonGraphBuilders'
import {UndirectedGraphAPI} from './UndirectedGraphAPI'
import {AdjacencyListGraph} from './AdjacencyListGraph'
import {BipartiteBFS} from './BipartiteBFS'
/**
* Factory functions for creating instances of undirected graphs' ADTs.
*/
export namespace UndirectedGraphBuilders {
import Graph = UndirectedGraphAPI.Graph
import Bipartite = UndirectedGraphAPI.Bipartite
import VerticesPair = CommonGraphAPI.VerticesPair
import vertex = CommonGraphBuilders.vertex
/**
* Creates new instance of {@link UndirectedGraphAPI.Graph}.
* @return {UndirectedGraphAPI.Graph<V>} new instance of <tt>Graph</tt>.
*/
export function graph<V>(): Graph<V> {
return new AdjacencyListGraph([])
}
/**
* Creates new instance of <tt>Graph</tt> from given keys of its edges. It means that for every pair like
* ['key1', 'key2'] it creates pair of vertices [V1('key1', 'key1'), V2('key2', 'key2'] and adds this pair of
* vertices as the edge (V1-V2).
* @param {[string , string][]} edges pairs of keys of vertices that describe edges.
* @return {UndirectedGraphAPI.Graph<string>} new graph with given edges.
*/
export function graphFromEdgesKeys(edges: [string, string][]): Graph<string> {
return edges.reduce((acc: Graph<string>, e) => acc.addEdge(vertex(e[0], e[0]), vertex(e[1], e[1])),
new AdjacencyListGraph<string>())
}
/**
* Creates new <tt>Graph</tt> with given edges.
* @param {CommonGraphAPI.VerticesPair<V>[]} edges edges to add into new graph.
* @return {UndirectedGraphAPI.Graph<V>} new <tt>Graph</tt> with given edges.
*/
export function graphFromEdges<V>(edges: VerticesPair<V>[]): Graph<V> {
return new AdjacencyListGraph(edges)
}
/**
* Creates an instance of <code>Bipartite</code> for given graph.
* @param {UndirectedGraphAPI.Graph<V>} g graph to apply the algorithm.
* @return {UndirectedGraphAPI.Bipartite<V>} implementation of <tt>Bipartite</tt>.
*/
export function bipartite<V>(g: Graph<V>): Bipartite<V> {
return new BipartiteBFS(g)
}
}
| prishedko/algorithms-ts | src/graphs/undirected/UndirectedGraphBuilders.ts | TypeScript | mit | 2,254 |
<?php
function _esc($n) {
$ESC = chr(27);
return $ESC . "[{$n}m";
}
$RESET_ALL = _esc(0);
$BRIGHT = _esc(1);
$DIM = _esc(2);
$NORMAL = _esc(2);
$BLACK = _esc(30);
$RED = _esc(31);
$GREEN = _esc(32);
$YELLOW = _esc(33);
$BLUE = _esc(34);
$MAGENTA = _esc(35);
$CYAN = _esc(36);
$WHITE = _esc(37);
$RESET = _esc(39);
$BG_BLACK = _esc(40);
$BG_RED = _esc(41);
$BG_GREEN = _esc(42);
$BG_YELLOW = _esc(43);
$BG_BLUE = _esc(44);
$BG_MAGENTA = _esc(45);
$BG_CYAN = _esc(46);
$BG_WHITE = _esc(47);
$BG_RESET = _esc(49); | basp/lily | style.php | PHP | mit | 603 |
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
| -------------------------------------------------------------------------
| URI ROUTING
| -------------------------------------------------------------------------
| This file lets you re-map URI requests to specific controller functions.
|
| Typically there is a one-to-one relationship between a URL string
| and its corresponding controller class/method. The segments in a
| URL normally follow this pattern:
|
| example.com/class/method/id/
|
| In some instances, however, you may want to remap this relationship
| so that a different class/function is called than the one
| corresponding to the URL.
|
| Please see the user guide for complete details:
|
| https://codeigniter.com/user_guide/general/routing.html
|
| -------------------------------------------------------------------------
| RESERVED ROUTES
| -------------------------------------------------------------------------
|
| There are three reserved routes:
|
| $route['default_controller'] = 'welcome';
|
| This route indicates which controller class should be loaded if the
| URI contains no data. In the above example, the "welcome" class
| would be loaded.
|
| $route['404_override'] = 'errors/page_missing';
|
| This route will tell the Router which controller/method to use if those
| provided in the URL cannot be matched to a valid route.
|
| $route['translate_uri_dashes'] = FALSE;
|
| This is not exactly a route, but allows you to automatically route
| controller and method names that contain dashes. '-' isn't a valid
| class or method name character, so it requires translation.
| When you set this option to TRUE, it will replace ALL dashes in the
| controller and method URI segments.
|
| Examples: my-controller/index -> my_controller/index
| my-controller/my-method -> my_controller/my_method
*/
$route['default_controller'] = 'beranda';
// $route['beranda'] = 'beranda';
$route['daftar'] = 'daftar';
// $route['tesc/mulai/(:any)'] = 'tesc/mulai/1';
$route['masuk'] = 'masuk';
// $route['404_override'] = '';
//$route['translate_uri_dashes'] = FALSE;
| 0x4164/olqt-ci | application/config/routes.php | PHP | mit | 2,114 |
namespace OmniXaml
{
public class DefaultInstanceLifeCycleListener : IInstanceLifeCycleListener
{
public void OnBegin(object instance)
{
}
public void OnAfterProperties(object instance)
{
}
public void OnAssociatedToParent(object instance)
{
}
public void OnEnd(object instance)
{
}
}
} | Perspex/OmniXAML | Source/OmniXaml/DefaultInstanceLifeCycleListener.cs | C# | mit | 397 |
<?php
/**
Using names.txt, a 46K text file containing over five-thousand first names, begin by
sorting it into alphabetical order. Then working out the alphabetical value for each name,
multiply this value by its alphabetical position in the list to obtain a name score.
For example, when the list is sorted into alphabetical order, COLIN, which is worth
3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So COLIN would obtain a score of
938 * 53 = 49714.
What is the total of all the name scores in the file?
**/
$alpha_values = array(
"A" => 1,
"B" => 2,
"C" => 3,
"D" => 4,
"E" => 5,
"F" => 6,
"G" => 7,
"H" => 8,
"I" => 9,
"J" => 10,
"K" => 11,
"L" => 12,
"M" => 13,
"N" => 14,
"O" => 15,
"P" => 16,
"Q" => 17,
"R" => 18,
"S" => 19,
"T" => 20,
"U" => 21,
"V" => 22,
"W" => 23,
"X" => 24,
"Y" => 25,
"Z" => 26,
);
$file_name = "names.txt";
$contents = file_get_contents($file_name);
$contents = str_replace("\"", "", $contents);
$contents = str_replace(" ", "", $contents);
$contents = str_replace("\n", "", $contents);
$names = explode(",", $contents);
sort($names, SORT_STRING);
$names = &array_unique($names);
$total = 0;
$sorted_index = 1;
foreach($names as $name) {
$rank = 0;
for($c = 0; $c < strlen($name); $c++) {
$rank += $alpha_values[$name[$c]];
}
$rank *= $sorted_index;
$total += $rank;
$sorted_index++;
}
print $total;
?>
| jbaldwin/project_euler | p022/p22.php | PHP | mit | 1,393 |
from setuptools import setup
readme = open('README.md').read()
setup(name='HDFserver',
version='0.1',
author='Yohannes Libanos',
license='MIT',
description='REST service for HDF5 data stores',
py_modules=['HDFserver'],
long_description=readme,) | yohannesHL/HDFserver | setup.py | Python | mit | 281 |
import copy
class ArtifactEmulator:
def __init__(self, random_str, ctx, base_url):
self._random_str = random_str
self._ctx = ctx
self._artifacts = {}
self._artifacts_by_id = {}
self._files = {}
self._base_url = base_url
self._portfolio_links = {}
def create(self, variables):
collection_name = variables["artifactCollectionNames"][0]
state = "PENDING"
aliases = []
latest = None
art_id = variables.get("digest", "")
# Find most recent artifact
versions = self._artifacts.get(collection_name)
if versions:
last_version = versions[-1]
latest = {"id": last_version["digest"], "versionIndex": len(versions) - 1}
art_seq = {"id": art_id, "latestArtifact": latest}
aliases.append(dict(artifactCollectionName=collection_name, alias="latest"))
base_url = self._base_url
direct_url = f"{base_url}/storage?file=wandb_manifest.json"
art_data = {
"id": art_id,
"digest": "abc123",
"state": state,
"labels": [],
"aliases": aliases,
"artifactSequence": art_seq,
"currentManifest": dict(file=dict(directUrl=direct_url)),
}
response = {"data": {"createArtifact": {"artifact": copy.deepcopy(art_data)}}}
# save in artifact emu object
art_seq["name"] = collection_name
art_data["artifactSequence"] = art_seq
art_data["state"] = "COMMITTED"
art_type = variables.get("artifactTypeName")
if art_type:
art_data["artifactType"] = {"id": 1, "name": art_type}
art_save = copy.deepcopy(art_data)
self._artifacts.setdefault(collection_name, []).append(art_save)
self._artifacts_by_id[art_id] = art_save
# save in context
self._ctx["artifacts_created"].setdefault(collection_name, {})
self._ctx["artifacts_created"][collection_name].setdefault("num", 0)
self._ctx["artifacts_created"][collection_name]["num"] += 1
if art_type:
self._ctx["artifacts_created"][collection_name]["type"] = art_type
return response
def link(self, variables):
pfolio_name = variables.get("artifactPortfolioName")
artifact_id = variables.get("artifactID") or variables.get("clientID")
if not pfolio_name or not artifact_id:
raise ValueError(
"query variables must contain artifactPortfolioName and either artifactID or clientID"
)
aliases = variables.get("aliases")
# We automatically create a portfolio for the user if we can't find the one given.
links = self._portfolio_links.setdefault(pfolio_name, [])
if not any(map(lambda x: x["id"] == artifact_id, links)):
art = {"id": artifact_id, "aliases": [a["alias"] for a in aliases]}
links.append(art)
self._ctx["portfolio_links"].setdefault(pfolio_name, {})
num = len(links)
self._ctx["portfolio_links"][pfolio_name]["num"] = num
response = {"data": {"linkArtifact": {"versionIndex": num - 1}}}
return response
def create_files(self, variables):
base_url = self._base_url
response = {
"data": {
"createArtifactFiles": {
"files": {
"edges": [
{
"node": {
"id": idx,
"name": af["name"],
"displayName": af["name"],
"uploadUrl": f"{base_url}/storage?file={af['name']}&id={af['artifactID']}",
"uploadHeaders": [],
"artifact": {"id": af["artifactID"]},
},
}
for idx, af in enumerate(variables["artifactFiles"])
],
},
},
},
}
return response
def query(self, variables, query=None):
public_api_query_str = "query Artifact($id: ID!) {"
public_api_query_str2 = "query ArtifactWithCurrentManifest($id: ID!) {"
art_id = variables.get("id")
art_name = variables.get("name")
assert art_id or art_name
is_public_api_query = query and (
query.startswith(public_api_query_str)
or query.startswith(public_api_query_str2)
)
if art_name:
collection_name, version = art_name.split(":", 1)
artifact = None
artifacts = self._artifacts.get(collection_name)
if artifacts:
if version == "latest":
version_num = len(artifacts)
else:
assert version.startswith("v")
version_num = int(version[1:])
artifact = artifacts[version_num - 1]
# TODO: add alias info?
elif art_id:
artifact = self._artifacts_by_id[art_id]
if is_public_api_query:
response = {"data": {"artifact": artifact}}
else:
response = {"data": {"project": {"artifact": artifact}}}
return response
def file(self, entity, digest):
# TODO?
return "ARTIFACT %s" % digest, 200
def storage(self, request):
fname = request.args.get("file")
if request.method == "PUT":
data = request.get_data(as_text=True)
self._files.setdefault(fname, "")
# TODO: extend? instead of overwrite, possible to differentiate wandb_manifest.json artifactid?
self._files[fname] = data
data = ""
if request.method == "GET":
data = self._files[fname]
return data, 200
| wandb/client | tests/utils/artifact_emu.py | Python | mit | 5,987 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
public class AnimalsTesting
{
public static Random rnd = new Random();
public static void Main()
{
TestCreatures();
Cat[] catArr = FillCatArr();
Dog[] dogArr = FillDogArr();
Frog[] frogArr = FillFrogArr();
Kitten[] kitArr = FillKittenArr();
Tomcat[] tomArr = FillTomArr();
Animal[] animals = new Animal[] { new Cat("cat", 2, true), new Dog("dog", 2, true), new Frog("frog", 2, true) };
Console.WriteLine(animals[1]);
decimal averageAgeCats = Animal.AverageAge(catArr);
decimal averageAgeDogs = Animal.AverageAge(dogArr);
decimal averageAgeFrogs = Animal.AverageAge(frogArr);
decimal averageAgeKittens = Animal.AverageAge(kitArr);
decimal averageAgeTomcats = Animal.AverageAge(tomArr);
Console.WriteLine("---------- Average ages ----------");
Console.WriteLine("Cats " + averageAgeCats);
Console.WriteLine("Dogs " + averageAgeDogs);
Console.WriteLine("Frogs " + averageAgeFrogs);
Console.WriteLine("Kittens " + averageAgeKittens);
Console.WriteLine("Tomcats " + averageAgeTomcats);
}
public static Tomcat[] FillTomArr()
{
var tomArr = new Tomcat[rnd.Next(5, 21)];
for (int i = 0; i < tomArr.Length; i++)
{
tomArr[i] = new Tomcat(GetRandomName(), rnd.Next(1, 16));
}
return tomArr;
}
public static Kitten[] FillKittenArr()
{
var kitArr = new Kitten[rnd.Next(5, 21)];
for (int i = 0; i < kitArr.Length; i++)
{
kitArr[i] = new Kitten(GetRandomName(), rnd.Next(1, 16));
}
return kitArr;
}
public static Frog[] FillFrogArr()
{
var frogArr = new Frog[rnd.Next(5, 21)];
for (int i = 0; i < frogArr.Length; i++)
{
frogArr[i] = new Frog(GetRandomName(), rnd.Next(1, 16), rnd.Next(1, 3) == 1 ? true : false);
}
return frogArr;
}
public static Dog[] FillDogArr()
{
var dogArr = new Dog[rnd.Next(5, 21)];
for (int i = 0; i < dogArr.Length; i++)
{
dogArr[i] = new Dog(GetRandomName(), rnd.Next(1, 16), rnd.Next(1, 3) == 1 ? true : false);
}
return dogArr;
}
public static Cat[] FillCatArr()
{
var catArr = new Cat[rnd.Next(5, 21)];
for (int i = 0; i < catArr.Length; i++)
{
catArr[i] = new Cat(GetRandomName(), rnd.Next(1, 16), rnd.Next(1, 3) == 1 ? true : false);
}
return catArr;
}
public static void TestCreatures()
{
Dog charlie = new Dog("Charlie", 4, true);
Console.WriteLine(charlie);
charlie.ProduceSound();
Console.WriteLine();
Frog quackster = new Frog("Rab", 1, false);
Console.WriteLine(quackster);
quackster.ProduceSound();
Console.WriteLine();
Cat miew = new Cat("Dangleton", 3, false);
Console.WriteLine(miew);
miew.ProduceSound();
Console.WriteLine();
Kitten kitty = new Kitten("KittyCat", 3);
Console.WriteLine(kitty);
kitty.ProduceSound();
Console.WriteLine();
Tomcat tom = new Tomcat("Tom", 2);
Console.WriteLine(tom);
tom.ProduceSound();
}
public static string GetRandomName()
{
StringBuilder name = new StringBuilder();
name.Append((char)rnd.Next(65, 91));
for (int i = 0; i < rnd.Next(2, 6); i++)
{
name.Append((char)rnd.Next(97, 123));
}
return name.ToString();
}
}
| dzhenko/TelerikAcademy | OOP/OOP-4-Object-Oriented-Programming-Principles-Part1/03. Animals/AnimalTesting.cs | C# | mit | 3,715 |
import { Token } from './token';
// -------------------------------------------------------------------------------------------------
// FIXTURES
// -------------------------------------------------------------------------------------------------
const EXAMPLE_ENCODED_TOKEN = 'eyJhbGciOiJSUzI1NiJ9.eyJlbWFpbCI6ImFiZWxAY29va2luZ2ZveC5ubCIsImV4c' +
'CI6MTQ5MTgyMDE0NCwiaWF0IjoxNDkxODE2NTQ0fQ.h9KHlT3W24GRunBMQfK6E7vf6exjMXbW8EejEdMlMOvzb48NmU-R' +
'k717DhPNVXlSIPFi8bJf-jXvoe82pe3_U7x2U_jTBCAGESpkidr1fQlFJpBgRkY4axm32khef8_4a8LQdqwvm4hVe2gnEM' +
'gbXpQFLLCafhtRo16AzIQ1SsvQDCccRWmZ4sG9wUY2qiFr_rRWkopB46OLNhX9pBSuvELe9H7Jo68TEMQU7H2uO3TKPyOt' +
'FqiRALCwRhl371h7ygqI9atrIt1Wmw08Mf_pS4pxWA_z2rZJWu6wgDe3HFNTYJwmr-bh4Awyz2WSXZPvcd1dqkR9jufcvX' +
'c8ZVtv0jvtjiHAR_EHpWKyv012acWlXCN0t7Cb6z1DqkabN0RxMbABOMG5AKcVzQ_Sq80-AJgE7ct2904sgFi7yGMaTjV4' +
'Mpsh5LrJDJ3GZmKTW-aANpA7lgdPgX0V8mxGcO6hpa71pFjrMXZlJtWKi1kz7iIrdM84iwiKfHnnLws_D-jYqtZShzvYbL' +
'dxdG6MgEYQLhrKzyuRVL4x_U4JysH0Px5q09Vo-6W551E9IizZnVTrR6OlDEg5QzA0FKAu4KKFrDSwpQN6KDgAPyNOGd0R' +
'HxBOgkb8sN4lNmcgdLAezv0yxmJVrbymFhJc0p70Nlcf7sZt4QQXfufzHgmr-yptCeA';
const EXAMPLE_ENCODED_HEADER = btoa(JSON.stringify({ 'alg': 'RS256' }));
const EXAMPLE_SIGNATURE = '7lgdPgX0V8mxGcO6hpa71pFjrMXZlJtWKi1kz7iIrdM84iwiKfHnnLws_D-jYqtZShzvYbL';
const EXAMPLE_EXPIRATION_MILLISECONDS = 60 * 60 * 1000; // 1 hour
const EXAMPLE_PAYLOAD = {
'exp': 1491820144,
'iat': 1491816544
};
/**
* Mock encoded token with provided timestamp, which is included in payload.
* @param issuedAt When the token was issued by the server.
* @returns string Encoded token.
*/
function mockEncodedToken(issuedAt: Date): string {
const iatMillis = issuedAt.getTime();
const expMillis = iatMillis + EXAMPLE_EXPIRATION_MILLISECONDS;
const payload = {
exp: Math.round(expMillis / 1000),
iat: Math.round(iatMillis / 1000)
};
const encodedPayloadRaw: string = btoa(JSON.stringify(payload));
const encodedPayload = encodedPayloadRaw.substring(0, encodedPayloadRaw.indexOf('='));
return EXAMPLE_ENCODED_HEADER + '.' + encodedPayload + '.' + EXAMPLE_SIGNATURE;
}
// -------------------------------------------------------------------------------------------------
// TESTS
// -------------------------------------------------------------------------------------------------
describe('Token', () => {
it('should throw when provided value is empty', () => {
expect(() => new Token(null)).toThrow();
});
it('should throw when provided value has unexpected format', () => {
expect(() => new Token('foo-bar')).toThrow();
});
it('should not throw when provided value is JWT encoded token', () => {
expect(() => new Token(EXAMPLE_ENCODED_TOKEN)).not.toThrow();
});
it('should be valid when expected', () => {
const token = new Token(mockEncodedToken(new Date()));
expect(token.isValid()).toEqual(true);
});
it('should not be valid when expired', () => {
// create expired date for mock token
const expired = new Date();
expired.setMilliseconds(expired.getMilliseconds() - EXAMPLE_EXPIRATION_MILLISECONDS - 1000);
const token = new Token(mockEncodedToken(expired));
expect(token.isValid()).toEqual(false);
});
});
| cookingfox/stibble-api-client-angular | src/app/stibble-api-client/token/token.spec.ts | TypeScript | mit | 3,236 |
package ast;
import java.util.*;
/**
* @author GAO RISHENG A0101891L
* This class is mainly for construction of AST nodes representing a constant array in C/Java/Python
* Program and its respective syntax generation
*
*/
public class ASTExpressionUnitLiteralArray extends ASTExpressionUnitLiteral{
private static final String NODE_TYPE = "Array";
private ArrayList<ASTExpression> entries;
private int size;
public ASTExpressionUnitLiteralArray(){
super();
initialize();
}
public void addValue(String value){
ASTExpressionUnitLiteral temp = new ASTExpressionUnitLiteral(value);
this.entries.add(temp);
temp.parent = this;
}
public void addValue(ASTExpression exp){
this.entries.add(exp);
exp.parent = this;
}
private void initialize() {
this.entries = new ArrayList<ASTExpression>();
this.size = entries.size();
}
public String typeof(){
return super.typeof()+"->"+NODE_TYPE;
}
public String toSyntax(int programmingLanguageSyntax) throws Exception{
switch(programmingLanguageSyntax){
case INDEX_C:
case INDEX_JAVA:
{
this.result = "";
this.result += "{";
int index = 0;
for(;index<size-1;index++){
this.result+= this.entries.get(index).toSyntax();
this.result+= ", ";
}
this.result+= this.entries.get(index).toSyntax();
this.result += "}";
return this.result;
}
case INDEX_PYTHON:
{
this.result = "";
this.result += "[";
int index = 0;
for(;index<size-1;index++){
this.result+= this.entries.get(index).toSyntax();
this.result+= ", ";
}
this.result+= this.entries.get(index).toSyntax();
this.result += "]";
return this.result;
}
default:
throw new Exception("Not supported Programming Language.");
}
}
}
| MartinGaoR/talk-to-code | src/ast/ASTExpressionUnitLiteralArray.java | Java | mit | 1,741 |
import React from 'react/addons';
import BaseComponent from './BaseComponent';
import Note from './Note';
/*
* @class Note
* @extends React.Component
*/
class Board extends BaseComponent {
constructor(props) {
super(props);
this.state = {
notes: []
}
this._bind(
'update',
'add',
'remove',
'nextId',
'eachNote'
);
}
nextId () {
this.uniqueId = this.uniqueId || 0;
return this.uniqueId++;
}
componentWillMount () {
var self = this;
if(this.props.count) {
$.getJSON("http://baconipsum.com/api/?type=all-meat&sentences=" +
this.props.count + "&start-with-lorem=1&callback=?", function(results){
results[0].split('. ').forEach(function(sentence){
self.add(sentence.substring(0,40));
});
});
}
}
add (text) {
var arr = this.state.notes;
arr.push({
id: this.nextId(),
note: text
});
this.setState({notes: arr});
}
update (newText, i) {
var arr = this.state.notes;
arr[i].note = newText;
this.setState({notes:arr});
}
remove (i) {
var arr = this.state.notes;
arr.splice(i, 1);
this.setState({notes: arr});
}
eachNote (note, i) {
return (
<Note key={note.id}
index={i}
onChange={this.update}
onRemove={this.remove}
>{note.note}</Note>
);
}
render () {
return (<div className="board">
{this.state.notes.map(this.eachNote)}
<button className="btn btn-sm btn-success glyphicon glyphicon-plus"
onClick={this.add.bind(null, "New Note")}></button>
</div>
);
}
}
// Prop types validation
Board.propTypes = {
//cart: React.PropTypes.object.isRequired,
count: function(props, propName) {
if (typeof props[propName] !== "number"){
return new Error('The count property must be a number');
}
if (props[propName] > 100) {
return new Error("Creating " + props[propName] + " notes is ridiculous");
}
}
};
export default Board;
| carmouche/es6-react-stickynotes | src/app/components/Board.js | JavaScript | mit | 2,320 |
namespace BlizzardAPI.Wow.Item
{
public class ItemSource
{
public int SourceId { get; set; }
public string SourceType { get; set; }
}
}
| EcadryM/BlizzardAPI | BlizzardAPI/BlizzardAPI.Wow/Item/ItemSource.cs | C# | mit | 167 |
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Input Sediaan Baru
</h1>
</section>
<section class="content">
<div class="row">
<!-- left column -->
<div class="col-md-12">
<!-- general form elements -->
<div class="box box-primary">
<div class="box-header with-border">
<h3 class="box-title">Data Master Sediaan</h3>
</div><!-- /.box-header -->
<!-- form start -->
<form role="form" id="form_input" action="<?=base_url()?>Sediaan/Insert" method="post">
<div class="box-body">
<div class="form-group">
<label for="id_sediaan">ID</label>
<input type="text" class="form-control required" id="id_sediaan" name="id_sediaan" placeholder="ID untuk Sediaan Baru">
</div>
<div class="form-group">
<label for="sediaan">Sediaan</label>
<input type="text" class="form-control required" id="nama_sediaan" name="nama_sediaan" placeholder="Masukkan Nama Sediaan">
</div>
<div class="form-group">
<label for="keterangan">Keterangan</label>
<textarea class="form-control required" id="keterangan" name="keterangan" placeholder="Masukkan Keterangan Sediaan"></textarea>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<input type="submit" class="btn btn-primary" value="Submit" />
</div>
</form>
</div><!-- /.box -->
</div> <!-- /.row -->
</section>
</div>
| Quallcode/forkes | application/views/body/master/sediaan/create_dsp.php | PHP | mit | 1,683 |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace HilbertTransformationTests.Data.NetflixReviews
{
public class Probe
{
/// <summary>
/// The key is a movie id, the value, a list of reviewer ids for reviewers whose movie review
/// for the corresponding movie we must guess.
/// </summary>
public Dictionary<int, List<int>> ReviewersByMovie { get; private set; } = new Dictionary<int, List<int>>();
public Probe(string filename)
{
LoadFromFile(filename);
}
/// <summary>
/// Load the probe set from a file.
///
/// Lines that end with a colon contain a movie id. (The colon is removed.)
/// All other lines contain a single reviewer id.
/// </summary>
/// <param name="filename"></param>
private void LoadFromFile(string filename)
{
var lines = File.ReadLines(filename);
List<int> currentMovieReviewList = null;
foreach(var line in lines.Select(s => s.Trim()).Where(s => s.Length > 0))
{
if (line.EndsWith(":"))
{
var currentMovieId = int.Parse(line.Replace(":", ""));
currentMovieReviewList = new List<int>();
ReviewersByMovie[currentMovieId] = currentMovieReviewList;
}
else
{
currentMovieReviewList.Add(int.Parse(line));
}
}
}
}
}
| paulchernoch/HilbertTransformation | HilbertTransformationTests/Data/NetflixReviews/Probe.cs | C# | mit | 1,639 |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package logica;
import javax.swing.ImageIcon;
import bibliothek.gui.dock.common.action.CButton;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
/**
*
* @author dark
*/
public class CargarArchivoArbol extends CButton {
private CodePanel panel;
private Core base;
DefaultMutableTreeNode carpetaRaiz = new DefaultMutableTreeNode("Carpeta");
DefaultTreeModel modelo = new DefaultTreeModel(carpetaRaiz);
private ArrayList<DesArbol> nodos = new ArrayList<>();
public CargarArchivoArbol(CodePanel panel) {
this.panel = panel;
setText("Abrir archivo");
setTooltip("Cargado de archivo");
Image image = null;
try {
File sourceimage = new File("/home/dark/NetBeansProjects/tesis-final/src/data/tutorial/icons/copy.png");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon icon = new ImageIcon(image);
setIcon(icon);
}
public CargarArchivoArbol(Core panel) {
this.base = panel;
setText("Abrir archivo");
setTooltip("Cargado de archivo");
Image image = null;
try {
// File sourceimage = new File("C:\\Users\\eugenio\\Documents\\proyectos\\CoreTesis\\Desarrollo\\Core\\src\\ima\\ico\\copy.png");
File sourceimage = new File("/home/exile/Documentos/github/java/CoreTesis/Desarrollo/Core/src/ima/ico/copy.png");
image = ImageIO.read(sourceimage);
} catch (IOException e) {
e.printStackTrace();
}
ImageIcon icon = new ImageIcon(image);
setIcon(icon);
}
@Override
protected void action() {
//panel.copy();
//create the root node
JFileChooser fc = new JFileChooser();
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
//FileNameExtensionFilter filter = new FileNameExtensionFilter("Archivos", "java");
int res = fc.showOpenDialog(this.getBase());
if (res == JFileChooser.APPROVE_OPTION) {
System.out.println(fc.getSelectedFile().getAbsolutePath());
File dir = new File(fc.getSelectedFile().getAbsolutePath());
String archivos[] = dir.list();
System.err.println(archivos.length);
leerDirectorio(archivos, fc.getSelectedFile().getAbsolutePath(),carpetaRaiz,0);
}
this.getBase().getTree().setModel(modelo);
}
public CodePanel getPanel() {
return panel;
}
public void setPanel(CodePanel panel) {
this.panel = panel;
}
public Core getBase() {
return base;
}
public void setBase(Core base) {
this.base = base;
}
public void leerDirectorio(String[] r, String path,DefaultMutableTreeNode padre,int i) {
for (String f : r) {
if (f.contains(".")) {
String ruta = path + "/" + f;
DefaultMutableTreeNode carpeta = new DefaultMutableTreeNode(f);
getNodos().add(new DesArbol(new File(ruta),f));
modelo.insertNodeInto(carpeta, padre, i++);
} else {
String ruta = path + "/" + f;
System.out.println(ruta);
File dir = new File(ruta);
String archivos[] = dir.list();
DefaultMutableTreeNode carpeta = new DefaultMutableTreeNode(f);
modelo.insertNodeInto(carpeta, padre, i++);
leerDirectorio(archivos, ruta,carpeta,0);
}
}
}
public DefaultMutableTreeNode getCarpetaRaiz() {
return carpetaRaiz;
}
public DefaultTreeModel getModelo() {
return modelo;
}
public ArrayList<DesArbol> getNodos() {
return nodos;
}
public DesArbol getNodo(String nom){
for(DesArbol d : getNodos()){
if(d.getNombre().equals(nom))
return d;
}
return null;
}
public boolean validarExistencia(String ruta){
System.err.println("ruta q llega : "+ruta);
System.out.println("esta es la respuesta: "+ruta.split("\\.").length);
System.out.println();
return ruta.split("\\.").length>0?true:false;
}
public String producirContenido(DesArbol a) {
try {
try {
return this.getCode(a.getFile().getAbsolutePath());
}catch (NullPointerException e){
}
} catch (IOException ex) {
}
return "n/a";
}
public String getCode(String ruta) throws IOException{
InputStream in = new FileInputStream(ruta);
if( in == null ){
return "n/a";
}
if( in != null ){
StringBuilder builder = new StringBuilder();
InputStreamReader reader = new InputStreamReader( in, "UTF-8" );
int next;
while( (next = reader.read()) != -1 ){
if( next == '\t' ){
builder.append( " " );
}
else{
builder.append( (char)next );
}
}
reader.close();
return builder.toString();
}
return "n/a";
}
}
| darkdrei/CoreTesis | Desarrollo/Core/src/logica/CargarArchivoArbol.java | Java | mit | 5,774 |
migration_file = `ls #{RAILS_ROOT}/db/migrate/*create_sic_uk_tables.rb`
if migration_file && migration_file[/[^\d](\d+)_create_sic_uk_tables.rb/]
version = $1
puts `cd #{RAILS_ROOT}; rake db:migrate:down VERSION=#{version} --trace`
puts "removing: #{migration_file}"
puts `rm #{migration_file}`
end
| robmckinnon/sic_uk | uninstall.rb | Ruby | mit | 308 |
#include "clustermove.h"
#include "aux/eigensupport.h"
namespace Faunus {
namespace Move {
double Cluster::clusterProbability(const Cluster::Tgroup &g1, const Cluster::Tgroup &g2) const {
if (spc.geo.sqdist(g1.cm, g2.cm) <= thresholdsq(g1.id, g2.id))
return 1.0;
return 0.0;
}
void Cluster::_to_json(json &j) const {
using namespace u8;
j = {{"dir", dir},
{"dp", dptrans},
{"dprot", dprot},
{"spread", spread},
{"dirrot", dirrot},
{rootof + bracket("r" + squared), std::sqrt(msqd.avg())},
{rootof + bracket(theta + squared) + "/" + degrees, std::sqrt(msqd_angle.avg()) / 1.0_deg},
{bracket("N"), N.avg()},
{"bias rejection rate", double(bias_rejected) / cnt},
{"clusterdistribution", clusterSizeDistribution}};
_roundjson(j, 3);
// print threshold matrix
auto &_j = j["threshold"];
for (auto i : ids)
for (auto j : ids)
if (i >= j) {
auto str = Faunus::molecules[i].name + " " + Faunus::molecules[j].name;
_j[str] = std::sqrt(thresholdsq(i, j));
_roundjson(_j[str], 3);
}
// print satellite molecules
if (not satellites.empty()) {
auto &_j = j["satellites"];
_j = json::array();
for (auto id : satellites)
_j.push_back(Faunus::molecules[id].name);
}
}
void Cluster::_from_json(const json &j) {
assertKeys(j, {"dp", "dprot", "dir", "threshold", "molecules", "repeat", "satellites", "dirrot"});
dptrans = j.at("dp");
dir = j.value("dir", Point(1, 1, 1));
dirrot = j.value("dirrot", Point(0, 0, 0)); // predefined axis of rotation
dprot = j.at("dprot");
spread = j.value("spread", true);
names = j.at("molecules").get<decltype(names)>(); // molecule names
ids = names2ids(molecules, names); // names --> molids
index.clear();
for (auto &g : spc.groups) // loop over all groups
if (not g.atomic) // only molecular groups
if (g.size() == g.capacity()) // only active particles
if (std::find(ids.begin(), ids.end(), g.id) != ids.end())
index.push_back(&g - &spc.groups.front());
if (repeat < 0)
repeat = index.size();
// read satellite ids (molecules NOT to be considered as cluster centers)
auto satnames = j.value("satellites", std::vector<std::string>()); // molecule names
auto vec = names2ids(Faunus::molecules, satnames); // names --> molids
satellites = std::set<int>(vec.begin(), vec.end());
for (auto id : satellites)
if (std::find(ids.begin(), ids.end(), id) == ids.end())
throw std::runtime_error("satellite molecules must be defined in `molecules`");
// read cluster thresholds
if (j.count("threshold") == 1) {
auto &_j = j.at("threshold");
// threshold is given as a single number
if (_j.is_number()) {
for (auto i : ids)
for (auto j : ids)
if (i >= j)
thresholdsq.set(i, j, std::pow(_j.get<double>(), 2));
}
// threshold is given as pairs of clustering molecules
else if (_j.is_object()) {
for (auto it = _j.begin(); it != _j.end(); ++it) {
auto v = words2vec<std::string>(it.key());
if (v.size() == 2) {
auto it1 = findName(Faunus::molecules, v[0]);
auto it2 = findName(Faunus::molecules, v[1]);
if (it1 == Faunus::molecules.end() or it2 == Faunus::molecules.end())
throw std::runtime_error("unknown molecule(s): ["s + v[0] + " " + v[1] + "]");
thresholdsq.set(it1->id(), it2->id(), std::pow(it.value().get<double>(), 2));
} else
throw std::runtime_error("threshold requires exactly two space-separated molecules");
}
} else
throw std::runtime_error("threshold must be a number or object");
}
}
void Cluster::findCluster(Space &spc, size_t first, std::set<size_t> &cluster) {
assert(first < spc.p.size());
std::set<size_t> pool(index.begin(), index.end());
assert(pool.count(first) > 0);
cluster.clear();
cluster.insert(first);
pool.erase(first);
size_t n;
do { // find cluster (not very clever...)
start:
n = cluster.size();
for (size_t i : cluster)
if (not spc.groups.at(i).empty()) // check if group is inactive
for (size_t j : pool)
if (i != j)
if (not spc.groups.at(j).empty()) { // check if group is inactive
// probability to cluster
double P = clusterProbability(spc.groups.at(i), spc.groups.at(j));
if (Movebase::slump() <= P) {
cluster.insert(j);
pool.erase(j);
if(spread)
goto start; // wow, first goto ever!
}
}
} while (cluster.size() != n);
// check if cluster is too large
double max = spc.geo.getLength().minCoeff() / 2;
for (auto i : cluster)
for (auto j : cluster)
if (j > i)
if (spc.geo.sqdist(spc.groups.at(i).cm, spc.groups.at(j).cm) >= max * max)
rotate = false; // skip rotation if cluster larger than half the box length
}
void Cluster::_move(Change &change) {
_bias = 0;
rotate = true;
if (not index.empty()) {
std::set<size_t> cluster; // all group index in cluster
// find "nuclei" or cluster center and exclude any molecule id listed as "satellite".
size_t first;
do {
first = *slump.sample(index.begin(), index.end()); // random molecule (nuclei)
} while (satellites.count(spc.groups[first].id) != 0);
findCluster(spc, first, cluster); // find cluster around first
N += cluster.size(); // average cluster size
clusterSizeDistribution[cluster.size()]++; // update cluster size distribution
Change::data d;
d.all = true;
dp = ranunit(slump, dir) * dptrans * slump();
if (rotate)
angle = dprot * (slump() - 0.5);
else
angle = 0;
auto boundary = spc.geo.getBoundaryFunc();
// lambda function to calculate cluster COM
auto clusterCOM = [&]() {
double sum_m = 0;
Point cm(0, 0, 0);
Point O = spc.groups[*cluster.begin()].cm;
for (auto i : cluster) {
auto &g = spc.groups[i];
Point t = g.cm - O;
boundary(t);
double m = g.mass();
cm += m * t;
sum_m += m;
}
cm = cm / sum_m + O;
boundary(cm);
return cm;
};
Point COM = clusterCOM(); // org. cluster center
Eigen::Quaterniond Q;
Point u = ranunit(slump);
if (dirrot.count() > 0)
u = dirrot;
Q = Eigen::AngleAxisd(angle, u); // quaternion
for (auto i : cluster) { // loop over molecules in cluster
auto &g = spc.groups[i];
if (rotate) {
Geometry::rotate(g.begin(), g.end(), Q, boundary, -COM);
g.cm = g.cm - COM;
boundary(g.cm);
g.cm = Q * g.cm + COM;
boundary(g.cm);
}
g.translate(dp, boundary);
d.index = i;
change.groups.push_back(d);
}
change.moved2moved = false; // do not calc. internal cluster energy
// Reject if cluster composition changes during move
// Note: this only works for the binary 0/1 probability function
// currently implemented in `findCluster()`.
std::set<size_t> aftercluster; // all group index in cluster _after_move
findCluster(spc, first, aftercluster); // find cluster around first
if (aftercluster == cluster)
_bias = 0;
else {
_bias = pc::infty; // bias is infinite --> reject
bias_rejected++; // count how many time we reject due to bias
}
#ifndef NDEBUG
// check if cluster mass center movement matches displacement
if (_bias == 0) {
Point newCOM = clusterCOM(); // org. cluster center
Point d = spc.geo.vdist(COM, newCOM); // distance between new and old COM
double _zero = (d + dp).norm(); // |d+dp| should ideally be zero...
assert(std::fabs(_zero) < 1e-6 && "cluster likely too large");
}
#endif
}
}
double Cluster::bias(Change &, double, double) { return _bias; }
void Cluster::_reject(Change &) {
msqd += 0;
msqd_angle += 0;
}
void Cluster::_accept(Change &) {
msqd += dp.squaredNorm();
msqd_angle += angle * angle;
}
Cluster::Cluster(Space &spc) : spc(spc) {
cite = "doi:10/cj9gnn";
name = "cluster";
repeat = -1; // meaning repeat N times
}
} // namespace Move
} // namespace Faunus
| gitesei/faunus | src/clustermove.cpp | C++ | mit | 9,289 |
/**
* Created by osboxes on 21/02/17.
*/
export * from './notes.component';
export * from './notes.routes';
| origamyllc/Mangular | src/client/app/notes/index.ts | TypeScript | mit | 110 |
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _htmlPdf = require('html-pdf');
var _htmlPdf2 = _interopRequireDefault(_htmlPdf);
var _handlebars = require('handlebars');
var _handlebars2 = _interopRequireDefault(_handlebars);
var _fs = require('fs');
var _fs2 = _interopRequireDefault(_fs);
var _path = require('path');
var _path2 = _interopRequireDefault(_path);
var _constants = require('../lib/constants');
var _constants2 = _interopRequireDefault(_constants);
var _moment = require('moment');
var _moment2 = _interopRequireDefault(_moment);
var _lodash = require('lodash');
var _lodash2 = _interopRequireDefault(_lodash);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function generateReport(reportName, data, res) {
var filePath = _path2.default.join(__dirname, '../views/' + reportName + '.html');
var html = _fs2.default.readFileSync(filePath, 'utf8');
var compiledTemplate = _handlebars2.default.compile(html);
var withData = compiledTemplate(data);
var options = { format: 'Letter' };
_htmlPdf2.default.create(withData, options).toBuffer(function (err, buffer) {
if (err) return console.log(err);
res.contentType("application/pdf");
return res.end(buffer, 'binary');
//console.log(res); // { filename: '/app/businesscard.pdf' }
});
}
function buildReportDataFromColumns(columns, skillData) {
console.log(_constants2.default.dateTypes);
return _lodash2.default.map(skillData, function (skillDatum) {
var dataObject = {
skillData: skillDatum,
columns: []
};
_lodash2.default.each(columns, function (column) {
var keys = column.key.split('.');
var value = skillDatum;
_lodash2.default.each(keys, function (key) {
if (value) value = value[key];
});
if (column.isDate) {
value = (0, _moment2.default)(value).format(_constants2.default.dateTypes.altDateFormat);
}
dataObject.columns.push({
value: value
});
});
return dataObject;
});
}
exports.default = { generateReport: generateReport, buildReportDataFromColumns: buildReportDataFromColumns };
//# sourceMappingURL=reportHelper.js.map | manuelnelson/patient-pal | dist/lib/reportHelper.js | JavaScript | mit | 2,378 |
<?php
class CommentWidget extends CWidget
{
public $type;
public $id;
public $limit;
public $uid;
public function init()
{
}
public function run()
{
$criteria=new CDbCriteria();
if($this->type==0)
$criteria->addCondition('dpid='.$this->id);
else
$criteria->addCondition('fdid='.$this->id);
//分页
$count=Comment::model()->count($criteria);
$paper=new CPagination($count);
$paper->pageSize=$this->limit;
$paper->applyLimit($criteria);
//列表
$criteria->limit=$this->limit;
$criteria->with='commentreply';
$criteria->order='id desc';
$list=Comment::model()->findAll($criteria);
$data=$list;
//用户信息
if($data)
{
foreach ($list as $v)
{
$uid[]=$v->uid;
if($v->commentreply)
foreach ($v->commentreply as $val)
$uid[]=$val->uid;
}
}
if($uid)
{
$uid=array_unique($uid);
$u=Member::model()->getUserInfo($uid);
}
$this->render('comment',array(
'data'=>$data,
'u'=>$u,
'pages'=>$paper,
'count'=>$count,
'type'=>$this->type,
'id'=>$this->id,
));
}
} | laijingsong/lacms | protected/widget/CommentWidget.php | PHP | mit | 1,135 |
// development configuration
// author: Kirk Austin
module.exports = {
environment: 'development',
server: {
name: 'Node Scratch',
port: 3001
},
log: {
name: 'node-scratch',
path: 'node-scratch.log'
}
}
| kirkaustin/node-scratch | config/development.js | JavaScript | mit | 225 |
import warnings
from collections import defaultdict
from queryset import QuerySet, QuerySetManager
from queryset import DoesNotExist, MultipleObjectsReturned
from queryset import DO_NOTHING
from mongoengine import signals
import sys
import pymongo
from bson import ObjectId
import operator
from functools import partial
from bson.dbref import DBRef
class NotRegistered(Exception):
pass
class InvalidDocumentError(Exception):
pass
class ValidationError(AssertionError):
"""Validation exception.
May represent an error validating a field or a
document containing fields with validation errors.
:ivar errors: A dictionary of errors for fields within this
document or list, or None if the error is for an
individual field.
"""
errors = {}
field_name = None
_message = None
def __init__(self, message="", **kwargs):
self.errors = kwargs.get('errors', {})
self.field_name = kwargs.get('field_name')
self.message = message
def __str__(self):
return self.message
def __repr__(self):
return '%s(%s,)' % (self.__class__.__name__, self.message)
def __getattribute__(self, name):
message = super(ValidationError, self).__getattribute__(name)
if name == 'message':
if self.field_name:
message = '%s' % message
if self.errors:
message = '%s(%s)' % (message, self._format_errors())
return message
def _get_message(self):
return self._message
def _set_message(self, message):
self._message = message
message = property(_get_message, _set_message)
def to_dict(self):
"""Returns a dictionary of all errors within a document
Keys are field names or list indices and values are the
validation error messages, or a nested dictionary of
errors for an embedded document or list.
"""
def build_dict(source):
errors_dict = {}
if not source:
return errors_dict
if isinstance(source, dict):
for field_name, error in source.iteritems():
errors_dict[field_name] = build_dict(error)
elif isinstance(source, ValidationError) and source.errors:
return build_dict(source.errors)
else:
return unicode(source)
return errors_dict
if not self.errors:
return {}
return build_dict(self.errors)
def _format_errors(self):
"""Returns a string listing all errors within a document"""
def generate_key(value, prefix=''):
if isinstance(value, list):
value = ' '.join([generate_key(k) for k in value])
if isinstance(value, dict):
value = ' '.join(
[generate_key(v, k) for k, v in value.iteritems()])
results = "%s.%s" % (prefix, value) if prefix else value
return results
error_dict = defaultdict(list)
for k, v in self.to_dict().iteritems():
error_dict[generate_key(v)].append(k)
return ' '.join(["%s: %s" % (k, v) for k, v in error_dict.iteritems()])
_document_registry = {}
def get_document(name):
doc = _document_registry.get(name, None)
if not doc:
# Possible old style names
end = ".%s" % name
possible_match = [k for k in _document_registry.keys() if k.endswith(end)]
if len(possible_match) == 1:
doc = _document_registry.get(possible_match.pop(), None)
if not doc:
raise NotRegistered("""
`%s` has not been registered in the document registry.
Importing the document class automatically registers it, has it
been imported?
""".strip() % name)
return doc
class BaseField(object):
"""A base class for fields in a MongoDB document. Instances of this class
may be added to subclasses of `Document` to define a document's schema.
.. versionchanged:: 0.5 - added verbose and help text
"""
name = None
# Fields may have _types inserted into indexes by default
_index_with_types = True
_geo_index = False
# These track each time a Field instance is created. Used to retain order.
# The auto_creation_counter is used for fields that MongoEngine implicitly
# creates, creation_counter is used for all user-specified fields.
creation_counter = 0
auto_creation_counter = -1
def __init__(self, db_field=None, name=None, required=False, default=None,
unique=False, unique_with=None, primary_key=False,
validation=None, choices=None, verbose_name=None, help_text=None):
self.db_field = (db_field or name) if not primary_key else '_id'
if name:
msg = "Fields' 'name' attribute deprecated in favour of 'db_field'"
warnings.warn(msg, DeprecationWarning)
self.name = None
self.required = required or primary_key
self.default = default
self.unique = bool(unique or unique_with)
self.unique_with = unique_with
self.primary_key = primary_key
self.validation = validation
self.choices = choices
self.verbose_name = verbose_name
self.help_text = help_text
# Adjust the appropriate creation counter, and save our local copy.
if self.db_field == '_id':
self.creation_counter = BaseField.auto_creation_counter
BaseField.auto_creation_counter -= 1
else:
self.creation_counter = BaseField.creation_counter
BaseField.creation_counter += 1
def __get__(self, instance, owner):
"""Descriptor for retrieving a value from a field in a document. Do
any necessary conversion between Python and MongoDB types.
"""
if instance is None:
# Document class being used rather than a document object
return self
# Get value from document instance if available, if not use default
value = instance._data.get(self.name)
if value is None:
value = self.default
# Allow callable default values
if callable(value):
value = value()
return value
def __set__(self, instance, value):
"""Descriptor for assigning a value to a field in a document.
"""
instance._data[self.name] = value
instance._mark_as_changed(self.name)
def error(self, message="", errors=None, field_name=None):
"""Raises a ValidationError.
"""
field_name = field_name if field_name else self.name
raise ValidationError(message, errors=errors, field_name=field_name)
def to_python(self, value):
"""Convert a MongoDB-compatible type to a Python type.
"""
return value
def to_mongo(self, value):
"""Convert a Python type to a MongoDB-compatible type.
"""
return self.to_python(value)
def prepare_query_value(self, op, value):
"""Prepare a value that is being used in a query for PyMongo.
"""
return value
def validate(self, value):
"""Perform validation on a value.
"""
pass
def _validate(self, value):
from mongoengine import Document, EmbeddedDocument
# check choices
if self.choices:
is_cls = isinstance(value, (Document, EmbeddedDocument))
value_to_check = value.__class__ if is_cls else value
err_msg = 'an instance' if is_cls else 'one'
if isinstance(self.choices[0], (list, tuple)):
option_keys = [option_key for option_key, option_value in self.choices]
if value_to_check not in option_keys:
self.error('Value must be %s of %s' % (err_msg, unicode(option_keys)))
elif value_to_check not in self.choices:
self.error('Value must be %s of %s' % (err_msg, unicode(self.choices)))
# check validation argument
if self.validation is not None:
if callable(self.validation):
if not self.validation(value):
self.error('Value does not match custom validation method')
else:
raise ValueError('validation argument for "%s" must be a '
'callable.' % self.name)
self.validate(value)
class ComplexBaseField(BaseField):
"""Handles complex fields, such as lists / dictionaries.
Allows for nesting of embedded documents inside complex types.
Handles the lazy dereferencing of a queryset by lazily dereferencing all
items in a list / dict rather than one at a time.
.. versionadded:: 0.5
"""
field = None
_dereference = False
def __get__(self, instance, owner):
"""Descriptor to automatically dereference references.
"""
if instance is None:
# Document class being used rather than a document object
return self
from fields import GenericReferenceField, ReferenceField
dereference = self.field is None or isinstance(self.field,
(GenericReferenceField, ReferenceField))
if not self._dereference and instance._initialised and dereference:
from dereference import DeReference
self._dereference = DeReference() # Cached
instance._data[self.name] = self._dereference(
instance._data.get(self.name), max_depth=1, instance=instance,
name=self.name
)
value = super(ComplexBaseField, self).__get__(instance, owner)
# Convert lists / values so we can watch for any changes on them
if isinstance(value, (list, tuple)) and not isinstance(value, BaseList):
value = BaseList(value, instance, self.name)
instance._data[self.name] = value
elif isinstance(value, dict) and not isinstance(value, BaseDict):
value = BaseDict(value, instance, self.name)
instance._data[self.name] = value
if self._dereference and instance._initialised and \
isinstance(value, (BaseList, BaseDict)) and not value._dereferenced:
value = self._dereference(
value, max_depth=1, instance=instance, name=self.name
)
value._dereferenced = True
instance._data[self.name] = value
return value
def __set__(self, instance, value):
"""Descriptor for assigning a value to a field in a document.
"""
instance._data[self.name] = value
instance._mark_as_changed(self.name)
def to_python(self, value):
"""Convert a MongoDB-compatible type to a Python type.
"""
from mongoengine import Document
if isinstance(value, basestring):
return value
if hasattr(value, 'to_python'):
return value.to_python()
is_list = False
if not hasattr(value, 'items'):
try:
is_list = True
value = dict([(k, v) for k, v in enumerate(value)])
except TypeError: # Not iterable return the value
return value
if self.field:
value_dict = dict([(key, self.field.to_python(item)) for key, item in value.items()])
else:
value_dict = {}
for k, v in value.items():
if isinstance(v, Document):
# We need the id from the saved object to create the DBRef
if v.pk is None:
self.error('You can only reference documents once they'
' have been saved to the database')
collection = v._get_collection_name()
value_dict[k] = DBRef(collection, v.pk)
elif hasattr(v, 'to_python'):
value_dict[k] = v.to_python()
else:
value_dict[k] = self.to_python(v)
if is_list: # Convert back to a list
return [v for k, v in sorted(value_dict.items(), key=operator.itemgetter(0))]
return value_dict
def to_mongo(self, value):
"""Convert a Python type to a MongoDB-compatible type.
"""
from mongoengine import Document
if isinstance(value, basestring):
return value
if hasattr(value, 'to_mongo'):
return value.to_mongo()
is_list = False
if not hasattr(value, 'items'):
try:
is_list = True
value = dict([(k, v) for k, v in enumerate(value)])
except TypeError: # Not iterable return the value
return value
if self.field:
value_dict = dict([(key, self.field.to_mongo(item)) for key, item in value.items()])
else:
value_dict = {}
for k, v in value.items():
if isinstance(v, Document):
# We need the id from the saved object to create the DBRef
if v.pk is None:
self.error('You can only reference documents once they'
' have been saved to the database')
# If its a document that is not inheritable it won't have
# _types / _cls data so make it a generic reference allows
# us to dereference
meta = getattr(v, 'meta', getattr(v, '_meta', {}))
if meta and not meta.get('allow_inheritance', True) and not self.field:
from fields import GenericReferenceField
value_dict[k] = GenericReferenceField().to_mongo(v)
else:
collection = v._get_collection_name()
value_dict[k] = DBRef(collection, v.pk)
elif hasattr(v, 'to_mongo'):
value_dict[k] = v.to_mongo()
else:
value_dict[k] = self.to_mongo(v)
if is_list: # Convert back to a list
return [v for k, v in sorted(value_dict.items(), key=operator.itemgetter(0))]
return value_dict
def validate(self, value):
"""If field is provided ensure the value is valid.
"""
errors = {}
if self.field:
if hasattr(value, 'iteritems'):
sequence = value.iteritems()
else:
sequence = enumerate(value)
for k, v in sequence:
try:
self.field._validate(v)
except ValidationError, error:
errors[k] = error.errors or error
except (ValueError, AssertionError), error:
errors[k] = error
if errors:
field_class = self.field.__class__.__name__
self.error('Invalid %s item (%s)' % (field_class, value),
errors=errors)
# Don't allow empty values if required
if self.required and not value:
self.error('Field is required and cannot be empty')
def prepare_query_value(self, op, value):
return self.to_mongo(value)
def lookup_member(self, member_name):
if self.field:
return self.field.lookup_member(member_name)
return None
def _set_owner_document(self, owner_document):
if self.field:
self.field.owner_document = owner_document
self._owner_document = owner_document
def _get_owner_document(self, owner_document):
self._owner_document = owner_document
owner_document = property(_get_owner_document, _set_owner_document)
class ObjectIdField(BaseField):
"""An field wrapper around MongoDB's ObjectIds.
"""
def to_python(self, value):
return value
def to_mongo(self, value):
if not isinstance(value, ObjectId):
try:
return ObjectId(unicode(value))
except Exception, e:
# e.message attribute has been deprecated since Python 2.6
self.error(unicode(e))
return value
def prepare_query_value(self, op, value):
return self.to_mongo(value)
def validate(self, value):
try:
ObjectId(unicode(value))
except:
self.error('Invalid Object ID')
class DocumentMetaclass(type):
"""Metaclass for all documents.
"""
def __new__(cls, name, bases, attrs):
def _get_mixin_fields(base):
attrs = {}
attrs.update(dict([(k, v) for k, v in base.__dict__.items()
if issubclass(v.__class__, BaseField)]))
# Handle simple mixin's with meta
if hasattr(base, 'meta') and not isinstance(base, DocumentMetaclass):
meta = attrs.get('meta', {})
meta.update(base.meta)
attrs['meta'] = meta
for p_base in base.__bases__:
#optimize :-)
if p_base in (object, BaseDocument):
continue
attrs.update(_get_mixin_fields(p_base))
return attrs
metaclass = attrs.get('__metaclass__')
super_new = super(DocumentMetaclass, cls).__new__
if metaclass and issubclass(metaclass, DocumentMetaclass):
return super_new(cls, name, bases, attrs)
doc_fields = {}
class_name = [name]
superclasses = {}
simple_class = True
for base in bases:
# Include all fields present in superclasses
if hasattr(base, '_fields'):
doc_fields.update(base._fields)
# Get superclasses from superclass
superclasses[base._class_name] = base
superclasses.update(base._superclasses)
else: # Add any mixin fields
attrs.update(_get_mixin_fields(base))
if hasattr(base, '_meta') and not base._meta.get('abstract'):
# Ensure that the Document class may be subclassed -
# inheritance may be disabled to remove dependency on
# additional fields _cls and _types
class_name.append(base._class_name)
if not base._meta.get('allow_inheritance_defined', True):
warnings.warn(
"%s uses inheritance, the default for allow_inheritance "
"is changing to off by default. Please add it to the "
"document meta." % name,
FutureWarning
)
if base._meta.get('allow_inheritance', True) == False:
raise ValueError('Document %s may not be subclassed' %
base.__name__)
else:
simple_class = False
doc_class_name = '.'.join(reversed(class_name))
meta = attrs.get('_meta', {})
meta.update(attrs.get('meta', {}))
if 'allow_inheritance' not in meta:
meta['allow_inheritance'] = True
# Only simple classes - direct subclasses of Document - may set
# allow_inheritance to False
if not simple_class and not meta['allow_inheritance'] and not meta['abstract']:
raise ValueError('Only direct subclasses of Document may set '
'"allow_inheritance" to False')
attrs['_meta'] = meta
attrs['_class_name'] = doc_class_name
attrs['_superclasses'] = superclasses
# Add the document's fields to the _fields attribute
field_names = {}
for attr_name, attr_value in attrs.items():
if hasattr(attr_value, "__class__") and \
issubclass(attr_value.__class__, BaseField):
attr_value.name = attr_name
if not attr_value.db_field:
attr_value.db_field = attr_name
doc_fields[attr_name] = attr_value
field_names[attr_value.db_field] = field_names.get(attr_value.db_field, 0) + 1
duplicate_db_fields = [k for k, v in field_names.items() if v > 1]
if duplicate_db_fields:
raise InvalidDocumentError("Multiple db_fields defined for: %s " % ", ".join(duplicate_db_fields))
attrs['_fields'] = doc_fields
attrs['_db_field_map'] = dict([(k, v.db_field) for k, v in doc_fields.items() if k != v.db_field])
attrs['_reverse_db_field_map'] = dict([(v, k) for k, v in attrs['_db_field_map'].items()])
from mongoengine import Document, EmbeddedDocument, DictField
new_class = super_new(cls, name, bases, attrs)
for field in new_class._fields.values():
field.owner_document = new_class
delete_rule = getattr(field, 'reverse_delete_rule', DO_NOTHING)
f = field
if isinstance(f, ComplexBaseField) and hasattr(f, 'field'):
delete_rule = getattr(f.field, 'reverse_delete_rule', DO_NOTHING)
if isinstance(f, DictField) and delete_rule != DO_NOTHING:
raise InvalidDocumentError("Reverse delete rules are not supported for %s (field: %s)" % (field.__class__.__name__, field.name))
f = field.field
if delete_rule != DO_NOTHING:
if issubclass(new_class, EmbeddedDocument):
raise InvalidDocumentError("Reverse delete rules are not supported for EmbeddedDocuments (field: %s)" % field.name)
f.document_type.register_delete_rule(new_class, field.name, delete_rule)
if field.name and hasattr(Document, field.name) and EmbeddedDocument not in new_class.mro():
raise InvalidDocumentError("%s is a document method and not a valid field name" % field.name)
module = attrs.get('__module__')
base_excs = tuple(base.DoesNotExist for base in bases
if hasattr(base, 'DoesNotExist')) or (DoesNotExist,)
exc = subclass_exception('DoesNotExist', base_excs, module)
new_class.add_to_class('DoesNotExist', exc)
base_excs = tuple(base.MultipleObjectsReturned for base in bases
if hasattr(base, 'MultipleObjectsReturned'))
base_excs = base_excs or (MultipleObjectsReturned,)
exc = subclass_exception('MultipleObjectsReturned', base_excs, module)
new_class.add_to_class('MultipleObjectsReturned', exc)
global _document_registry
_document_registry[doc_class_name] = new_class
return new_class
def add_to_class(self, name, value):
setattr(self, name, value)
class TopLevelDocumentMetaclass(DocumentMetaclass):
"""Metaclass for top-level documents (i.e. documents that have their own
collection in the database.
"""
def __new__(cls, name, bases, attrs):
super_new = super(TopLevelDocumentMetaclass, cls).__new__
# Classes defined in this package are abstract and should not have
# their own metadata with DB collection, etc.
# __metaclass__ is only set on the class with the __metaclass__
# attribute (i.e. it is not set on subclasses). This differentiates
# 'real' documents from the 'Document' class
#
# Also assume a class is abstract if it has abstract set to True in
# its meta dictionary. This allows custom Document superclasses.
if (attrs.get('__metaclass__') == TopLevelDocumentMetaclass or
('meta' in attrs and attrs['meta'].get('abstract', False))):
# Make sure no base class was non-abstract
non_abstract_bases = [b for b in bases
if hasattr(b, '_meta') and not b._meta.get('abstract', False)]
if non_abstract_bases:
raise ValueError("Abstract document cannot have non-abstract base")
return super_new(cls, name, bases, attrs)
collection = ''.join('_%s' % c if c.isupper() else c for c in name).strip('_').lower()
id_field = None
abstract_base_indexes = []
base_indexes = []
base_meta = {}
# Subclassed documents inherit collection from superclass
for base in bases:
if hasattr(base, '_meta'):
if 'collection' in attrs.get('meta', {}) and not base._meta.get('abstract', False):
import warnings
msg = "Trying to set a collection on a subclass (%s)" % name
warnings.warn(msg, SyntaxWarning)
del(attrs['meta']['collection'])
if base._get_collection_name():
collection = base._get_collection_name()
# Propagate inherited values
keys_to_propogate = (
'index_background', 'index_drop_dups', 'index_opts',
'allow_inheritance', 'queryset_class', 'db_alias',
)
for key in keys_to_propogate:
if key in base._meta:
base_meta[key] = base._meta[key]
id_field = id_field or base._meta.get('id_field')
if base._meta.get('abstract', False):
abstract_base_indexes += base._meta.get('indexes', [])
else:
base_indexes += base._meta.get('indexes', [])
try:
base_meta['objects'] = base.__getattribute__(base, 'objects')
except TypeError:
pass
except AttributeError:
pass
# defaults
meta = {
'abstract': False,
'collection': collection,
'max_documents': None,
'max_size': None,
'ordering': [], # default ordering applied at runtime
'indexes': [], # indexes to be ensured at runtime
'id_field': id_field,
'index_background': False,
'index_drop_dups': False,
'index_opts': {},
'queryset_class': QuerySet,
'delete_rules': {},
'allow_inheritance': True
}
allow_inheritance_defined = ('allow_inheritance' in base_meta or
'allow_inheritance'in attrs.get('meta', {}))
meta['allow_inheritance_defined'] = allow_inheritance_defined
meta.update(base_meta)
# Apply document-defined meta options
meta.update(attrs.get('meta', {}))
attrs['_meta'] = meta
# Set up collection manager, needs the class to have fields so use
# DocumentMetaclass before instantiating CollectionManager object
new_class = super_new(cls, name, bases, attrs)
collection = attrs['_meta'].get('collection', None)
if callable(collection):
new_class._meta['collection'] = collection(new_class)
# Provide a default queryset unless one has been manually provided
manager = attrs.get('objects', meta.get('objects', QuerySetManager()))
if hasattr(manager, 'queryset_class'):
meta['queryset_class'] = manager.queryset_class
new_class.objects = manager
indicies = list(meta['indexes']) + abstract_base_indexes
user_indexes = [QuerySet._build_index_spec(new_class, spec)
for spec in indicies] + base_indexes
new_class._meta['indexes'] = user_indexes
unique_indexes = cls._unique_with_indexes(new_class)
new_class._meta['unique_indexes'] = unique_indexes
for field_name, field in new_class._fields.items():
# Check for custom primary key
if field.primary_key:
current_pk = new_class._meta['id_field']
if current_pk and current_pk != field_name:
raise ValueError('Cannot override primary key field')
if not current_pk:
new_class._meta['id_field'] = field_name
# Make 'Document.id' an alias to the real primary key field
new_class.id = field
if not new_class._meta['id_field']:
new_class._meta['id_field'] = 'id'
new_class._fields['id'] = ObjectIdField(db_field='_id')
new_class.id = new_class._fields['id']
return new_class
@classmethod
def _unique_with_indexes(cls, new_class, namespace=""):
unique_indexes = []
for field_name, field in new_class._fields.items():
# Generate a list of indexes needed by uniqueness constraints
if field.unique:
field.required = True
unique_fields = [field.db_field]
# Add any unique_with fields to the back of the index spec
if field.unique_with:
if isinstance(field.unique_with, basestring):
field.unique_with = [field.unique_with]
# Convert unique_with field names to real field names
unique_with = []
for other_name in field.unique_with:
parts = other_name.split('.')
# Lookup real name
parts = QuerySet._lookup_field(new_class, parts)
name_parts = [part.db_field for part in parts]
unique_with.append('.'.join(name_parts))
# Unique field should be required
parts[-1].required = True
unique_fields += unique_with
# Add the new index to the list
index = [("%s%s" % (namespace, f), pymongo.ASCENDING) for f in unique_fields]
unique_indexes.append(index)
# Grab any embedded document field unique indexes
if field.__class__.__name__ == "EmbeddedDocumentField" and field.document_type != new_class:
field_namespace = "%s." % field_name
unique_indexes += cls._unique_with_indexes(field.document_type,
field_namespace)
return unique_indexes
class BaseDocument(object):
_dynamic = False
_created = True
_dynamic_lock = True
_initialised = False
def __init__(self, **values):
signals.pre_init.send(self.__class__, document=self, values=values)
self._data = {}
# Assign default values to instance
for attr_name, field in self._fields.items():
value = getattr(self, attr_name, None)
setattr(self, attr_name, value)
# Set passed values after initialisation
if self._dynamic:
self._dynamic_fields = {}
dynamic_data = {}
for key, value in values.items():
if key in self._fields or key == '_id':
setattr(self, key, value)
elif self._dynamic:
dynamic_data[key] = value
else:
for key, value in values.items():
key = self._reverse_db_field_map.get(key, key)
setattr(self, key, value)
# Set any get_fieldname_display methods
self.__set_field_display()
if self._dynamic:
self._dynamic_lock = False
for key, value in dynamic_data.items():
setattr(self, key, value)
# Flag initialised
self._initialised = True
signals.post_init.send(self.__class__, document=self)
def __setattr__(self, name, value):
# Handle dynamic data only if an initialised dynamic document
if self._dynamic and not self._dynamic_lock:
field = None
if not hasattr(self, name) and not name.startswith('_'):
from fields import DynamicField
field = DynamicField(db_field=name)
field.name = name
self._dynamic_fields[name] = field
if not name.startswith('_'):
value = self.__expand_dynamic_values(name, value)
# Handle marking data as changed
if name in self._dynamic_fields:
self._data[name] = value
if hasattr(self, '_changed_fields'):
self._mark_as_changed(name)
if not self._created and name in self._meta.get('shard_key', tuple()):
from queryset import OperationError
raise OperationError("Shard Keys are immutable. Tried to update %s" % name)
super(BaseDocument, self).__setattr__(name, value)
def __expand_dynamic_values(self, name, value):
"""expand any dynamic values to their correct types / values"""
if not isinstance(value, (dict, list, tuple)):
return value
is_list = False
if not hasattr(value, 'items'):
is_list = True
value = dict([(k, v) for k, v in enumerate(value)])
if not is_list and '_cls' in value:
cls = get_document(value['_cls'])
value = cls(**value)
value._dynamic = True
value._changed_fields = []
return value
data = {}
for k, v in value.items():
key = name if is_list else k
data[k] = self.__expand_dynamic_values(key, v)
if is_list: # Convert back to a list
data_items = sorted(data.items(), key=operator.itemgetter(0))
value = [v for k, v in data_items]
else:
value = data
# Convert lists / values so we can watch for any changes on them
if isinstance(value, (list, tuple)) and not isinstance(value, BaseList):
value = BaseList(value, self, name)
elif isinstance(value, dict) and not isinstance(value, BaseDict):
value = BaseDict(value, self, name)
return value
def validate(self):
"""Ensure that all fields' values are valid and that required fields
are present.
"""
# Get a list of tuples of field names and their current values
fields = [(field, getattr(self, name))
for name, field in self._fields.items()]
# Ensure that each field is matched to a valid value
errors = {}
for field, value in fields:
if value is not None:
try:
field._validate(value)
except ValidationError, error:
errors[field.name] = error.errors or error
except (ValueError, AttributeError, AssertionError), error:
errors[field.name] = error
elif field.required:
errors[field.name] = ValidationError('Field is required',
field_name=field.name)
if errors:
raise ValidationError('ValidationError', errors=errors)
def to_mongo(self):
"""Return data dictionary ready for use with MongoDB.
"""
data = {}
for field_name, field in self._fields.items():
value = getattr(self, field_name, None)
if value is not None:
data[field.db_field] = field.to_mongo(value)
# Only add _cls and _types if allow_inheritance is not False
if not (hasattr(self, '_meta') and
self._meta.get('allow_inheritance', True) == False):
data['_cls'] = self._class_name
data['_types'] = self._superclasses.keys() + [self._class_name]
if '_id' in data and data['_id'] is None:
del data['_id']
if not self._dynamic:
return data
for name, field in self._dynamic_fields.items():
data[name] = field.to_mongo(self._data.get(name, None))
return data
@classmethod
def _get_collection_name(cls):
"""Returns the collection name for this class.
"""
return cls._meta.get('collection', None)
@classmethod
def _from_son(cls, son):
"""Create an instance of a Document (subclass) from a PyMongo SON.
"""
# get the class name from the document, falling back to the given
# class if unavailable
class_name = son.get('_cls', cls._class_name)
data = dict(("%s" % key, value) for key, value in son.items())
if '_types' in data:
del data['_types']
if '_cls' in data:
del data['_cls']
# Return correct subclass for document type
if class_name != cls._class_name:
cls = get_document(class_name)
changed_fields = []
errors_dict = {}
for field_name, field in cls._fields.items():
if field.db_field in data:
value = data[field.db_field]
try:
data[field_name] = (value if value is None
else field.to_python(value))
if field_name != field.db_field:
del data[field.db_field]
except (AttributeError, ValueError), e:
errors_dict[field_name] = e
elif field.default:
default = field.default
if callable(default):
default = default()
if isinstance(default, BaseDocument):
changed_fields.append(field_name)
if errors_dict:
errors = "\n".join(["%s - %s" % (k, v) for k, v in errors_dict.items()])
raise InvalidDocumentError("""
Invalid data to create a `%s` instance.\n%s""".strip() % (cls._class_name, errors))
obj = cls(**data)
obj._changed_fields = changed_fields
obj._created = False
return obj
def _mark_as_changed(self, key):
"""Marks a key as explicitly changed by the user
"""
if not key:
return
key = self._db_field_map.get(key, key)
if hasattr(self, '_changed_fields') and key not in self._changed_fields:
self._changed_fields.append(key)
def _get_changed_fields(self, key='', inspected=None):
"""Returns a list of all fields that have explicitly been changed.
"""
from mongoengine import EmbeddedDocument, DynamicEmbeddedDocument
_changed_fields = []
_changed_fields += getattr(self, '_changed_fields', [])
inspected = inspected or set()
if hasattr(self, 'id'):
if self.id in inspected:
return _changed_fields
inspected.add(self.id)
field_list = self._fields.copy()
if self._dynamic:
field_list.update(self._dynamic_fields)
for field_name in field_list:
db_field_name = self._db_field_map.get(field_name, field_name)
key = '%s.' % db_field_name
field = self._data.get(field_name, None)
if hasattr(field, 'id'):
if field.id in inspected:
continue
inspected.add(field.id)
if isinstance(field, (EmbeddedDocument, DynamicEmbeddedDocument)) and db_field_name not in _changed_fields: # Grab all embedded fields that have been changed
_changed_fields += ["%s%s" % (key, k) for k in field._get_changed_fields(key, inspected) if k]
elif isinstance(field, (list, tuple, dict)) and db_field_name not in _changed_fields: # Loop list / dict fields as they contain documents
# Determine the iterator to use
if not hasattr(field, 'items'):
iterator = enumerate(field)
else:
iterator = field.iteritems()
for index, value in iterator:
if not hasattr(value, '_get_changed_fields'):
continue
list_key = "%s%s." % (key, index)
_changed_fields += ["%s%s" % (list_key, k) for k in value._get_changed_fields(list_key, inspected) if k]
return _changed_fields
def _delta(self):
"""Returns the delta (set, unset) of the changes for a document.
Gets any values that have been explicitly changed.
"""
# Handles cases where not loaded from_son but has _id
doc = self.to_mongo()
set_fields = self._get_changed_fields()
set_data = {}
unset_data = {}
parts = []
if hasattr(self, '_changed_fields'):
set_data = {}
# Fetch each set item from its path
for path in set_fields:
parts = path.split('.')
d = doc
new_path = []
for p in parts:
if isinstance(d, DBRef):
break
elif p.isdigit():
d = d[int(p)]
elif hasattr(d, 'get'):
d = d.get(p)
new_path.append(p)
path = '.'.join(new_path)
set_data[path] = d
else:
set_data = doc
if '_id' in set_data:
del(set_data['_id'])
# Determine if any changed items were actually unset.
for path, value in set_data.items():
if value or isinstance(value, bool):
continue
# If we've set a value that ain't the default value dont unset it.
default = None
if self._dynamic and len(parts) and parts[0] in self._dynamic_fields:
del(set_data[path])
unset_data[path] = 1
continue
elif path in self._fields:
default = self._fields[path].default
else: # Perform a full lookup for lists / embedded lookups
d = self
parts = path.split('.')
db_field_name = parts.pop()
for p in parts:
if p.isdigit():
d = d[int(p)]
elif hasattr(d, '__getattribute__') and not isinstance(d, dict):
real_path = d._reverse_db_field_map.get(p, p)
d = getattr(d, real_path)
else:
d = d.get(p)
if hasattr(d, '_fields'):
field_name = d._reverse_db_field_map.get(db_field_name,
db_field_name)
if field_name in d._fields:
default = d._fields.get(field_name).default
else:
default = None
if default is not None:
if callable(default):
default = default()
if default != value:
continue
del(set_data[path])
unset_data[path] = 1
return set_data, unset_data
@classmethod
def _geo_indices(cls, inspected=None):
inspected = inspected or []
geo_indices = []
inspected.append(cls)
from fields import EmbeddedDocumentField, GeoPointField
for field in cls._fields.values():
if not isinstance(field, (EmbeddedDocumentField, GeoPointField)):
continue
if hasattr(field, 'document_type'):
field_cls = field.document_type
if field_cls in inspected:
continue
if hasattr(field_cls, '_geo_indices'):
geo_indices += field_cls._geo_indices(inspected)
elif field._geo_index:
geo_indices.append(field)
return geo_indices
def __getstate__(self):
removals = ["get_%s_display" % k for k, v in self._fields.items() if v.choices]
for k in removals:
if hasattr(self, k):
delattr(self, k)
return self.__dict__
def __setstate__(self, __dict__):
self.__dict__ = __dict__
self.__set_field_display()
def __set_field_display(self):
for attr_name, field in self._fields.items():
if field.choices: # dynamically adds a way to get the display value for a field with choices
setattr(self, 'get_%s_display' % attr_name, partial(self.__get_field_display, field=field))
def __get_field_display(self, field):
"""Returns the display value for a choice field"""
value = getattr(self, field.name)
if field.choices and isinstance(field.choices[0], (list, tuple)):
return dict(field.choices).get(value, value)
return value
def __iter__(self):
return iter(self._fields)
def __getitem__(self, name):
"""Dictionary-style field access, return a field's value if present.
"""
try:
if name in self._fields:
return getattr(self, name)
except AttributeError:
pass
raise KeyError(name)
def __setitem__(self, name, value):
"""Dictionary-style field access, set a field's value.
"""
# Ensure that the field exists before settings its value
if name not in self._fields:
raise KeyError(name)
return setattr(self, name, value)
def __contains__(self, name):
try:
val = getattr(self, name)
return val is not None
except AttributeError:
return False
def __len__(self):
return len(self._data)
def __repr__(self):
try:
u = unicode(self).encode('utf-8')
except (UnicodeEncodeError, UnicodeDecodeError):
u = '[Bad Unicode data]'
return '<%s: %s>' % (self.__class__.__name__, u)
def __str__(self):
if hasattr(self, '__unicode__'):
return unicode(self).encode('utf-8')
return '%s object' % self.__class__.__name__
def __eq__(self, other):
if isinstance(other, self.__class__) and hasattr(other, 'id'):
if self.id == other.id:
return True
return False
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
if self.pk is None:
# For new object
return super(BaseDocument, self).__hash__()
else:
return hash(self.pk)
class BaseList(list):
"""A special list so we can watch any changes
"""
_dereferenced = False
_instance = None
_name = None
def __init__(self, list_items, instance, name):
self._instance = instance
self._name = name
return super(BaseList, self).__init__(list_items)
def __setitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).__setitem__(*args, **kwargs)
def __delitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).__delitem__(*args, **kwargs)
def __getstate__(self):
self.observer = None
return self
def __setstate__(self, state):
self = state
return self
def append(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).append(*args, **kwargs)
def extend(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).extend(*args, **kwargs)
def insert(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).insert(*args, **kwargs)
def pop(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).pop(*args, **kwargs)
def remove(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).remove(*args, **kwargs)
def reverse(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).reverse(*args, **kwargs)
def sort(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseList, self).sort(*args, **kwargs)
def _mark_as_changed(self):
if hasattr(self._instance, '_mark_as_changed'):
self._instance._mark_as_changed(self._name)
class BaseDict(dict):
"""A special dict so we can watch any changes
"""
_dereferenced = False
_instance = None
_name = None
def __init__(self, dict_items, instance, name):
self._instance = instance
self._name = name
return super(BaseDict, self).__init__(dict_items)
def __setitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__setitem__(*args, **kwargs)
def __delete__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__delete__(*args, **kwargs)
def __delitem__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__delitem__(*args, **kwargs)
def __delattr__(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).__delattr__(*args, **kwargs)
def __getstate__(self):
self.instance = None
self._dereferenced = False
return self
def __setstate__(self, state):
self = state
return self
def clear(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).clear(*args, **kwargs)
def pop(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).pop(*args, **kwargs)
def popitem(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).popitem(*args, **kwargs)
def update(self, *args, **kwargs):
self._mark_as_changed()
return super(BaseDict, self).update(*args, **kwargs)
def _mark_as_changed(self):
if hasattr(self._instance, '_mark_as_changed'):
self._instance._mark_as_changed(self._name)
if sys.version_info < (2, 5):
# Prior to Python 2.5, Exception was an old-style class
import types
def subclass_exception(name, parents, unused):
import types
return types.ClassType(name, parents, {})
else:
def subclass_exception(name, parents, module):
return type(name, parents, {'__module__': module})
| newvem/mongoengine | mongoengine/base.py | Python | mit | 50,511 |
import Users from 'meteor/vulcan:users';
import { Utils, addGraphQLMutation, addGraphQLResolvers } from 'meteor/vulcan:core';
/**
* @summary Verify that the un/subscription can be performed
* @param {String} action
* @param {Collection} collection
* @param {String} itemId
* @param {Object} user
* @returns {Object} collectionName, fields: object, item, hasSubscribedItem: boolean
*/
const prepareSubscription = (action, collection, itemId, user) => {
// get item's collection name
const collectionName = collection._name.slice(0,1).toUpperCase() + collection._name.slice(1);
// get item data
const item = collection.findOne(itemId);
// there no user logged in or no item, abort process
if (!user || !item) {
return false;
}
// edge case: Users collection
if (collectionName === 'Users') {
// someone can't subscribe to themself, abort process
if (item._id === user._id) {
return false;
}
} else {
// the item's owner is the subscriber, abort process
if (item.userId && item.userId === user._id) {
return false;
}
}
// assign the right fields depending on the collection
const fields = {
subscribers: 'subscribers',
subscriberCount: 'subscriberCount',
};
// return true if the item has the subscriber's id in its fields
const hasSubscribedItem = !!_.deep(item, fields.subscribers) && _.deep(item, fields.subscribers) && _.deep(item, fields.subscribers).indexOf(user._id) !== -1;
// assign the right update operator and count depending on the action type
const updateQuery = action === 'subscribe' ? {
findOperator: '$ne', // where 'IT' isn't...
updateOperator: '$addToSet', // ...add 'IT' to the array...
updateCount: 1, // ...and log the addition +1
} : {
findOperator: '$eq', // where 'IT' is...
updateOperator: '$pull', // ...remove 'IT' from the array...
updateCount: -1, // ...and log the subtraction -1
};
// return the utility object to pursue
return {
collectionName,
fields,
item,
hasSubscribedItem,
...updateQuery,
};
};
/**
* @summary Perform the un/subscription after verification: update the collection item & the user
* @param {String} action
* @param {Collection} collection
* @param {String} itemId
* @param {Object} user: current user (xxx: legacy, to replace with this.userId)
* @returns {Boolean}
*/
const performSubscriptionAction = (action, collection, itemId, user) => {
// subscription preparation to verify if can pursue and give shorthand variables
const subscription = prepareSubscription(action, collection, itemId, user);
// Abort process if the situation matches one of these cases:
// - subscription preparation failed (ex: no user, no item, subscriber is author's item, ... see all cases above)
// - the action is subscribe but the user has already subscribed to this item
// - the action is unsubscribe but the user hasn't subscribed to this item
if (!subscription || (action === 'subscribe' && subscription.hasSubscribedItem) || (action === 'unsubscribe' && !subscription.hasSubscribedItem)) {
throw Error(Utils.encodeIntlError({id: 'app.mutation_not_allowed', value: 'Already subscribed'}))
}
// shorthand for useful variables
const { collectionName, fields, item, findOperator, updateOperator, updateCount } = subscription;
// Perform the action, eg. operate on the item's collection
const result = collection.update({
_id: itemId,
// if it's a subscription, find where there are not the user (ie. findOperator = $ne), else it will be $in
[fields.subscribers]: { [findOperator]: user._id }
}, {
// if it's a subscription, add a subscriber (ie. updateOperator = $addToSet), else it will be $pull
[updateOperator]: { [fields.subscribers]: user._id },
// if it's a subscription, the count is incremented of 1, else decremented of 1
$inc: { [fields.subscriberCount]: updateCount },
});
// log the operation on the subscriber if it has succeeded
if (result > 0) {
// id of the item subject of the action
let loggedItem = {
itemId: item._id,
};
// in case of subscription, log also the date
if (action === 'subscribe') {
loggedItem = {
...loggedItem,
subscribedAt: new Date()
};
}
// update the user's list of subscribed items
Users.update({
_id: user._id
}, {
[updateOperator]: { [`subscribedItems.${collectionName}`]: loggedItem }
});
const updatedUser = Users.findOne({_id: user._id}, {fields: {_id:1, subscribedItems: 1}});
return updatedUser;
} else {
throw Error(Utils.encodeIntlError({id: 'app.something_bad_happened'}))
}
};
/**
* @summary Generate mutations 'collection.subscribe' & 'collection.unsubscribe' automatically
* @params {Array[Collections]} collections
*/
const subscribeMutationsGenerator = (collection) => {
// generic mutation function calling the performSubscriptionAction
const genericMutationFunction = (collectionName, action) => {
// return the method code
return function(root, { documentId }, context) {
// extract the current user & the relevant collection from the graphql server context
const { currentUser, [Utils.capitalize(collectionName)]: collection } = context;
// permission check
if (!Users.canDo(context.currentUser, `${collectionName}.${action}`)) {
throw new Error(Utils.encodeIntlError({id: "app.noPermission"}));
}
// do the actual subscription action
return performSubscriptionAction(action, collection, documentId, currentUser);
};
};
const collectionName = collection._name;
// add mutations to the schema
addGraphQLMutation(`${collectionName}Subscribe(documentId: String): User`),
addGraphQLMutation(`${collectionName}Unsubscribe(documentId: String): User`);
// create an object of the shape expected by mutations resolvers
addGraphQLResolvers({
Mutation: {
[`${collectionName}Subscribe`]: genericMutationFunction(collectionName, 'subscribe'),
[`${collectionName}Unsubscribe`]: genericMutationFunction(collectionName, 'unsubscribe'),
},
});
};
// Finally. Add the mutations to the Meteor namespace 🖖
// vulcan:users is a dependency of this package, it is alreay imported
subscribeMutationsGenerator(Users);
// note: leverage weak dependencies on packages
const Posts = Package['vulcan:posts'] ? Package['vulcan:posts'].default : null;
// check if vulcan:posts exists, if yes, add the mutations to Posts
if (!!Posts) {
subscribeMutationsGenerator(Posts);
}
// check if vulcan:categories exists, if yes, add the mutations to Categories
const Categories = Package['vulcan:categories'] ? Package['vulcan:categories'].default : null;
if (!!Categories) {
subscribeMutationsGenerator(Categories);
}
export default subscribeMutationsGenerator;
| acidsound/Telescope | packages/vulcan-subscribe/lib/mutations.js | JavaScript | mit | 6,946 |
<?php
defined('BASEPATH') or exit('No direct script access allowed');
class MY_Loader extends CI_Loader{
public function _construct(){
parent::_construct();
}
public function view($view, $vars = array(), $layout='', $return = FALSE)
{
$layout=($layout=='')?config_item('layout'):$layout;
$vars['contenido']=$this->_ci_load(array('_ci_view' => $view, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => TRUE));
return $this->_ci_load(array('_ci_view' => $layout, '_ci_vars' => $this->_ci_object_to_array($vars), '_ci_return' => $return));
}
}
?> | maxdarkx/batalla_naval | application/core/MY_Loader.php | PHP | mit | 575 |
<?php
/**
* Webiny Platform (http://www.webiny.com/)
*
* @copyright Copyright Webiny LTD
*/
namespace Apps\Webiny\Php\Lib\UserProvider;
use Apps\Webiny\Php\Entities\ApiToken;
use Apps\Webiny\Php\Entities\SystemApiTokenUser;
use Apps\Webiny\Php\Entities\User;
use Apps\Webiny\Php\Lib\WebinyTrait;
/**
* This class handles `Webiny.User.Provide` event and returns one if the platform user entities.
*
* It is registered with the default event priority of 300.
* To add your own user provider, register an event handler with higher priority (ex: 310).
*/
class UserProviderEventHandler
{
use WebinyTrait;
public function handle(UserProviderEvent $event)
{
$data = $event->getData();
$token = $data['meta']['apiToken'] ?? null;
if ($token === 'system') {
return SystemApiTokenUser::load();
}
if ($this->wDatabase()->isId($token)) {
/* @var $apiToken ApiToken */
$apiToken = ApiToken::findById($token);
if ($apiToken) {
return $apiToken->user;
}
}
return isset($data['id']) ? User::findById($data['id']) : null;
}
} | Webiny/Webiny | Php/Lib/UserProvider/UserProviderEventHandler.php | PHP | mit | 1,174 |
package kamil09875.bfparser.syntax;
import java.io.IOException;
import kamil09875.bfparser.BFMemory;
import kamil09875.bfparser.Translator;
public enum BFISet implements BFInstruction{
LEFT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Moving left");
memory.dump();
}
memory.left();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.left();
}
},
RIGHT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Moving right");
memory.dump();
}
memory.right();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.right();
}
},
ADD{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Increasing current value");
memory.dump();
}
memory.add();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.add();
}
},
SUB{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Decreasing current value");
memory.dump();
}
memory.sub();
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.sub();
}
},
OUTPUT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Outputting current value");
memory.dump();
System.out.print("Output: " + memory.get() + " = ");
}
System.out.print((char)memory.get());
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.output();
}
},
INPUT{
@Override
public void execute(final BFMemory memory, final boolean debug){
if(debug){
System.out.println("Setting current value to user input");
memory.dump();
}
try{
memory.set(System.in.read());
}catch(IOException e){
memory.set(-1);
}
if(debug){
System.out.println(" vvv");
memory.dump();
System.out.println();
BFMemory.waitForUser();
}
}
@Override
public String translate(final Translator translator){
return translator.input();
}
};
}
| kamil09875/brainfuck-parser | src/kamil09875/bfparser/syntax/BFISet.java | Java | mit | 2,972 |
import test from 'ava';
import { defaultColors } from './defaultColors.js';
const tests = [
{
name: 'Dark background color defined in theme',
theme: {
colors: {
background: '#333333'
}
},
expectedResult: {
tickText: {
secondary: '#9d9d9d',
primary: '#d9d9d9'
},
series: '#f1f1f1',
value: '#d9d9d9',
axis: '#f1f1f1',
gridline: '#707070',
fallbackBaseColor: '#f1f1f1'
}
},
{
name: 'Custom chart element basecolor,background & blend ratios defined in theme',
theme: {
colors: {
background: '#FCB716',
chartContentBaseColor: '#ffffff',
bgBlendRatios: {
gridline: 0.5,
tickText: {
primary: 0,
secondary: 0
}
}
}
},
expectedResult: {
tickText: {
secondary: '#ffffff',
primary: '#ffffff'
},
series: '#ffffff',
value: '#fef2e4',
axis: '#ffffff',
gridline: '#fedeb5',
fallbackBaseColor: '#ffffff'
}
},
{
name: "No fail when theme doesn't have any data",
theme: {},
expectedResult: {
tickText: {
secondary: '#a6a6a6',
primary: '#7b7b7b'
},
series: '#333333',
value: '#7b7b7b',
axis: '#333333',
gridline: '#e8e8e8',
fallbackBaseColor: '#333333'
}
}
];
tests.forEach(({ theme, name, expectedResult }) => {
test(name, t => {
t.deepEqual(defaultColors(theme), expectedResult);
});
});
| datawrapper/datawrapper | libs/shared/defaultColors.test.js | JavaScript | mit | 1,909 |
// Cloud normal
module.exports = function updateRole(params) {
/*
█████╗ ███████╗██╗ ██╗███╗ ██╗ ██████╗ ██╗ █████╗ ██╗ ██╗ █████╗ ██╗ ██╗
██╔══██╗██╔════╝╚██╗ ██╔╝████╗ ██║██╔════╝ ██╔╝██╔══██╗██║ ██║██╔══██╗╚██╗ ██╔╝
███████║███████╗ ╚████╔╝ ██╔██╗ ██║██║ ██╔╝ ███████║██║ █╗ ██║███████║ ╚████╔╝
██╔══██║╚════██║ ╚██╔╝ ██║╚██╗██║██║ ██╔╝ ██╔══██║██║███╗██║██╔══██║ ╚██╔╝
██║ ██║███████║ ██║ ██║ ╚████║╚██████╗██╔╝ ██║ ██║╚███╔███╔╝██║ ██║ ██║
╚═╝ ╚═╝╚══════╝ ╚═╝ ╚═╝ ╚═══╝ ╚═════╝╚═╝ ╚═╝ ╚═╝ ╚══╝╚══╝ ╚═╝ ╚═╝ ╚═╝
*/
Parse.Cloud.define("testAsync", (req, res) => {
(async () => {
try {
let isQueryAll = req.params.all !== undefined ? true : false;
let userName =
req.params.userName !== undefined
? req.params.userName
: req.user.get("username");
let roleName = req.params.roleName || req.params.role || req.params.r;
!isQueryAll &&
roleName === undefined &&
res.error("Vui lòng nhập tên role");
var userResult = await new Parse.Query(Parse.User)
.equalTo("username", userName)
.find({ useMasterKey: true });
var roleResult = isQueryAll
? await new Parse.Query(Parse.Role)
.equalTo("users", userResult[0])
.find()
: await new Parse.Query(Parse.Role)
.equalTo("name", roleName)
.equalTo("users", userResult[0])
.find();
res.success(
isQueryAll ? res.success(roleResult) : res.success(roleResult[0])
);
} catch (error) {
res.error(error.message);
}
})(); //end async
}); //end define test Async
//NEW
Parse.Cloud.define("isInRole", (req, res) => {
console.log(req);
req.user === undefined && res.error("Vui lòng đăng nhập ");
let roleName = req.params.roleName || req.params.role || req.params.r;
roleName === undefined && res.error("Vui lòng nhập tên role");
(async () => {
var roleResult = await new Parse.Query(Parse.Role)
.equalTo("name", roleName)
.equalTo("users", req.user)
.find();
roleResult.length !== 0 ? res.success(true) : res.success(false);
})();
}); //kết thúc isInRole function.
}; //end cloud
| cuduy197/parse-express | cloud/dev.js | JavaScript | mit | 3,221 |
using System.Collections.Generic;
using GraphLib.CommonOperations;
using GraphLib.VertexCreation;
using GraphLib.Vertices;
using GraphLib.Visiting;
namespace GraphLib.SccDetection
{
public class SccDetector
{
private readonly Graph _graph;
public SccDetector(Graph graph)
{
_graph = graph;
}
public List<List<IVertex>> Process()
{
var reversedGraph = ReverseVertex.Execute(_graph);
FinishingTimeVisitor finishingTimeVisitor = new FinishingTimeVisitor(reversedGraph.VertexCount);
reversedGraph.Visit(new DfsVisitAlgorighm(), finishingTimeVisitor);
SccVisitor sccVisitor = new SccVisitor();
_graph.Visit(new DfsVisitAlgorighm(), sccVisitor, finishingTimeVisitor.SortedVertexTags);
return sccVisitor.Result;
}
public static GraphOptions OptimizedOptions(IVertexTagFactory vertexTagFactory = null)
{
return new GraphOptions(GraphDirection.Directed, VerticesStoreMode.Outcome, GraphPreferedUsage.OptimizedForInsert, false, vertexTagFactory);
}
}
}
| tihilv/GraphLib | GraphLib/SccDetection/SccDetector.cs | C# | mit | 1,143 |
namespace GeckoUBL.Ubl21.Cac
{
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
[System.Xml.Serialization.XmlRootAttribute("BillingReference", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)]
public class BillingReferenceType {
/// <remarks/>
public DocumentReferenceType InvoiceDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType SelfBilledInvoiceDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType CreditNoteDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType SelfBilledCreditNoteDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType DebitNoteDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType ReminderDocumentReference { get; set; }
/// <remarks/>
public DocumentReferenceType AdditionalDocumentReference { get; set; }
/// <remarks/>
[System.Xml.Serialization.XmlElementAttribute("BillingReferenceLine")]
public BillingReferenceLineType[] BillingReferenceLine { get; set; }
}
} | JohnGrekso/GeckoUBL | src/GeckoUBL/Ubl21/Cac/BillingReferenceType.cs | C# | mit | 1,419 |
import composeWithTracker from 'compose-with-tracker'
import { Meteor } from 'meteor/meteor'
export default composeWithTracker((props, onData) => {
onData(null, {
isLoggingIn: Meteor.loggingIn(),
user: Meteor.user() || {},
})
})
| FractalFlows/Emergence | app/imports/client/Pages/User/container.js | JavaScript | mit | 242 |
var ipc = require('ipc_utils')
var id = 1;
var binding = {
getCurrent: function () {
var cb, getInfo;
if (arguments.length == 1) {
cb = arguments[0]
} else {
getInfo = arguments[0]
cb = arguments[1]
}
var responseId = ++id
ipc.once('chrome-windows-get-current-response-' + responseId, function(evt, win) {
cb(win)
})
ipc.send('chrome-windows-get-current', responseId, getInfo)
},
getAll: function (getInfo, cb) {
if (arguments.length == 1) {
cb = arguments[0]
} else {
getInfo = arguments[0]
cb = arguments[1]
}
var responseId = ++id
ipc.once('chrome-windows-get-all-response-' + responseId, function(evt, win) {
cb(win)
})
ipc.send('chrome-windows-get-all', responseId, getInfo)
},
create: function (createData, cb) {
console.warn('chrome.windows.create is not supported yet')
},
update: function (windowId, updateInfo, cb) {
var responseId = ++id
cb && ipc.once('chrome-windows-update-response-' + responseId, function (evt, win) {
cb(win)
})
ipc.send('chrome-windows-update', responseId, windowId, updateInfo)
},
WINDOW_ID_NONE: -1,
WINDOW_ID_CURRENT: -2
};
exports.binding = binding;
| posix4e/electron | atom/common/api/resources/windows_bindings.js | JavaScript | mit | 1,251 |
package main
import (
"flag"
"fmt"
"log"
"net/http"
"github.com/julienschmidt/httprouter"
"github.com/yuriadams/smssender/api/controllers"
)
var (
logOn *bool
port *int
urlBase string
)
func init() {
domain := flag.String("d", "localhost", "domain")
port = flag.Int("p", 8888, "port")
logOn = flag.Bool("l", true, "log on/off")
flag.Parse()
urlBase = fmt.Sprintf("http://%s:%d", *domain, *port)
}
func main() {
smsc := controllers.NewSMSController()
r := httprouter.New()
r.GET("/", smsc.GetSMSHandler)
r.POST("/api/sendSMS", smsc.SendSMSHandler)
logging("Starting server %d...", *port)
log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", *port), r))
}
func logging(format string, v ...interface{}) {
if *logOn {
log.Printf(fmt.Sprintf("%s\n", format), v...)
}
}
| yuriadams/smssender | server.go | GO | mit | 797 |
// Template Source: BaseMethodRequestBuilder.java.tt
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
package com.microsoft.graph.requests;
import com.microsoft.graph.requests.ReportRootGetYammerActivityCountsRequest;
import com.microsoft.graph.models.ReportRoot;
import com.microsoft.graph.models.Report;
import com.microsoft.graph.http.BaseFunctionRequestBuilder;
import com.microsoft.graph.models.ReportRootGetYammerActivityCountsParameterSet;
import com.microsoft.graph.core.IBaseClient;
import com.google.gson.JsonElement;
import javax.annotation.Nullable;
import javax.annotation.Nonnull;
// **NOTE** This file was generated by a tool and any changes will be overwritten.
/**
* The class for the Report Root Get Yammer Activity Counts Request Builder.
*/
public class ReportRootGetYammerActivityCountsRequestBuilder extends BaseFunctionRequestBuilder<Report> {
/**
* The request builder for this ReportRootGetYammerActivityCounts
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
*/
public ReportRootGetYammerActivityCountsRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
super(requestUrl, client, requestOptions);
}
/**
* The request builder for this ReportRootGetYammerActivityCounts
*
* @param requestUrl the request URL
* @param client the service client
* @param requestOptions the options for this request
* @param parameters the parameters for the service method
*/
public ReportRootGetYammerActivityCountsRequestBuilder(@Nonnull final String requestUrl, @Nonnull final IBaseClient<?> client, @Nullable final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions, @Nonnull final ReportRootGetYammerActivityCountsParameterSet parameters) {
super(requestUrl, client, requestOptions);
if(parameters != null) {
functionOptions = parameters.getFunctionOptions();
}
}
/**
* Creates the ReportRootGetYammerActivityCountsRequest
*
* @param requestOptions the options for the request
* @return the ReportRootGetYammerActivityCountsRequest instance
*/
@Nonnull
public ReportRootGetYammerActivityCountsRequest buildRequest(@Nullable final com.microsoft.graph.options.Option... requestOptions) {
return buildRequest(getOptions(requestOptions));
}
/**
* Creates the ReportRootGetYammerActivityCountsRequest with specific requestOptions instead of the existing requestOptions
*
* @param requestOptions the options for the request
* @return the ReportRootGetYammerActivityCountsRequest instance
*/
@Nonnull
public ReportRootGetYammerActivityCountsRequest buildRequest(@Nonnull final java.util.List<? extends com.microsoft.graph.options.Option> requestOptions) {
final ReportRootGetYammerActivityCountsRequest request = new ReportRootGetYammerActivityCountsRequest(
getRequestUrl(),
getClient(),
requestOptions);
for (com.microsoft.graph.options.FunctionOption option : functionOptions) {
request.addFunctionOption(option);
}
return request;
}
}
| microsoftgraph/msgraph-sdk-java | src/main/java/com/microsoft/graph/requests/ReportRootGetYammerActivityCountsRequestBuilder.java | Java | mit | 3,693 |
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var _this = this;
var _1 = require("../../../");
describe("StatefulAccessor", function () {
beforeEach(function () {
_1.Utils.guidCounter = 0;
var SomeAccessor = (function (_super) {
__extends(SomeAccessor, _super);
function SomeAccessor() {
_super.apply(this, arguments);
this.state = new _1.ValueState();
}
return SomeAccessor;
}(_1.StatefulAccessor));
_this.accessor = new SomeAccessor("genres.raw");
_this.searchkit = new _1.SearchkitManager("/");
_this.searchkit.addAccessor(_this.accessor);
});
it("constructor()", function () {
expect(_this.accessor.uuid).toBe("genres.raw1");
expect(_this.accessor.key).toEqual("genres.raw");
expect(_this.accessor.urlKey).toEqual("genres_raw");
});
it("setSearchkitManager()", function () {
expect(_this.accessor.searchkit).toBe(_this.searchkit);
expect(_this.accessor.state).toBe(_this.accessor.resultsState);
});
it("translate()", function () {
_this.searchkit.translate = function (key) {
return { a: 'b' }[key];
};
expect(_this.accessor.translate("a")).toBe("b");
});
it("onStateChange()", function () {
expect(function () { return _this.accessor.onStateChange({}); })
.not.toThrow();
});
it("fromQueryObject", function () {
var queryObject = {
genres_raw: [1, 2],
authors_raw: [3, 4]
};
_this.accessor.fromQueryObject(queryObject);
expect(_this.accessor.state.getValue())
.toEqual([1, 2]);
});
it("getQueryObject()", function () {
_this.accessor.state = new _1.ValueState([1, 2]);
expect(_this.accessor.getQueryObject())
.toEqual({ genres_raw: [1, 2] });
});
it("getResults()", function () {
_this.accessor.results = [1, 2];
expect(_this.accessor.getResults()).toEqual([1, 2]);
});
it("getAggregations()", function () {
expect(_this.accessor.getAggregations(["foo"], 10))
.toEqual(10);
_this.accessor.results = {
aggregations: {
some_count: { value: 11 }
}
};
expect(_this.accessor.getAggregations(["some_count", "value"], 10))
.toEqual(11);
});
it("setResultsState()", function () {
delete _this.accessor.resultsState;
expect(_this.accessor.state)
.not.toBe(_this.accessor.resultsState);
_this.accessor.setResultsState();
expect(_this.accessor.state)
.toBe(_this.accessor.resultsState);
});
it("resetState()", function () {
_this.accessor.state = _this.accessor.state.setValue("foo");
expect(_this.accessor.state.getValue()).toBe("foo");
_this.accessor.resetState();
expect(_this.accessor.state.getValue()).toBe(null);
});
it("buildSharedQuery", function () {
var query = new _1.ImmutableQuery();
expect(_this.accessor.buildSharedQuery(query))
.toBe(query);
});
it("buildOwnQuery", function () {
var query = new _1.ImmutableQuery();
expect(_this.accessor.buildOwnQuery(query))
.toBe(query);
});
});
//# sourceMappingURL=StatefulAccessorSpec.js.map | viktorkh/elastickit_express | node_modules/searchkit/lib/src/__test__/core/accessors/StatefulAccessorSpec.js | JavaScript | mit | 3,647 |
<?php
namespace LiveData\Bundle\ShopBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Customer
*
* @ORM\Table()
* @ORM\Entity(repositoryClass="LiveData\Bundle\ShopBundle\Entity\CustomerRepository")
*/
class Customer
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="lastname", type="string", length=32)
*/
private $lastname;
/**
* @var string
*
* @ORM\Column(name="firstname", type="string", length=32)
*/
private $firstname;
/**
* @var \DateTime
*
* @ORM\Column(name="birthday", type="date")
*/
private $birthday;
/**
* @var string
*
* @ORM\Column(name="address", type="string", length=128, nullable=true)
*/
private $address;
/**
* @var integer
*
* @ORM\Column(name="zipCode", type="integer", nullable=true)
*/
private $zipCode;
/**
* @ORM\ManyToOne(targetEntity="City", inversedBy="customers")
* @ORM\JoinColumn(name="city_id", referencedColumnName="id", onDelete="set null")
*/
private $city;
/**
* @var integer
*
* @ORM\Column(name="sex", type="integer", nullable=true)
*/
private $sex;
/**
* @ORM\OneToMany(targetEntity="Sale", mappedBy="customer")
*/
private $sales;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set lastname
*
* @param string $lastname
* @return Customer
*/
public function setLastname($lastname)
{
$this->lastname = $lastname;
return $this;
}
/**
* Get lastname
*
* @return string
*/
public function getLastname()
{
return $this->lastname;
}
/**
* Set firstname
*
* @param string $firstname
* @return Customer
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* @return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Set birthday
*
* @param \DateTime $birthday
* @return Customer
*/
public function setBirthday($birthday)
{
$this->birthday = $birthday;
return $this;
}
/**
* Get birthday
*
* @return \DateTime
*/
public function getBirthday()
{
return $this->birthday;
}
/**
* Set address
*
* @param string $address
* @return Customer
*/
public function setAddress($address)
{
$this->address = $address;
return $this;
}
/**
* Get address
*
* @return string
*/
public function getAddress()
{
return $this->address;
}
/**
* Set zipCode
*
* @param integer $zipCode
* @return Customer
*/
public function setZipCode($zipCode)
{
$this->zipCode = $zipCode;
return $this;
}
/**
* Get zipCode
*
* @return integer
*/
public function getZipCode()
{
return $this->zipCode;
}
/**
* Set city
*
* @param \stdClass $city
* @return Customer
*/
public function setCity($city)
{
$this->city = $city;
return $this;
}
/**
* Get city
*
* @return \stdClass
*/
public function getCity()
{
return $this->city;
}
/**
* Set sex
*
* @param integer $sex
* @return Customer
*/
public function setSex($sex)
{
$this->sex = $sex;
return $this;
}
/**
* Get sex
*
* @return integer
*/
public function getSex()
{
return $this->sex;
}
/**
* Constructor
*/
public function __construct()
{
$this->sales = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Add sales
*
* @param \LiveData\Bundle\ShopBundle\Entity\Sale $sales
* @return Customer
*/
public function addSale(\LiveData\Bundle\ShopBundle\Entity\Sale $sales)
{
$this->sales[] = $sales;
return $this;
}
/**
* Remove sales
*
* @param \LiveData\Bundle\ShopBundle\Entity\Sale $sales
*/
public function removeSale(\LiveData\Bundle\ShopBundle\Entity\Sale $sales)
{
$this->sales->removeElement($sales);
}
/**
* Get sales
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getSales()
{
return $this->sales;
}
public function getGender() {
if($this->sex ==1)
return 'M';
return 'F';
}
}
| MDBK/LiveData | src/LiveData/Bundle/ShopBundle/Entity/Customer.php | PHP | mit | 4,980 |
const {
SearchkitManager,SearchkitProvider,
SearchBox, Hits, RefinementListFilter, Pagination,
CheckboxFilter,
HierarchicalMenuFilter, HitsStats, SortingSelector, NoHits,
GroupedSelectedFilters, SelectedFilters, ResetFilters,
RangeFilter, NumericRefinementListFilter,
ViewSwitcherHits, ViewSwitcherToggle, Select, Toggle,
ItemList, CheckboxItemList, ItemHistogramList, Tabs, TagCloud, MenuFilter,
renderComponent, PageSizeSelector, RangeSliderHistogramInput, Panel, PaginationSelect,
InputFilter, TagFilter, TagFilterList, TagFilterConfig,
TermQuery, RangeQuery, BoolMust,
Layout, LayoutBody, LayoutResults, SideBar, TopBar, ActionBar, ActionBarRow
} = require("../../../../../src")
const host = "http://demo.searchkit.co/api/movies"
import * as ReactDOM from "react-dom";
import * as React from "react";
const searchkit = new SearchkitManager(host)
const _ = require("lodash")
const map = require("lodash/map")
const isUndefined = require("lodash/isUndefined")
import { TogglePanel } from './TogglePanel'
require("../../../../../theming/theme.scss")
require("./customisations.scss")
const MovieHitsGridItem = (props)=> {
const {bemBlocks, result} = props
let url = "http://www.imdb.com/title/" + result._source.imdbId
const source:any = _.extend({}, result._source, result.highlight)
return (
<div className={bemBlocks.item().mix(bemBlocks.container("item"))} data-qa="hit">
<a href={url} target="_blank">
<img data-qa="poster" className={bemBlocks.item("poster")} src={result._source.poster} width="170" height="240"/>
<div data-qa="title" className={bemBlocks.item("title")} dangerouslySetInnerHTML={{__html:source.title}}>
</div>
</a>
</div>
)
}
const MovieHitsListItem = (props)=> {
const {bemBlocks, result} = props
let url = "http://www.imdb.com/title/" + result._source.imdbId
const source:any = _.extend({}, result._source, result.highlight)
const { title, poster, writers = [], actors = [], genres = [], plot, released, rated } = source;
return (
<div className={bemBlocks.item().mix(bemBlocks.container("item"))} data-qa="hit">
<div className={bemBlocks.item("poster")}>
<img data-qa="poster" src={result._source.poster}/>
</div>
<div className={bemBlocks.item("details")}>
<a href={url} target="_blank"><h2 className={bemBlocks.item("title")} dangerouslySetInnerHTML={{__html:source.title}}></h2></a>
<h3 className={bemBlocks.item("subtitle")}>Released in {source.year}, rated {source.imdbRating}/10</h3>
<ul className={bemBlocks.item("tags")}>
<li>Genres: <TagFilterList field="genres.raw" values={genres} /></li>
<li>Writers: <TagFilterList field="writers.raw" values={writers} /></li>
<li>Actors: <TagFilterList field="actors.raw" values={actors} /></li>
</ul>
<div className={bemBlocks.item("text")} dangerouslySetInnerHTML={{__html:source.plot}}></div>
</div>
</div>
)
}
export class MovieHitsCell extends React.Component<any, {}> {
render(){
const { hit, columnKey, columnIdx } = this.props
if (columnKey === "poster"){
return (
<td key={columnIdx + '-' + columnKey} style={{margin: 0, padding: 0, width: 40}}>
<img data-qa="poster" src={hit._source.poster} style={{width: 40}}/>
</td>
)
} else {
return <td key={columnIdx + '-' + columnKey}>{hit._source[columnKey]}</td>
}
}
}
export class HitsTable extends React.Component<any, {}>{
constructor(props){
super(props)
this.renderHeader = this.renderHeader.bind(this)
this.renderCell = this.renderCell.bind(this)
}
renderHeader(column, idx){
if ((typeof column) === "string"){
return <th key={idx + "-" + column}>{column}</th>
} else {
const label = isUndefined(column.label) ? column.key : column.label
return <th key={idx + "-" + column.key} style={column.style}>{label}</th>
}
}
renderCell(hit, column, idx){
const { cellComponent } = this.props
const key = ((typeof column) === "string") ? column : column.key
var element;
if (cellComponent){
return renderComponent(cellComponent, {hit, columnKey: key, key, column, columnIdx: idx})
} else {
return <td key={idx + '-' + key}>{hit._source[key]}</td>
}
}
render(){
const { columns, hits } = this.props
return (
<div style={{width: '100%', boxSizing: 'border-box', padding: 8}}>
<table className="sk-table sk-table-striped" style={{width: '100%', boxSizing: 'border-box'}}>
<thead>
<tr>{map(columns, this.renderHeader)}</tr>
</thead>
<tbody>
{map(hits, hit => (
<tr key={hit._id}>
{map(columns, (col, idx) => this.renderCell(hit, col, idx))}
</tr>
))}
</tbody>
</table>
</div>
)
}
}
class MovieHitsTable extends React.Component<any, {}> {
render(){
const { hits } = this.props
return (
<div style={{width: '100%', boxSizing: 'border-box', padding: 8}}>
<table className="sk-table sk-table-striped" style={{width: '100%', boxSizing: 'border-box'}}>
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Year</th>
<th>Rating</th>
</tr>
</thead>
<tbody>
{map(hits, hit => (
<tr key={hit._id}>
<td style={{margin: 0, padding: 0, width: 40}}>
<img data-qa="poster" src={hit._source.poster} style={{width: 40}}/>
</td>
<td>{hit._source.title}</td>
<td>{hit._source.year}</td>
<td>{hit._source.imdbRating}</td>
</tr>
))}
</tbody>
</table>
</div>
)
}
}
const listComponents = {
list: ItemList,
checkbox: CheckboxItemList,
histogram: ItemHistogramList,
select: Select,
tabs: (props) => <Tabs {...props} showCount={false}/>,
tags: (props) => <TagCloud {...props} showCount={false} />,
toggle: (props) => <Toggle {...props} showCount={false}/>
}
class App extends React.Component<any, any> {
constructor(props){
super(props)
this.state = {
viewMode: "list"
}
}
handleViewModeChange(e){
this.setState({viewMode: e.target.value})
}
render(){
return (
<SearchkitProvider searchkit={searchkit}>
<Layout>
<TopBar>
<SearchBox autofocus={true} searchOnChange={false} prefixQueryFields={["actors^1","type^2","languages","title^10"]}/>
</TopBar>
<LayoutBody>
<SideBar>
<Panel title="Selected Filters" collapsable={true} defaultCollapsed={false}>
<SelectedFilters/>
</Panel>
<CheckboxFilter id="rated-r" title="Rating" label="Rated R" filter={TermQuery("rated.raw", 'R')} />
<CheckboxFilter id="recent" title="Date" label="Recent" filter={RangeQuery("year", {gt: 2012})} />
<CheckboxFilter id="old-movies" title="Movile filter" label="Old movies" filter={
BoolMust([
RangeQuery("year", {lt: 1970}),
TermQuery("type.raw", "Movie")
])} />
<InputFilter id="author_q" title="Actors filter" placeholder="Search actors" searchOnChange={false} blurAction="search" queryFields={["actors"]}/>
<InputFilter id="writer_q" title="Writers filter" placeholder="Search writers" searchOnChange={false} blurAction="restore" queryFields={["writers"]}/>
<MenuFilter field={"type.raw"} size={10} title="Movie Type" id="types" listComponent={listComponents[this.state.viewMode]}
containerComponent={
(props) => (
<TogglePanel {...props} rightComponent={(
<select value={this.state.listMode} onChange={this.handleViewModeChange.bind(this) }>
<option value="list">List</option>
<option value="checkbox">Checkbox</option>
<option value="histogram">Histogram</option>
<option value="select">Select</option>
<option value="tabs">Tabs</option>
<option value="tags">TagCloud</option>
<option value="toggle">Toggle</option>
</select>
)} />
)
}/>
<HierarchicalMenuFilter fields={["type.raw", "genres.raw"]} title="Categories" id="categories"/>
<RangeFilter min={0} max={100} field="metaScore" id="metascore" title="Metascore" showHistogram={true}/>
<RangeFilter min={0} max={10} field="imdbRating" id="imdbRating" title="IMDB Rating" showHistogram={true} rangeComponent={RangeSliderHistogramInput}/>
<TagFilterConfig id="genres" title="Genres" field="genres.raw" />
<RefinementListFilter id="actors" title="Actors" field="actors.raw" size={10}/>
<RefinementListFilter translations={{"facets.view_more":"View more writers"}} id="writers" title="Writers" field="writers.raw" operator="OR" size={10}/>
<RefinementListFilter id="countries" title="Countries" field="countries.raw" operator="OR" size={10}/>
<NumericRefinementListFilter countFormatter={(count)=>"#"+count} listComponent={Select} id="runtimeMinutes" title="Length" field="runtimeMinutes" options={[
{title:"All"},
{title:"up to 20", from:0, to:20},
{title:"21 to 60", from:21, to:60},
{title:"60 or more", from:61, to:1000}
]}/>
</SideBar>
<LayoutResults>
<ActionBar>
<ActionBarRow>
<HitsStats translations={{
"hitstats.results_found":"{hitCount} results found"
}}/>
<ViewSwitcherToggle/>
{/*<ViewSwitcherToggle listComponent={Select}/>*/}
<PageSizeSelector options={[4,12,25]} listComponent={Toggle }/>
<SortingSelector options={[
{label:"Relevance", field:"_score", order:"desc"},
{label:"Latest Releases", field:"released", order:"desc"},
{label:"Earliest Releases", field:"released", order:"asc"}
]}/>
{/*<SortingSelector options={[
{label:"Relevance", field:"_score", order:"desc"},
{label:"Latest Releases", field:"released", order:"desc"},
{label:"Earliest Releases", field:"released", order:"asc"}
]} listComponent={Toggle}/>*/}
</ActionBarRow>
<ActionBarRow>
<GroupedSelectedFilters/>
<ResetFilters/>
</ActionBarRow>
</ActionBar>
<ViewSwitcherHits
hitsPerPage={12} highlightFields={["title","plot"]}
sourceFilter={["plot", "title", "poster", "imdbId", "imdbRating", "year", "genres", "writers", "actors"]}
hitComponents = {[
{key:"grid", title:"Grid", itemComponent:MovieHitsGridItem},
{key:"list", title:"List", itemComponent:MovieHitsListItem},
{key:"movie-table", title:"Movies", listComponent:MovieHitsTable, defaultOption:true},
{key:"table", title:"Table", listComponent:<HitsTable
cellComponent={MovieHitsCell}
columns={[
{key: 'poster', label: '', style:{ width: 40}},
'title',
'year',
{key: 'imdbRating', label: 'rating'}
]} />}
]}
scrollTo="body"
/>
<NoHits suggestionsField={"title"}/>
<Pagination showNumbers={true}/>
<PaginationSelect/>
</LayoutResults>
</LayoutBody>
</Layout>
</SearchkitProvider>
)
}
}
ReactDOM.render(<App/>, document.getElementById("root"))
| viktorkh/elastickit_express | node_modules/searchkit/test/e2e/server/apps/playground/index.tsx | TypeScript | mit | 12,381 |
/*
The MIT License
Copyright (c) 2010-2021 Paul R. Holser, Jr.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.pholser.junit.quickcheck.runner;
import static java.lang.String.format;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.fail;
import static org.junit.experimental.results.PrintableResult.testResult;
import static org.junit.experimental.results.ResultMatchers.hasFailureContaining;
import com.pholser.junit.quickcheck.From;
import com.pholser.junit.quickcheck.Property;
import com.pholser.junit.quickcheck.UtilityClassesUninstantiabilityHarness;
import com.pholser.junit.quickcheck.test.generator.AnInt;
import org.junit.Test;
import org.junit.runner.RunWith;
public class PropertyFalsifiedUtilityClassTest
extends UtilityClassesUninstantiabilityHarness {
public PropertyFalsifiedUtilityClassTest() {
super(PropertyFalsified.class);
}
@Test public void counterexampleFoundWithAllParameters() {
String propertyName = "mySuperProperty";
String[] arguments = {"first", "second", "third"};
long[] seeds = {12345, 8842};
String assertionName = "assertion name";
AssertionError error = new AssertionError(assertionName);
AssertionError actual =
PropertyFalsified.counterexampleFound(
propertyName,
arguments,
seeds,
error);
String expected =
format(
"Property named 'mySuperProperty' failed (assertion name)%n"
+ "With arguments: [first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test
public void counterexampleFoundWhenAssertionErrorPassedHasNoMessage() {
String propertyName = "mySuperProperty";
String[] arguments = {"first", "second", "third"};
long[] seeds = {12345, 8842};
AssertionError error = new AssertionError();
AssertionError actual =
PropertyFalsified.counterexampleFound(
propertyName,
arguments,
seeds,
error);
String expected =
format(
"Property named 'mySuperProperty' failed:%n"
+ "With arguments: [first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test public void smallerCounterexampleFoundWithAllParameters() {
String propertyName = "mySuperProperty";
String[] originalArguments = {"first", "second", "third"};
String[] arguments = {"first"};
long[] seeds = {12345, 8842};
String smallerFailureName = "smaller name";
AssertionError smallerFailure = new AssertionError(smallerFailureName);
String assertionName = "assertion name";
AssertionError originalFailure = new AssertionError(assertionName);
AssertionError actual =
PropertyFalsified.smallerCounterexampleFound(
propertyName,
originalArguments,
arguments,
seeds,
smallerFailure,
originalFailure);
String expected =
format(
"Property named 'mySuperProperty' failed (smaller name):%n"
+ "With arguments: [first]%n"
+ "Original failure message: assertion name%n"
+ "First arguments found to also provoke a failure: "
+ "[first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test
public void smallerCounterexampleFoundEvenIfSmallerFailureIsNotNamed() {
String propertyName = "mySuperProperty";
String[] originalArguments = {"first", "second", "third"};
String[] arguments = {"first"};
long[] seeds = {12345, 8842};
AssertionError smallerFailure = new AssertionError();
String assertionName = "assertion name";
AssertionError originalFailure = new AssertionError(assertionName);
AssertionError actual =
PropertyFalsified.smallerCounterexampleFound(
propertyName,
originalArguments,
arguments,
seeds,
smallerFailure,
originalFailure);
String expected =
format(
"Property named 'mySuperProperty' failed:%n"
+ "With arguments: [first]%n"
+ "Original failure message: assertion name%n"
+ "First arguments found to also provoke a failure: "
+ "[first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test
public void smallerCounterexampleFoundEvenIfOriginalFailureIsNotNamed() {
String propertyName = "mySuperProperty";
String[] originalArguments = {"first", "second", "third"};
String[] arguments = {"first"};
long[] seeds = {12345, 8842};
AssertionError smallerFailure = new AssertionError();
AssertionError originalFailure = new AssertionError();
AssertionError actual =
PropertyFalsified.smallerCounterexampleFound(
propertyName,
originalArguments,
arguments,
seeds,
smallerFailure,
originalFailure);
String expected =
format(
"Property named 'mySuperProperty' failed:%n"
+ "With arguments: [first]%n"
+ "First arguments found to also provoke a failure: "
+ "[first, second, third]%n"
+ "Seeds for reproduction: [12345, 8842]");
assertThat(actual.getMessage(), equalTo(expected));
}
@Test public void github_212_failWithIllegalFormatSpecifierInMessage() {
assertThat(
testResult(Failing.class),
hasFailureContaining("Failure with a %D in the text"));
}
@RunWith(JUnitQuickcheck.class)
public static class Failing {
@Property public void prop(@From(AnInt.class) int n) {
fail("Failure with a %D in the text");
}
}
}
| pholser/junit-quickcheck | core/src/test/java/com/pholser/junit/quickcheck/runner/PropertyFalsifiedUtilityClassTest.java | Java | mit | 7,581 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace BorderControl
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| schumann2k/BorderControl | BorderControl/Program.cs | C# | mit | 514 |
package openblocks.client.model;
import cpw.mods.fml.common.eventhandler.SubscribeEvent;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.EntityOtherPlayerMP;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelRenderer;
import net.minecraft.client.renderer.entity.RenderManager;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.MathHelper;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.client.event.RenderPlayerEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.common.MinecraftForge;
import openblocks.common.CraneRegistry;
import openblocks.common.entity.EntityMagnet;
import openblocks.common.item.ItemCraneBackpack;
import org.lwjgl.opengl.GL11;
public class ModelCraneBackpack extends ModelBiped {
public static final ModelCraneBackpack instance = new ModelCraneBackpack();
private static final ResourceLocation texture = new ResourceLocation(ItemCraneBackpack.TEXTURE_CRANE);
private static final float DEG_TO_RAD = (float)Math.PI / 180;
private final ModelRenderer arm;
public ModelCraneBackpack() {
textureWidth = 128;
textureHeight = 64;
bipedBody = new ModelRenderer(this, 0, 0);
bipedBody.setTextureSize(textureWidth, textureHeight);
bipedBody.setRotationPoint(0, 0, 0);
// main body
bipedBody.addBox(-4, 0, -2, 8, 12, 8);
// support
bipedBody.setTextureOffset(32, 0);
bipedBody.addBox(-1, -16, 6, 2, 24, 2);
// arm
arm = new ModelRenderer(this, 0, 0);
arm.setTextureSize(textureWidth, textureHeight);
arm.setRotationPoint(0, -16, 7);
arm.addBox(-1, 0, 1, 2, 2, 42);
}
@Override
public void setRotationAngles(float swingTime, float swingAmpl, float rightArmAngle, float headAngleX, float headAngleY, float scale, Entity entity) {
super.setRotationAngles(swingTime, swingAmpl, rightArmAngle, headAngleX, headAngleY, scale, entity);
if (isSneak) {
arm.rotationPointZ = -0.15f; // good enough values
arm.offsetY = -0.125f;
} else {
arm.rotationPointZ = 7;
arm.offsetY = 0;
}
}
@Override
public void render(Entity entity, float swingTime, float swingAmpl, float rightArmAngle, float headAngleX, float headAngleY, float scale) {
isSneak = entity != null && entity.isSneaking();
setRotationAngles(swingTime, swingAmpl, rightArmAngle, headAngleX, headAngleY, scale, entity);
bipedBody.render(scale);
arm.rotateAngleY = (float)Math.PI + bipedHead.rotateAngleY;
arm.render(scale);
}
private static float interpolateAngle(float current, float prev, float partialTickTime) {
float interpolated = prev + partialTickTime * (current - prev);
return (90 + interpolated) * DEG_TO_RAD;
}
private static double interpolatePos(double current, double prev, float partialTickTime) {
return prev + partialTickTime * (current - prev);
}
@SubscribeEvent
public void renderLines(RenderPlayerEvent.Pre evt) {
final EntityPlayer player = evt.entityPlayer;
if (!ItemCraneBackpack.isWearingCrane(player)) return;
final EntityMagnet magnet = CraneRegistry.instance.getMagnetForPlayer(player);
if (magnet == null) return;
double playerX = interpolatePos(player.posX, player.lastTickPosX, evt.partialRenderTick)
- RenderManager.renderPosX;
double playerY = interpolatePos(player.posY, player.lastTickPosY, evt.partialRenderTick)
- RenderManager.renderPosY;
double playerZ = interpolatePos(player.posZ, player.lastTickPosZ, evt.partialRenderTick)
- RenderManager.renderPosZ;
if (player instanceof EntityOtherPlayerMP) playerY += 1.62;
final float offset = interpolateAngle(player.renderYawOffset, player.prevRenderYawOffset, evt.partialRenderTick);
final float head = interpolateAngle(player.rotationYawHead, player.prevRotationYawHead, evt.partialRenderTick);
double armX = playerX;
double armY = playerY;
double armZ = playerZ;
double armLength;
if (player.isSneaking()) {
armY += 0.70;
armLength = 2;
} else {
armX += -0.45 * MathHelper.cos(offset);
armY += 0.65;
armZ += -0.45 * MathHelper.sin(offset);
armLength = 2.4;
}
armX += armLength * MathHelper.cos(head);
armZ += armLength * MathHelper.sin(head);
final double magnetX = interpolatePos(magnet.posX, magnet.lastTickPosX, evt.partialRenderTick) - RenderManager.renderPosX;
final double magnetY = interpolatePos(magnet.posY, magnet.lastTickPosY, evt.partialRenderTick) - RenderManager.renderPosY + magnet.height - 0.1;
final double magnetZ = interpolatePos(magnet.posZ, magnet.lastTickPosZ, evt.partialRenderTick) - RenderManager.renderPosZ;
GL11.glLineWidth(2);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_LINE_STIPPLE);
GL11.glColor3f(1, 1, 0);
GL11.glLineStipple(3, (short)0x0555);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3d(armX, armY, armZ);
GL11.glVertex3d(magnetX, magnetY, magnetZ);
GL11.glEnd();
GL11.glDisable(GL11.GL_LINE_STIPPLE);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
drawLine(magnetX, magnetY, magnetZ, armX, armY, armZ);
}
private static void drawLineFPP(EntityPlayer player, float partialTickTime) {
EntityMagnet magnet = CraneRegistry.instance.getMagnetForPlayer(player);
if (magnet == null) return;
final float yaw = interpolateAngle(player.rotationYaw, player.prevRotationYaw, partialTickTime);
final double posX = 1.9 * MathHelper.cos(yaw);
final double posZ = 1.9 * MathHelper.sin(yaw);
final double centerX = interpolatePos(player.posX, player.lastTickPosX, partialTickTime);
final double centerY = interpolatePos(player.posY, player.lastTickPosY, partialTickTime);
final double centerZ = interpolatePos(player.posZ, player.lastTickPosZ, partialTickTime);
final double magnetX = interpolatePos(magnet.posX, magnet.lastTickPosX, partialTickTime) - centerX;
final double magnetY = interpolatePos(magnet.posY, magnet.lastTickPosY, partialTickTime) - centerY + magnet.height - 0.05;
final double magnetZ = interpolatePos(magnet.posZ, magnet.lastTickPosZ, partialTickTime) - centerZ;
drawLine(magnetX, magnetY, magnetZ, posX, 0.6, posZ);
}
private static void drawLine(double x1, double y1, double z1, double x2, double y2, double z2) {
GL11.glLineWidth(2);
GL11.glDisable(GL11.GL_TEXTURE_2D);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_LINE_STIPPLE);
GL11.glColor3f(0, 0, 0);
GL11.glLineStipple(5, (short)0x5555);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3d(x1, y1, z1);
GL11.glVertex3d(x2, y2, z2);
GL11.glEnd();
GL11.glColor3f(1, 1, 0);
GL11.glLineStipple(5, (short)0xAAAA);
GL11.glBegin(GL11.GL_LINES);
GL11.glVertex3d(x1, y1, z1);
GL11.glVertex3d(x2, y2, z2);
GL11.glEnd();
GL11.glDisable(GL11.GL_LINE_STIPPLE);
GL11.glEnable(GL11.GL_LIGHTING);
GL11.glEnable(GL11.GL_TEXTURE_2D);
}
private void drawArm(RenderWorldLastEvent evt, final EntityPlayer player) {
final TextureManager tex = Minecraft.getMinecraft().getTextureManager();
tex.bindTexture(texture);
GL11.glColor3f(1, 1, 1);
GL11.glDisable(GL11.GL_LIGHTING);
GL11.glPushMatrix();
// values adjusted to roughly match TPP crane position
GL11.glRotated(-player.rotationYaw, 0, 1, 0);
GL11.glTranslatef(0, 1.6f, -1f);
arm.rotateAngleY = 0;
arm.render(1.0f / 16.0f);
GL11.glPopMatrix();
GL11.glEnable(GL11.GL_LIGHTING);
}
@SubscribeEvent
public void renderFppArm(RenderWorldLastEvent evt) {
final Minecraft mc = Minecraft.getMinecraft();
if (mc.gameSettings.thirdPersonView != 0) return;
final Entity rve = mc.renderViewEntity;
if (!(rve instanceof EntityPlayer)) return;
final EntityPlayer player = (EntityPlayer)rve;
if (!ItemCraneBackpack.isWearingCrane(player)) return;
drawArm(evt, player);
drawLineFPP(player, evt.partialTicks);
}
public void init() {
MinecraftForge.EVENT_BUS.register(this);
}
}
| emmertf/OpenBlocks | src/main/java/openblocks/client/model/ModelCraneBackpack.java | Java | mit | 8,011 |