C# - duplicated output for start date in date range iteration - date

I am trying to make simple app and got stuck. User chooses start date from date picker1 28.01.2015 and end date picker2 29.01.2015 then marks what he/she wants via checkboxes and presses button. The output in console should look similar to this depending on what is marked.
tar zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log`
but instead date picked as start date is returned twice in console and I have no idea what is wrong:
zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150128.log;zxcvf /.../c/folder/folder/$HOSTNAME.20150129.log
Code below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Renci.SshNet;
using System.Configuration;
namespace TestApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
}
...
private void button1_Click(object sender, EventArgs e)
{
GlobalMethods configRead = new GlobalMethods();
configRead.ConfigRead();
GlobalMethods dateIterator = new GlobalMethods();
dateIterator.Iterator();
GlobalVariables.comminit = null;
}
private void checkBox1_CheckedChanged(object sender, EventArgs e)
{
if (checkBox1.Checked)
{
GlobalVariables.cLM = true;
}
else if (!checkBox1.Checked)
{
GlobalVariables.cLM = false;
}
}
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateStart = dateTimePicker1.Value;
}
private void dateTimePicker2_ValueChanged(object sender, EventArgs e)
{
GlobalVariables.dateEnd = dateTimePicker2.Value;
//string endDate = dateTimePicker2.Value.ToString("yyyyMMdd");
}
}
public static class GlobalVariables
{
// Log variables below
public static Boolean mLM;
public static Boolean cLM;
public static Boolean hLM;
public static Boolean pLM;
public static Boolean prLM;
public static Boolean compressMarked = true;
public static String iterate;
public static String comminit;
public static String pH;
public static String pP;
public static String pC;
public static String ppP;
public static String pM;
// Time variables below
public static DateTime dateStart = DateTime.Now;
public static DateTime dateEnd = DateTime.Now;
}
public class Instructions
{
public static String hLl()
{
if (GlobalVariables.compressMarked)
{
return "tar zxcvf " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;";
}
else { return "wget " + GlobalVariables.pH + "$HOSTNAME." + GlobalVariables.iterate + ".log;"; }
}
...
public static String commandsBath()
{
if (GlobalVariables.mLM == true)
{
GlobalVariables.comminit += mLl();
}
if (GlobalVariables.cLM == true)
{
GlobalVariables.comminit += cLl();
}
if (GlobalVariables.hLM == true)
{
GlobalVariables.comminit += hLl();
}
if (GlobalVariables.pLM == true)
{
GlobalVariables.comminit += pLl();
}
if (GlobalVariables.prLM == true)
{
GlobalVariables.comminit += pLlp();
}
return GlobalVariables.comminit;
}
}
public class GlobalMethods
{
public void Iterator()
{
for (DateTime i = GlobalVariables.dateStart; i <= GlobalVariables.dateEnd; i = i.AddDays(1))
{
string iterated = i.ToString("yyyyMMdd");
GlobalVariables.iterate = iterated;
}
}
public void ConfigRead()
{
...
}
public void ConfigWrite()
{
...
}
}
}
Hopefully someone can help.

Never mind, found the solution. Instead of using += and add results of if statements it is better to use String builder like below. This way it works correctly and is more simple.
var sb = new StringBuilder();
if (GlobalVariables.mLM == true) sb.Append(mLl());
if (GlobalVariables.cLM == true) sb.Append(cLl());
...
return GlobalVariables.comminit = sb.ToString();

Related

How do you isolate a text string from in a chatbox/text field in Unity?

I am making a chatbot (well I'm attempting!) and I have set up wit.ai to handle the text-to-speech of the bot. My issue is that I am pulling all of the chat into the speaker on each update which is overloading the TTS, when I really only want the line of the Bot (Dave) to go through the speaker and update with each new line. How can I isolate only the bots lines? Would love some help with this!
public class SimpleCharacter : MonoBehaviour
{
public GameObject item;
public Scrollbar verticalScrollbar;
public ScrollRect scrollRect;
public TMP_Text chatText;
private Animator anim;
public TTSSpeaker _speaker;
// Start is called before the first frame update
void Start()
{
Debug.Log("Simple Character start 0 ");
anim = GetComponentInChildren<Animator>();
if (anim == null)
{
Debug.Log("Simple Character anim is null");
}
Debug.Log("Simple Character start 1");
}
public void Think (string text)
{
string chat = chatText.text;
chat = chat + "/n" + text;
chatText.text = text;
anim.SetTrigger("Think");
}
public void Talk(List<Choice> choices)
{
string chat = chatText.text;
chatText.text = "";
Debug.Log("////////////////////// : " + chat);
chat = chat + "/n" + choices[0].ToString();
Debug.Log("////////////////////// : " + chat);
chatText.text = chat;
chatText.text = choices[0].ToString();
anim.SetTrigger("Talk");
}
public void Talk (string text)
{
string chat = chatText.text;
chat = chat + "/n" + text;
chatText.text = chat;
chatText.text = text;
_speaker.Speak(chatText.text);
}
}
Daves's lines are being received from this character's script
namespace OpenAI_Unity
{
public class OAICharacter : OAICompletion
{
protected override StringBuilder GetDefaultInformation()
{
Debug.Log("GetDefaultInformation - OAICharacter");
var sb = base.GetDefaultInformation();
sb.Replace("[Subject]", this.characterName);
sb.Append($"\n\nHuman: Hi\n{characterName}: Hello\nHuman: ");
return sb;
}
public override string Description { get => $"The following is a conversation between a Human and {characterName}.\n"; set => throw new System.NotImplementedException(); }
public override string InjectStartText { get => "\n" + characterName + ":"; set => throw new System.NotImplementedException(); }
[SerializeField]
private string characterName = "Dave";
public override string InjectRestartText { get => "\nHuman: "; set => throw new System.NotImplementedException(); }
public override string[] StopSequences { get => new string[] { "\n", "Human:" }; set => throw new System.NotImplementedException(); }
public override int NumOutputs { get => 1; set => throw new NotImplementedException(); }
private void ThrowError (string value)
{
Debug.LogError($"Can not set OAICharacter variable to {value}! If you want to modify these please use an OAISimpleObject instead");
}
}
}
This is the controller script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using OpenAI_Unity;
using TMPro;
public class ChatController : MonoBehaviour
{
public OAICharacter _oaiCharacter;
public TMP_InputField questionInput;
// Start is called before the first frame update
void Start()
{
questionInput.onEndEdit.AddListener((string data) =>
{
if (!string.IsNullOrEmpty(data))
{
_oaiCharacter.AddToStory(data);
}
questionInput.text = "";
});
}
// Update is called once per frame
void Update()
{
if (Input.GetKeyDown(KeyCode.Tab))
{
questionInput.Select();
questionInput.ActivateInputField();
}
}
}
And the completion
namespace OpenAI_Unity
{
/// <summary>
/// Used for objects that communicate with OpenAI Completion
/// Abstract itself, for a Generic and fully customizable Completion object use OAIGenericCompletion
/// </summary>
public abstract class OAICompletion : MonoBehaviour
{
public abstract string Description
{
get; set;
}
public abstract string InjectStartText
{
get; set;
}
public abstract string InjectRestartText
{
get; set;
}
public abstract string[] StopSequences
{
get; set;
}
public EngineEnum engine;
public enum EngineEnum
{
Ada,
Babbage,
Curie,
Davinci
}
public enum LogLevel
{
None,
Responses,
ResponsesAndMemory
}
public LogLevel logLevel;
public int Max_tokens = 16;
[Range(0, 1)]
public double Temperature = 0.1;
[Range(0, 1)]
public double Top_p = 1;
public abstract int NumOutputs {get;set;}
[Range(0, 1)]
public double PresencePenalty = 1;
[Range(0, 1)]
public double FrequencyPenalty = 1;
public int LogProbs = 1;
public StringEvent QuestionReceivedEvent;
public ChoicesEvent ResponseReceivedEvent;
public ChoiceEvent ResponseReceivedEvent1;
/// <summary>
/// This can be disabled when using multiple responses, since they should not be manually added to the entire memory
/// </summary>
[HideInInspector]
public bool autoAddResponseToMemory = true;
public StringBuilder memory ;
private void Start()
{
Debug.Log("OAI Completion start 0 ");
memory = GetDefaultInformation();
Debug.Log("Start - memory: " + memory);
Debug.Log("OAI Completion start 1 ");
}
public void Brainwash(bool resetToDefault = true)
{
memory = resetToDefault ? GetDefaultInformation() : new StringBuilder();
}
/// <summary>
/// D
/// </summary>
/// <returns></returns>
protected virtual StringBuilder GetDefaultInformation()
{
Debug.Log("GetDefaultInformation - OAICompletion");
StringBuilder sb = new StringBuilder();
sb.Append(Description);
foreach (OAIBehavior behavior in GetComponents<OAIBehavior>())
{
string behaviorText = behavior.GetAsText();
sb.Append(behaviorText);
sb.Append(" ");
}
return sb;
}
public async void AddToStory(string value)
{
//QuestionReceivedEvent?.Invoke(value);
//Character should remember what they said before, since every time we send a request it requires the full 'story' to OpenAI
memory.Append(value).Append(InjectStartText);
QuestionReceivedEvent?.Invoke(memory.ToString());
if (logLevel == LogLevel.ResponsesAndMemory)
{
Debug.Log(memory);
}
if (!OAIEngine.Instance)
{
Debug.LogError("No OAIEngine object found in scene. Make sure there's a GameObject with an OAIEngine Component in your scene");
return;
}
//We allow the engine to change per request (= per character and per statement)
OAIEngine.Instance.Api.UsingEngine = GetEngine(engine);
if (NumOutputs < 1)
{
Debug.LogWarning($"NumOutputs was set to {NumOutputs}. You should have at least 1 output!");
NumOutputs = 1;
} else if (autoAddResponseToMemory && NumOutputs > 1)
{
Debug.Log("Multiple or no outputs are requested while autoAddResponseToMemory is still true. You should set this to false and manually call 'AddResponseToMemory' after selecting your prefered response.");
}
Debug.Log("Stop Seq: " + StopSequences[0] + " _ " + StopSequences[1]);
var c = new CompletionRequest(memory.ToString(), Max_tokens, Temperature, Top_p, NumOutputs, PresencePenalty, FrequencyPenalty, LogProbs, StopSequences);
var results = await OAIEngine.Instance.Api.Completions.CreateCompletionsAsync(c);
//ResponseReceivedEvent?.Invoke(results.Completions);
//We make it easy by auto-adding responses to the memory
if (autoAddResponseToMemory)
{
var r = results.Completions[0].Text;
AddResponseToMemory(r);
if (logLevel == LogLevel.Responses || logLevel == LogLevel.ResponsesAndMemory)
{
Debug.Log(r);
}
}
}
public void AddResponseToMemory (string value)
{
memory.Append(value).Append(InjectRestartText);
ResponseReceivedEvent1?.Invoke(memory.ToString());
Debug.Log("Memory: " + memory);
}
private Engine GetEngine(EngineEnum e)
{
switch (e)
{
case EngineEnum.Ada:
return Engine.Ada;
case EngineEnum.Babbage:
return Engine.Babbage;
case EngineEnum.Curie:
return Engine.Curie;
case EngineEnum.Davinci:
return Engine.Davinci;
}
return Engine.Default;
}
}
}
You should work with the text string that is passed to the function instead of the entire chat text. Assuming that all spoken dialog starts with "Dave: " you can easily detect this substring in the text, remove it and pass it to your text to speech.
using System;
string botName = "Dave: ";
public void Talk(string text){
chatText.text += "\n" + text;
if(text.StartsWith(botName)){
string spokenText = text.Remove(0, botName.Length)
_speaker.Speak(spokenText);
}
}

Sync player names in unity multi-player

I'm trying to sync all the player names on server and client side, I'm following this tutorial, but I've made some changes to the code.
InitiateMultiplayer.cs
using Unity.Netcode;
using UnityEngine;
using System;
using System.Collections.Generic;
using System.Text;
namespace Multiplayer
{
public class InitiateMultiplayer : MonoBehaviour
{
[Serializable]
public class ConnectionPayload
{
public string password;
public string playerName;
}
public struct PlayerData
{
public string PlayerName { get; private set; }
public PlayerData(string playerName)
{
PlayerName = playerName;
}
}
private static Dictionary<ulong, PlayerData> clientData;
// Start is called before the first frame update
void Start()
{
NetworkManager.Singleton.NetworkConfig.ConnectionApproval = true;
switch (Buttons.GameMode)
{
case "Host":
clientData = new Dictionary<ulong, PlayerData>();
clientData[NetworkManager.Singleton.LocalClientId] = new PlayerData(Buttons.PlayerName);
NetworkManager.Singleton.ConnectionApprovalCallback += ApprovalCheck;
NetworkManager.Singleton.StartHost();
break;
case "Client":
Debug.Log("Client Started");
var payload = JsonUtility.ToJson(new ConnectionPayload()
{
password = "",
playerName = Buttons.PlayerName,
});
byte[] payloadBytes = Encoding.ASCII.GetBytes(payload);
// Set password ready to send to the server to validate
NetworkManager.Singleton.NetworkConfig.ConnectionData = payloadBytes;
NetworkManager.Singleton.StartClient();
break;
default:
break;
}
}
public static PlayerData? GetPlayerData(ulong clientId)
{
if (clientData.TryGetValue(clientId, out PlayerData playerData))
{
return playerData;
}
return null;
}
private void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
{
Debug.Log("approving");
string payload = Encoding.ASCII.GetString(request.Payload);
var connectionPayload = JsonUtility.FromJson<ConnectionPayload>(payload);
response.Approved = true;
response.Position = Vector3.zero;
response.Rotation = Quaternion.identity;
if (response.Approved)
{
response.CreatePlayerObject = true;
Debug.Log("approved");
response.PlayerPrefabHash = null;
response.Pending = false;
if (!clientData.TryGetValue(request.ClientNetworkId, out PlayerData playerData)) {
Debug.Log("we dont got data");
clientData[request.ClientNetworkId] = new PlayerData(connectionPayload.playerName);
}
}
}
}
}
Player.cs
using Unity.Netcode;
using UnityEngine;
using TMPro;
using Unity.Collections;
namespace Multiplayer
{
public class Player : NetworkBehaviour
{
[SerializeField] private TMP_Text displayNameText;
[SerializeField] private Renderer playerBody3D;
private NetworkVariable<FixedString32Bytes> displayName = new NetworkVariable<FixedString32Bytes>();
public override void OnNetworkSpawn()
{
if (!IsServer) { return; }
Debug.Log("Sapwned");
InitiateMultiplayer.PlayerData? playerData = InitiateMultiplayer.GetPlayerData(OwnerClientId);
if (playerData.HasValue)
{
Debug.Log("data -"+playerData.Value.PlayerName);
displayName.Value = playerData.Value.PlayerName;
}
}
private void OnEnable()
{
displayName.OnValueChanged += HandleDisplayNameChanged;
}
private void OnDisable()
{
displayName.OnValueChanged -= HandleDisplayNameChanged;
}
private void HandleDisplayNameChanged(FixedString32Bytes oldDisplayName, FixedString32Bytes newDisplayName)
{
if (IsClient) Debug.Log("client");
Debug.Log("Change in value"+newDisplayName.ToString());
displayNameText.text = newDisplayName.ToString();
}
}
}
The issue I'm facing is that the names are getting synced only on the server side, on the client side the palyer names are the default text.

Trying to read values returned on jsp form submission in springboot project by setters and use the combination to call another java class

So, I have values in getter setter variables when I click on form submit but now want to have those values in variables and check combination of them to run code from another java class
I have tried using parametrized constructor or may be having a common setter but that did not help.
package com.grt.dto;
import java.util.Set;
public class WDPayrollRecon {
public Set<String> dataType;
public String planCountry;
public String payPeriod;
public String currentPeriod;
public String lastPayPeriod;
Set<String> test;
public Set<String> getdataType() {
return dataType;
}
public void setdataType(Set<String> dataType) {
this.dataType = dataType;
System.out.println("this is dataType" +dataType);
test = dataType;
}
public String getPlanCountry() {
return planCountry;
}
public void setPlanCountry(String planCountry) {
this.planCountry = planCountry;
}
public String getPayPeriod() {
return payPeriod;
}
public void setPayPeriod(String payPeriod) {
this.payPeriod = payPeriod;
}
public String getCurrentPeriod() {
return currentPeriod;
}
public void setCurrentPeriod(String currentPeriod) {
this.currentPeriod = currentPeriod;
}
public String getlastPayPeriod() {
return lastPayPeriod;
}
public void setlastPayPeriod(String lastPayPeriod) {
this.lastPayPeriod = lastPayPeriod;
}
public WDPayrollRecon()
{
}
public WDPayrollRecon(Set<String> dataType,String planCountry,String payPeriod,String currentPeriod,String lastPayPeriod)
{
this.dataType = dataType;
this.planCountry = planCountry;
this.payPeriod = payPeriod;
this.currentPeriod = currentPeriod;
this.lastPayPeriod = lastPayPeriod;
if(dataType.contains("GTLI")& planCountry.equals("USA")){
System.out.println("This is test");
}
else{
System.out.println("This is not test");
}
}
}

Signalr & WebSocketSharp in Unity3d

I've currently built a simple Signalr Hub which I'm pushing messages to from a Unity5 project. Given that SignalR2 client doesn't work with Unity5 I'm using websocketsharp in order to intercept the websocket frames. The messages are being pushed to the Hub successfully, but when I attempt to call a method on the client, I do not get the payload string, only the message identifier {"I": 0}
Looking through the SignalR documentation, it looks like this gets sent last, but I have no idea how I can get a hold it it. I'm sure its something simple, but for the life of me I can't figure it out.
UPDATE
Upon request, I've added the code for the project below...
SignalRClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using WebSocketSharp;
namespace Assets.Scripts
{
class SignalRClient
{
private WebSocket _ws;
private string _connectionToken;
private Dictionary<string, UnTypedActionContainer> _actionMap;
private readonly string _socketUrl = "http://localhost/";
private readonly string _socket = "ws://localhost/";
public SignalRClient()
{
_actionMap = new Dictionary<string, UnTypedActionContainer>();
var webRequest = (HttpWebRequest)WebRequest.Create(_socketUrl + "/signalr/negotiate?connectionData=%5B%7B%22name%22%3A%22myHub%22%7D%5D&clientProtocol=1.3");
var response = (HttpWebResponse)webRequest.GetResponse();
using (var sr = new StreamReader(response.GetResponseStream()))
{
var payload = sr.ReadToEnd();
UnityEngine.Debug.Log(payload);
_connectionToken = Uri.EscapeDataString(JsonConvert.DeserializeObject<NegotiateResponse>(payload).ConnectionToken);
//UnityEngine.Debug.Log(_connectionToken);
}
}
public void Open()
{
_ws = _ws == null
? new WebSocket(_socket + "signalr/connect?transport=webSockets&connectionToken=" + _connectionToken)
: new WebSocket(_socket + "signalr/reconnect?transport=webSockets&connectionToken=" + _connectionToken);
AttachAndConnect();
}
public void Close()
{
_ws.Close();
}
public void SendMessage(string name, string message)
{
//{"H":"chathub","M":"Send","A":["tester","hello"],"I":0}
var payload = new RollerBallWrapper()
{
H = "myhub",
M = "Send",
A = new[] { name, message },
I = 12
};
var wsPacket = JsonConvert.SerializeObject(payload);
_ws.Send(wsPacket);
}
private void AttachAndConnect()
{
_ws.OnClose += _ws_OnClose;
_ws.OnError += _ws_OnError;
_ws.OnMessage += _ws_OnMessage;
_ws.OnOpen += _ws_OnOpen;
_ws.Connect();
}
void _ws_OnOpen(object sender, EventArgs e)
{
UnityEngine.Debug.Log("Opened Connection");
}
//
// This seems to be retriving the last frame containing the Identifier
void _ws_OnMessage(object sender, MessageEventArgs e)
{
//UnityEngine.Debug.Log(e.Data); // Returns {"I":"0"} ????
}
void _ws_OnError(object sender, WebSocketSharp.ErrorEventArgs e)
{
UnityEngine.Debug.Log(e.Message);
}
void _ws_OnClose(object sender, CloseEventArgs e)
{
UnityEngine.Debug.Log(e.Reason + " Code: " + e.Code + " WasClean: " + e.WasClean);
}
public void On<T>(string method, Action<T> callback) where T : class
{
_actionMap.Add(method, new UnTypedActionContainer
{
Action = new Action<object>(x =>
{
callback(x as T);
}),
ActionType = typeof(T)
});
}
}
internal class UnTypedActionContainer
{
public Action<object> Action { get; set; }
public Type ActionType { get; set; }
}
class MessageWrapper
{
public string C { get; set; }
public RollerBallWrapper[] M { get; set; }
}
class RollerBallWrapper
{
public string H { get; set; }
public string M { get; set; }
public string[] A { get; set; }
public int I { get; set; }
}
}
MyHub.cs
using System;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNet.SignalR;
public class MyHub : Hub
{
public void Send(string name, string message)
{
var myConn = Context.ConnectionId;
Clients.All.broadcastMessage("John", "Hello");
}
}
The problem is the websocket connection. I had the following:
new WebSocket(_socket + "signalr/connect?transport=webSockets&connectionToken=" + _connectionToken)
Which was missing 2 critical querystring parameters: connectionData and tid in addition to the connectionToken and transport. I wrongly assumed that these weren't needed.
I hope this helps anyone who didn't read the documentation like me :)

responding to the model's property changes in asp.net mvc2

I am having a model not in EF, but in plain text. I have to have the updated events handled for each of the model's properties so that i can log their changes.
Is there a way for this to be achieved.
Implement the INotifyPropertyChanged interface.
A simple example:
using System.ComponentModel;
public class MyModel : INotifyPropertyChanged
{
string _myProperty;
public event PropertyChangedEventHandler PropertyChanged;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
public void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
You can use it like...
public class Test
{
public static void Main()
{
var model = new MyModel();
model.PropertyChanged += new PropertyChangedEventHandler(LogChange);
model.MyProperty="apples";
model.MyProperty="oranges";
model.MyProperty="pears";
}
public static void LogChange(object sender, PropertyChangedEventArgs args)
{
Console.WriteLine(args.PropertyName + " has changed!");
Console.WriteLine("New value: "
+ sender.GetType().GetProperty(args.PropertyName)
.GetValue(sender, null));
}
}