I'm currently trying to use gestures recognizers in Unity3D. For this I need a library of gestures to be compared with the gesture I'm making.
I'm using a script to save and load from another Unity user since I have no idea how to do it myself.
The problem I'm facing is:
If I save the gestures as json file during gameplay, I can compare them in the same run. But if I restart the run, it stops being able to read the json file and returns NULL or no match as if there were nothing in the json file.
[Serializable]
public class GestureTemplates
{
public List<DrawnGesture> templates;
public GestureTemplates()
{
templates = new List<DrawnGesture>();
}
}
private string gestureFileName = "gestures.json";
void Start () {
LoadTemplates();
}
private void SaveTemplates()
{
string filePath = Application.dataPath + "/streamingAssets/" + gestureFileName;
string saveData = JsonUtility.ToJson(templates);
File.WriteAllText(filePath, saveData);
Debug.Log("Template Saved");
}
private void LoadTemplates()
{
templates = new GestureTemplates();
string filePath = Path.Combine(Application.streamingAssetsPath, gestureFileName);
if (File.Exists(filePath))
{
string data = File.ReadAllText(filePath);
templates = JsonUtility.FromJson<GestureTemplates>(data);
}
}
What I've noticed is it takes a while to save, but it does in fact save since it calls the debug.Log line and the save file can be used in the same run.
Any help would be highly appreciated.
Edit: Nevermind. It's not saving either. It's saving as a Json file with an empty list. The variable is working on the run, but it's not saving nor loading.
Related
Recently i am trying to upload a file to IPFS and download/retrieve it using ipfs core api. And for this purpose a use .net library ipfs(c#) library. its works fine for a txt file but when i uploaded a pdf file and tries to download it gives me some kind of string.i thought that that string maybe my pdf file all content but that string proves me wrong. when i tries to compare my original pdf file string with (current string) that is totally diffferent..
my pdf file hash : QmWPCRv8jBfr9sDjKuB5sxpVzXhMycZzwqxifrZZdQ6K9o
and my c# code the get this(api) ==>
static void Main(string[] args)
{
var ipfs = new IpfsClient();
const string filename = "QmWPCRv8jBfr9sDjKuB5sxpVzXhMycZzwqxifrZZdQ6K9o";
var text = ipfs.FileSystem.ReadAllTextAsync(filename).Result;
}
my question is whtat i have done wrong and i have done some wrong then how can i get a pdf file ?? how ??
First of all please check if you can access to the file from live environment:
e.g.
https://ipfs.infura.io/ipfs/QmNtg1uDy1A71udMa2ipTfKghArRQFspfFkncunamW29SA
https://ipfs.io/ipfs/
if the file was uploaded correctly you can IpfsClient package to do this action:
Define property that references on ipfs env (e.g. via infura)
_ipfsClient = new IpfsClient("https://ipfs.infura.io:5001");
Introduce method to download the file by hash
public async Task<byte[]> DownloadAsync(string hash)
{
using (var stream = await _ipfsClient.FileSystem.ReadFileAsync(hash))
{
using (var ms = new MemoryStream())
{
stream.CopyTo(ms);
return ms.ToArray();
}
}
}
If you use web api - introduce controller to return exactly pdf
public async Task<IActionResult> Get(string hash)
{
var data = await _ipfsDownloadService.DownloadAsync(hash);
return File(data, "application/pdf");
}
So I have an SSIS package that I am working on right now that requires something that I have yet to do. The package currently just has a For Each Loop container that stores the value of the file name it finds in the User::WatchFolder to a variable and then moves that file to another folder for a process to pick up. What I have been tasked with is augmenting this so that the process remains unchanged for .837 file that does not contain a certain set of character but redirecting the files that come through with the word 'RELAY' in them. From there I also need to open up this EDI file and replace the string '5010' with '5010R', save it and move to a separate folder.
I have moved data in a Data flow task based on certain criteria using a Conditional Split, but this is not data from a table or database, so I'm not sure if this can be accomplished in a Control Flow task. Also, I'm assuming that the string can be replaced via a Script Task, but I'm not sure (again) if this is something that would live in the Control flow or in some sort of Data Flow task.
This is what the package looks like thus far.
SSIS Package so far
EDIT: So far I have created a script task using C# to find and replace the values using ReadFile(FilePath) into a variable called FileContent and then doing a FileContent.Replace("someText","someOtherText")
and then writing the contents back to the file using StreamReader and StreamWriter. That part seems to work fine, but I'm not sure now how to move the file depending on whether it contains a certain value in the FileName.
public void Main()
{
String ErrInfo = "";
String FilePath = Dts.Variables["User::FileName"].Value.ToString();
try
{
String FileContent; //Variable to store File Contents
FileContent = ReadFile(FilePath, ErrInfo);
if (ErrInfo.Length > 0)
{
Dts.Log("Error while reading File " + FilePath, 0, null);
Dts.Log(ErrInfo, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
//FileContent Before Replace;
MessageBox.Show(FileContent);
//Find and Replace --> Modify WHERE clause
FileContent = FileContent.Replace(
"Relay5010 ",
"Relay5010R"
);
//FileContent After Replace;
MessageBox.Show(FileContent);
Dts.Variables["User::FileContent"].Value = FileContent;
//Write the contents back to File
WriteToFile(FilePath, FileContent, ErrInfo);
if (ErrInfo.Length > 0)
{
Dts.Log("Error while writing File " + FilePath, 0, null);
Dts.Log(ErrInfo, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
return;
}
}
catch (Exception e)
{
Dts.Log(e.Message, 0, null);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
public String ReadFile(String FilePath, String ErrInfo)
{
String strContents;
StreamReader sReader;
try
{
sReader = File.OpenText(FilePath);
strContents = sReader.ReadToEnd();
sReader.Close();
return strContents;
}
catch (Exception e)
{
MessageBox.Show(ErrInfo);
ErrInfo = e.Message;
return "";
}
}
public void WriteToFile(String FilePath, String strContents, String ErrInfo)
{
StreamWriter sWriter;
try
{
sWriter = new StreamWriter(FilePath);
sWriter.Write(strContents);
sWriter.Close();
}
catch (Exception e)
{
MessageBox.Show(ErrInfo);
ErrInfo = e.Message;
}
}
#region ScriptResults declaration
/// <summary>
/// This enum provides a convenient shorthand within the scope of this class for setting the
/// result of the script.
///
/// This code was generated automatically.
/// </summary>
enum ScriptResults
{
Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,
Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure
};
#endregion
}
}
Truth is, I'd love to leave the existing files alone and let them run down their normal path and just divert the ones containing the "R" value and those can have the script task applied to them. Is there possibly a way other than another script task? I am just trying to see if SSIS lends me another tool so that this can be done in the most straight forward way possible
This is my first question posted as well so if there is something else I missed here, I won't be offended if it is pointed out!
I am using groovy configuration with logback. Occasionally, I will log a directory or file location, and I'd like it to come up in my HTML log as a link. Here is what my configuration looks like currently.
appender("htmlLog", FileAppender) {
file = "${logPath}/${logName}.html"
append = false
encoder(LayoutWrappingEncoder) {
layout("ch.qos.logback.classic.html.HTMLLayout"){
pattern = "%d{yyyy/MM/dd HH:mm:ss}%-5p%logger{0}%m"
}
}
}
Anyone have a thought as to how I could get this?
There are two obstacles to generating anchor tags or any other HTML within the table. I'm working against logback 1.2.3
First you need a way to convert your message, looking for paths and replacing them with anchors. Creating custom converters that you can use from the pattern is straightforward and documented here. My crude implementation looks like this, you'll probably want to modify the path detection to suit you:
package ch.qos.logback.classic.html;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.helpers.Transform;
public class LinkConverter extends ClassicConverter {
public String convert(ILoggingEvent iLoggingEvent) {
String message = iLoggingEvent.getMessage();
message = Transform.escapeTags(message);
message = message.replaceAll(" (/\\S+)", " file://$1");
return message;
}
}
This is attempting to escape any suspicious characters before replacing strings like /path/to/thing with an anchor tag.
Secondly, the HTMLLayout escapes everything, this is so it doesn't generate a malformed table and improves security (scripts can't be injected etc). So even with your new converter wired up and referenced correctly HTMLLayout will escape the anchor.
To get around this I extended HTMLLayout, unfortunately you have to override the guts of the class and put it in the same package to access package private fields.
All you want to change is the escaping line, I changed it to String s = c.getClass().equals(LinkConverter.class) ? c.convert(event): Transform.escapeTags(c.convert(event)); to try and minimise the impact.
Here is the full implementation:
package ch.qos.logback.classic.html;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.CoreConstants;
import ch.qos.logback.core.helpers.Transform;
import ch.qos.logback.core.pattern.Converter;
public class UnsafeHTMLLayout extends HTMLLayout{
public String doLayout(ILoggingEvent event) {
StringBuilder buf = new StringBuilder();
this.startNewTableIfLimitReached(buf);
boolean odd = true;
if((this.counter++ & 1L) == 0L) {
odd = false;
}
String level = event.getLevel().toString().toLowerCase();
buf.append(CoreConstants.LINE_SEPARATOR);
buf.append("<tr class=\"");
buf.append(level);
if(odd) {
buf.append(" odd\">");
} else {
buf.append(" even\">");
}
buf.append(CoreConstants.LINE_SEPARATOR);
for(Converter c = this.head; c != null; c = c.getNext()) {
this.appendEventToBuffer(buf, c, event);
}
buf.append("</tr>");
buf.append(CoreConstants.LINE_SEPARATOR);
if(event.getThrowableProxy() != null) {
this.throwableRenderer.render(buf, event);
}
return buf.toString();
}
private void appendEventToBuffer(StringBuilder buf, Converter<ILoggingEvent> c, ILoggingEvent event) {
buf.append("<td class=\"");
buf.append(this.computeConverterName(c));
buf.append("\">");
String s = c.getClass().equals(LinkConverter.class) ? c.convert(event): Transform.escapeTags(c.convert(event));
buf.append(s);
buf.append("</td>");
buf.append(CoreConstants.LINE_SEPARATOR);
}
}
My final logback configuration looks like this:
import ch.qos.logback.classic.html.LinkConverter
conversionRule("linkEscaper", LinkConverter.class)
appender("htmlLog", FileAppender) {
file = "/tmp/out.html"
append = false
encoder(LayoutWrappingEncoder) {
layout("ch.qos.logback.classic.html.UnsafeHTMLLayout"){
pattern = "%d{yyyy/MM/dd HH:mm:ss}%-5p%logger{0}%linkEscaper"
}
}
}
root(INFO, ["htmlLog"])
Here's my repo with this code.
I am having one VSIX project, which will made some changes in Project.json file of ASPNET5 project. am using the following to edit .json file.
ProjectJson jsonObj = JsonConvert.DeserializeObject<ProjectJson>(jsonContents);
jsonObj = JsonConvert.DeserializeObject<ProjectJson>(jsonContents);
var resultJson = JsonConvert.SerializeObject(jsonObj, Formatting.Indented);
JsonSerializer serializer = new JsonSerializer();
using (StreamWriter sw = new StreamWriter(projectObjects.ProjectJsonPath))
{
var writer = new JsonTextWriter(sw);
serializer.Serialize(writer, resultJson);
}
// File.WriteAllText(projectObjects.ProjectJsonPath, resultJson);
by using both stream writer and writealltext am getting the following message in ASPNET 5 project
The file has unsaved changes inside this editor and has been changed
externally. do you want to reload it?
how to edit .json file without getting the above message?
Its actually the opposite. Since the environment thinks that the file wants to reload with unsaved changes.
You should uncheck the detect file changes. And when you do, it won't detect the external changes and will not warn you, beware though, that if you try to save the file after it has been modified you will lose the external change.(not a problem in your case I guess) and in order to see the changes you will have to close, not save the file and reopen it.
Source : VS2008: Disable asking whether to reload files changed outside the IDE
This is the option you want to check programmatically. I don't know how exactly you can do that but you can find topics about settings at MSDN (Creating an option page and Creating a setting category). Using those topics you can have a sense of how options are created.
Basically what you need to do is to load VS settings file (VS.vssettings) and inject another Xml line. (Have a look at Examining the Settings File section on MSDN)
Update
To be extremely clear the VS settings file is located under
Documents\Your_VS_Version\Settings\CurrentSettings.vssettings
and you need to load the xml and change 'AutoloadExternalChanges' to value 'true'.
You need to tell the environment to ignore file changes. This can be achieved using the IVsFileChangeEx and IVsDocDataFileChangeControl interfaces.
Here is a utility class (derived from the original Visual Studio 2010 SDK Managed Package Framework sample that you can still find here: http://www.getcodesamples.com/src/8641B4F/98B3955E) that should help:
using (SuspendFileChanges suspend = new SuspendFileChanges(site, filePath))
{
// do something with files
suspend.Sync(); // if you optionally want to tell the IDE it has changed
}
The utility class:
public class SuspendFileChanges: IDisposable
{
private readonly IServiceProvider _serviceProvider;
private readonly List<string> _urls;
private readonly IVsDocDataFileChangeControl[] _controls;
public SuspendFileChanges(IServiceProvider serviceProvider, string url)
: this(serviceProvider, new string[] { url })
{
}
public SuspendFileChanges(IServiceProvider serviceProvider, params string[] urls)
{
if (serviceProvider == null)
throw new ArgumentNullException("serviceProvider");
if (urls == null)
throw new ArgumentNullException("urls");
_serviceProvider = serviceProvider;
_urls = new List<string>(urls);
_controls = new IVsDocDataFileChangeControl[_urls.Count];
// or use Package.GetGlobalService ...
IVsRunningDocumentTable rdt = (IVsRunningDocumentTable)serviceProvider.GetService(typeof(SVsRunningDocumentTable));
IVsFileChangeEx fileChange = (IVsFileChangeEx)serviceProvider.GetService(typeof(SVsFileChangeEx));
for(int i = 0; i < _urls.Count; i++)
{
string url = _urls[i];
if (url == null)
continue;
fileChange.IgnoreFile(0, url, 1);
IVsHierarchy hierarchy;
uint itemId;
uint docCookie;
IntPtr docData;
rdt.FindAndLockDocument((uint)_VSRDTFLAGS.RDT_NoLock, url, out hierarchy, out itemId, out docData, out docCookie);
if (docData != IntPtr.Zero)
{
_controls[i] = Marshal.GetObjectForIUnknown(docData) as IVsDocDataFileChangeControl;
if (_controls[i] != null)
{
_controls[i].IgnoreFileChanges(1);
}
Marshal.Release(docData);
}
}
}
public void Sync()
{
IVsFileChangeEx fileChange = (IVsFileChangeEx)_serviceProvider.GetService(typeof(SVsFileChangeEx));
if (fileChange == null)
throw new InvalidOperationException();
foreach (string url in _urls)
{
if (url == null)
continue;
fileChange.SyncFile(url);
}
}
public void Dispose()
{
IVsFileChangeEx fileChange = (IVsFileChangeEx)_serviceProvider.GetService(typeof(SVsFileChangeEx));
if (fileChange != null)
{
foreach (string url in _urls)
{
if (url == null)
continue;
fileChange.IgnoreFile(0, url, 0);
}
}
foreach (IVsDocDataFileChangeControl control in _controls)
{
if (control != null)
{
control.IgnoreFileChanges(0);
}
}
}
}
I want to store json values in my device. Because everytime application takes time to load json values. Instead of doing number of times to load, just want to load entire json values once. and without internet I can work with that. Once internet get connected, the application automatically load json values. How can I do this ?
You Can use Database for that.
This way also you can store it.
Arraylist<ClassName> jsondata=new ArrayList<ClassName>
Here's an example:
public Class ClassName
{
string fname;
string lname;
public void setfname(String fname)
{
this.fname=fname;
}
public void setlname(String lname)
{
this.lname=lname;
}
public String getlname(String lname)
{
return lname;
}
public String getfname(String fname)
{
return fname;
}
You can use SharedPreferences to save the json in application's storage space.
code
/* save */
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
Editor editor = pref.edit();
editor.put("myjson", json.toString());
editor.commit();
/* restore */
JSONObject ret = null;
SharedPreferences pref = context.getSharedPreferences("mydata", MODE_PRIVATE);
String jsonStr = pref.getString("myjson", null);
if (!TextUtil.isEmpty(jsonStr)) {
ret = new JSONObject(jsonStr); // need try-catch
}
======
Do the restore every time the app is launching.
For the second part "Once internet get connected, the application automatically load json values."
You need to listen the network state change broadcast. When you get broadcast said the network (or wifi) is connected, grab the newest json from server, replace the json in the memory and save it to SharedPreferences