示例#1
0
    def _test_get_by_type(self, current_type):
        import System
        from Merlin.Testing.TypeSample import EnumInt64
        current_type.SetStaticFields()

        self.assertEqual(current_type.StaticByteField, 0)
        self.assertEqual(current_type.StaticSByteField, 1)
        self.assertEqual(current_type.StaticUInt16Field, 2)
        self.assertEqual(current_type.StaticInt16Field, 3)
        self.assertEqual(current_type.StaticUInt32Field, 4)
        self.assertEqual(current_type.StaticInt32Field, 5)
        self.assertEqual(current_type.StaticUInt64Field, 6)
        self.assertEqual(current_type.StaticInt64Field, 7)
        self.assertEqual(current_type.StaticDoubleField, 8)
        self.assertEqual(current_type.StaticSingleField, 9)
        self.assertEqual(current_type.StaticDecimalField, 10)
        self.assertEqual(current_type.StaticCharField, 'a')
        self.assertEqual(current_type.StaticBooleanField, True)
        self.assertEqual(current_type.StaticStringField, 'testing')

        self.assertEqual(current_type.StaticObjectField.Flag, 1111)
        self.assertEqual(current_type.StaticEnumField, EnumInt64.B)
        self.assertEqual(current_type.StaticDateTimeField,
                         System.DateTime(50000))
        self.assertEqual(current_type.StaticSimpleStructField.Flag, 1234)
        self.assertEqual(current_type.StaticSimpleGenericStructField.Flag, 32)
        self.assertEqual(current_type.StaticNullableStructNotNullField.Flag,
                         56)
        self.assertEqual(current_type.StaticNullableStructNullField, None)
        self.assertEqual(current_type.StaticSimpleClassField.Flag, 54)
        self.assertEqual(current_type.StaticSimpleGenericClassField.Flag,
                         "string")
        self.assertEqual(current_type.StaticSimpleInterfaceField.Flag, 87)
示例#2
0
    def _test_get_by_type(self, current_type):
        import System
        from Merlin.Testing.TypeSample import EnumInt16
        self.assertEqual(current_type.InitOnlyByteField, 0)
        self.assertEqual(current_type.InitOnlySByteField, 1)
        self.assertEqual(current_type.InitOnlyUInt16Field, 2)
        self.assertEqual(current_type.InitOnlyInt16Field, 3)
        self.assertEqual(current_type.InitOnlyUInt32Field, 4)
        self.assertEqual(current_type.InitOnlyInt32Field, 5)
        self.assertEqual(current_type.InitOnlyUInt64Field, 6)
        self.assertEqual(current_type.InitOnlyInt64Field, 7)
        self.assertEqual(current_type.InitOnlyDoubleField, 8)
        self.assertEqual(current_type.InitOnlySingleField, 9)
        self.assertEqual(current_type.InitOnlyDecimalField, 10)

        self.assertEqual(current_type.InitOnlyCharField, 'P')
        self.assertEqual(current_type.InitOnlyBooleanField, True)

        self.assertEqual(current_type.InitOnlyEnumField, EnumInt16.B)
        self.assertEqual(current_type.InitOnlyStringField, 'ruby')

        self.assertEqual(current_type.InitOnlyDateTimeField,
                         System.DateTime(5))
        self.assertEqual(current_type.InitOnlySimpleStructField.Flag, 10)
        self.assertEqual(current_type.InitOnlySimpleGenericStructField.Flag,
                         20)
        self.assertEqual(current_type.InitOnlyNullableStructField_NotNull.Flag,
                         30)
        self.assertEqual(current_type.InitOnlyNullableStructField_Null, None)
        self.assertEqual(current_type.InitOnlySimpleClassField.Flag, 40)
        self.assertEqual(current_type.InitOnlySimpleGenericClassField.Flag,
                         "ironruby")

        self.assertEqual(current_type.InitOnlySimpleInterfaceField.Flag, 50)
示例#3
0
def set_sun(location, hoy, north=0):
    """Set the sun in the Rhino scene to correspond to a given location and DateTime.

    Args:
        location: A Ladybug Location object to set the latitude, longitude and
            time zone of the Rhino sun path.
        hoy: A number between 0 and 8760 that represent the hour of the year at
            which to evaluate the sun position. Note that this does not need to
            be an integer and decimal values can be used to specify date times
            that are not on the hour mark.
        north: A number between -360 and 360 for the counterclockwise
            difference between the North and the positive Y-axis in degrees.
            90 is West and 270 is East. (Default: 0).

    Returns:
        The Rhino sun object.
    """
    # process the hoy into a .NET date/time
    lb_dt = DateTime.from_hoy(hoy)
    rh_dt = System.DateTime(lb_dt.year, lb_dt.month, lb_dt.day, lb_dt.hour,
                            lb_dt.minute, 0)

    # enable the sun and set its position based on the location and date/time
    sun_position = doc.Lights.Sun
    sun.Enabled.SetValue(sun_position, True)
    sun.TimeZone.SetValue(sun_position, location.time_zone)
    sun.SetPosition(sun_position, rh_dt, location.latitude, location.longitude)

    # set the north of the sun, ensuring the the y-axis is North
    sun.North.SetValue(sun_position, 90 + north)
    return sun
    def _test_verify(self, o):
        import System
        from Merlin.Testing.TypeSample import EnumInt64
        self.assertEqual(o.InstanceByteField, 5)
        self.assertEqual(o.InstanceSByteField, 10)
        self.assertEqual(o.InstanceUInt16Field, 20)
        self.assertEqual(o.InstanceInt16Field, 30)
        self.assertEqual(o.InstanceUInt32Field, 40)
        self.assertEqual(o.InstanceInt32Field, 50)
        self.assertEqual(o.InstanceUInt64Field, 60)
        self.assertEqual(o.InstanceInt64Field, 70)
        self.assertEqual(o.InstanceDoubleField, 80)
        self.assertEqual(o.InstanceSingleField, 90)
        self.assertEqual(o.InstanceDecimalField, 100)
        self.assertEqual(o.InstanceCharField, 'd')
        self.assertEqual(o.InstanceBooleanField, False)
        self.assertEqual(o.InstanceStringField, 'TESTING')

        self.assertEqual(o.InstanceObjectField, "number_to_string")
        self.assertEqual(o.InstanceEnumField, EnumInt64.C)
        self.assertEqual(o.InstanceDateTimeField, System.DateTime(500000))
        self.assertEqual(o.InstanceSimpleStructField.Flag, 12340)
        self.assertEqual(o.InstanceSimpleGenericStructField.Flag, 320)
        self.assertEqual(o.InstanceNullableStructNotNullField, None)
        self.assertEqual(o.InstanceNullableStructNullField.Flag, 650)
        self.assertEqual(o.InstanceSimpleClassField.Flag, 540)
        self.assertEqual(o.InstanceSimpleGenericClassField.Flag, "STRING")

        self.assertEqual(o.InstanceSimpleInterfaceField.Flag, 78)
示例#5
0
    def _test_verify(self, current_type):
        import System
        from Merlin.Testing.FieldTest import EnumInt64
        self.assertEqual(current_type.StaticByteField, 5)
        self.assertEqual(current_type.StaticSByteField, 10)
        self.assertEqual(current_type.StaticUInt16Field, 20)
        self.assertEqual(current_type.StaticInt16Field, 30)
        self.assertEqual(current_type.StaticUInt32Field, 40)
        self.assertEqual(current_type.StaticInt32Field, 50)
        self.assertEqual(current_type.StaticUInt64Field, 60)
        self.assertEqual(current_type.StaticInt64Field, 70)
        self.assertEqual(current_type.StaticDoubleField, 80)
        self.assertEqual(current_type.StaticSingleField, 90)
        self.assertEqual(current_type.StaticDecimalField, 100)
        self.assertEqual(current_type.StaticCharField, 'd')
        self.assertEqual(current_type.StaticBooleanField, False)
        self.assertEqual(current_type.StaticStringField, 'TESTING')

        self.assertEqual(current_type.StaticObjectField, "number_to_string")
        self.assertEqual(current_type.StaticEnumField, EnumInt64.C)
        self.assertEqual(current_type.StaticDateTimeField,
                         System.DateTime(500000))
        self.assertEqual(current_type.StaticSimpleStructField.Flag, 12340)
        self.assertEqual(current_type.StaticSimpleGenericStructField.Flag, 320)
        self.assertEqual(current_type.StaticNullableStructNotNullField, None)
        self.assertEqual(current_type.StaticNullableStructNullField.Flag, 650)
        self.assertEqual(current_type.StaticSimpleClassField.Flag, 540)
        self.assertEqual(current_type.StaticSimpleGenericClassField.Flag,
                         "STRING")

        self.assertEqual(current_type.StaticSimpleInterfaceField.Flag, 78)
示例#6
0
    def _test_get_by_descriptor(self, o, vf, t):
        import System
        from Merlin.Testing.TypeSample import EnumInt64
        o.SetInstanceFields()
        v = vf and o.Value or o

        self.assertEqual(t.__dict__['InstanceByteField'].__get__(v, t), 0)
        self.assertEqual(t.__dict__['InstanceSByteField'].__get__(v, t), 1)
        self.assertEqual(t.__dict__['InstanceUInt16Field'].__get__(v, t), 2)
        self.assertEqual(t.__dict__['InstanceInt16Field'].__get__(v, t), 3)
        self.assertEqual(t.__dict__['InstanceUInt32Field'].__get__(v, t), 4)
        self.assertEqual(t.__dict__['InstanceInt32Field'].__get__(v, t), 5)
        self.assertEqual(t.__dict__['InstanceUInt64Field'].__get__(v, t), 6)
        self.assertEqual(t.__dict__['InstanceInt64Field'].__get__(v, t), 7)
        self.assertEqual(t.__dict__['InstanceDoubleField'].__get__(v, t), 8)
        self.assertEqual(t.__dict__['InstanceSingleField'].__get__(v, t), 9)
        self.assertEqual(t.__dict__['InstanceDecimalField'].__get__(v, t), 10)
        self.assertEqual(t.__dict__['InstanceCharField'].__get__(v, t), 'a')
        self.assertEqual(t.__dict__['InstanceBooleanField'].__get__(v, t), True)
        self.assertEqual(t.__dict__['InstanceStringField'].__get__(v, t), 'testing')

        self.assertEqual(t.__dict__['InstanceObjectField'].__get__(v, t).Flag, 1111)
        self.assertEqual(t.__dict__['InstanceEnumField'].__get__(v, t), EnumInt64.B)
        self.assertEqual(t.__dict__['InstanceDateTimeField'].__get__(v, t), System.DateTime(50000))
        self.assertEqual(t.__dict__['InstanceSimpleStructField'].__get__(v, t).Flag, 1234)
        self.assertEqual(t.__dict__['InstanceSimpleGenericStructField'].__get__(v, t).Flag, 32) 
        self.assertEqual(t.__dict__['InstanceNullableStructNotNullField'].__get__(v, t).Flag, 56)
        self.assertEqual(t.__dict__['InstanceNullableStructNullField'].__get__(v, t), None)
        self.assertEqual(t.__dict__['InstanceSimpleClassField'].__get__(v, t).Flag, 54)
        self.assertEqual(t.__dict__['InstanceSimpleGenericClassField'].__get__(v, t).Flag, "string")

        self.assertEqual(t.__dict__['InstanceSimpleInterfaceField'].__get__(v, t).Flag, 87)
    def _test_get_by_instance(self, o):
        import System
        from Merlin.Testing.TypeSample import EnumInt64
        o.SetInstanceFields()

        self.assertEqual(o.InstanceByteField, 0)
        self.assertEqual(o.InstanceSByteField, 1)
        self.assertEqual(o.InstanceUInt16Field, 2)
        self.assertEqual(o.InstanceInt16Field, 3)
        self.assertEqual(o.InstanceUInt32Field, 4)
        self.assertEqual(o.InstanceInt32Field, 5)
        self.assertEqual(o.InstanceUInt64Field, 6)
        self.assertEqual(o.InstanceInt64Field, 7)
        self.assertEqual(o.InstanceDoubleField, 8)
        self.assertEqual(o.InstanceSingleField, 9)
        self.assertEqual(o.InstanceDecimalField, 10)
        self.assertEqual(o.InstanceCharField, 'a')
        self.assertEqual(o.InstanceBooleanField, True)
        self.assertEqual(o.InstanceStringField, 'testing')

        self.assertEqual(o.InstanceObjectField.Flag, 1111)
        self.assertEqual(o.InstanceEnumField, EnumInt64.B)
        self.assertEqual(o.InstanceDateTimeField, System.DateTime(50000))
        self.assertEqual(o.InstanceSimpleStructField.Flag, 1234)
        self.assertEqual(o.InstanceSimpleGenericStructField.Flag, 32)
        self.assertEqual(o.InstanceNullableStructNotNullField.Flag, 56)
        self.assertEqual(o.InstanceNullableStructNullField, None)
        self.assertEqual(o.InstanceSimpleClassField.Flag, 54)
        self.assertEqual(o.InstanceSimpleGenericClassField.Flag, "string")

        self.assertEqual(o.InstanceSimpleInterfaceField.Flag, 87)
示例#8
0
    def _test_set_by_type(self, current_type):
        import System
        from Merlin.Testing.FieldTest import EnumInt64
        current_type.SetStaticFields()

        # pass correct values
        current_type.StaticByteField = 5
        current_type.StaticSByteField = 10
        current_type.StaticUInt16Field = 20
        current_type.StaticInt16Field = 30
        current_type.StaticUInt32Field = 40
        current_type.StaticInt32Field = 50
        current_type.StaticUInt64Field = 60
        current_type.StaticInt64Field = 70
        current_type.StaticDoubleField = 80
        current_type.StaticSingleField = 90
        current_type.StaticDecimalField = 100
        current_type.StaticCharField = 'd'
        current_type.StaticBooleanField = False
        current_type.StaticStringField = 'testing'.upper()

        current_type.StaticObjectField = "number_to_string"
        current_type.StaticEnumField = EnumInt64.C
        current_type.StaticDateTimeField = System.DateTime(500000)
        current_type.StaticSimpleStructField = SimpleStruct(12340)
        current_type.StaticSimpleGenericStructField = SimpleGenericStruct[
            System.UInt16](320)
        current_type.StaticNullableStructNotNullField = None
        current_type.StaticNullableStructNullField = SimpleStruct(650)
        current_type.StaticSimpleClassField = SimpleClass(540)
        current_type.StaticSimpleGenericClassField = SimpleGenericClass[str](
            "string".upper())
        current_type.StaticSimpleInterfaceField = ClassImplementSimpleInterface(
            78)

        # verify
        self._test_verify(current_type)

        # set values which need conversion.
        current_type.StaticInt16Field = long(100)
        self.assertEqual(current_type.StaticInt16Field, 100)

        current_type.StaticBooleanField = 0
        self.assertEqual(current_type.StaticBooleanField, False)

        # set bad values
        def f1():
            current_type.StaticInt16Field = "abc"

        def f2():
            current_type.StaticCharField = "abc"

        def f3():
            current_type.StaticEnumField = EnumInt32.B

        for f in [f1, f2, f3]:
            self.assertRaises(TypeError, f)
示例#9
0
def py_date_like_to_net_datetime(datetime_like: tp.Union[datetime, date, str, pd.Period]):
    """Converts either a pandas Period, str, datetime or date to a .NET DateTime."""
    if isinstance(datetime_like, str):
        datetime_like = dateutil.parser.parse(datetime_like)
    if hasattr(datetime_like, 'hour'):
        time_args = (datetime_like.hour, datetime_like.minute, datetime_like.second)
    else:
        time_args = (0, 0, 0)
    return dotnet.DateTime(datetime_like.year, datetime_like.month, datetime_like.day, *time_args)
示例#10
0
def setupDfs0():
  global shePath
  global dfs
  global dfsDataX
  global dfsDataY
  global nX
  global nY
  global nZ
  import clr
  global simStart
  global simStart
  now = MShePy.wm.currentTime()
  clr.AddReference("DHI.Mike.Install, Version=1.0.0.0, Culture=neutral, PublicKeyToken=c513450b5d0bf0bf") # "fully qualified" name required!
  from DHI.Mike.Install import MikeImport, MikeProducts
  MikeImport.SetupLatest()
  clr.AddReference("DHI.Generic.MikeZero.DFS")
  clr.AddReference("DHI.Generic.MikeZero.EUM")
  clr.AddReference("System")
  import System
  from System import Array
  from DHI.Generic.MikeZero import eumUnit, eumItem, eumQuantity
  from DHI.Generic.MikeZero.DFS import DfsFactory, DfsBuilder, DfsSimpleType, DataValueType
  shePath = MShePy.wm.getSheFilePath()
  sheDir = os.path.dirname(shePath)
  filename = os.path.join(sheDir, 'BndFluxes.dfs2')
  builder = DfsBuilder.Create(filename, "MSHE SZ boundary fluxes output per layer", 0)
  builder.SetDataType(1)
  factory = DfsFactory()
  builder.SetGeographicalProjection(factory.CreateProjectionGeoOrigin("NON-UTM", 0, 0, 0))
  simStart = now
  nowSys = System.DateTime(now.year, now.month, now.day, now.hour, now.minute, now.second)
  # note: time unit given here has to be used in WriteItemTimeStepNext
  axis = factory.CreateTemporalNonEqCalendarAxis(eumUnit.eumUsec, nowSys)
  builder.SetTemporalAxis(axis)
  builder.DeleteValueFloat = -1e-30
  (startTime, endTime, values) = MShePy.wm.getValues(MShePy.paramTypes.SZ_X_FLO) # just for the geometry
  (nX, nY, nZ) = values.shape()
  (x0, y0) = MShePy.wm.gridCellToCoord(0, 0)
  (x1, y1) = MShePy.wm.gridCellToCoord(1, 1)
  dfsDataX = Array.CreateInstance(System.Single, nX * nY)
  dfsDataY = Array.CreateInstance(System.Single, nX * nY)
  for x in range(nX):
    for y in range(nY):
      if(not MShePy.wm.gridIsInModel(x, y)):
        dfsDataX[x + y * nX] = builder.DeleteValueFloat
        dfsDataY[x + y * nX] = builder.DeleteValueFloat
  dx = x1 - x0  # cell size, dx == dy
  axis = factory.CreateAxisEqD2(eumUnit.eumUmeter, nX, x0 - dx / 2, dx, nY, y0 - dx / 2, dx)
  itemBuilder = builder.CreateDynamicItemBuilder()
  itemBuilder.SetValueType(DataValueType.MeanStepBackward)
  itemBuilder.SetAxis(axis)
  for iz in range(nZ):
    for xy in ['x', 'y']:
      itemBuilder.Set('Boundary inflow layer {0}, {1}-direction'.format(iz + 1, xy), eumQuantity.Create(eumItem.eumIDischarge, eumUnit.eumUm3PerSec), DfsSimpleType.Float)
      builder.AddDynamicItem(itemBuilder.GetDynamicItemInfo()) 
  builder.CreateFile(filename)
  dfs = builder.GetFile()
示例#11
0
def test_meta_attrs():
    if is_cli or is_silverlight:
        import System
        dateTime = System.DateTime()
    
        AreEqual(dateTime.ToString, dateTime.__getattribute__("ToString"))
        AssertErrorWithMessage(AttributeError, "attribute 'ToString' of 'DateTime' object is read-only", dateTime.__setattr__, "ToString", "foo")
        AssertErrorWithMessage(AttributeError, "attribute 'ToString' of 'DateTime' object is read-only", dateTime.__delattr__, "ToString")
    
        arrayList = System.Collections.Generic.List[int]()
        arrayList.__setattr__("Capacity", 123)
        AreEqual(arrayList.Capacity, 123)
    
    AreEqual(me.__file__, me.__getattribute__("__file__"))
    me.__setattr__("__file__", "foo")
    AreEqual(me.__file__, "foo")
    me.__delattr__("__file__")
    
    class C(object):
        def foo(self): pass
    
    # C.foo is "unbound method" on IronPython but "function" on CPython
    if is_cli or is_silverlight:
        AreEqual(C.foo, C.__getattribute__(C, "foo"))
    else:
        AreEqual(C.foo.im_func, C.__getattribute__(C, "foo"))
    AreEqual(C.__doc__, C.__getattribute__(C, "__doc__"))
    
    # fancy type.__doc__ access...
    x = type.__dict__['__doc__'].__get__

    class C(object): __doc__ = 'foo'

    class D(object): pass

    AreEqual(x(D, None), None)
    AreEqual(x(C, None), 'foo')

    class C(object): __doc__ = 42

    AreEqual(x(C, None), 42)
    
    AssertErrorWithMessage(TypeError, "can't apply this __setattr__ to type object", C.__setattr__, C, "__str__", "foo")
    AssertErrorWithMessage(TypeError, "can't apply this __delattr__ to type object", C.__delattr__, C, "__str__")
    
    s = "hello"
    
    AreEqual(s.center, s.__getattribute__("center"))
    
    AssertErrorWithMessages(AttributeError, "attribute 'center' of 'str' object is read-only",
                                            "'str' object attribute 'center' is read-only", s.__setattr__, "center", "foo")
    
    AssertErrorWithMessages(AttributeError, "attribute 'center' of 'str' object is read-only",
                                            "'str' object attribute 'center' is read-only", s.__delattr__, "center")
    
    AssertError(TypeError, getattr, object(), None)
示例#12
0
 def getSystime(self, mtimeOffset):
     # print( systime.Ticks  )
     Ticks = (mtimeOffset + self.jizhunoffset) * glbUNIT
     systime = System.DateTime(int(Ticks))
     # a=float(SysDatetimeObj.Ticks)/glbUNIT - self.jizhunoffset
     # i= int(a)
     # print("getSystime:::", systime )
     # if i == 1447204343:
     # print("====",a,i,SysDatetimeObj.Ticks-self.jizhunDT.Ticks- 8*3600*10000*1000)
     return systime  #int(a)
示例#13
0
文件: dotnet.py 项目: famiuer/mikeio
def to_dotnet_datetime(x):
    """Convert from python datetime to .NET System.DateTime """
    return System.DateTime(
        x.year,
        x.month,
        x.day,
        x.hour,
        x.minute,
        x.second,
    )
示例#14
0
    def lyr_to_dfsu(self, lyr_name, output_dfsu):
        """
        Create model layer .dfsu file `lyr` attribute. References `lyrs`
        attribute dictionary as value at element coordinates to write to
        .dfsu file.

        See also `lyr_from_shape`.

        Parameters
        ----------
        lyr_name : str
            Layer name as key to `lyrs` attribute dictionary
        output_dfsu : str
            Path to output .dfsu file

        Returns
        -------
        weights : array, shape (n_components,)

        """
        # Check that lyr_name is correct
        assert self.lyrs[lyr_name].shape[0] == self.num_elements, \
            "Length of input layer must equal number of mesh elements"

        # Load mesh file and mesh object
        mesh_class = dfs.mesh.MeshFile()
        dhi_mesh = mesh_class.ReadMesh(self.filename)

        # Call dfsu builder
        builder = dfs.dfsu.DfsuBuilder.Create(dfs.dfsu.DfsuFileType.Dfsu2D)
        builder.SetFromMeshFile(dhi_mesh)

        # Create arbitrary date and timestep; this is not a dynamic dfsu
        date = dt.datetime(2018, 1, 1, 0, 0, 0, 0)
        time_step = 1.0
        builder.SetTimeInfo(System.DateTime(date.year, date.month, date.day),
                            time_step)

        # Create dfsu attribute
        builder.AddDynamicItem(
            lyr_name,
            eumQuantity(eumItem.eumIManningsM, eumUnit.eumUMeter2One3rdPerSec))

        # Create file
        dfsu_file = builder.CreateFile(output_dfsu)

        # Add lyr_name values
        net_arr = Array.CreateInstance(System.Single, self.num_elements)
        for i, val in enumerate(self.lyrs[lyr_name]):
            net_arr[i] = val
        dfsu_file.WriteItemTimeStepNext(0, net_arr)

        # Close file
        dfsu_file.Close()
示例#15
0
    def test_meta_attrs(self):
        """__getattribute__, __setattr__, __delattr__ on builtins"""
        if is_cli:
            import System
            dateTime = System.DateTime()

            self.assertEqual(dateTime.ToString, dateTime.__getattribute__("ToString"))
            self.assertRaisesMessage(AttributeError, "'DateTime' object attribute 'ToString' is read-only", dateTime.__setattr__, "ToString", "foo")
            self.assertRaisesMessage(AttributeError, "'DateTime' object attribute 'ToString' is read-only", dateTime.__delattr__, "ToString")

            arrayList = System.Collections.Generic.List[int]()
            arrayList.__setattr__("Capacity", 123)
            self.assertEqual(arrayList.Capacity, 123)

        self.assertEqual(me.__file__, me.__getattribute__("__file__"))
        me.__setattr__("__file__", "foo")
        self.assertEqual(me.__file__, "foo")
        me.__delattr__("__file__")

        class C(object):
            def foo(self): pass

        self.assertEqual(C.foo, C.__getattribute__(C, "foo"))
        self.assertEqual(C.__doc__, C.__getattribute__(C, "__doc__"))

        # fancy type.__doc__ access...
        x = type.__dict__['__doc__'].__get__

        class C(object): __doc__ = 'foo'

        class D(object): pass

        self.assertEqual(x(D, None), None)
        self.assertEqual(x(C, None), 'foo')

        class C(object): __doc__ = 42

        self.assertEqual(x(C, None), 42)

        self.assertRaisesMessage(TypeError, "can't apply this __setattr__ to type object", C.__setattr__, C, "__str__", "foo")
        self.assertRaisesMessage(TypeError, "can't apply this __delattr__ to type object", C.__delattr__, C, "__str__")

        s = "hello"

        self.assertEqual(s.center, s.__getattribute__("center"))

        self.assertRaisesMessage(AttributeError, "'str' object attribute 'center' is read-only", s.__setattr__, "center", "foo")

        self.assertRaisesMessage(AttributeError, "'str' object attribute 'center' is read-only", s.__delattr__, "center")

        self.assertRaises(TypeError, getattr, object(), None)
示例#16
0
        def date_time_controls(is_enabled, picker_date_event_method,
                               slider_date_event_method,
                               picker_time_event_method,
                               slider_time_event_method):

            current_date_time = System.DateTime.Now
            #date slider and pickers
            date = forms.DateTimePicker()
            date.Mode = forms.DateTimePickerMode.Date
            date.Value = current_date_time
            date.Size = drawing.Size(30, 20)
            date.ValueChanged += picker_date_event_method
            date.Enabled = is_enabled
            #
            date_label = forms.Label(Text='Day of year:')
            date_label.Size = drawing.Size(140, 15)
            date_slider = EtoUtil.create_slider(
                value=current_date_time.Now.DayOfYear,
                min=1,
                max=365,
                snap_to_tick=False,
                tick_frequency=31,
                change_event_method=slider_date_event_method,
                is_enabled=is_enabled)

            # Time slider and picker
            time = forms.DateTimePicker()
            time.Mode = forms.DateTimePickerMode.Time
            time.Value = System.DateTime(1, 1, 1, current_date_time.Hour, 0, 0)
            time.Size = drawing.Size(30, 20)
            time.ValueChanged += picker_time_event_method
            time.Enabled = is_enabled
            #
            time_label = forms.Label(Text='Hour of day:')
            time_label.Size = drawing.Size(140, 15)
            time_slider = EtoUtil.create_slider(
                value=current_date_time.Hour,
                min=0,
                max=23,
                snap_to_tick=True,
                tick_frequency=1,
                change_event_method=slider_time_event_method,
                is_enabled=is_enabled)

            layout = EtoUtil.create_layout_from_control_matrix(
                [[date_label], [date_slider, date], [time_label],
                 [time_slider, time]])

            return layout, date, date_slider, time, time_slider
示例#17
0
    def test_builtin_attributes(self):
        import System

        def AssignMethodOfBuiltin():
            def mylen():
                pass

            l = list()
            l.len = mylen

        self.assertRaises(AttributeError, AssignMethodOfBuiltin)

        def DeleteMethodOfBuiltin():
            l = list()
            del l.len

        self.assertRaises(AttributeError, DeleteMethodOfBuiltin)

        def SetAttrOfBuiltin():
            l = list()
            l.attr = 1

        self.assertRaises(AttributeError, SetAttrOfBuiltin)

        def SetDictElementOfBuiltin():
            l = list()
            l.__dict__["attr"] = 1

        self.assertRaises(AttributeError, SetDictElementOfBuiltin)

        def SetAttrOfCLIType():
            d = System.DateTime()
            d.attr = 1

        self.assertRaises(AttributeError, SetAttrOfCLIType)

        def SetDictElementOfCLIType():
            d = System.DateTime()
            d.__dict__["attr"] = 1

        self.assertRaises(AttributeError, SetDictElementOfCLIType)

        self.assertRaisesMessage(
            TypeError, "vars() argument must have __dict__ attribute", vars,
            list())
        self.assertRaisesMessage(
            TypeError, "vars() argument must have __dict__ attribute", vars,
            System.DateTime())
示例#18
0
    def _test_set_by_descriptor(self, current_type):
        import System
        from Merlin.Testing.FieldTest import EnumInt64
        current_type.SetStaticFields()
        o = current_type()

        # pass correct values
        current_type.__dict__['StaticByteField'].__set__(None, 5)
        current_type.__dict__['StaticSByteField'].__set__(None, 10)
        #current_type.__dict__['StaticSByteField'].__set__(o, 10)
        current_type.__dict__['StaticUInt16Field'].__set__(None, 20)
        current_type.__dict__['StaticInt16Field'].__set__(None, 30)
        current_type.__dict__['StaticUInt32Field'].__set__(None, 40)
        current_type.__dict__['StaticInt32Field'].__set__(None, 50)
        current_type.__dict__['StaticUInt64Field'].__set__(None, 60)
        current_type.__dict__['StaticInt64Field'].__set__(None, 70)
        current_type.__dict__['StaticDoubleField'].__set__(None, 80)
        current_type.__dict__['StaticSingleField'].__set__(None, 90)
        current_type.__dict__['StaticDecimalField'].__set__(None, 100)
        current_type.__dict__['StaticCharField'].__set__(None, 'd')
        current_type.__dict__['StaticBooleanField'].__set__(None, False)
        current_type.__dict__['StaticStringField'].__set__(None, 'TESTING')

        current_type.__dict__['StaticObjectField'].__set__(
            None, "number_to_string")
        current_type.__dict__['StaticEnumField'].__set__(None, EnumInt64.C)
        current_type.__dict__['StaticDateTimeField'].__set__(
            None, System.DateTime(500000))
        current_type.__dict__['StaticSimpleStructField'].__set__(
            None, SimpleStruct(12340))
        current_type.__dict__['StaticSimpleGenericStructField'].__set__(
            None, SimpleGenericStruct[System.UInt16](320))
        current_type.__dict__['StaticNullableStructNotNullField'].__set__(
            None, None)
        current_type.__dict__['StaticNullableStructNullField'].__set__(
            None, SimpleStruct(650))
        current_type.__dict__['StaticSimpleClassField'].__set__(
            None, SimpleClass(540))
        current_type.__dict__['StaticSimpleGenericClassField'].__set__(
            None, SimpleGenericClass[str]("STRING"))
        current_type.__dict__['StaticSimpleInterfaceField'].__set__(
            None, ClassImplementSimpleInterface(78))

        # verify
        self._test_verify(current_type)
示例#19
0
 def BuildICS(self):
     self.LogMsg("info", "ElmcityEventParser", ','.join(sys.path))
     msg = "BuildICS: called with %s unfiltered events, url: %s, filter: |%s|, tz_source: |%s|" % (
         len(self.events), self.url, self.filter, self.tz_source)
     self.LogMsg("info", msg, None)
     try:
         self.ApplyFilter()
         cal = DDay.iCal.iCalendar()
         if (self.tz_source is not None):
             tzinfo = CalendarAggregator.Utils.TzinfoFromName(
                 self.tz_source)
             CalendarAggregator.Collector.AddTimezoneToDDayICal(
                 cal, tzinfo)
         for event in self.events:
             ical_evt = DDay.iCal.Event()
             ical_evt.Summary = event.title
             dt = event.start
             if (event.start_is_utc):
                 utc_dtstart = System.DateTime(dt.year, dt.month,
                                               dt.day, dt.hour,
                                               dt.minute, dt.second,
                                               System.DateTimeKind.Utc)
                 ical_evt.Start = DDay.iCal.iCalDateTime(utc_dtstart)
             else:
                 ical_evt.Start = DDay.iCal.iCalDateTime(
                     dt.year, dt.month, dt.day, dt.hour, dt.minute,
                     dt.second)
             ical_evt.Start.TZID = tzinfo.Id
             ical_evt.UID = CalendarAggregator.Event.MakeEventUid(
                 ical_evt)
             cal.Events.Add(ical_evt)
         serializer = DDay.iCal.Serialization.iCalendar.iCalendarSerializer(
         )
         self.LogMsg(
             "info", "BuildICS: serializing %s filtered events" %
             len(self.events), None)
         self.ics = serializer.SerializeToString(cal)
     except:
         self.LogMsg('exception', 'BuildICS', traceback.format_exc())
示例#20
0
 def f16():
     o.InitOnlyDateTimeField = System.DateTime(300)
示例#21
0
    def create(
        self,
        filename,
        data,
        start_time=None,
        dt=1,
        datetimes=None,
        items=None,
        length_x=1,
        length_y=1,
        x0=0,
        y0=0,
        coordinate=None,
        timeseries_unit=TimeStep.SECOND,
        title=None,
    ):
        """
        Create a dfs2 file

        Parameters
        ----------

        filename: str
            Location to write the dfs2 file
        data: list[np.array]
            list of matrices, one for each item. Matrix dimension: time, y, x
        start_time: datetime, optional
            start date of type datetime.
        timeseries_unit: Timestep, optional
            TimeStep default TimeStep.SECOND
        dt: float, optional
            The time step. Therefore dt of 5.5 with timeseries_unit of TimeStep.MINUTE
            means 5 mins and 30 seconds. Default 1
        datetimes: list[datetime], optional
            datetimes, creates a non-equidistant calendar axis
        items: list[ItemInfo], optional
            List of ItemInfo corresponding to a variable types (ie. Water Level).
        coordinate:
            ['UTM-33', 12.4387, 55.2257, 327]  for UTM, Long, Lat, North to Y orientation. Note: long, lat in decimal degrees
        x0: float, optional
            Lower right position
        x0: float, optional
            Lower right position
        length_x: float, optional
            length of each grid in the x direction (projection units)
        length_y: float, optional
            length of each grid in the y direction (projection units)
        
        title: str, optional
            title of the dfs2 file. Default is blank.
        """

        if title is None:
            title = ""

        n_time_steps = np.shape(data[0])[0]
        number_y = np.shape(data[0])[1]
        number_x = np.shape(data[0])[2]

        n_items = len(data)

        if start_time is None:
            start_time = datetime.now()

        if coordinate is None:
            coordinate = ["LONG/LAT", 0, 0, 0]

        if items is None:
            items = [ItemInfo(f"temItem {i+1}") for i in range(n_items)]

        if not all(np.shape(d)[0] == n_time_steps for d in data):
            raise Warning(
                "ERROR data matrices in the time dimension do not all match in the data list. "
                "Data is list of matices [t,y,x]")
        if not all(np.shape(d)[1] == number_y for d in data):
            raise Warning(
                "ERROR data matrices in the Y dimension do not all match in the data list. "
                "Data is list of matices [t,y,x]")
        if not all(np.shape(d)[2] == number_x for d in data):
            raise Warning(
                "ERROR data matrices in the X dimension do not all match in the data list. "
                "Data is list of matices [t,y,x,]")

        if len(items) != n_items:
            raise Warning(
                "number of items must correspond to the number of arrays in data list"
            )

        if datetimes is None:
            equidistant = True

            if not type(start_time) is datetime:
                raise Warning("start_time must be of type datetime ")
        else:
            equidistant = False
            start_time = datetimes[0]

        # if not isinstance(timeseries_unit, int):
        #    raise Warning("timeseries_unit must be an integer. timeseries_unit: second=1400, minute=1401, hour=1402, "
        #                  "day=1403, month=1405, year= 1404See dfsutil options for help ")

        system_start_time = System.DateTime(
            start_time.year,
            start_time.month,
            start_time.day,
            start_time.hour,
            start_time.minute,
            start_time.second,
        )

        # Create an empty dfs2 file object
        factory = DfsFactory()
        builder = Dfs2Builder.Create(title, "mikeio", 0)

        # Set up the header
        builder.SetDataType(0)

        if coordinate[0] == "LONG/LAT":
            builder.SetGeographicalProjection(
                factory.CreateProjectionGeoOrigin(coordinate[0], coordinate[1],
                                                  coordinate[2],
                                                  coordinate[3]))
        else:
            builder.SetGeographicalProjection(
                factory.CreateProjectionProjOrigin(coordinate[0],
                                                   coordinate[1],
                                                   coordinate[2],
                                                   coordinate[3]))

        if equidistant:
            builder.SetTemporalAxis(
                factory.CreateTemporalEqCalendarAxis(timeseries_unit,
                                                     system_start_time, 0, dt))
        else:
            builder.SetTemporalAxis(
                factory.CreateTemporalNonEqCalendarAxis(
                    eumUnit.eumUsec, system_start_time))

        builder.SetSpatialAxis(
            factory.CreateAxisEqD2(eumUnit.eumUmeter, number_x, x0, length_x,
                                   number_y, y0, length_y))

        for i in range(n_items):
            builder.AddDynamicItem(
                items[i].name,
                eumQuantity.Create(items[i].type, items[i].unit),
                DfsSimpleType.Float,
                DataValueType.Instantaneous,
            )

        try:
            builder.CreateFile(filename)
        except IOError:
            print("cannot create dfs2 file: ", filename)

        dfs = builder.GetFile()
        deletevalue = dfs.FileInfo.DeleteValueFloat  # -1.0000000031710769e-30

        for i in range(n_time_steps):
            for item in range(n_items):
                d = data[item][i, :, :]
                d[np.isnan(d)] = deletevalue
                d = d.reshape(number_y, number_x)
                d = np.flipud(d)
                darray = Array[System.Single](np.array(
                    d.reshape(d.size, 1)[:, 0]))

                if equidistant:
                    dfs.WriteItemTimeStepNext(0, darray)
                else:
                    t = datetimes[i]
                    relt = (t - start_time).seconds
                    dfs.WriteItemTimeStepNext(relt, darray)

        dfs.Close()
 def f17():
     t.__dict__['InstanceDateTimeField'].__set__(
         v, System.DateTime(500000))
 def f17():
     t.InstanceDateTimeField.__set__(v, System.DateTime(500000))
 def f17():
     v.InstanceDateTimeField = System.DateTime(500000)
示例#25
0
    def _test_get_by_descriptor(self, current_type):
        import System
        from Merlin.Testing.FieldTest import EnumInt64
        current_type.SetStaticFields()
        o = current_type()
        self.assertEqual(
            current_type.__dict__['StaticByteField'].__get__(
                None, current_type), 0)
        self.assertEqual(
            current_type.__dict__['StaticSByteField'].__get__(o, current_type),
            1)
        self.assertEqual(
            current_type.__dict__['StaticUInt16Field'].__get__(
                None, current_type), 2)
        self.assertEqual(
            current_type.__dict__['StaticInt16Field'].__get__(o, current_type),
            3)
        self.assertEqual(
            current_type.__dict__['StaticUInt32Field'].__get__(
                None, current_type), 4)
        self.assertEqual(
            current_type.__dict__['StaticInt32Field'].__get__(o, current_type),
            5)
        self.assertEqual(
            current_type.__dict__['StaticUInt64Field'].__get__(
                None, current_type), 6)
        self.assertEqual(
            current_type.__dict__['StaticInt64Field'].__get__(o, current_type),
            7)
        self.assertEqual(
            current_type.__dict__['StaticDoubleField'].__get__(
                None, current_type), 8)
        self.assertEqual(
            current_type.__dict__['StaticSingleField'].__get__(
                o, current_type), 9)
        self.assertEqual(
            current_type.__dict__['StaticDecimalField'].__get__(
                None, current_type), 10)
        self.assertEqual(
            current_type.__dict__['StaticCharField'].__get__(o, current_type),
            'a')
        self.assertEqual(
            current_type.__dict__['StaticBooleanField'].__get__(
                None, current_type), True)
        self.assertEqual(
            current_type.__dict__['StaticStringField'].__get__(
                o, current_type), 'testing')

        self.assertEqual(
            current_type.__dict__['StaticObjectField'].__get__(
                None, current_type).Flag, 1111)
        self.assertEqual(
            current_type.__dict__['StaticEnumField'].__get__(o, current_type),
            EnumInt64.B)
        self.assertEqual(
            current_type.__dict__['StaticDateTimeField'].__get__(
                None, current_type), System.DateTime(50000))
        self.assertEqual(
            current_type.__dict__['StaticSimpleStructField'].__get__(
                o, current_type).Flag, 1234)
        self.assertEqual(
            current_type.__dict__['StaticSimpleGenericStructField'].__get__(
                None, current_type).Flag, 32)
        self.assertEqual(
            current_type.__dict__['StaticNullableStructNotNullField'].__get__(
                o, current_type).Flag, 56)
        self.assertEqual(
            current_type.__dict__['StaticNullableStructNullField'].__get__(
                None, current_type), None)
        self.assertEqual(
            current_type.__dict__['StaticSimpleClassField'].__get__(
                o, current_type).Flag, 54)
        self.assertEqual(
            current_type.__dict__['StaticSimpleGenericClassField'].__get__(
                None, current_type).Flag, "string")

        self.assertEqual(
            current_type.__dict__['StaticSimpleInterfaceField'].__get__(
                o, current_type).Flag, 87)
示例#26
0
 def SetDictElementOfCLIType():
     d = System.DateTime()
     d.__dict__["attr"] = 1
示例#27
0
 def SetAttrOfCLIType():
     d = System.DateTime()
     d.attr = 1
示例#28
0
def getTimeLength(temTime):
    ot = System.DateTime(1970, 1, 1, 0, 0, 0)
    delta = temTime - ot
    lenTime = delta.TotalMilliseconds
    return lenTime
示例#29
0
    def _test_get_by_descriptor(self, current_type):
        import System
        from Merlin.Testing.TypeSample import EnumInt16
        o = current_type()
        self.assertEqual(
            current_type.__dict__['InitOnlyByteField'].__get__(
                None, current_type), 0)
        self.assertEqual(
            current_type.__dict__['InitOnlySByteField'].__get__(
                o, current_type), 1)
        self.assertEqual(
            current_type.__dict__['InitOnlyUInt16Field'].__get__(
                None, current_type), 2)
        self.assertEqual(
            current_type.__dict__['InitOnlyInt16Field'].__get__(
                o, current_type), 3)
        self.assertEqual(
            current_type.__dict__['InitOnlyUInt32Field'].__get__(
                None, current_type), 4)
        self.assertEqual(
            current_type.__dict__['InitOnlyInt32Field'].__get__(
                o, current_type), 5)
        self.assertEqual(
            current_type.__dict__['InitOnlyUInt64Field'].__get__(
                None, current_type), 6)
        self.assertEqual(
            current_type.__dict__['InitOnlyInt64Field'].__get__(
                o, current_type), 7)
        self.assertEqual(
            current_type.__dict__['InitOnlyDoubleField'].__get__(
                None, current_type), 8)
        self.assertEqual(
            current_type.__dict__['InitOnlySingleField'].__get__(
                o, current_type), 9)
        self.assertEqual(
            current_type.__dict__['InitOnlyDecimalField'].__get__(
                None, current_type), 10)

        self.assertEqual(
            current_type.__dict__['InitOnlyCharField'].__get__(
                o, current_type), "P")
        self.assertEqual(
            current_type.__dict__['InitOnlyBooleanField'].__get__(
                None, current_type), True)
        self.assertEqual(
            current_type.__dict__['InitOnlyStringField'].__get__(
                o, current_type), "ruby")

        self.assertEqual(
            current_type.__dict__['InitOnlyEnumField'].__get__(
                None, current_type), EnumInt16.B)
        self.assertEqual(
            current_type.__dict__['InitOnlyDateTimeField'].__get__(
                o, current_type), System.DateTime(5))

        self.assertEqual(
            current_type.__dict__['InitOnlySimpleStructField'].__get__(
                None, current_type).Flag, 10)
        self.assertEqual(
            current_type.__dict__['InitOnlySimpleGenericStructField'].__get__(
                o, current_type).Flag, 20)
        self.assertEqual(
            current_type.__dict__['InitOnlyNullableStructField_NotNull'].
            __get__(None, current_type).Flag, 30)
        self.assertEqual(
            current_type.__dict__['InitOnlyNullableStructField_Null'].__get__(
                o, current_type), None)
        self.assertEqual(
            current_type.__dict__['InitOnlySimpleClassField'].__get__(
                None, current_type).Flag, 40)
        self.assertEqual(
            current_type.__dict__['InitOnlySimpleGenericClassField'].__get__(
                o, current_type).Flag, "ironruby")
        self.assertEqual(
            current_type.__dict__['InitOnlySimpleInterfaceField'].__get__(
                None, current_type).Flag, 50)

        for t in [current_type, SimpleStruct, SimpleClass]:
            self.assertRaisesRegexp(
                TypeError, "(expected .*, got type)",
                lambda: current_type.__dict__['InitOnlySimpleGenericClassField'
                                              ].__get__(t, current_type))

        for t in [None, o, SimpleClass, SimpleStruct]:
            self.assertEqual(
                current_type.__dict__['InitOnlyEnumField'].__get__(None, t),
                EnumInt16.B)
示例#30
0
 def f16(): o.InitOnlyDateTimeField = System.DateTime(300)
 
 def f17(): o.InitOnlySimpleStructField = SimpleStruct(30)