def __init__(self, mode):
        f = FileStream(Path.Combine(SCRIPTDIRECTORY, "DuplicateForm.xaml"),
                       FileMode.Open)
        self.win = XamlReader.Load(XmlReader.Create(f))
        f.Close()

        self._action = None

        self.RenameText = "The file you are moving will be renamed: "

        #Load the images and icon
        path = FileInfo(__file__).DirectoryName
        arrow = BitmapImage()
        arrow.BeginInit()

        arrow.UriSource = Uri(Path.Combine(SCRIPTDIRECTORY, "arrow.png"),
                              UriKind.Absolute)
        arrow.EndInit()
        self.win.FindName("Arrow1").Source = arrow
        self.win.FindName("Arrow2").Source = arrow
        self.win.FindName("Arrow3").Source = arrow

        icon = BitmapImage()
        icon.BeginInit()
        icon.UriSource = Uri(ICON, UriKind.Absolute)
        icon.EndInit()

        self.win.Icon = icon

        self.win.FindName("CancelButton").Click += self.CancelClick
        self.win.FindName("Cancel").Click += self.CancelClick
        self.win.FindName("ReplaceButton").Click += self.ReplaceClick
        self.win.FindName("RenameButton").Click += self.RenameClick

        self.win.Closing += self.FormClosing

        #The the correct text based on what mode we are in
        #Mode is set by default so only change if in Copy or Simulation mode
        if mode == Mode.Copy:
            self.win.FindName("MoveHeader").Content = "Copy and Replace"
            self.win.FindName(
                "MoveText"
            ).Content = "Replace the file in the destination folder with the file you are copying:"

            self.win.FindName("DontMoveHeader").Content = "Don't Copy"

            self.win.FindName(
                "RenameHeader").Content = "Copy, but keep both files"
            self.RenameText = "The file you are copying will be renamed: "
            self.win.FindName(
                "RenameText"
            ).Text = "The file you are copying will be renamed: "

        if mode == Mode.Simulate:
            self.win.FindName(
                "Subtitle"
            ).Content = "Click the file you want to keep (simulated, no files will be deleted or moved)"
Пример #2
0
def load(filename:str)->panscore.Score:
    """
    打开svip文件,返回panscore.Score对象
    """
    serializer = BinaryFormatter()
    reader = FileStream(filename, FileMode.Open, FileAccess.Read)
    for i in range(11):
        reader.ReadByte()
    data = serializer.Deserialize(reader)
    reader.Close()
    return parsefile(data)
Пример #3
0
def testFileStream():
    print 'Verifying FileStream against MemoryStream'
    stopwatch = Stopwatch.StartNew()
    for i in xrange(128):
        m = MemoryStream()
        file = Path.GetTempFileName()
        f = FileStream(file, FileMode.Open)
        try:
            streams = [m, f]
            randomOperations(128, streams)
        finally:
            f.Close()
            File.Delete(file)
    stopwatch.Stop()
    print '%s' % stopwatch.Elapsed
Пример #4
0
def process(context):
    filename = context.Request.Url.AbsolutePath
    if not filename:
        filename = "index.html"
    if filename[0] == '/':
        filename = filename[1:]
    print(filename)
    filename = Path.Combine(root, filename)
    print(filename)
    if not File.Exists(filename):
        context.Response.Abort()
        return
    input = FileStream(filename, FileMode.Open)
    bytes = Array.CreateInstance(Byte, 1024 * 16)
    nbytes = input.Read(bytes, 0, bytes.Length)
    while nbytes > 0:
        context.Response.OutputStream.Write(bytes, 0, nbytes)
        nbytes = input.Read(bytes, 0, bytes.Length)
    input.Close()
    context.Response.OutputStream.Close()
Пример #5
0
 def setUp(self):
     self.temp_directory = Env.GetEnvironmentVariable("TEMP")
     #check temp dir exists
     self.assertTrue(Directory.Exists(self.temp_directory))
     #check temp file in temp dir does not exist
     if File.Exists(self.tempFileFullPath1 or self.tempFileFullPath2
                    or self.tempFileFullPath1):
         File.Delete(self.tempFileFullPath1)
         File.Delete(self.tempFileFullPath2)
         File.Delete(self.tempFileFullPath3)
     #create a file to check and delete
     fs1 = FileStream(self.tempFileFullPath1, FileMode.Create)
     fs2 = FileStream(self.tempFileFullPath2, FileMode.Create)
     fs3 = FileStream(self.tempFileFullPath3, FileMode.Create)
     fs1.Close()
     fs2.Close()
     fs3.Close()
Пример #6
0
                def onSave():
                    try:
                        fs = None
                        sr = None
                        sw = None

                        try:
                            fs = FileStream(__file__, FileMode.Open,
                                            FileAccess.ReadWrite,
                                            FileShare.Read)
                            encoding = UTF8Encoding(False)
                            sr = StreamReader(fs, encoding, True)
                            lines = Regex.Replace(
                                Regex.Replace(
                                    sr.ReadToEnd(), "username\\s*=\\s*\"\"",
                                    String.Format("username = \"{0}\"",
                                                  username),
                                    RegexOptions.CultureInvariant),
                                "password\\s*=\\s*\"\"",
                                String.Format("password = \"{0}\"", password),
                                RegexOptions.CultureInvariant)
                            fs.SetLength(0)
                            sw = StreamWriter(fs, encoding)
                            sw.Write(lines)

                        finally:
                            if sw is not None:
                                sw.Close()

                            if sr is not None:
                                sr.Close()

                            if fs is not None:
                                fs.Close()

                    except Exception, e:
                        Trace.WriteLine(e.clsException.Message)
                        Trace.WriteLine(e.clsException.StackTrace)
Пример #7
0
 def CleanUp(self, sender, e):
     #ISOTIMEFORMAT='%Y-%m-%d %X'
     #print  time.strftime("%a%b%d%H:%M:%S%Y", time.localtime())
     #print  time.strftime("%a%b%d%H:%M:%S%Y", time.localtime())
     name = time.strftime("%a%b%d%H%M%S%Y",
                          time.localtime()) + "camera1.jpg"
     try:
         filestream = FileStream(name, FileMode.Create)
     except:
         filestream = FileStream(
             time.strftime("%a%b%d%H%M%S%Y", time.localtime()) +
             "camera2.jpg", FileMode.Create)
     encoder = JpegBitmapEncoder()
     encoder.FlipHorizontal = True
     encoder.FlipVertical = True
     encoder.Frames.Add(BitmapFrame.Create(self.CameraDisplay.Source))
     encoder.Save(filestream)
     #Receive=receive_window(self.Addr,name)
     filestream.Close()
     self.Cameracapturedll.Release()
     self.ss.pathBlock.Text = name
     self.ss.StartTransFile(name)
     self.Hide()
Пример #8
0
 def __init__(self):
     self.Scopes = [SheetsService.Scope.Spreadsheets]
     self.ApplicationName = "RedBim"
     self.stream = FileStream(os.path.join(GOOGLE, 'credentials.json'),
                         FileMode.Open, FileAccess.Read)
     self.credPath = os.path.join(GOOGLE, "token.json")
     self.credential = GoogleWebAuthorizationBroker.AuthorizeAsync(
         GoogleClientSecrets.Load(self.stream).Secrets,
         self.Scopes,
         "user",
         CancellationToken.None,
         FileDataStore(self.credPath, True)).Result
     BCS = BaseClientService.Initializer()
     BCS.HttpClientInitializer = self.credential
     BCS.ApplicationName = self.ApplicationName
     self.service = SheetsService(BCS)
Пример #9
0
        def onValidate():
            fs = None

            try:
                fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.Read)

                doc = XmlDocument()
                doc.Load(fs)

                if doc.DocumentElement.Name.Equals("script"):
                    for childNode1 in doc.DocumentElement.ChildNodes:
                        if childNode1.Name.Equals("character"):
                            hasName = False

                            for xmlAttribute in childNode1.Attributes:
                                if xmlAttribute.Name.Equals("name"):
                                    hasName = True

                            if not hasName:
                                if CultureInfo.CurrentCulture.Equals(
                                        CultureInfo.GetCultureInfo("ja-JP")):
                                    errorList.Add("characterタグにname属性がありません。")
                                else:
                                    errorList.Add(
                                        "Could not find name attribute in character tag."
                                    )

                            for childNode2 in childNode1.ChildNodes:
                                if childNode2.Name.Equals("sequence"):
                                    parseSequence(
                                        childNode2,
                                        Path.GetDirectoryName(fileName),
                                        warningList, errorList)

                else:
                    if CultureInfo.CurrentCulture.Equals(
                            CultureInfo.GetCultureInfo("ja-JP")):
                        errorList.Add("scriptタグがありません。")
                    else:
                        errorList.Add("Could not find script tag.")

            except Exception, e:
                errorList.Add(e.clsException.Message)
Пример #10
0
    def evaluate(self, result, step_info, collector):
        inf = float("inf")
        load = self.result.Properties['ElasticFoundationObj'].Value
        comp_file = path.join(
            ExtAPI.Application.InvokeUIThread(
                lambda: self.result.Analysis.WorkingDir),
            load.Properties['nodeFile'].Value)

        with FileStream(comp_file, FileMode.Open) as nstream:
            formatter = BinaryFormatter()
            nodes = formatter.Deserialize(nstream)

        csv_outfile = path.join(
            ExtAPI.Application.InvokeUIThread(
                lambda: self.result.Analysis.WorkingDir),
            self.result.Caption.strip() + '.csv')
        with open(csv_outfile, 'wb' if step_info.Set == 1 else 'ab') as rfile:
            writer = csv.writer(rfile)
            if not self.steps_completed:
                writer.writerow(['Set', 'Fx', 'Fy', 'Fz', 'Total'])
            with ExtAPI.Application.InvokeUIThread(
                    lambda: self.result.Analysis.GetResultsData()) as reader:
                reader.CurrentResultSet = step_info.Set
                forces = reader.GetResult('F')
                fx = fy = fz = 0.0
                for k in nodes.Keys:
                    node = nodes[k]
                    nfx, nfy, nfz = forces.GetNodeValues(node)
                    fx += nfx
                    fy += nfy
                    fz += nfz
                    collector.SetValues(k, (nfx, nfy, nfz))
                self.result.Properties['ReactSummary/x'].Value = fx
                self.result.Properties['ReactSummary/y'].Value = fy
                self.result.Properties['ReactSummary/z'].Value = fz
                total = sqrt(fx**2 + fy**2 + fz**2)
                self.result.Properties['ReactSummary/total'].Value = total
                if step_info.Set not in self.steps_completed:
                    writer.writerow([step_info.Set, fx, fy, fz, total])
                    self.steps_completed.append(step_info.Set)
Пример #11
0
    t4 = 'talk!'
    txt = controls['TextBox']['Text']
    print 'B1' in str(s)
    if 'B1' in str(s):
        txt.Text += t1
    elif 'B2' in str(s):
        txt.Text += t2
    elif 'B3' in str(s):
        txt.Text += t3
    elif 'B4' in str(s):
        txt.Text += t4


def talk(s, e):
    spk = SpeechSynthesizer()
    spk.Speak(controls['TextBox']['Text'].Text)


file = FileStream(xaml_path, FileMode.Open, FileAccess.Read)
xr = XmlReader.Create(file)
win = XamlReader.Load(xr)
controls = {}
Waddle(win, controls)

if __name__ == "__main__":
    for butt in controls['Button']:
        if butt != 'Speak':
            controls['Button'][butt].Click += changeSpeech
    controls['Button']['Speak'].Click += talk

    Application().Run(win)
Пример #12
0
    def gen_springs(self, solver_data, stream):
        # pylint: disable=too-many-statements
        stream.WriteLine(
            "/com,*********** Elastic Foundation - {0} ***********".format(
                self.load.Properties['id'].Value))
        et_x = solver_data.GetNewElementType()
        et_y = solver_data.GetNewElementType()
        et_z = solver_data.GetNewElementType()

        mesh = self.load.Analysis.MeshData

        # Get Node Ids
        node_ids = []
        for geo_id in self.load.Properties['Geometry'].Value.Ids:
            node_ids += mesh.MeshRegionById(geo_id).NodeIds

        node_ids = list(set(node_ids))

        #Gen Coincident nodes
        cnode_ids = [int(solver_data.GetNewNodeId()) for x in node_ids]
        node_count = len(cnode_ids)

        stream.WriteLine('nblock, 3, , {0}'.format(len(cnode_ids)))
        stream.WriteLine('(1i9,3e18.9e3)')
        factor = self.api.Application.InvokeUIThread(lambda: solver_unit(
            self.api, 1.0, mesh.Unit, 'Length', self.load.Analysis))

        post_data = SerializableDictionary[int, int]()

        for node_id, cnode_id in zip(node_ids, cnode_ids):
            post_data[node_id] = cnode_id
            pos = [
                x * factor
                for x in (mesh.NodeById(node_id).X, mesh.NodeById(node_id).Y,
                          mesh.NodeById(node_id).Z)
            ]
            stream.WriteLine('{0:9d}{1:18.9e}{2:18.9e}{3:18.9e}'.format(
                cnode_id, *pos))
        stream.WriteLine('-1')

        # Check to see if using Name Selection
        if self.load.Properties[
                'Geometry/DefineBy'].Value == 'Named Selection':
            comp_mob_name = self.load.Properties['Geometry'].Value.Name
        else:
            comp_mob_name = 'elasfound_targ_{0}'.format(
                self.load.Properties['id'].Value)
            ansys.createNodeComponent(node_ids,
                                      comp_mob_name,
                                      mesh,
                                      stream,
                                      fromGeoIds=False)

        comp_ref_name = 'elasfound_ref_{0}'.format(
            self.load.Properties['id'].Value)
        ansys.createNodeComponent(cnode_ids,
                                  comp_ref_name,
                                  mesh,
                                  stream,
                                  fromGeoIds=False)

        factor = self.api.Application.InvokeUIThread(lambda: to_solve_unit(
            self.api, 1.0, 'Stiffness', self.load.Analysis))

        stream.WriteLine('ET, {0}, COMBIN14, 0, 1, 0'.format(et_x))
        stream.WriteLine('R, {0},{1:25.16e},{2:25.16e}'.format(
            et_x, self.load.Properties['SpringDef/xStiff'].Value / node_count *
            factor, self.load.Properties['SpringDef/Damping/xDamp'].Value
            if self.load.Properties['SpringDef/Damping/xDamp'].Value else 0.0))
        stream.WriteLine()

        stream.WriteLine('ET, {0}, COMBIN14, 0, 2, 0'.format(et_y))
        stream.WriteLine('R, {0},{1:25.16e},{2:25.16e}'.format(
            et_y, self.load.Properties['SpringDef/yStiff'].Value / node_count *
            factor, self.load.Properties['SpringDef/Damping/yDamp'].Value
            if self.load.Properties['SpringDef/Damping/yDamp'].Value else 0.0))
        stream.WriteLine()

        stream.WriteLine('ET, {0}, COMBIN14, 0, 3, 0'.format(et_z))
        stream.WriteLine('R, {0},{1:25.16e},{2:25.16e}'.format(
            et_z, self.load.Properties['SpringDef/zStiff'].Value / node_count *
            factor, self.load.Properties['SpringDef/Damping/zDamp'].Value
            if self.load.Properties['SpringDef/Damping/zDamp'].Value else 0.0))
        stream.WriteLine()

        stream.WriteLine('CMSEL, S, {0}'.format(comp_mob_name))
        stream.WriteLine('CMSEL, A, {0}'.format(comp_ref_name))
        stream.WriteLine('CSYS, {0}'.format(
            self.api.Application.InvokeUIThread(lambda: self.load.Properties[
                'SpringDef/cs'].Value.CoordinateSystemID)))
        stream.WriteLine('NROTAT, ALL')
        stream.WriteLine('ALLSELL, ALL')
        stream.WriteLine()

        stream.WriteLine('EBLOCK,19,SOLID')
        stream.WriteLine('(19i9)')
        line = '{0:9d}' * 4 + '{1:9d}' * 4 + '{2:9d}{3:9d}{4:9d}{5:9d}{6:9d}'
        for e_num in [et_x, et_y, et_z]:
            for node_id, cnode_id in zip(node_ids, cnode_ids):
                stream.WriteLine(
                    line.format(int(e_num), 0, 2, 0,
                                int(solver_data.GetNewElementId()), cnode_id,
                                node_id))
        stream.WriteLine('-1')
        stream.WriteLine('D, {0}, ALL, 0.0'.format(comp_ref_name))

        self.load.Properties['nodeFile'].Value = comp_ref_name + '.bin'
        with FileStream(self.load.Properties['nodeFile'].Value,
                        FileMode.Create) as nstream:
            formatter = BinaryFormatter()
            formatter.Serialize(nstream, post_data)
from System.Xml import XmlDocument

from System.IO import StreamReader, File, FileStream, FileMode

from System.Windows.Forms import Application, DialogResult
import configureform

import losettings

from loworkerform import ProfileSelector

SETTINGSFILE = "losettingsx.dat"

try:
    print "Loading test data"
    f = FileStream("Sample.dat", FileMode.Open)
    bf = BinaryFormatter()
    books = bf.Deserialize(f)
    print "Done loading sample data"
    print "Starting to load profiles"
    profiles, last_used_profiles = losettings.load_profiles(SETTINGSFILE)
    print "Done loading profiles"
    Application.EnableVisualStyles()

    selector = ProfileSelector(profiles.keys(), last_used_profiles)

    selector.ShowDialog()

    print selector.get_profiles_to_use()

    form = configureform.ConfigureForm(profiles, last_used_profiles[0], books)
Пример #14
0
    def onSignInClick(source, rea):
        config = None
        directory = Path.Combine(
            Environment.GetFolderPath(
                Environment.SpecialFolder.ApplicationData),
            Assembly.GetEntryAssembly().GetName().Name)
        backgroundBrush = None
        textColor = SystemColors.ControlTextBrush

        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["BackgroundImage"] is not None:
            fileName = config.AppSettings.Settings[
                "BackgroundImage"].Value if directory is None else Path.Combine(
                    directory,
                    config.AppSettings.Settings["BackgroundImage"].Value)
            fs = None
            bi = BitmapImage()

            try:
                fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                FileShare.Read)

                bi.BeginInit()
                bi.StreamSource = fs
                bi.CacheOption = BitmapCacheOption.OnLoad
                bi.CreateOptions = BitmapCreateOptions.None
                bi.EndInit()

            finally:
                if fs is not None:
                    fs.Close()

            backgroundBrush = ImageBrush(bi)
            backgroundBrush.TileMode = TileMode.Tile
            backgroundBrush.ViewportUnits = BrushMappingMode.Absolute
            backgroundBrush.Viewport = Rect(0, 0, bi.Width, bi.Height)
            backgroundBrush.Stretch = Stretch.None

            if backgroundBrush.CanFreeze:
                backgroundBrush.Freeze()

        if backgroundBrush is None and config.AppSettings.Settings[
                "BackgroundColor"] is not None:
            if config.AppSettings.Settings["BackgroundColor"].Value.Length > 0:
                backgroundBrush = SolidColorBrush(
                    ColorConverter.ConvertFromString(
                        config.AppSettings.Settings["BackgroundColor"].Value))

                if backgroundBrush.CanFreeze:
                    backgroundBrush.Freeze()

        if config.AppSettings.Settings["TextColor"] is not None:
            if config.AppSettings.Settings["TextColor"].Value.Length > 0:
                textColor = ColorConverter.ConvertFromString(
                    config.AppSettings.Settings["TextColor"].Value)

        textBrush = SolidColorBrush(textColor)

        if textBrush.CanFreeze:
            textBrush.Freeze()

        window = Window()

        def onClick(source, args):
            global username, password

            if not String.IsNullOrEmpty(
                    usernameTextBox.Text) and not String.IsNullOrEmpty(
                        passwordBox.Password):
                username = usernameTextBox.Text
                password = passwordBox.Password

                def onSave():
                    try:
                        fs = None
                        sr = None
                        sw = None

                        try:
                            fs = FileStream(__file__, FileMode.Open,
                                            FileAccess.ReadWrite,
                                            FileShare.Read)
                            encoding = UTF8Encoding(False)
                            sr = StreamReader(fs, encoding, True)
                            lines = Regex.Replace(
                                Regex.Replace(
                                    sr.ReadToEnd(), "username\\s*=\\s*\"\"",
                                    String.Format("username = \"{0}\"",
                                                  username),
                                    RegexOptions.CultureInvariant),
                                "password\\s*=\\s*\"\"",
                                String.Format("password = \"{0}\"", password),
                                RegexOptions.CultureInvariant)
                            fs.SetLength(0)
                            sw = StreamWriter(fs, encoding)
                            sw.Write(lines)

                        finally:
                            if sw is not None:
                                sw.Close()

                            if sr is not None:
                                sr.Close()

                            if fs is not None:
                                fs.Close()

                    except Exception, e:
                        Trace.WriteLine(e.clsException.Message)
                        Trace.WriteLine(e.clsException.StackTrace)

                def onCompleted(task):
                    global menuItem

                    for window in Application.Current.Windows:
                        if window is Application.Current.MainWindow and window.ContextMenu is not None:
                            if window.ContextMenu.Items.Contains(menuItem):
                                window.ContextMenu.Items.Remove(menuItem)
                                window.ContextMenu.Opened -= onOpened

                                if window.ContextMenu.Items[10].GetType(
                                ).IsInstanceOfType(window.ContextMenu.Items[
                                        window.ContextMenu.Items.Count - 4]):
                                    window.ContextMenu.Items.RemoveAt(10)

                    menuItem = None

                Task.Factory.StartNew(
                    onSave, TaskCreationOptions.LongRunning).ContinueWith(
                        onCompleted,
                        TaskScheduler.FromCurrentSynchronizationContext())

            window.Close()
Пример #15
0
	def onUpdate():
		temp = 0
		windSpeed = 0
		windDeg = 0
		weatherIdList = List[Double]()
		weatherPathHashSet = HashSet[String]()
		weatherStreamList = List[MemoryStream]()
		weatherConditionList = List[String]()

		if NetworkInterface.GetIsNetworkAvailable():
			try:
				request = WebRequest.Create(Uri(String.Concat("http://api.openweathermap.org/data/2.5/find?q=", urlEncode(location), "&units=metric&cnt=1")))
				response = None
				stream = None
				streamReader = None

				try:
					nowDateTime = DateTime.Now
					response = request.GetResponse()
					stream = response.GetResponseStream()
					streamReader = StreamReader(stream)
					jsonDictionary = JsonDecoder.decode(streamReader.ReadToEnd())

					if jsonDictionary is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(jsonDictionary) and jsonDictionary.ContainsKey("list") and jsonDictionary["list"] is not None and clr.GetClrType(Array).IsInstanceOfType(jsonDictionary["list"]):
						for obj in jsonDictionary["list"]:
							if obj is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj):
								if obj.ContainsKey("main") and obj["main"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["main"]) and obj["main"].ContainsKey("temp"):
									temp = obj["main"]["temp"]

								if obj.ContainsKey("wind") and obj["wind"] is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(obj["wind"]):
									if obj["wind"].ContainsKey("speed"):
										windSpeed = obj["wind"]["speed"]

									if obj["wind"].ContainsKey("deg"):
										windDeg = obj["wind"]["deg"]

								if obj.ContainsKey("weather") and obj["weather"] is not None and clr.GetClrType(Array).IsInstanceOfType(obj["weather"]):
									for o in obj["weather"]:
										if o is not None and clr.GetClrType(Dictionary[String, Object]).IsInstanceOfType(o) and o.ContainsKey("id") and o["id"] is not None:
											weatherIdList.Add(o["id"])
																
								for id in weatherIdList:
									digit = Convert.ToInt32(id / 100)
									path = None
									s = None

									if digit == 2:
										path = "Assets\\Cloud-Lightning.png"
										weatherConditionList.Add("Thunderstorm")

									elif  digit == 3:
										path = "Assets\\Cloud-Drizzle.png"
										weatherConditionList.Add("Drizzle")
														
									elif  digit == 5:
										d = Convert.ToInt32(id / 10)

										if d == 0:
											if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18:
												path = "Assets\\Cloud-Rain-Sun.png"
																
											else:
												path = "Assets\\Cloud-Rain-Moon.png"

										else:
											path = "Assets\\Cloud-Rain.png"

										weatherConditionList.Add("Rain")
														
									elif  digit == 6:
										path = "Assets\\Cloud-Snow.png"
										weatherConditionList.Add("Snow")
														
									elif  digit == 7:
										path = "Assets\\Cloud-Fog.png"
															
										if Convert.ToInt32(id) == 701:
											weatherConditionList.Add("Mist")

										elif Convert.ToInt32(id) == 711:
											weatherConditionList.Add("Smoke")

										elif Convert.ToInt32(id) == 721:
											weatherConditionList.Add("Haze")

										elif Convert.ToInt32(id) == 731:
											weatherConditionList.Add("Dust")

										elif Convert.ToInt32(id) == 741:
											weatherConditionList.Add("Fog")
														
									elif  digit == 8:
										if Convert.ToInt32(id) == 800:
											if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18:
												path = "Assets\\Sun.png"
												weatherConditionList.Add("Sunny")
																
											else:
												path = "Assets\\Moon.png"
												weatherConditionList.Add("Clear")

										elif Convert.ToInt32(id) >= 801 and Convert.ToInt32(id) <= 803:
											if nowDateTime.Hour > 6 and nowDateTime.Hour <= 18:
												path = "Assets\\Cloud-Sun.png"
																
											else:
												path = "Assets\\Cloud-Moon.png"

											weatherConditionList.Add("Cloudy")

										elif Convert.ToInt32(id) == 804:
											path = "Assets\\Cloud.png"
											weatherConditionList.Add("Overcast")
															
									else:
										if Convert.ToInt32(id) == 900:
											path = "Assets\\Tornado.png"
											weatherConditionList.Add("Tornado")

										elif Convert.ToInt32(id) == 905:
											path = "Assets\\Wind.png"
											weatherConditionList.Add("Windy")

										elif Convert.ToInt32(id) == 906:
											path = "Assets\\Cloud-Hail.png"
											weatherConditionList.Add("Hail")

									if path is not None and weatherPathHashSet.Contains(path) == False:
										fs = None

										try:
											fs = FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read)
											ms = MemoryStream()
											buffer = Array.CreateInstance(Byte, fs.Length)
											bytesRead = fs.Read(buffer, 0, buffer.Length)

											while bytesRead > 0:
												ms.Write(buffer, 0, bytesRead)
												bytesRead = fs.Read(buffer, 0, buffer.Length)

											ms.Seek(0, SeekOrigin.Begin)
											weatherStreamList.Add(ms)

										finally:
											if fs is not None:
												fs.Close()

										weatherPathHashSet.Add(path)

				finally:
					if streamReader is not None:
						streamReader.Close()

					if stream is not None:
						stream.Close()
			
					if response is not None:
						response.Close()

			except Exception, e:
				Trace.WriteLine(e.clsException.Message)
				Trace.WriteLine(e.clsException.StackTrace)
Пример #16
0
	def onCompleted(task):
		global idList

		if task.Result.Key.Count > 0:
			sequenceList = List[Sequence]()

			for sequence in Script.Instance.Sequences:
				if sequence.Name.Equals("Weather"):
					sequenceList.Add(sequence)

			for s in task.Result.Key:
				Script.Instance.TryEnqueue(Script.Instance.Prepare(sequenceList, s))

		if Application.Current.MainWindow.IsVisible and task.Result.Value.Value.Value.Value.Count > 0 and not Enumerable.SequenceEqual[Double](idList, task.Result.Value.Value.Value.Key):
			width = 128
			height = 128
			max = 4
			window = Window()
			contentControl = ContentControl()
			grid = Grid()
			storyboard = Storyboard()

			def onCurrentStateInvalidated(sender, args):
				if sender.CurrentState == ClockState.Filling:
					window.Close()

			storyboard.CurrentStateInvalidated += onCurrentStateInvalidated
		
			def onLoaded(sender, args):
				time = 0
				speed = task.Result.Value.Value.Key.Key * 1000 / 60 / 60

				contentControl.Width = contentControl.ActualWidth * 1.5 if contentControl.ActualWidth > contentControl.ActualHeight else contentControl.ActualHeight * 1.5 
				contentControl.Height = contentControl.ActualWidth * 1.5 if contentControl.ActualWidth > contentControl.ActualHeight else contentControl.ActualHeight * 1.5
				contentControl.RenderTransform.CenterX = contentControl.Width / 2
				contentControl.RenderTransform.CenterY = contentControl.Height / 2

				doubleAnimation1 = DoubleAnimation(contentControl.Opacity, 1, TimeSpan.FromMilliseconds(500))
				doubleAnimation2 = DoubleAnimation(1.5, 1, TimeSpan.FromMilliseconds(500))
				doubleAnimation3 = DoubleAnimation(1.5, 1, TimeSpan.FromMilliseconds(500))
				doubleAnimation4 = DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(500))
				doubleAnimation5 = DoubleAnimation(1, 1.5, TimeSpan.FromMilliseconds(500))
				doubleAnimation6 = DoubleAnimation(1, 1.5, TimeSpan.FromMilliseconds(500))
				sineEase1 = SineEase()
				sineEase2 = SineEase()

				sineEase1.EasingMode = EasingMode.EaseOut
				sineEase2.EasingMode = EasingMode.EaseIn
				doubleAnimation1.EasingFunction = doubleAnimation2.EasingFunction = doubleAnimation3.EasingFunction = sineEase1
				doubleAnimation4.EasingFunction = doubleAnimation5.EasingFunction = doubleAnimation6.EasingFunction = sineEase2

				doubleAnimation4.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds((250 * (max - 1) * 2 + 1000 + 3000) * task.Result.Value.Value.Value.Value.Count - 500))
				doubleAnimation5.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds((250 * (max - 1) * 2 + 1000 + 3000) * task.Result.Value.Value.Value.Value.Count - 500))
				doubleAnimation6.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds((250 * (max - 1) * 2 + 1000 + 3000) * task.Result.Value.Value.Value.Value.Count - 500))

				storyboard.Children.Add(doubleAnimation1)
				storyboard.Children.Add(doubleAnimation2)
				storyboard.Children.Add(doubleAnimation3)
				storyboard.Children.Add(doubleAnimation4)
				storyboard.Children.Add(doubleAnimation5)
				storyboard.Children.Add(doubleAnimation6)

				Storyboard.SetTarget(doubleAnimation1, contentControl)
				Storyboard.SetTarget(doubleAnimation2, contentControl)
				Storyboard.SetTarget(doubleAnimation3, contentControl)
				Storyboard.SetTarget(doubleAnimation4, contentControl)
				Storyboard.SetTarget(doubleAnimation5, contentControl)
				Storyboard.SetTarget(doubleAnimation6, contentControl)
				Storyboard.SetTargetProperty(doubleAnimation1, PropertyPath(ContentControl.OpacityProperty))
				Storyboard.SetTargetProperty(doubleAnimation2, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleXProperty))
				Storyboard.SetTargetProperty(doubleAnimation3, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleYProperty))
				Storyboard.SetTargetProperty(doubleAnimation4, PropertyPath(ContentControl.OpacityProperty))
				Storyboard.SetTargetProperty(doubleAnimation5, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleXProperty))
				Storyboard.SetTargetProperty(doubleAnimation6, PropertyPath("(0).(1)", ContentControl.RenderTransformProperty, ScaleTransform.ScaleYProperty))

				for element1 in grid.Children:
					for element2 in element1.Children:
						w = element2.Width / 2 if speed > 15 else element2.Width / 2 * speed / 15;
						da1 = DoubleAnimation(element2.Opacity, 1, TimeSpan.FromMilliseconds(1000))
						da2 = DoubleAnimation(-w if Convert.ToInt32(task.Result.Value.Value.Key.Value / 180) % 2 == 0 else w, 0, TimeSpan.FromMilliseconds(1000))
						da3 = DoubleAnimation(1, 0, TimeSpan.FromMilliseconds(1000))
						da4 = DoubleAnimation(0, w if Convert.ToInt32(task.Result.Value.Value.Key.Value / 180) % 2 == 0 else -w, TimeSpan.FromMilliseconds(1000))
						se1 = SineEase()
						se2 = SineEase()

						da1.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag))
						da2.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag))
						da3.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag * 2 + 250 * (max - 1) - 250 * element2.Tag + 3000))
						da4.BeginTime = Nullable[TimeSpan](TimeSpan.FromMilliseconds(time + 250 * element2.Tag * 2 + 250 * (max - 1) - 250 * element2.Tag + 3000))

						se1.EasingMode = EasingMode.EaseOut
						se2.EasingMode = EasingMode.EaseIn
						da1.EasingFunction = da2.EasingFunction = se1
						da3.EasingFunction = da4.EasingFunction = se2

						storyboard.Children.Add(da1)
						storyboard.Children.Add(da2)
						storyboard.Children.Add(da3)
						storyboard.Children.Add(da4)

						Storyboard.SetTarget(da1, element2)
						Storyboard.SetTarget(da2, element2)
						Storyboard.SetTarget(da3, element2)
						Storyboard.SetTarget(da4, element2)
						Storyboard.SetTargetProperty(da1, PropertyPath(Rectangle.OpacityProperty))
						Storyboard.SetTargetProperty(da2, PropertyPath("(0).(1)", Rectangle.RenderTransformProperty, TranslateTransform.XProperty))
						Storyboard.SetTargetProperty(da3, PropertyPath(Rectangle.OpacityProperty))
						Storyboard.SetTargetProperty(da4, PropertyPath("(0).(1)", Rectangle.RenderTransformProperty, TranslateTransform.XProperty))

					time += 250 * (max - 1) + 1000 + 3000

				storyboard.Begin()
			
			fs = None
			bi = BitmapImage()

			try:
				fs = FileStream("Assets\\Background-Popup.png", FileMode.Open, FileAccess.Read, FileShare.Read)

				bi.BeginInit()
				bi.StreamSource = fs
				bi.CacheOption = BitmapCacheOption.OnLoad
				bi.CreateOptions = BitmapCreateOptions.None
				bi.EndInit()

			finally:
				if fs is not None:
					fs.Close()

			window.Owner = Application.Current.MainWindow
			window.Title = Application.Current.MainWindow.Title
			window.WindowStartupLocation = WindowStartupLocation.CenterOwner
			window.AllowsTransparency = True
			window.WindowStyle = WindowStyle.None
			window.ResizeMode = ResizeMode.NoResize
			window.ShowActivated = False
			window.ShowInTaskbar = Application.Current.MainWindow.ContextMenu.Items[5].IsChecked
			window.Topmost = True
			window.SizeToContent = SizeToContent.WidthAndHeight
			window.Background = Brushes.Transparent
			window.Loaded += onLoaded
			
			contentControl.UseLayoutRounding = True
			contentControl.HorizontalAlignment = HorizontalAlignment.Stretch
			contentControl.VerticalAlignment = VerticalAlignment.Stretch
			contentControl.Opacity = 0
			contentControl.RenderTransform = ScaleTransform(1, 1)

			window.Content = contentControl

			imageBrush = ImageBrush(bi)
			imageBrush.TileMode = TileMode.None
			imageBrush.Stretch = Stretch.Fill
			imageBrush.ViewboxUnits = BrushMappingMode.Absolute
			imageBrush.Viewbox = Rect(0, 0, bi.Width, bi.Height)
			imageBrush.AlignmentX = AlignmentX.Left
			imageBrush.AlignmentY = AlignmentY.Top
			imageBrush.Opacity = 0.5

			dg = DrawingGroup()
			dc = dg.Open()
			dc.DrawRectangle(SolidColorBrush(Color.FromArgb(Byte.MaxValue * 50 / 100, 0, 0, 0)), None, Rect(0, 0, bi.Width, bi.Height))
			dc.DrawRectangle(imageBrush, None, Rect(0, 0, bi.Width, bi.Height))
			dc.Close()

			backgroundBrush = ImageBrush(DrawingImage(dg))
			backgroundBrush.TileMode = TileMode.Tile
			backgroundBrush.ViewportUnits = BrushMappingMode.Absolute
			backgroundBrush.Viewport = Rect(0, 0, bi.Width, bi.Height)
			backgroundBrush.Stretch = Stretch.None

			if backgroundBrush.CanFreeze:
				backgroundBrush.Freeze()

			grid.HorizontalAlignment = HorizontalAlignment.Stretch
			grid.VerticalAlignment = VerticalAlignment.Stretch
			grid.Background = backgroundBrush
			grid.Width = 150
			grid.Height = 150
			grid.Clip = EllipseGeometry(Rect(0, 0, 150, 150))

			dropShadowEffect = DropShadowEffect()
			dropShadowEffect.BlurRadius = 1
			dropShadowEffect.Color = Colors.Black
			dropShadowEffect.Direction = 270
			dropShadowEffect.Opacity = 0.5
			dropShadowEffect.ShadowDepth = 1

			if dropShadowEffect.CanFreeze:
				dropShadowEffect.Freeze()

			grid.Effect = dropShadowEffect

			contentControl.Content = grid

			solidColorBrush = SolidColorBrush(colorFromAhsb(Byte.MaxValue, 60, 1.0, 1.0) if task.Result.Value.Key < 0 else colorFromAhsb(Byte.MaxValue, 0, 1.0, 0.4) if task.Result.Value.Key > 37 else colorFromAhsb(Byte.MaxValue, 60 - 60 * task.Result.Value.Key / 37, 1.0, 0.4 + 0.6 * Math.Pow(Math.E, (37 / 5 - task.Result.Value.Key) - 37 / 5) if task.Result.Value.Key < 37 / 5 else 0.4))

			if solidColorBrush.CanFreeze:
				solidColorBrush.Freeze()


			for stream in task.Result.Value.Value.Value.Value:
				try:
					bi = BitmapImage()
					bi.BeginInit()
					bi.StreamSource = stream
					bi.CacheOption = BitmapCacheOption.OnLoad
					bi.CreateOptions = BitmapCreateOptions.None
					bi.EndInit()

				finally:
					stream.Close()

				imageBrush = ImageBrush(bi)
				imageBrush.TileMode = TileMode.None
				imageBrush.ViewportUnits = BrushMappingMode.Absolute
				imageBrush.Viewport = Rect(0, 0, width, height)
				imageBrush.Stretch = Stretch.Uniform

				if imageBrush.CanFreeze:
					imageBrush.Freeze()

				g = Grid()
				g.HorizontalAlignment = HorizontalAlignment.Center
				g.VerticalAlignment = VerticalAlignment.Center
				g.Background = Brushes.Transparent
				g.Width = width
				g.Height = height

				grid.Children.Add(g)

				for i in range(max):
					rectangle = Rectangle()
					rectangle.HorizontalAlignment = HorizontalAlignment.Left
					rectangle.VerticalAlignment = VerticalAlignment.Top
					rectangle.Width = width
					rectangle.Height = height
					rectangle.Fill = solidColorBrush
					rectangle.Opacity = 0
					rectangle.OpacityMask = imageBrush
					rectangle.Clip = RectangleGeometry(Rect(0, height / max * i, width, height / max))
					rectangle.RenderTransform = TranslateTransform(0, 0)
					rectangle.Tag = i
					
					g.Children.Add(rectangle)

			window.Show()

			idList.Clear()
			idList.AddRange(task.Result.Value.Value.Value.Key)
analysis_idx = 0

import csv
from os import path
from System.IO import FileStream, FileMode
from System.Runtime.Serialization.Formatters.Binary import BinaryFormatter

analysis = ExtAPI.DataModel.Project.Model.Analyses[analysis_idx]

esupports = analysis.GetLoadObjects("ElasticFoundation")

for support in esupports:
    comp_file = path.join(analysis.WorkingDir,
                          support.Properties['nodeFile'].Value)

    with FileStream(comp_file, FileMode.Open) as nstream:
        formatter = BinaryFormatter()
        nodes = formatter.Deserialize(nstream)

    csv_outfile = path.join(analysis.WorkingDir,
                            support.Caption.strip() + '.csv')

    with open(csv_outfile, 'wb') as rfile:
        writer = csv.writer(rfile)
        writer.writerow(['Set', 'Fx', 'Fy', 'Fz', 'Total'])
        with analysis.GetResultsData() as reader:
            for step, time in enumerate(reader.ListTimeFreq):
                reader.CurrentResultSet = step + 1
                forces = reader.GetResult('F')
                fx = fy = fz = 0.0
                for k in nodes.Keys:
Пример #18
0
import clr

# --------------------------------------------------------
# System.IOを使用したファイル書き込み
clr.AddReference('System.IO')
from System.IO import FileStream

file = FileStream("Net.txt", 2, 2)
file.Write(b'aaaaa', 0, 5)
file.Close
Пример #19
0
        "Characters"].Value if directory is None else Path.Combine(
            directory, config.AppSettings.Settings["Characters"].Value)

    if not File.Exists(path):
        characterList = List[Character]()

        for fileName in Directory.EnumerateFiles(
                Path.GetDirectoryName(Assembly.GetEntryAssembly().Location),
                "*", SearchOption.AllDirectories):
            extension = Path.GetExtension(fileName)

            if extension.Equals(".xml", StringComparison.OrdinalIgnoreCase):
                fs = None

                try:
                    fs = FileStream(fileName, FileMode.Open, FileAccess.Read,
                                    FileShare.Read)
                    rootElement = XDocument.Load(fs).Root

                    if rootElement.Name.LocalName.Equals("script"):
                        for characterElement in rootElement.Elements(
                                "character"):
                            for sequenceElement in characterElement.Elements(
                                    "sequence"):
                                character = Character()
                                originX = 0
                                originY = 0
                                x = 0
                                y = 0
                                width = 0
                                height = 0
Пример #20
0
        def onLoad():
            streamList1 = List[MemoryStream]()
            streamList2 = List[MemoryStream]()

            for i in range(10):
                ms = None
                fs = None

                try:
                    fs = FileStream(
                        String.Format("Assets\\Number-{0}.png",
                                      i.ToString(
                                          CultureInfo.InvariantCulture)),
                        FileMode.Open, FileAccess.Read, FileShare.Read)
                    ms = MemoryStream()
                    buffer = Array.CreateInstance(Byte, fs.Length)
                    bytesRead = fs.Read(buffer, 0, buffer.Length)

                    while bytesRead > 0:
                        ms.Write(buffer, 0, bytesRead)
                        bytesRead = fs.Read(buffer, 0, buffer.Length)

                    ms.Seek(0, SeekOrigin.Begin)

                    streamList1.Add(ms)

                except:
                    if ms is not None:
                        ms.Close()
                        ms = None

                finally:
                    if fs is not None:
                        fs.Close()

            for path in [
                    "Assets\\Hour.png", "Assets\\Minute.png",
                    "Assets\\Second.png"
            ]:
                ms = None
                fs = None

                try:
                    fs = FileStream(path, FileMode.Open, FileAccess.Read,
                                    FileShare.Read)
                    ms = MemoryStream()
                    buffer = Array.CreateInstance(Byte, fs.Length)
                    bytesRead = fs.Read(buffer, 0, buffer.Length)

                    while bytesRead > 0:
                        ms.Write(buffer, 0, bytesRead)
                        bytesRead = fs.Read(buffer, 0, buffer.Length)

                    ms.Seek(0, SeekOrigin.Begin)

                    streamList2.Add(ms)

                except:
                    if ms is not None:
                        ms.Close()
                        ms = None

                finally:
                    if fs is not None:
                        fs.Close()

            return KeyValuePair[List[MemoryStream],
                                List[MemoryStream]](streamList1, streamList2)
Пример #21
0
def CreateFile(filePath, overwrite=False):
    fileMode = FileMode.Create if overwrite else FileMode.CreateNew
    fileStream = FileStream(filePath, FileMode.Create, FileAccess.Write,
                            FileShare.ReadWrite)
    return fileStream
Пример #22
0
def OpenFile(filePath, readonly=True):
    fileAccess = FileAccess.Read if readonly else FileAccess.ReadWrite
    fileStream = FileStream(filePath, FileMode.Open, fileAccess,
                            FileShare.ReadWrite)
    return fileStream
Пример #23
0

	public static bool Write(SafeHandle fileHandle, Option dumpType)
	{
		return Write(fileHandle, dumpType, ExceptionInfo.None);
	}
	
	public static bool Write(SafeHandle fileHandle)
	{
		return Write(fileHandle, Option.WithFullMemory, ExceptionInfo.None);
	}
}
"""

try:
    print('Generating assembly')
    assembly = Generate(unmanaged_code, 'MiniDump')
    clr.AddReference(assembly)
    print('Importing assembly')
    import MiniDump

    systemRoot = Environment.GetEnvironmentVariable("SystemRoot")
    dumpFile = "{0}\\Temp\\debug.bin".format(systemRoot)

    print('Creating dump')
    with FileStream(dumpFile, FileMode.Create, FileAccess.ReadWrite,
                    FileShare.Write) as fs:
        MiniDump.Write(fs.SafeFileHandle)
    print 'Succsessfully written LSASS.exe dumpfile to %s' % dumpFile
except Exception as e:
    print(str(e))