コード例 #1
0
ファイル: __init__.py プロジェクト: lynch829/PyESAPI
def fill_in_profiles(dose_or_image, profile_fxn, row_buffer, dtype, pre_buffer=None):
    '''fills in 3D profile data (dose or segments)'''
    mask_array = np.zeros((dose_or_image.XSize, dose_or_image.YSize, dose_or_image.ZSize))

    # note used ZSize-1 to match zero indexed loops below and compute_voxel_points_matrix(...)
    z_direction = VVector.op_Multiply(Double((dose_or_image.ZSize - 1) * dose_or_image.ZRes), dose_or_image.ZDirection)
    y_step = VVector.op_Multiply(dose_or_image.YRes, dose_or_image.YDirection)

    for x in range(dose_or_image.XSize):  # scan X dimensions
        start_x = VVector.op_Addition(dose_or_image.Origin,
                                      VVector.op_Multiply(Double(x * dose_or_image.XRes), dose_or_image.XDirection))

        for y in range(dose_or_image.YSize):  # scan Y dimension
            stop = VVector.op_Addition(start_x, z_direction)

            # get the profile along Z dimension
            if pre_buffer is None:
                profile_fxn(start_x, stop, row_buffer)
            else:
                profile_fxn(start_x, stop, pre_buffer)
                pre_buffer.CopyTo(row_buffer, 0)

            # save data
            mask_array[x, y, :] = to_ndarray(row_buffer, dtype)

            # add step for next point
            start_x = VVector.op_Addition(start_x, y_step)

    return mask_array
コード例 #2
0
def getRate(handPoker, boardPoker, numOpp):
    speed = 0.1
    win = Hand.WinOdds(handPoker, boardPoker, "", numOpp, speed)
    _, ppotv, npotv = Hand.HandPotential(handPoker, boardPoker, Double(0),
                                         Double(0), numOpp, speed)
    hs = Hand.HandStrength(handPoker, boardPoker, numOpp, speed)
    ehs = hs * (1 - npotv) + (1 - hs) * ppotv
    #logging.debug("win:{:.5f},ppotv:{:.5f},npotv:{:.5f},hs:{:.5f},ehs{:.5f}".format(win,ppotv,npotv,hs,ehs))
    return win, ppotv, npotv, hs, ehs
コード例 #3
0
ファイル: python_test.py プロジェクト: cpnei/HandEvaluator
def test_HandPotential():
    pp = Double(0)
    np = Double(0)
    Pocket = "ac as"
    Board = "4d 5d 6c"
    r = Hand.HandPotential(Pocket, Board, pp, np)
    print("Positive potential", pp)
    print("Negative potential", np)
    print(r)
コード例 #4
0
ファイル: h5_cmpd.py プロジェクト: gabrich10/HDF5DotNet
def createDatasetWithCompoundType(h5file):

    mtype = createMemType()
    ftype = createFileType()

    npoints = 4
    shape = Array[Int64]((npoints, ))
    dspace = H5S.create_simple(shape.Length, shape)

    dset = H5D.create(h5file, 'DS1', ftype, dspace)

    ms = MemoryStream()
    writer = BinaryWriter(ms)

    writer.Write(Int32(1153))
    s = 'Exterior (static)'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(53.23))
    writer.Write(Double(24.57))

    writer.Write(Int32(1184))
    s = 'Intake'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(55.12))
    writer.Write(Double(22.95))

    writer.Write(Int32(1027))
    s = 'Intake manifold'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(103.55))
    writer.Write(Double(31.23))

    writer.Write(Int32(1313))
    s = 'Exhaust manifold'
    if IntPtr.Size == 8:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt64())
    else:
        writer.Write(Marshal.StringToHGlobalAnsi(s).ToInt32())
    writer.Write(Double(1252.89))
    writer.Write(Double(84.11))

    byteArray = ms.ToArray()

    H5D.write(dset, mtype, H5Array[Byte](byteArray))

    H5S.close(dspace)
    H5T.close(ftype)
    H5T.close(mtype)

    return dset
コード例 #5
0
    def __setattr__(self, key, value):
        try:
            _type = self.get_type(key)
        except AttributeError:
            raise AttributeError(f"{key} is not a valid field of {self.db_name}")

        if not self.assignment_types_are_equal(_type, value):
            raise Exception(f"Trying to assign incorrect type to {key}")

        default_arguments = (self.data, getattr(self.api, key.upper()))

        error = None
        if _type == self.api.ADK_FIELD_TYPE.eChar:
            error = self.api.AdkSetStr(*default_arguments, String(f"{value}"))[0]
        elif _type == self.api.ADK_FIELD_TYPE.eDouble:
            error = self.api.AdkSetDouble(*default_arguments, Double(value))
        elif _type == self.api.ADK_FIELD_TYPE.eBool:
            error = self.api.AdkSetBool(*default_arguments, Boolean(value))
        elif _type == self.api.ADK_FIELD_TYPE.eDate:
            error = self.api.AdkSetDate(*default_arguments, self.to_date(value))

        if error and error.lRc != self.api.ADKE_OK:
            error_message = self.api.AdkGetErrorText(
                error, self.api.ADK_ERROR_TEXT_TYPE.elRc
            )
            raise Exception(error_message)
コード例 #6
0
    def rows(self):
        """
        Returns a list of rows which are of type _Pdata
        You may access any fields, do assignments and delete rows like any other _Pdata objects
        """
        _row_db_id = self.api.AdkGetRowDataId(self.data, Int32(0))[1]
        _nrows_field_id = self.api.AdkGetNrowsFieldId(self.data, Int32(0))[1]
        _rows_field_id = self.api.AdkGetRowsFieldId(self.data, Int32(0))[1]
        nrows = self.api.AdkGetDouble(self.data, _nrows_field_id, Double(0.0))[1]

        _existing_rows = []
        for index in range(int(nrows)):
            data = self.api.AdkGetRowData(self.data, index, Int32(0))[1]
            _existing_rows.append(
                _Pdata(
                    self.api,
                    _row_db_id,
                    data,
                    parent_pdata=self,
                    is_a_row=True,
                    row_index=index + 1,
                )
            )

        return _existing_rows
コード例 #7
0
 def _Py_Decimal(self, value):
     '''
     Casting a python double to System.Decimal results in the Decimal having only integer values, likely due to an
     improper selection of the overloaded Decimal function. Casting it first to System.Double, which always maintains
     precision, then from Double to Decimal, where the proper overloaded function is clear, bypasses this issue
     :param value: a python double
     :return: the input as a System.Decimal
     '''
     return Decimal(Double(value))
コード例 #8
0
ファイル: sarsaAgent.py プロジェクト: sypannapis/holdem
    def readState(self, state, playerid):
        self.call_risk = float(state.community_state.to_call) / (
            state.community_state.totalpot + state.community_state.to_call)
        #assert self.call_risk <= 0.5
        pocket = card_list_to_str(state.player_states[playerid].hand)
        board = card_list_to_str(state.community_card)
        self.stack = state.player_states[playerid].stack
        self.call_level = float(state.community_state.to_call) / 20
        if self.call_level < 1:
            self.call_level = 0
        else:
            self.call_level = int(np.log2(self.call_level))

        #self.logger.info("debug:", board, ",", self.lastboard)
        if state.community_state.round != self.round:
            self.round = state.community_state.round
            self.hand_odds = self.calcHandOdds(pocket, board)
            if self.round < 3 and self.round > 0:
                (r, self.ppot,
                 self.npot) = Hand.HandPotential(pocket, board, Double(0),
                                                 Double(0))
            else:
                (self.ppot, self.npot) = (0.0, 0.0)
            self.lastboard = board
            self._roundRaiseCount = 0

        self.n_opponent = 0
        for p in state.player_states:
            if p.playing_hand:
                self.n_opponent += 1
        if state.player_states[playerid].playing_hand:
            # self is not opponent
            self.n_opponent -= 1

        available_actions = [
            action_table.CALL, action_table.RAISE, action_table.FOLD
        ]
        if state.player_states[
                playerid].stack == 0 or self._roundRaiseCount == 4:
            available_actions.remove(action_table.RAISE)
        if state.community_state.to_call <= state.player_states[
                playerid].betting:
            available_actions.remove(action_table.FOLD)
        return available_actions
コード例 #9
0
ファイル: python_test.py プロジェクト: cpnei/HandEvaluator
def test_MCWinRate():
    wr = Double(0)
    
    start_time = time.time()
    Pocket = "ac as"
    Board = "4d 5d 6c"
    for i in [10, 100, 1000, 10000, 100000, 1000000]:
        r = Hand.MCWinRate(Pocket, Board, "", 10, i, wr)
        etime = (time.time()-start_time)
        print(i, r)
        print("elapsed time=", etime)
コード例 #10
0
    def create_rows(self, quantity=1):
        """
        Returns a list containg rows of _Pdata type.
        Example:
            rows = invoice.create_rows(2)
            rows[0].adk_ooi_... = "hello"
            rows[1].adk_ooi_... = "world"
            invoice.save()

        Args:
            quantity: number of rows to create
        """
        if quantity < 1:
            raise ValueError("New row quantity must be 1 or higher.")

        _row_db_id = self.api.AdkGetRowDataId(self.data, Int32(0))[1]
        _nrows_field_id = self.api.AdkGetNrowsFieldId(self.data, Int32(0))[1]
        _rows_field_id = self.api.AdkGetRowsFieldId(self.data, Int32(0))[1]
        nrows = self.api.AdkGetDouble(self.data, _nrows_field_id, Double(0.0))[1]

        _rows = self.api.AdkCreateDataRow(_row_db_id, int(nrows) + quantity)
        self.api.AdkSetDouble(self.data, _nrows_field_id, Double(nrows + quantity))
        self.api.AdkSetData(self.data, _rows_field_id, _rows)

        row_objects = []
        for index in range(quantity):
            actual_nrows_index = nrows + index
            row_objects.append(
                _Pdata(
                    self.api,
                    _row_db_id,
                    self.api.AdkGetDataRow(_rows, actual_nrows_index),
                    parent_pdata=self,
                    row_index=actual_nrows_index,
                )
            )

        return row_objects
コード例 #11
0
	def parseNumber(json, index, success):
		index = JsonDecoder.skipWhitespace(json, index)
		lastIndex = JsonDecoder.getLastIndexOfNumber(json, index)
		charLength = (lastIndex - index) + 1

		sb = StringBuilder()
						
		for i in range(charLength):
			sb.Append(json[index + i])

		success, number = Double.TryParse(sb.ToString(), NumberStyles.Any, CultureInfo.InvariantCulture)
		index = lastIndex + 1
		
		return number, index, success
コード例 #12
0
ファイル: h5_compound.py プロジェクト: gabrich10/HDF5DotNet
def createDatasetWithCompoundType(h5file):

    # component name -> (offset, size, type)

    ht = { 'a_name': (0, 4, H5T_NATIVE_INT),
           'b_name': (4, 4, H5T_NATIVE_FLOAT),
           'c_name': (8, 8, H5T_NATIVE_DOUBLE) }

    sizeof = 0
    for k in ht.keys():
        sizeof  += ht[k][1]

    dtype = H5T.create(H5T.CreateClass.COMPOUND, sizeof)
    for k in ht.keys():
        H5T.insert(dtype, k, ht[k][0], ht[k][2])

    npoints = 10
    shape = Array[Int64]((npoints,))
    dspace = H5S.create_simple(shape.Length, shape)

    dset = H5D.create(h5file, 'ArrayOfStructures', dtype, dspace)

    # create an array of Byte
    # use BitConverter to get Byte representations

    shape = Array[Int64]((npoints*sizeof,))
    byteArray = Array.CreateInstance(Byte, shape)

    for i in range(npoints):

        offset = i*sizeof

        a = Int32(i)
        Array.Copy(BitConverter.GetBytes(a), 0, byteArray,
                   offset+ht['a_name'][0], ht['a_name'][1])
        b = Single(i*i)
        Array.Copy(BitConverter.GetBytes(b), 0, byteArray,
                   offset+ht['b_name'][0], ht['b_name'][1])
        c = Double(1.0/(i+1.0))
        Array.Copy(BitConverter.GetBytes(c), 0, byteArray,
                   offset+ht['c_name'][0], ht['c_name'][1])

    H5D.write(dset, dtype, H5Array[Byte](byteArray))

    H5S.close(dspace)
    H5T.close(dtype)

    return dset
コード例 #13
0
    def __getattr__(self, key):
        try:
            _type = self.get_type(key)
        except AttributeError:
            raise AttributeError(f"{key} is not a valid field of {self.db_name}")

        default_arguments = (self.data, getattr(self.api, key.upper()))

        if _type == self.api.ADK_FIELD_TYPE.eChar:
            return self.api.AdkGetStr(*default_arguments, String(""))[1]
        elif _type == self.api.ADK_FIELD_TYPE.eDouble:
            return self.api.AdkGetDouble(*default_arguments, Double(0.0))[1]
        elif _type == self.api.ADK_FIELD_TYPE.eBool:
            return self.api.AdkGetBool(*default_arguments, Boolean(0))[1]
        elif _type == self.api.ADK_FIELD_TYPE.eDate:
            return self.api.AdkGetDate(*default_arguments, DateTime())[1]
コード例 #14
0
    def set_dac_voltage(self, V, ch_number, device_number=0):
        """
        Sets the output voltage in volts.

        Parameters
        ----------
        V : float
            output voltage
        ch_number : int
            channel number 0,1,2,3 or 4
        device_number : int
            Index of the LCDriver

        Returns
        -------
        bool
            True if command is sent successfully
        """
        max_volts = self.get_max_voltage()
        if V > max_volts:
            V = max_volts
        elif V < 0.0:
            V = 0.0
        return self.lcdriver.SetDACVoltage(Double(V), Byte(ch_number), device_number)
コード例 #15
0
ファイル: test_ironmath.py プロジェクト: slozier/ironpython3
    def test_bigint(self):
        from System import Int64, Boolean, Char, Double, Single, IConvertible
        from System.Numerics import BigInteger
        self.assertEqual(
            BigInteger.Add(
                big(1),
                99999999999999999999999999999999999999999999999999999999999),
            BigInteger.Subtract(
                100000000000000000000000000000000000000000000000000000000001,
                big(1)))
        self.assertEqual(BigInteger.Multiply(big(400), big(500)),
                         BigInteger.Divide(big(1000000), big(5)))
        self.assertEqual(BigInteger.Multiply(big(400), big(8)),
                         big(400) << big(3))
        self.assertEqual(BigInteger.Divide(big(400), big(8)),
                         big(400) >> big(3))
        self.assertEqual((big(400) << big(100)) >> big(100), big(400))
        self.assertEqual((-12345678987654321 << big(100)) >> big(100),
                         -12345678987654321)
        self.assertRaises(ValueError, lambda x, y: x >> y, big(400), -big(100))
        self.assertRaises(ValueError, lambda x, y: x << y, big(400), -big(100))
        self.assertRaises(ValueError, lambda x, y: x >> y, -12345678987654321,
                          -big(100))
        self.assertRaises(ValueError, lambda x, y: x << y, -12345678987654321,
                          -big(100))
        self.assertEqual(
            ~(~big(
                -123456781234567812345678123456781234567812345678123456781234567812345678
            )),
            -123456781234567812345678123456781234567812345678123456781234567812345678
        )
        self.assertEqual(
            ~big(
                -1234567812345678123456781234567812345678123456781234567812345678123456781234567812345678
            ),
            -(-1234567812345678123456781234567812345678123456781234567812345678123456781234567812345678
              + big(1)))
        self.assertTrue(
            big(-1234567812345678123456781234567812345678123456781234567812345678123456781234567812345678
                ) ^
            (~big(
                -1234567812345678123456781234567812345678123456781234567812345678123456781234567812345678
            )), -big(1))
        self.assertEqual(
            big(0xff00ff00) & (big(0x00ff00ff) | big(0xaabbaabb)),
            big(0xaa00aa00))
        self.assertEqual(
            big(-9999999999999999999999999999999999999999) %
            1000000000000000000, -(9999999999999999999999999999999999999999 %
                                   big(-1000000000000000000)))

        self.assertEqual(Int64(big(0x7fffffffffffffff)), 9223372036854775807)
        self.assertRaises(OverflowError, Int64, big(0x8000000000000000))

        self.assertEqual(Boolean(big(-0)), False)
        self.assertEqual(Boolean(big(int(-1212321.3213))), True)
        self.assertEqual(Boolean(big(1212321384892342394723947)), True)

        self.assertEqual(Char(big(0)), Char.MinValue)
        self.assertEqual(Char(big(65)), IConvertible.ToChar('A', self.p))
        self.assertEqual(Char(big(0xffff)), Char.MaxValue)
        self.assertRaises(OverflowError, Char, big(-1))

        self.assertEqual(Double(big(100)), 100.0)
        self.assertEqual(Single(big(100)), 100.0)
        self.assertEqual(Single(big(100)),
                         IConvertible.ToSingle(int(100.1213123), self.p))

        self.assertTrue(big(100) != 100.32)
        self.assertEqual(big(100), 100.0)

        self.assertTrue(100.32 != big(100))
        self.assertEqual(100.0, big(100))
コード例 #16
0
ファイル: python_test.py プロジェクト: cpnei/HandEvaluator
def CalcWinrate_mc(Pocket, Board):
    wr = Double(0)
    r = Hand.MCWinRate(Pocket, Board, "", 10, 1000000, wr)
    return r
コード例 #17
0
 def flash_t_p(cls, flash_from_temperature, flash_from_pressure,
               flash_to_temperature, flash_to_pressure,
               overall_volumetric_flow_rate, light_ends_composition,
               light_ends_molar_flow_rate_fraction, oil_characterization,
               standard_pressure, standard_temperature):
     flash_calculator = Calculator()
     flash_calculator.Initialize()
     property_package_name = settings.DWSIM_PROPERTY_PACKAGE
     property_package = flash_calculator.GetPropPackInstance(
         property_package_name)
     # Cast flash conditions to list type to support old, scalar (one-stage) input
     flash_from_pressure = flash_from_pressure if isinstance(
         flash_from_pressure, list) else [flash_from_pressure]
     flash_from_temperature = flash_from_temperature if isinstance(
         flash_from_temperature, list) else [flash_from_temperature]
     flash_to_pressure = flash_to_pressure if isinstance(
         flash_to_pressure, list) else [flash_to_pressure]
     flash_to_temperature = flash_to_temperature if isinstance(
         flash_to_temperature, list) else [flash_to_temperature]
     from_pressure = []
     from_temperature = []
     to_pressure = []
     to_temperature = []
     flashes = 0
     for pressure_stage in range(0, len(flash_to_pressure)):
         if flash_to_pressure[pressure_stage] > 0.0:
             flashes += 1
         else:
             break
     if flashes == 0:
         raise ValueError('No valid flash stage outlet pressures.')
     compound_names = []
     mole_fractions = []
     assay = None
     heavy_ends = None
     light_ends = None
     if light_ends_composition:
         compound_names = [
             components[0] for components in light_ends_composition
         ]
         mole_fractions = [
             components[1] for components in light_ends_composition
         ]
         light_ends = flash_calculator.CreateMaterialStream(
             compound_names, mole_fractions)
         light_ends.SetPropertyPackage(property_package)
         light_ends.ClearAllProps()
         light_ends.SetProp("fraction", "Overall", None, "", "mole",
                            mole_fractions)
     compound_names = []
     mole_fractions = []
     if oil_characterization:
         compounds, assay = oil_characterization
         compound_names = [compound.Name for compound in compounds]
         mole_fractions = [
             compound.MoleFraction *
             (1.0 - light_ends_molar_flow_rate_fraction)
             for compound in compounds
         ]
         heavy_ends = MaterialStream("", "")
         DWSIMWrapper._add_components_to_material_stream(
             compounds, heavy_ends)
         heavy_ends.SetPropertyPackage(property_package)
         heavy_ends.ClearAllProps()
         heavy_ends.SetProp("fraction", "Overall", None, "", "mole",
                            mole_fractions)
     flashed_phase_rates = [0.0, 0.0]  # [liquid_rate, vapor_rate]
     mixture = None
     liquid = None
     for flash_stage in range(0, flashes):
         from_pressure.append(
             Double(
                 UnitConverter.convert_pressure(
                     flash_from_pressure[flash_stage], "psia", "Pa")))
         from_temperature.append(
             Double(
                 UnitConverter.convert_temperature(
                     flash_from_temperature[flash_stage], "F", "K")))
         to_pressure.append(
             Double(
                 UnitConverter.convert_pressure(
                     flash_to_pressure[flash_stage], "psia", "Pa")))
         to_temperature.append(
             Double(
                 UnitConverter.convert_temperature(
                     flash_to_temperature[flash_stage], "F", "K")))
         if flash_stage == 0:  # Mix heavy and light ends for first stage flash
             mixture = DWSIMWrapper._mix_and_flash_material_streams(
                 [light_ends, heavy_ends], property_package,
                 from_pressure[flash_stage], from_temperature[flash_stage],
                 to_pressure[flash_stage], to_temperature[flash_stage],
                 overall_volumetric_flow_rate)
         else:  # Flash liquid phase from preceding stage for remaining stages
             mixture = DWSIMWrapper._mix_and_flash_material_streams(
                 liquid, property_package, from_pressure[flash_stage],
                 from_temperature[flash_stage], to_pressure[flash_stage],
                 to_temperature[flash_stage], overall_volumetric_flow_rate)
         # Retrieve liquid phase composition for subsequent stage flashes
         liquid_compounds = DWSIMWrapper._extract_liquid_composition(
             mixture)
         liquid = MaterialStream("", "")
         DWSIMWrapper._add_components_to_material_stream(
             liquid_compounds, liquid)
         phase_data = mixture.GetPresentPhases(None, None)
         if "Liquid" in phase_data[1]:
             liquid_flow_rate = mixture.GetProp("totalFlow", "Liquid", None,
                                                "", "mole")
             liquid_molecular_weight = mixture.GetSinglePhaseProp(
                 "molecularWeight", "Liquid", "", None)
             liquid_density = mixture.GetSinglePhaseProp(
                 "density", "Liquid", "mass", None)
             liquid_volumetric_flow_rate = liquid_flow_rate[
                 0] * liquid_molecular_weight[0] / (settings.KMOL_TO_MOL *
                                                    liquid_density[0])
             # Return final shrunken oil rate from last stage (assume incompressible)
             flashed_phase_rates[0] = UnitConverter.convert_volume(
                 liquid_volumetric_flow_rate, "m3", "bbl")
             # Recalculate overall volumetric flow rate to correspond to residual liquid for next stage
             overall_volumetric_flow_rate = flashed_phase_rates[0]
         if "Vapor" in phase_data[1]:
             vapor_flow_rate = mixture.GetProp("totalFlow", "Vapor", None,
                                               "", "mole")
             vapor_molecular_weight = mixture.GetSinglePhaseProp(
                 "molecularWeight", "Vapor", "", None)
             vapor_density = mixture.GetSinglePhaseProp(
                 "density", "Vapor", "mass", None)
             vapor_volumetric_flow_rate = vapor_flow_rate[
                 0] * vapor_molecular_weight[0] / (settings.KMOL_TO_MOL *
                                                   vapor_density[0])
             # Return sum of flashed gas rates at standard conditions for all stages
             flashed_phase_rates[
                 1] += UnitConverter.convert_volume_to_standard_conditions(
                     vapor_volumetric_flow_rate, "m3", "Mcf",
                     UnitConverter.convert_pressure(
                         flash_to_pressure[flash_stage], "psia", "Pa"),
                     UnitConverter.convert_temperature(
                         flash_to_temperature[flash_stage], "F", "K"),
                     UnitConverter.convert_pressure(standard_pressure,
                                                    "psia", "Pa"),
                     UnitConverter.convert_temperature(
                         standard_temperature, "F", "K"))
         # pdb.set_trace()
     return flashed_phase_rates
コード例 #18
0
)

from CommandInterfaceDLS import *
from System import String, Double

# COM port
instrument = "COM3"

# Create an instance DLS interface
myDLS = DLS()

# Open a socket
result = myDLS.OpenInstrument(instrument)

if result == 0:
    print('Success')
else:
    print('Fail')

# Dummy arguments of the expected type
# https://stackoverflow.com/questions/54692267/python-net-call-c-sharp-method-which-has-a-return-value-and-an-out-parameter
dummy_out0 = Double(0.)
dummy_out1 = String('')

# Call DLS functions. Here, VE is used.
result = myDLS.TP(dummy_out0, dummy_out1)

print("current position:", result)

# Close DLS connection
myDLS.CloseInstrument()
コード例 #19
0
                                    "sequence"):
                                character = Character()
                                originX = 0
                                originY = 0
                                x = 0
                                y = 0
                                width = 0
                                height = 0

                                for attribute in characterElement.Attributes():
                                    if attribute.Name.LocalName.Equals("name"):
                                        character.Name = attribute.Value
                                    elif attribute.Name.LocalName.Equals(
                                            "origin-x"):
                                        originX = Double.Parse(
                                            attribute.Value,
                                            CultureInfo.InvariantCulture)
                                    elif attribute.Name.LocalName.Equals(
                                            "origin-y"):
                                        originY = Double.Parse(
                                            attribute.Value,
                                            CultureInfo.InvariantCulture)
                                    elif attribute.Name.LocalName.Equals(
                                            "x"
                                    ) or attribute.Name.LocalName.Equals(
                                            "left"):
                                        x = Double.Parse(
                                            attribute.Value,
                                            CultureInfo.InvariantCulture)
                                    elif attribute.Name.LocalName.Equals(
                                            "y"
コード例 #20
0
ファイル: RunICM.PY プロジェクト: eragon288/MIKE-OPERATIONS
def RunICM(Adapter):
    """
    <Script>
    <Author>ANK</Author>
    <Description>run an ICM model</Description>
    <Parameters>
    <Parameter name="Adapter" type="IRuntimeAdapter">handle to the adapter</Parameter>
    </Parameters>
    </Script>
    """
    tsMgr = app.Modules.Get("Time series Manager")

    # get the adapter root folder
    rootfolder = Adapter.RootFolderPath
    
    # convert dfs0-input files to Dummy_Inflow.csv
    
    # open dummy inflow and read all lines
    inflowPath = Path.Combine(rootfolder, "MODEL_SETUP\\import\\Dummy Inflow.csv")
    inflowLines = File.ReadAllLines(inflowPath)
    
    # read dfs0-files one by one
    l=8
    tslist = []
    while inflowLines[l].split(",")[0]!="P_DATETIME" :
        tsname = inflowLines[l].split(",")[0]
        tsFile = Path.Combine(rootfolder, "INPUT_DATA", tsname+".dfs0")
        tslist.extend(TsUtilities.ReadFromDFS0(tsMgr, tsFile))
        l = l + 1;

    # make new lines
    newLines = []
    i=0
    while True:
        if i==6:
            # replace startdate
            line = tslist[0].Start.ToString("dd/MM/yyyy HH:mm:ss") + inflowLines[i][19:]
        else:
            line = inflowLines[i]

        newLines.append(line)
        
        if inflowLines[i].split(",")[0]=="P_DATETIME" :
            break;
        i = i + 1;
    
    # continue with timesteps
    for t in range(tslist[0].Count):
        line = tslist[0].Get(t).XValue.ToString("dd/MM/yyyy HH:mm:ss")
        for ds in tslist:
            line += "," + ds.Get(t).YValue.ToString(CultureInfo.InvariantCulture)
        
        newLines.append(line)

    # rewrite the input file
    File.WriteAllLines(inflowPath, newLines)
        
    # run the adapter bat-file
    startInfo = ProcessStartInfo()
    startInfo.CreateNoWindow = False;
    startInfo.UseShellExecute = False;
    startInfo.FileName = Path.Combine(rootfolder, "MODEL_SETUP", "run.bat");
    startInfo.WorkingDirectory = Path.Combine(rootfolder, "MODEL_SETUP")
    with Process.Start(startInfo) as exeProcess :
        exeProcess.WaitForExit();

    # convert exported csv-files to dfs0
    # convert node depths
    dslist = []
    for fil in Directory.GetFiles(Path.Combine(rootfolder,"MODEL_SETUP\\export"),"Node_*_depnod.csv"):
        lines = File.ReadAllLines(fil)
        
        headers = lines[0].split(",")
        for h in headers[2:]:
            ds = tsMgr.TimeSeriesList.CreateNew()
            ds.Name = h.strip()
            ds.YAxisVariable = "Water Level"
            
            dslist.append(ds)
            
    
        for line in lines[1:] :
            if not "[" in line:
                values = line.split(",")
                t = DateTime.ParseExact(values[0].strip(),"dd/MM/yyyy HH:mm:ss", CultureInfo.InvariantCulture)
                for v in range(2,values.Count):
                    ds = dslist[v-2]
                    vp = ds.CreateNew()
                    vp.XValue = t
                    vp.YValue = Double.Parse(values[v].strip(), CultureInfo.InvariantCulture)
                    ds.Add(vp)    
        
        # save to dfs0
        for ds in dslist:
            fil = Path.Combine(rootfolder,"OUTPUT_DATA",ds.Name+".dfs0")
            TsUtilities.ExportToDfs0(ds,fil)
コード例 #21
0
ファイル: pm_thorlabs.py プロジェクト: luspock/PyExp
 def __init__(self):
     self.identifier = "USB0::0x1313::0x8078::P0011895::INSTR"
     self.instance = None
     self.temp_double = Double(0)
     self.MaxWavelength = 1100
     self.MinWavelength = 400
コード例 #22
0
ファイル: Settings.py プロジェクト: soracoder/Apricot
def onOpened(s, e):
    global menuItem

    menuItem.Items.Clear()

    config = None
    directory = Path.Combine(
        Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
        Assembly.GetEntryAssembly().GetName().Name)

    if Directory.Exists(directory):
        fileName1 = Path.GetFileName(Assembly.GetEntryAssembly().Location)

        for fileName2 in Directory.EnumerateFiles(directory, "*.config"):
            if fileName1.Equals(Path.GetFileNameWithoutExtension(fileName2)):
                exeConfigurationFileMap = ExeConfigurationFileMap()
                exeConfigurationFileMap.ExeConfigFilename = fileName2
                config = ConfigurationManager.OpenMappedExeConfiguration(
                    exeConfigurationFileMap, ConfigurationUserLevel.None)

    if config is None:
        config = ConfigurationManager.OpenExeConfiguration(
            ConfigurationUserLevel.None)
        directory = None

    if config.AppSettings.Settings["ActivateThreshold"] is not None:
        threshold = Int64.Parse(
            config.AppSettings.Settings["ActivateThreshold"].Value)

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "トーク間隔"
        else:
            childMenuItem.Header = "Talking Interval"

        menuItem.Items.Add(childMenuItem)

        intervalMenuItem1 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem1.Header = "15秒"
        else:
            intervalMenuItem1.Header = "15 seconds"

        if threshold == 150000000:
            intervalMenuItem1.IsChecked = True

        def onIntervalClick1(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "150000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem1.Click += onIntervalClick1

        childMenuItem.Items.Add(intervalMenuItem1)

        intervalMenuItem2 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem2.Header = "30秒"
        else:
            intervalMenuItem2.Header = "30 seconds"

        if threshold == 300000000:
            intervalMenuItem2.IsChecked = True

        def onIntervalClick2(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "300000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem2.Click += onIntervalClick2

        childMenuItem.Items.Add(intervalMenuItem2)

        intervalMenuItem3 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem3.Header = "1分"
        else:
            intervalMenuItem3.Header = "1 minute"

        if threshold == 600000000:
            intervalMenuItem3.IsChecked = True

        def onIntervalClick3(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "600000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem3.Click += onIntervalClick3

        childMenuItem.Items.Add(intervalMenuItem3)

        intervalMenuItem4 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem4.Header = "2分"
        else:
            intervalMenuItem4.Header = "2 minutes"

        if threshold == 1200000000:
            intervalMenuItem4.IsChecked = True

        def onIntervalClick4(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "1200000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem4.Click += onIntervalClick4

        childMenuItem.Items.Add(intervalMenuItem4)

        intervalMenuItem5 = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            intervalMenuItem5.Header = "3分"
        else:
            intervalMenuItem5.Header = "3 minutes"

        if threshold == 1800000000:
            intervalMenuItem5.IsChecked = True

        def onIntervalClick5(sender, args):
            config.AppSettings.Settings[
                "ActivateThreshold"].Value = "1800000000"
            config.Save(ConfigurationSaveMode.Modified)

        intervalMenuItem5.Click += onIntervalClick5

        childMenuItem.Items.Add(intervalMenuItem5)

    childMenuItem = MenuItem()

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        childMenuItem.Header = "テーマ"
    else:
        childMenuItem.Header = "Theme"

    menuItem.Items.Add(Separator())
    menuItem.Items.Add(childMenuItem)

    menuItem1 = MenuItem()
    menuItem2 = MenuItem()
    menuItem3 = MenuItem()
    menuItem4 = MenuItem()
    menuItem5 = MenuItem()
    menuItem6 = MenuItem()
    menuItem7 = MenuItem()
    menuItem8 = MenuItem()
    menuItem9 = MenuItem()
    menuItem10 = MenuItem()

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        menuItem1.Header = "ブループリント"
        menuItem2.Header = "ドット"
        menuItem3.Header = "布"
        menuItem4.Header = "リネン"
        menuItem5.Header = "ノイズ1"
        menuItem6.Header = "ノイズ2"
        menuItem7.Header = "紙"
        menuItem8.Header = "ペンタゴン"
        menuItem9.Header = "雪"
        menuItem10.Header = "ストライプ"
    else:
        menuItem1.Header = "Blueprint"
        menuItem2.Header = "Dots"
        menuItem3.Header = "Fabric"
        menuItem4.Header = "Linen"
        menuItem5.Header = "Noise 1"
        menuItem6.Header = "Noise 2"
        menuItem7.Header = "Paper"
        menuItem8.Header = "Pentagon"
        menuItem9.Header = "Snow"
        menuItem10.Header = "Stripes"

    if config.AppSettings.Settings[
            "BackgroundColor"] is not None and config.AppSettings.Settings[
                "BackgroundImage"] is not None and config.AppSettings.Settings[
                    "TextColor"] is not None and config.AppSettings.Settings[
                        "LinkColor"]:
        backColor = config.AppSettings.Settings["BackgroundColor"].Value
        backImage = config.AppSettings.Settings["BackgroundImage"].Value
        textColor = config.AppSettings.Settings["TextColor"].Value
        linkColor = config.AppSettings.Settings["LinkColor"].Value

        if backColor.Equals("#FF2574B0") and backImage.Equals(
                "Assets\\Background-Blueprint.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFEEC27"):
            menuItem1.IsChecked = True

        def onClick1(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF2574B0"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Blueprint.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFEEC27"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem1.Click += onClick1

        if backColor.Equals("#FF252525") and backImage.Equals(
                "Assets\\Background-Dots.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FF00C0FF"):
            menuItem2.IsChecked = True

        def onClick2(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF252525"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Dots.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FF00C0FF"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem2.Click += onClick2

        if backColor.Equals("#FFEAEAEA") and backImage.Equals(
                "Assets\\Background-Fabric.png") and textColor.Equals(
                    "#FF000000") and linkColor.Equals("#FFFF0066"):
            menuItem3.IsChecked = True

        def onClick3(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFEAEAEA"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Fabric.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF000000"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF0066"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem3.Click += onClick3

        if backColor.Equals("#FF252525") and backImage.Equals(
                "Assets\\Background-Linen.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFF6600"):
            menuItem4.IsChecked = True

        def onClick4(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF252525"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Linen.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem4.Click += onClick4

        if backColor.Equals("#FFF2F2F2") and backImage.Equals(
                "Assets\\Background-Noise1.png") and textColor.Equals(
                    "#FF333333") and linkColor.Equals("#FFFF0066"):
            menuItem5.IsChecked = True

        def onClick5(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFF2F2F2"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Noise1.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF333333"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF0066"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem5.Click += onClick5

        if backColor.Equals("#FF262727") and backImage.Equals(
                "Assets\\Background-Noise2.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFF6600"):
            menuItem6.IsChecked = True

        def onClick6(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF262727"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Noise2.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem6.Click += onClick6

        if backColor.Equals("#FFFCFCFC") and backImage.Equals(
                "Assets\\Background-Paper.png") and textColor.Equals(
                    "#FF000000") and linkColor.Equals("#FFFF0099"):
            menuItem7.IsChecked = True

        def onClick7(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFFCFCFC"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Paper.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF000000"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF0099"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem7.Click += onClick7

        if backColor.Equals("#FFEEEEEE") and backImage.Equals(
                "Assets\\Background-Pentagon.png") and textColor.Equals(
                    "#FF333333") and linkColor.Equals("#FF00A0E9"):
            menuItem8.IsChecked = True

        def onClick8(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFEEEEEE"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Pentagon.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF333333"
            config.AppSettings.Settings["LinkColor"].Value = "#FF00A0E9"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem8.Click += onClick8

        if backColor.Equals("#FFFBFBFB") and backImage.Equals(
                "Assets\\Background-Snow.png") and textColor.Equals(
                    "#FF000000") and linkColor.Equals("#FF00A0E9"):
            menuItem9.IsChecked = True

        def onClick9(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FFFBFBFB"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Snow.png"
            config.AppSettings.Settings["TextColor"].Value = "#FF000000"
            config.AppSettings.Settings["LinkColor"].Value = "#FF00A0E9"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem9.Click += onClick9

        if backColor.Equals("#FF39343D") and backImage.Equals(
                "Assets\\Background-Stripes.png") and textColor.Equals(
                    "#FFFFFFFF") and linkColor.Equals("#FFFF6600"):
            menuItem10.IsChecked = True

        def onClick10(sender, args):
            config.AppSettings.Settings["BackgroundColor"].Value = "#FF39343D"
            config.AppSettings.Settings[
                "BackgroundImage"].Value = "Assets\\Background-Stripes.png"
            config.AppSettings.Settings["TextColor"].Value = "#FFFFFFFF"
            config.AppSettings.Settings["LinkColor"].Value = "#FFFF6600"
            config.Save(ConfigurationSaveMode.Modified)

        menuItem10.Click += onClick10

    childMenuItem.Items.Add(menuItem1)
    childMenuItem.Items.Add(menuItem2)
    childMenuItem.Items.Add(menuItem3)
    childMenuItem.Items.Add(menuItem4)
    childMenuItem.Items.Add(menuItem5)
    childMenuItem.Items.Add(menuItem6)
    childMenuItem.Items.Add(menuItem7)
    childMenuItem.Items.Add(menuItem8)
    childMenuItem.Items.Add(menuItem9)
    childMenuItem.Items.Add(menuItem10)

    if config.AppSettings.Settings["DropShadow"] is not None:
        dropShadow = Boolean.Parse(
            config.AppSettings.Settings["DropShadow"].Value)

        childMenuItem = MenuItem()
        childMenuItem.IsCheckable = True
        childMenuItem.IsChecked = dropShadow

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "ドロップシャドウを有効にする"
        else:
            childMenuItem.Header = "Enable Drop Shadow"

        def onClick(sender, args):
            config.AppSettings.Settings[
                "DropShadow"].Value = sender.IsChecked.ToString()
            config.Save(ConfigurationSaveMode.Modified)

        childMenuItem.Click += onClick

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

    menuItem.Items.Add(Separator())

    if config.AppSettings.Settings["FontFamily"] is not None:
        fontFamilyName = config.AppSettings.Settings["FontFamily"].Value

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フォント"
        else:
            childMenuItem.Header = "Font"

        menuItem.Items.Add(childMenuItem)

        for fontFamily in [
                "Arial", "Calibri", "Cambria", "Candara", "Constantia",
                "Corbel", "Courier New", "Geogia", "MS UI Gothic", "Segoe UI",
                "Tahoma", "Times New Roman", "Verdana", "メイリオ", "MS ゴシック"
        ]:
            fontMenuItem = MenuItem()
            fontMenuItem.Header = fontFamily

            if fontFamily.Equals(fontFamilyName):
                fontMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["FontFamily"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            fontMenuItem.Click += onClick

            childMenuItem.Items.Add(fontMenuItem)

    if config.AppSettings.Settings["FontSize"] is not None:
        fontSize = config.AppSettings.Settings["FontSize"].Value

        fontSizeConverter = FontSizeConverter()
        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フォントサイズ"
        else:
            childMenuItem.Header = "Font Size"

        menuItem.Items.Add(childMenuItem)

        for size in [
                "8pt", "9pt", "10pt", "11pt", "12pt", "14pt", "16pt", "18pt",
                "20pt", "22pt", "24pt"
        ]:
            fontMenuItem = MenuItem()
            fontMenuItem.Header = size

            if fontSize.Equals(size):
                fontMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["FontSize"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            fontMenuItem.Click += onClick

            childMenuItem.Items.Add(fontMenuItem)

        if config.AppSettings.Settings["LineHeight"] is not None:
            lineHeight = Double.Parse(
                config.AppSettings.Settings["LineHeight"].Value)
            maxLineHeight = Convert.ToInt32(
                fontSizeConverter.ConvertFromString(fontSize)) * 2

            if maxLineHeight < lineHeight:
                maxLineHeight = lineHeight

            childMenuItem2 = MenuItem()

            if CultureInfo.CurrentCulture.Equals(
                    CultureInfo.GetCultureInfo("ja-JP")):
                childMenuItem2.Header = "行間"
            else:
                childMenuItem2.Header = "Line Height"

            menuItem.Items.Add(childMenuItem2)

            for i in range(
                    Convert.ToInt32(
                        fontSizeConverter.ConvertFromString(fontSize)),
                    Convert.ToInt32(maxLineHeight) + 1):
                lineHeightMenuItem = MenuItem()
                lineHeightMenuItem.Header = i.ToString()

                if lineHeight == i:
                    lineHeightMenuItem.IsChecked = True

                def onClick(sender, args):
                    config.AppSettings.Settings[
                        "LineHeight"].Value = sender.Header
                    config.Save(ConfigurationSaveMode.Modified)

                lineHeightMenuItem.Click += onClick

                childMenuItem2.Items.Add(lineHeightMenuItem)

    if config.AppSettings.Settings["FrameRate"] is not None:
        frameRate = Double.Parse(
            config.AppSettings.Settings["FrameRate"].Value)

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フレームレート"
        else:
            childMenuItem.Header = "Frame Rate"

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

        for i in [24, 30, 60]:
            frameRateMenuItem = MenuItem()
            frameRateMenuItem.Header = i.ToString()

            if frameRate == Convert.ToDouble(i):
                frameRateMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["FrameRate"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            frameRateMenuItem.Click += onClick

            childMenuItem.Items.Add(frameRateMenuItem)

    if config.AppSettings.Settings["Subscriptions"] is not None:
        path = config.AppSettings.Settings["Subscriptions"].Value

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "フィード"
        else:
            childMenuItem.Header = "Subscriptions"

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

        editMenuItem = MenuItem()
        editMenuItem.Tag = path

        def onEdit(sender, args):
            global program

            path = sender.Tag

            def onStart(state):
                Process.Start(state)

            psi = ProcessStartInfo()

            if String.IsNullOrEmpty(program):
                psi.FileName = path
            else:
                psi.FileName = program
                psi.Arguments = path

            Task.Factory.StartNew(onStart, psi)

        editMenuItem.Click += onEdit

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            editMenuItem.Header = "フィードの編集..."
        else:
            editMenuItem.Header = "Edit..."

        childMenuItem.Items.Add(editMenuItem)
        childMenuItem.Items.Add(Separator())

        if directory is not None:
            fileName = Path.Combine(directory, path)

            if File.Exists(fileName):
                path = fileName

        def parseOutline(m, n):
            if not n.HasChildNodes:
                return None

            for xmlNode in n.ChildNodes:
                if xmlNode.Name.Equals("outline"):
                    text = None
                    xmlUrl = None
                    htmlUrl = None

                    for xmlAttribute in xmlNode.Attributes:
                        if xmlAttribute.Name.Equals(
                                "title") or xmlAttribute.Name.Equals("text"):
                            text = xmlAttribute.Value
                        elif xmlAttribute.Name.Equals("xmlUrl"):
                            xmlUrl = xmlAttribute.Value
                        elif xmlAttribute.Name.Equals("htmlUrl"):
                            htmlUrl = xmlAttribute.Value

                    if not String.IsNullOrEmpty(text):
                        if String.IsNullOrEmpty(xmlUrl):
                            mi = MenuItem()
                            mi.Header = text

                            parsedMenuItem = parseOutline(mi, xmlNode)

                            if parsedMenuItem is None:
                                m.Items.Add(mi)
                            else:
                                m.Items.Add(parsedMenuItem)
                        elif not String.IsNullOrEmpty(xmlUrl):
                            mi = MenuItem()

                            def onClick(sender, args):
                                if not String.IsNullOrEmpty(sender.Tag):

                                    def onStart(state):
                                        Process.Start(state)

                                    Task.Factory.StartNew(onStart, sender.Tag)

                            mi.Header = text
                            mi.Click += onClick
                            mi.Tag = htmlUrl

                            m.Items.Add(mi)

            return m

        doc = XmlDocument()
        doc.Load(path)

        for xmlNode in doc.SelectNodes("/opml/body"):
            parseOutline(childMenuItem, xmlNode)

    if config.AppSettings.Settings["Timeout"] is not None:
        timeout = Int32.Parse(config.AppSettings.Settings["Timeout"].Value)

        childMenuItem = MenuItem()

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "タイムアウト"
        else:
            childMenuItem.Header = "Timeout"

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

        for i in [15000, 30000, 60000, 120000, 180000]:
            timeMenuItem = MenuItem()
            timeMenuItem.Header = i.ToString()

            if timeout == i:
                timeMenuItem.IsChecked = True

            def onClick(sender, args):
                config.AppSettings.Settings["Timeout"].Value = sender.Header
                config.Save(ConfigurationSaveMode.Modified)

            timeMenuItem.Click += onClick

            childMenuItem.Items.Add(timeMenuItem)

    if config.AppSettings.Settings["Cache"] is not None:
        path = config.AppSettings.Settings["Cache"].Value

        if directory is not None:
            path = Path.Combine(directory, path)

        childMenuItem = MenuItem()
        childMenuItem.Tag = path

        if CultureInfo.CurrentCulture.Equals(
                CultureInfo.GetCultureInfo("ja-JP")):
            childMenuItem.Header = "キャッシュをクリア"
        else:
            childMenuItem.Header = "Clear Cache"

        def onClick(sender, args):
            if Directory.Exists(childMenuItem.Tag):
                for fileName in Directory.EnumerateFiles(childMenuItem.Tag):
                    File.Delete(fileName)

        childMenuItem.Click += onClick

        menuItem.Items.Add(Separator())
        menuItem.Items.Add(childMenuItem)

    childMenuItem = MenuItem()

    if CultureInfo.CurrentCulture.Equals(CultureInfo.GetCultureInfo("ja-JP")):
        childMenuItem.Header = "GCを強制的に実行"
    else:
        childMenuItem.Header = "Force Garbage Collection"

    def onClick(sender, args):
        GC.Collect()

    childMenuItem.Click += onClick

    menuItem.Items.Add(childMenuItem)