Here are the examples of the csharp api System.Threading.Thread.Sleep(System.TimeSpan) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
2528 Examples
19
Source : SteamBotController.cs
with GNU General Public License v3.0
from 00000vish
with GNU General Public License v3.0
from 00000vish
static void OnDisconnected(SteamClient.DisconnectedCallback callback)
{
// after recieving an AccountLogonDenied, we'll be disconnected from steam
// so after we read an authcode from the user, we need to reconnect to begin the logon flow again
Console.WriteLine("Disconnected from Steam, reconnecting in 5...");
Thread.Sleep(TimeSpan.FromSeconds(5));
//means disconnect was not users request so we reconnect
if (loggedIn)
{
steamClient.Connect();
}
}
19
Source : FLRPC.cs
with GNU General Public License v3.0
from 0x2b00b1e5
with GNU General Public License v3.0
from 0x2b00b1e5
public static void Start()
{
Active = true;
// loop
Csecret = settings.Secret;
while (client != null && Active)
{
// Get info
FLInfo InitInfo = GetFLInfo();
// Try to read any keys if available
if (Console.In.Peek() != -1)
{
switch (Console.ReadKey(true).Key)
{
case ConsoleKey.H:
Console.WriteLine("Commands: \n s: turn on secret mode \n q: Quit \n h: help \n Other settings can be changed in the settings.xml file");
break;
case ConsoleKey.S:
if (Csecret)
{
Csecret = false;
Console.WriteLine("\n Secret Mode turned off!");
rp.State = InitInfo.projectName;
}
else if (!Csecret)
{
Csecret = true;
Console.WriteLine("\n Secret Mode turned on!");
rp.State = settings.SecretMessage;
}
break;
case ConsoleKey.Q:
StopAndExit();
break;
}
}
if (client != null)
client.Invoke();
//Skip update if nothing changes
if (InitInfo.appName == rp.Details && InitInfo.projectName == rp.State && Csecret == Psecret)
continue;
if (InitInfo.projectName == null && rp.State == settings.NoNameMessage && Csecret == Psecret)
continue;
//Fill State and details
if (InitInfo.projectName == null)
{
rp.State = settings.NoNameMessage;
rp.Details = InitInfo.appName;
}
else
{
rp.Details = InitInfo.appName;
rp.State = InitInfo.projectName;
}
if (Csecret)
{
rp.State = settings.SecretMessage;
}
Psecret = Csecret;
client.SetPresence(rp);
Thread.Sleep(settings.RefeshInterval);
}
}
19
Source : RedisConnector.cs
with MIT License
from 2881099
with MIT License
from 2881099
void Reconnect()
{
int attempts = 0;
while (attempts++ < ReconnectAttempts || ReconnectAttempts == -1)
{
if (Connect(-1))
return;
Thread.Sleep(TimeSpan.FromMilliseconds(ReconnectWait));
}
throw new IOException("Could not reconnect after " + attempts + " attempts");
}
19
Source : MainFormHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
private void UpdateTaskRun(Config config)
{
var updateHandle = new UpdateHandle();
while (true)
{
Utils.SaveLog("UpdateTaskRun");
Thread.Sleep(60000);
if (config.autoUpdateInterval <= 0)
{
continue;
}
updateHandle.UpdateGeoFile("geosite", config, (bool success, string msg) =>
{
_updateUI(false, msg);
if (success)
Utils.SaveLog("geosite" + msg);
});
Thread.Sleep(60000);
updateHandle.UpdateGeoFile("geoip", config, (bool success, string msg) =>
{
_updateUI(false, msg);
if (success)
Utils.SaveLog("geoip" + msg);
});
Thread.Sleep(1000 * 3600 * config.autoUpdateInterval);
}
}
19
Source : StatisticsHandler.cs
with GNU General Public License v3.0
from 2dust
with GNU General Public License v3.0
from 2dust
public void Run()
{
while (!exitFlag_)
{
try
{
if (Enable && channel_.State == ChannelState.Ready)
{
QueryStatsResponse res = null;
try
{
res = client_.QueryStats(new QueryStatsRequest() { Pattern = "", Reset = true });
}
catch (Exception ex)
{
//Utils.SaveLog(ex.Message, ex);
}
if (res != null)
{
string itemId = config_.gereplacedemId();
ServerStareplacedem serverStareplacedem = GetServerStareplacedem(itemId);
//TODO: parse output
ParseOutput(res.Stat, out ulong up, out ulong down);
serverStareplacedem.todayUp += up;
serverStareplacedem.todayDown += down;
serverStareplacedem.totalUp += up;
serverStareplacedem.totalDown += down;
if (UpdateUI)
{
updateFunc_(up, down, new List<ServerStareplacedem> { serverStareplacedem });
}
}
}
Thread.Sleep(config_.statisticsFreshRate);
channel_.ConnectAsync();
}
catch (Exception ex)
{
//Utils.SaveLog(ex.Message, ex);
}
}
}
19
Source : Machine.cs
with MIT License
from 3RD-Dimension
with MIT License
from 3RD-Dimension
private void Work()
{
try
{
StreamReader reader = new StreamReader(Connection);
StreamWriter writer = new StreamWriter(Connection);
int StatusPollInterval = Properties.Settings.Default.StatusPollInterval;
int ControllerBufferSize = Properties.Settings.Default.ControllerBufferSize;
BufferState = 0;
TimeSpan WaitTime = TimeSpan.FromMilliseconds(0.5);
DateTime LastStatusPoll = DateTime.Now + TimeSpan.FromSeconds(0.5);
DateTime StartTime = DateTime.Now;
DateTime LastFilePosUpdate = DateTime.Now;
bool filePosChanged = false;
bool SendMacroStatusReceived = false;
writer.Write("\n$G\n");
writer.Write("\n$#\n");
writer.Flush();
while (true)
{
Task<string> lineTask = reader.ReadLineAsync();
while (!lineTask.IsCompleted)
{
if (!Connected)
{
return;
}
while (ToSendPriority.Count > 0)
{
writer.Write((char)ToSendPriority.Dequeue());
writer.Flush();
}
if (Mode == OperatingMode.SendFile)
{
if (File.Count > FilePosition && (File[FilePosition].Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = File[FilePosition].Replace(" ", ""); // don't send whitespace to machine
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
if (PauseLines[FilePosition] && Properties.Settings.Default.PauseFileOnHold)
{
Mode = OperatingMode.Manual;
}
if (++FilePosition >= File.Count)
{
Mode = OperatingMode.Manual;
}
filePosChanged = true;
}
}
else if (Mode == OperatingMode.SendMacro)
{
switch (Status)
{
case "Idle":
if (BufferState == 0 && SendMacroStatusReceived)
{
SendMacroStatusReceived = false;
string send_line = (string)ToSendMacro.Dequeue();
send_line = Calculator.Evaluate(send_line, out bool success);
if (!success)
{
ReportError("Error while evaluating macro!");
ReportError(send_line);
ToSendMacro.Clear();
}
else
{
send_line = send_line.Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
}
break;
case "Run":
case "Hold":
break;
default: // grbl is in some kind of alarm state
ToSendMacro.Clear();
break;
}
if (ToSendMacro.Count == 0)
Mode = OperatingMode.Manual;
}
else if (ToSend.Count > 0 && (((string)ToSend.Peek()).Length + 1) < (ControllerBufferSize - BufferState))
{
string send_line = ((string)ToSend.Dequeue()).Replace(" ", "");
writer.Write(send_line);
writer.Write('\n');
writer.Flush();
RecordLog("> " + send_line);
RaiseEvent(UpdateStatus, send_line);
RaiseEvent(LineSent, send_line);
BufferState += send_line.Length + 1;
Sent.Enqueue(send_line);
}
DateTime Now = DateTime.Now;
if ((Now - LastStatusPoll).TotalMilliseconds > StatusPollInterval)
{
writer.Write('?');
writer.Flush();
LastStatusPoll = Now;
}
//only update file pos every X ms
if (filePosChanged && (Now - LastFilePosUpdate).TotalMilliseconds > 500)
{
RaiseEvent(FilePositionChanged);
LastFilePosUpdate = Now;
filePosChanged = false;
}
Thread.Sleep(WaitTime);
}
string line = lineTask.Result;
RecordLog("< " + line);
if (line == "ok")
{
if (Sent.Count != 0)
{
BufferState -= ((string)Sent.Dequeue()).Length + 1;
}
else
{
MainWindow.Logger.Info("Received OK without anything in the Sent Buffer");
BufferState = 0;
}
}
else
{
if (line.StartsWith("error:"))
{
if (Sent.Count != 0)
{
string errorline = (string)Sent.Dequeue();
RaiseEvent(ReportError, $"{line}: {errorline}");
BufferState -= errorline.Length + 1;
}
else
{
if ((DateTime.Now - StartTime).TotalMilliseconds > 200)
RaiseEvent(ReportError, $"Received <{line}> without anything in the Sent Buffer");
BufferState = 0;
}
Mode = OperatingMode.Manual;
}
else if (line.StartsWith("<"))
{
RaiseEvent(ParseStatus, line);
SendMacroStatusReceived = true;
}
else if (line.StartsWith("[PRB:"))
{
RaiseEvent(ParseProbe, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("["))
{
RaiseEvent(UpdateStatus, line);
RaiseEvent(LineReceived, line);
}
else if (line.StartsWith("ALARM"))
{
RaiseEvent(ReportError, line);
Mode = OperatingMode.Manual;
ToSend.Clear();
ToSendMacro.Clear();
}
else if (line.Length > 0)
RaiseEvent(LineReceived, line);
}
}
}
catch (Exception ex)
{
RaiseEvent(ReportError, $"Fatal Error in Work Loop: {ex.Message}");
RaiseEvent(() => Disconnect());
}
}
19
Source : SdkWrapper.cs
with MIT License
from 8bitbytes
with MIT License
from 8bitbytes
public SdkReponses ExecuteFlightPlan(flightplans.FlightPlan flightPlan)
{
var nonCommandActions = flightPlan.Items.Where(a => a.Action.Type == TelloSdkCoreNet.actions.Action.ActionTypes.Read).ToArray();
if (nonCommandActions.Length > 0)
{
throw new ArgumentException("Flight plans cannot include query actions");
}
foreach (var fpi in flightPlan.Items)
{
var exeCount = fpi.NumberOfTimesToExecute;
while (exeCount > 0)
{
fpi.Action.Client = _udpClient;
if (fpi.Action.Execute() == SdkReponses.FAIL)
{
if(fpi.Action.LastException != null)
{
throw fpi.Action.LastException;
}
return SdkReponses.FAIL;
}
System.Threading.Thread.Sleep((int)fpi.SecondsToWaitBeforeNext * 1000);
exeCount--;
}
}
return SdkReponses.OK;
}
19
Source : SpinWait.cs
with MIT License
from a11s
with MIT License
from a11s
public void SpinOnce()
{
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
}
Thread.Sleep(0);
}
19
Source : SpinWait.cs
with MIT License
from a11s
with MIT License
from a11s
public void SpinOnce()
{
Thread.Sleep(0);
}
19
Source : TestUnlimitedBuffer.cs
with MIT License
from a1q123456
with MIT License
from a1q123456
[TestMethod]
public void TestParalleWriteAndRead()
{
var random = new Random();
var buffer = new ByteBuffer(512, 35767);
var th1 = new Thread(() =>
{
byte i = 0;
while (true)
{
var arr = new byte[new Random().Next(256, 512)];
for (var j = 0; j < arr.Length; j++)
{
arr[j] = i;
i++;
if (i > 100)
{
i = 0;
}
}
buffer.WriteToBuffer(arr);
}
});
th1.IsBackground = true;
th1.Start();
var th2 = new Thread(() =>
{
while (true)
{
var arr = new byte[new Random().Next(129, 136)];
if (buffer.Length >= arr.Length)
{
buffer.TakeOutMemory(arr);
for (int i = 1; i < arr.Length; i++)
{
replacedert.IsTrue(arr[i] - arr[i - 1] == 1 || arr[i - 1] - arr[i] == 100);
}
}
}
});
th2.IsBackground = true;
th2.Start();
Thread.Sleep(TimeSpan.FromSeconds(30));
}
19
Source : EndlessItemsControl.cs
with MIT License
from ABTSoftware
with MIT License
from ABTSoftware
private void AddMoreItems()
{
var isBusy = (bool)GetValue(IsBusyProperty);
if (!isBusy)
{
SetValue(IsBusyProperty, true);
SetValue(IsBusyProperty, false);
SetValue(IsBusyProperty, true);
var delay = (TimeSpan)GetValue(PreLoadingDelayProperty);
Task.Factory.StartNew(() =>
{
Thread.Sleep(delay);
var items = _allItems.Take(10).ToList();
items.ForEach(item =>
{
Dispatcher.BeginInvoke(new Action(() => Currenreplacedems.Add(item)));
_allItems.Remove(item);
});
}).ContinueWith(_ =>
{
Dispatcher.BeginInvoke(new Action(() => SetValue(IsBusyProperty, false)));
});
}
}
19
Source : FileCache.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
public void Clear()
{
//Before we can delete the entire file tree, we have to wait for any latent writes / reads to finish
//To do this, we wait for access to our cacheLock file. When we get access, we have to immediately
//release it (can't delete a file that is open!), which somewhat muddies our condition of needing
//exclusive access to the FileCache. However, the time between closing and making the call to
//delete is so small that we probably won't run into an exception most of the time.
FileStream cacheLock = null;
TimeSpan totalTime = new TimeSpan(0);
TimeSpan interval = new TimeSpan(0, 0, 0, 0, 50);
TimeSpan timeToWait = AccessTimeout;
if (AccessTimeout == new TimeSpan())
{
//if access timeout is not set, make really large wait time
timeToWait = new TimeSpan(5, 0, 0);
}
while (cacheLock == null && timeToWait > totalTime)
{
cacheLock = GetCleaningLock();
Thread.Sleep(interval);
totalTime += interval;
}
if (cacheLock == null)
{
throw new TimeoutException("FileCache AccessTimeout reached when attempting to clear cache.");
}
cacheLock.Close();
//now that we've waited for everything to stop, we can delete the cache directory.
Directory.Delete(CacheDir, true);
}
19
Source : FileCacheManager.cs
with Apache License 2.0
from acarteas
with Apache License 2.0
from acarteas
protected FileStream GetStream(string path, FileMode mode, FileAccess access, FileShare share)
{
FileStream stream = null;
TimeSpan interval = new TimeSpan(0, 0, 0, 0, 50);
TimeSpan totalTime = new TimeSpan();
while (stream == null)
{
try
{
stream = File.Open(path, mode, access, share);
}
catch (IOException ex)
{
Thread.Sleep(interval);
totalTime += interval;
//if we've waited too long, throw the original exception.
if (AccessTimeout.Ticks != 0)
{
if (totalTime > AccessTimeout)
{
throw ex;
}
}
}
}
return stream;
}
19
Source : RunnerService.cs
with MIT License
from actions
with MIT License
from actions
protected override void OnStart(string[] args)
{
RunningLoop = Task.Run(
() =>
{
try
{
bool stopping;
WriteInfo("Starting Actions Runner Service");
TimeSpan timeBetweenRetries = TimeSpan.FromSeconds(5);
lock (ServiceLock)
{
stopping = Stopping;
}
while (!stopping)
{
WriteInfo("Starting Actions Runner listener");
lock (ServiceLock)
{
RunnerListener = CreateRunnerListener();
RunnerListener.OutputDataReceived += RunnerListener_OutputDataReceived;
RunnerListener.ErrorDataReceived += RunnerListener_ErrorDataReceived;
RunnerListener.Start();
RunnerListener.BeginOutputReadLine();
RunnerListener.BeginErrorReadLine();
}
RunnerListener.WaitForExit();
int exitCode = RunnerListener.ExitCode;
// exit code 0 and 1 need stop service
// exit code 2 and 3 need restart runner
switch (exitCode)
{
case 0:
Stopping = true;
WriteInfo(Resource.RunnerExitWithoutError);
break;
case 1:
Stopping = true;
WriteInfo(Resource.RunnerExitWithTerminatedError);
break;
case 2:
WriteInfo(Resource.RunnerExitWithError);
break;
case 3:
WriteInfo(Resource.RunnerUpdateInProcess);
var updateResult = HandleRunnerUpdate();
if (updateResult == RunnerUpdateResult.Succeed)
{
WriteInfo(Resource.RunnerUpdateSucceed);
}
else if (updateResult == RunnerUpdateResult.Failed)
{
WriteInfo(Resource.RunnerUpdateFailed);
Stopping = true;
}
else if (updateResult == RunnerUpdateResult.SucceedNeedRestart)
{
WriteInfo(Resource.RunnerUpdateRestartNeeded);
_restart = true;
ExitCode = int.MaxValue;
Stop();
}
break;
default:
WriteInfo(Resource.RunnerExitWithUndefinedReturnCode);
break;
}
if (Stopping)
{
ExitCode = exitCode;
Stop();
}
else
{
// wait for few seconds before restarting the process
Thread.Sleep(timeBetweenRetries);
}
lock (ServiceLock)
{
RunnerListener.OutputDataReceived -= RunnerListener_OutputDataReceived;
RunnerListener.ErrorDataReceived -= RunnerListener_ErrorDataReceived;
RunnerListener.Dispose();
RunnerListener = null;
stopping = Stopping;
}
}
}
catch (Exception exception)
{
WriteException(exception);
ExitCode = 99;
Stop();
}
});
}
19
Source : MainWindow.xaml.cs
with MIT License
from Actipro
with MIT License
from Actipro
private void OnBackgroundWorkerDoWork(object sender, DoWorkEventArgs e) {
// This example just delays several seconds instead of doing real work
Thread.Sleep(TimeSpan.FromSeconds(3));
}
19
Source : Dependencies.cs
with Apache License 2.0
from adamralph
with Apache License 2.0
from adamralph
[Fact]
public static async Task DependencyOrderWhenParallelAndSkipping()
{
// arrange
var clock = 0;
var (buildStartTime, test1StartTime, test2StartTime) = (0, 0, 0);
var targets = new TargetCollection
{
CreateTarget(
"build",
() =>
{
Thread.Sleep(TimeSpan.FromSeconds(1)); // a weak way to encourage the tests to run first
buildStartTime = Interlocked.Increment(ref clock);
}),
CreateTarget("test1", new[] { "build" }, () => test1StartTime = Interlocked.Increment(ref clock)),
CreateTarget("test2", new[] { "build" }, () => test2StartTime = Interlocked.Increment(ref clock)),
};
// act
await targets.RunAsync(new List<string> { "--parallel", "--skip-dependencies", "test1", "test2", "build" }, _ => false, default, Console.Out, Console.Error, false);
// replacedert
replacedert.Equal(1, buildStartTime);
replacedert.Equal(5, test1StartTime + test2StartTime);
}
19
Source : UpdateManager.cs
with MIT License
from admaiorastudio
with MIT License
from admaiorastudio
public async Task StartAsync()
{
// Kill any previous running processes
KillRunningProcesses();
string serverreplacedemblyPath = Path.Combine(Path.GetDirectoryName(replacedembly.GetExecutingreplacedembly().Location), @"Server\RealXamlServer.dll");
if (File.Exists(serverreplacedemblyPath))
{
ProcessStartInfo psiServer = new ProcessStartInfo("dotnet");
psiServer.Arguments = $"\"{serverreplacedemblyPath}\"";
psiServer.Verb = "runas";
//psiServer.CreateNoWindow = true;
//psiServer.WindowStyle = ProcessWindowStyle.Hidden;
_pServer = Process.Start(psiServer);
System.Threading.Thread.Sleep(1500);
}
if (_pServer == null)
throw new InvalidOperationException("Unable to start RealXaml server.");
if (File.Exists(_processDatFilePath))
File.Delete(_processDatFilePath);
using (var s = File.CreateText(_processDatFilePath))
{
await s.WriteAsync(_pServer.Id.ToString());
}
string ipAddress = NetworkHelper.GetLocalIPAddress();
_hubConnection = new HubConnectionBuilder()
.WithUrl($"http://localhost:5001/hub")
.Build();
await _hubConnection.StartAsync();
if (_hubConnection.State != HubConnectionState.Connected)
{
_hubConnection = null;
throw new InvalidOperationException("Unable to connect.");
}
_hubConnection.On("HelloIde", WhenHelloIde);
_hubConnection.On("ByeIde", WhenByeIde);
_hubConnection.On<string>("ClientRegistered", WhenClientRegistered);
_hubConnection.On<string, byte[]>("XamlReceived", WhenXamlReceived);
_hubConnection.On<string, string>("replacedemblyReceived", WhenreplacedemblyReceived);
_hubConnection.On<string>("PageAppeared", WhenPageAppeared);
_hubConnection.On<string>("PageDisappeared", WhenPageDisappeared);
_hubConnection.On<string>("ExceptionThrown", WhenExceptionThrown);
_hubConnection.On<string>("IdeNotified", WhenIdeNotified);
_ideId = Guid.NewGuid();
await _hubConnection.SendAsync("RegisterIde", _ideId.ToString());
}
19
Source : Program.cs
with Apache License 2.0
from Aguafrommars
with Apache License 2.0
from Aguafrommars
private static async Task<TokenResponse> RequestTokenAsync(DeviceAuthorizationResponse authorizeResponse)
{
var disco = await _cache.GetAsync();
if (disco.IsError) throw new Exception(disco.Error);
var client = new HttpClient();
while (true)
{
var response = await client.RequestDeviceTokenAsync(new DeviceTokenRequest
{
Address = disco.TokenEndpoint,
ClientId = "device",
DeviceCode = authorizeResponse.DeviceCode
});
if (response.IsError)
{
if (response.Error == OidcConstants.TokenErrors.AuthorizationPending || response.Error == OidcConstants.TokenErrors.SlowDown)
{
Console.WriteLine($"{response.Error}...waiting.");
Thread.Sleep(authorizeResponse.Interval * 1000);
}
else
{
throw new Exception(response.Error);
}
}
else
{
return response;
}
}
}
19
Source : Program.cs
with MIT License
from Airkek
with MIT License
from Airkek
private static void proxyUpdater()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
int sec = 600;
while (true)
{
if (stopwatch.ElapsedMilliseconds / 1000 >= sec)
{
string proxies = String.Empty;
foreach(string proxyUrl in Urls)
{
using (HttpRequest req = new HttpRequest())
{
try
{
proxies += req.Get(proxyUrl).ToString() + "\r\n";
}
catch
{
}
}
}
scraper.SafeUpdate(proxies);
sec += 600;
}
Thread.Sleep(1000);
}
}
19
Source : Program.cs
with MIT License
from Airkek
with MIT License
from Airkek
static void Worker()
{
while (true)
{
try
{
using (var req = new HttpRequest()
{
Proxy = scraper.Next(),
Cookies = new CookieStorage()
})
{
req.UserAgentRandomize();
req.Cookies.Container.Add(new Uri("https://www.youtube.com"), new Cookie("CONSENT", "YES+cb.20210629-13-p0.en+FX+407"));
var sres = req.Get($"https://www.youtube.com/watch?v={id}").ToString();
var viewersTemp = string.Join("", RegularExpressions.Viewers.Match(sres).Groups[1].Value.Where(char.IsDigit));
if (!string.IsNullOrEmpty(viewersTemp))
viewers = viewersTemp;
replacedle = RegularExpressions.replacedle.Match(sres).Groups[1].Value;
var url = RegularExpressions.ViewUrl.Match(sres).Groups[1].Value;
url = url.Replace(@"\u0026", "&").Replace("%2C", ",").Replace(@"\/", "/");
var query = System.Web.HttpUtility.ParseQueryString(url);
var cl = query.Get(query.AllKeys[0]);
var ei = query.Get("ei");
var of = query.Get("of");
var vm = query.Get("vm");
var cpn = GetCPN();
var start = DateTime.UtcNow;
var st = random.Next(1000, 10000);
var et = GetCmt(start);
var lio = GetLio(start);
var rt = random.Next(10, 200);
var lact = random.Next(1000, 8000);
var rtn = rt + 300;
var args = new Dictionary<string, string>
{
["ns"] = "yt",
["el"] = "detailpage",
["cpn"] = cpn,
["docid"] = id,
["ver"] = "2",
["cmt"] = et.ToString(),
["ei"] = ei,
["fmt"] = "243",
["fs"] = "0",
["rt"] = rt.ToString(),
["of"] = of,
["euri"] = "",
["lact"] = lact.ToString(),
["live"] = "dvr",
["cl"] = cl,
["state"] = "playing",
["vm"] = vm,
["volume"] = "100",
["cbr"] = "Firefox",
["cbrver"] = "83.0",
["c"] = "WEB",
["cplayer"] = "UNIPLAYER",
["cver"] = "2.20201210.01.00",
["cos"] = "Windows",
["cosver"] = "10.0",
["cplatform"] = "DESKTOP",
["delay"] = "5",
["hl"] = "en_US",
["rtn"] = rtn.ToString(),
["aftm"] = "140",
["rti"] = rt.ToString(),
["muted"] = "0",
["st"] = st.ToString(),
["et"] = et.ToString(),
["lio"] = lio.ToString()
};
string urlToGet = buildUrl(args);
req.AcceptEncoding ="gzip, deflate";
req.AddHeader("Host", "www.youtube.com");
req.Get(urlToGet.Replace("watchtime", "playback"));
req.AcceptEncoding ="gzip, deflate";
req.AddHeader("Host", "www.youtube.com");
req.Get(urlToGet);
Interlocked.Increment(ref botted);
}
}
catch
{
Interlocked.Increment(ref errors);
}
Thread.Sleep(1);
}
}
19
Source : Program.cs
with MIT License
from Airkek
with MIT License
from Airkek
static void Log()
{
while (true)
{
Console.SetCursorPosition(0, pos);
Console.WriteLine($"\r\nBotted: {botted}\r\nErrors: {errors}\r\nProxies: {scraper.Length} \r\nThreads: {threadsCount}\r\nreplacedle: {replacedle} \r\nViewers: {viewers} \r\n");
Thread.Sleep(250);
}
}
19
Source : DelayAction.cs
with MIT License
from AkiniKites
with MIT License
from AkiniKites
public void Start(TimeSpan time)
{
lock (_lock)
{
if (!_running)
_running = true;
else
return;
}
Task.Run(() =>
{
Thread.Sleep(time);
lock (_lock)
{
if (_running)
_action();
_running = false;
}
});
}
19
Source : ConnectionCheckerSpec.cs
with Apache License 2.0
from akkadotnet
with Apache License 2.0
from akkadotnet
[Fact(DisplayName = "KafkaConnectionChecker must wait for response and retryInterval before perform new ask")]
public void WaitForResponseBeforeAsking()
{
WithCheckerActorRef(checker =>
{
ExpectListTopicsRequest(_retryInterval);
Thread.Sleep(_retryInterval);
checker.Tell(new Metadata.Topics(new Try<List<TopicMetadata>>(new List<TopicMetadata>())));
ExpectListTopicsRequest(_retryInterval);
});
}
19
Source : Fisher.cs
with Apache License 2.0
from AlexWan
with Apache License 2.0
from AlexWan
private void Logic()
{
while(true)
{
Thread.Sleep(TimeRebuildOrder.ValueInt * 1000);
if (_isDisposed)
{
return;
}
if (Regime.ValueString == "Off")
{
continue;
}
if (_sma.DataSeries[0].Values == null ||
_sma.ParametersDigit[0].Value + 3 > _sma.DataSeries[0].Values.Count)
{
continue;
}
CanselAllOrders();
CloseAllPositions();
OpenOrders();
}
}
19
Source : WaitConditionsBase.cs
with MIT License
from alfa-laboratory
with MIT License
from alfa-laboratory
protected bool WaitFor(Func<bool> test, string exceptionMessage = "Waiting for Text to change.")
{
var stopwatch = new Stopwatch();
stopwatch.Start();
if (test()) return true;
while (stopwatch.ElapsedMilliseconds <= _waitMs)
{
if (test()) return true;
Thread.Sleep(_interval);
}
throw new WebDriverTimeoutException(exceptionMessage);
}
19
Source : RedisCacheTests.cs
with MIT License
from AliBazzi
with MIT License
from AliBazzi
[Fact]
public async Task GetAsync_Does_Not_Return_Expired_Entries()
{
string key = nameof(GetAsync_Does_Not_Return_Expired_Entries);
string expected = "test_value";
await _cache.SetAsync(key, expected, TimeSpan.FromSeconds(2));
var actual = await _cache.GetAsync(key);
replacedert.Equal(expected, actual);
Thread.Sleep(TimeSpan.FromSeconds(2.1));
actual = await _cache.GetAsync(key);
replacedert.Null(actual);
}
19
Source : PersistedGrantStoreTests.cs
with MIT License
from AliBazzi
with MIT License
from AliBazzi
[Fact]
public async Task GetAsync_Does_Not_Return_Expired_Entries()
{
var now = DateTime.Now;
_clock.Setup(x => x.UtcNow).Returns(now);
string key = $"{nameof(GetAsync_Does_Not_Return_Expired_Entries)}-{now:O}";
string expected = "this is a test";
var grant = new PersistedGrant { Key = key, Data = expected, ClientId = "client1", SubjectId = "sub1", Type = "type1", Expiration = now.AddSeconds(1) };
await _store.StoreAsync(grant);
var actual = await _store.GetAsync(key);
replacedert.Equal(expected, actual.Data);
Thread.Sleep(TimeSpan.FromSeconds(2));
actual = await _store.GetAsync(key);
replacedert.Null(actual);
}
19
Source : Peer.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void Upload()
{
TimeSpan timeout = TimeSpan.FromMilliseconds(250);
Piece piece = null;
RequestMessage rm;
if (!this.isUploading)
{
this.isUploading = true;
while (!this.IsDisposed)
{
foreach (PeerMessage message in this.DequeueUploadMessages())
{
if (message is RequestMessage)
{
rm = message as RequestMessage;
if (piece == null ||
piece.PieceIndex != rm.PieceIndex)
{
// get the piece
piece = this.pieceManager.GetPiece(rm.PieceIndex);
}
if (piece != null &&
piece.PieceLength > rm.BlockOffset)
{
// return the piece
this.EnqueueSendMessage(new PieceMessage(rm.PieceIndex, rm.BlockOffset, (int)piece.GetBlockLength(rm.PieceIndex), piece.GetBlock(rm.PieceIndex)));
}
else
{
// invalid requeste received -> ignore
}
}
else if (message is CancelMessage)
{
// TODO
}
else if (message is InterestedMessage)
{
this.LeechingState = LeechingState.Interested;
}
else if (message is UninterestedMessage)
{
this.LeechingState = LeechingState.Uninterested;
}
}
Thread.Sleep(timeout);
}
this.isUploading = false;
}
}
19
Source : Peer.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void Download()
{
TimeSpan timeout = TimeSpan.FromMilliseconds(250);
TimeSpan chokeTimeout = TimeSpan.FromSeconds(10);
Stopwatch stopwatch = Stopwatch.StartNew();
PieceMessage pm;
Piece piece = null;
bool[] bitFieldData = Array.Empty<bool>();
byte[] pieceData = Array.Empty<byte>();
int unchokeMessagesSent = 0;
if (!this.isDownloading)
{
this.isDownloading = true;
this.communicator.PieceData = new byte[this.pieceManager.PieceLength];
while (!this.IsDisposed)
{
if (this.pieceManager.IsComplete)
{
break;
}
// process messages
foreach (PeerMessage message in this.DequeueDownloadMessages())
{
if (message is PieceMessage)
{
pm = message as PieceMessage;
if (piece != null &&
piece.PieceIndex == pm.PieceIndex &&
piece.BitField[pm.BlockOffset / this.pieceManager.BlockLength] == false)
{
// update piece
piece.PutBlock(pm.BlockOffset);
if (piece.IsCompleted ||
piece.IsCorrupted)
{
// remove piece in order to start a next one
piece = null;
}
}
}
else if (message is ChokeMessage)
{
this.SeedingState = SeedingState.Choked;
piece = null;
}
else if (message is UnchokeMessage)
{
this.SeedingState = SeedingState.Unchoked;
unchokeMessagesSent = 0;
}
}
if (this.HandshakeState == HandshakeState.SendAndReceived)
{
if (this.SeedingState == SeedingState.Choked)
{
if (stopwatch.Elapsed > chokeTimeout)
{
// choked -> send interested
this.EnqueueSendMessage(new InterestedMessage());
if (++unchokeMessagesSent > 10)
{
this.OnCommunicationErrorOccurred(this, new PeerCommunicationErrorEventArgs($"Choked for more than {TimeSpan.FromSeconds(chokeTimeout.TotalSeconds * 10)}.", true));
}
stopwatch.Restart();
}
else
{
Thread.Sleep(timeout);
}
}
else if (this.SeedingState == SeedingState.Unchoked)
{
if (piece == null)
{
// find a missing piece
for (int pieceIndex = 0; pieceIndex < this.BitField.Length; pieceIndex++)
{
if (this.pieceManager.BitField[pieceIndex] == PieceStatus.Missing)
{
if (this.BitField[pieceIndex] ||
this.pieceManager.IsEndGame)
{
pieceData = pieceData.Length == this.pieceManager.GetPieceLength(pieceIndex) ? pieceData : new byte[this.pieceManager.GetPieceLength(pieceIndex)];
bitFieldData = bitFieldData.Length == this.pieceManager.GetBlockCount(pieceIndex) ? bitFieldData : new bool[this.pieceManager.GetBlockCount(pieceIndex)];
// check it out
piece = this.pieceManager.CheckOut(pieceIndex, pieceData, bitFieldData);
if (piece != null)
{
this.communicator.PieceData = pieceData;
break;
}
}
}
}
if (piece != null)
{
// request blocks from the missing piece
for (int i = 0; i < piece.BitField.Length; i++)
{
if (!piece.BitField[i])
{
this.EnqueueSendMessage(new RequestMessage(piece.PieceIndex, (int)piece.GetBlockOffset(i), (int)piece.GetBlockLength(piece.GetBlockOffset(i))));
}
}
}
}
}
}
Thread.Sleep(timeout);
}
this.isDownloading = false;
}
}
19
Source : Peer.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void KeepAlive()
{
TimeSpan keepAliveTimeout = TimeSpan.FromSeconds(60);
TimeSpan timeout = TimeSpan.FromSeconds(10);
if (!this.isKeepingAlive)
{
this.isKeepingAlive = true;
while (!this.IsDisposed)
{
if (!this.isDownloading &&
!this.isUploading)
{
break;
}
else if (this.lastMessageSentTime == null &&
this.lastMessageReceivedTime == null)
{
Thread.Sleep(timeout);
}
else if (DateTime.UtcNow - this.lastMessageSentTime > keepAliveTimeout ||
DateTime.UtcNow - this.lastMessageReceivedTime > keepAliveTimeout)
{
this.OnCommunicationErrorOccurred(this, new PeerCommunicationErrorEventArgs($"No message exchanged in over {keepAliveTimeout}.", true));
break;
}
else
{
Thread.Sleep(timeout);
}
}
this.isKeepingAlive = false;
}
}
19
Source : Peer.cs
with MIT License
from aljazsim
with MIT License
from aljazsim
private void Send()
{
TimeSpan timeout = TimeSpan.FromMilliseconds(250);
IEnumerable<PeerMessage> messages;
while (!this.IsDisposed)
{
messages = this.DequeueSendMessages();
if (messages.Count() > 0)
{
if (this.communicator != null &&
!this.communicator.IsDisposed)
{
foreach (var message in messages)
{
Debug.WriteLine($"{this.Endpoint} -> {message}");
}
// send message
this.communicator.Send(messages);
this.UpdateTrafficParameters(0, messages.Sum(x => x.Length));
}
}
this.lastMessageSentTime = DateTime.UtcNow;
Thread.Sleep(timeout);
}
}
19
Source : DefaultRedisProvider.cs
with MIT License
from AlphaYu
with MIT License
from AlphaYu
protected override CacheValue<T> BaseGet<T>(string cacheKey, Func<T> dataRetriever, TimeSpan expiration)
{
ArgumentCheck.NotNullOrWhiteSpace(cacheKey, nameof(cacheKey));
ArgumentCheck.NotNegativeOrZero(expiration, nameof(expiration));
if (!_cacheOptions.PenetrationSetting.Disable)
{
var exists = _redisDb.BloomExistsAsync(_cacheOptions.PenetrationSetting.BloomFilterSetting.Name, cacheKey).GetAwaiter().GetResult();
if (!exists)
{
if (_cacheOptions.EnableLogging)
_logger?.LogInformation($"Cache Penetrated : cachekey = {cacheKey}");
return CacheValue<T>.NoValue;
}
}
var result = _redisDb.StringGet(cacheKey);
if (!result.IsNull)
{
_cacheStats.OnHit();
if (_cacheOptions.EnableLogging)
_logger?.LogInformation($"Cache Hit : cachekey = {cacheKey}");
var value = _serializer.Deserialize<T>(result);
return new CacheValue<T>(value, true);
}
_cacheStats.OnMiss();
if (_cacheOptions.EnableLogging)
_logger?.LogInformation($"Cache Missed : cachekey = {cacheKey}");
var flag = _redisDb.Lock(cacheKey, _cacheOptions.LockMs / 1000);
if (!flag.Success)
{
System.Threading.Thread.Sleep(_cacheOptions.SleepMs);
return Get(cacheKey, dataRetriever, expiration);
}
try
{
var item = dataRetriever();
if (item != null)
{
Set(cacheKey, item, expiration);
return new CacheValue<T>(item, true);
}
else
{
return CacheValue<T>.NoValue;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
finally
{
//remove mutex key
_redisDb.SafedUnLock(cacheKey, flag.LockValue);
}
}
19
Source : EndToEndTests.cs
with BSD 3-Clause "New" or "Revised" License
from Altinn
with BSD 3-Clause "New" or "Revised" License
from Altinn
[Fact]
public async void ComplexProcessApp()
{
// Arrange
org = "tdd";
app = "complex-process";
instanceOwnerId = 1000;
string token = PrincipalUtil.GetToken(1);
HttpClient client = GetTestClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
#region Start Process
// Arrange
Instance template = new Instance
{
InstanceOwner = new InstanceOwner { PartyId = instanceOwnerId.ToString() }
};
string expectedCurrentTaskName = "Task_1";
// Act
string url = $"/{org}/{app}/instances/";
HttpResponseMessage response = await client.PostAsync(
url,
new StringContent(template.ToString(), Encoding.UTF8, "application/json"));
// replacedert
response.EnsureSuccessStatusCode();
Instance createdInstance =
JsonConvert.DeserializeObject<Instance>(await response.Content.ReadreplacedtringAsync());
instanceGuid = createdInstance.Id.Split('/')[1];
string dataGuid = createdInstance.Data.Where(d => d.DataType.Equals("default")).Select(d => d.Id).First();
replacedert.Equal(expectedCurrentTaskName, createdInstance.Process.CurrentTask.ElementId);
#endregion
#region Upload invalid attachment type
// Act
url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/data?dataType=invalidDataType";
response = await client.PostAsync(url, null);
// replacedert
replacedert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
#endregion
#region Move process to next step
// Arrange
string expectedNextTask = "Task_2";
url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/process/next";
// Act
response = await client.GetAsync(url);
List<string> nextTasks =
JsonConvert.DeserializeObject<List<string>>(await response.Content.ReadreplacedtringAsync());
string actualNextTask = nextTasks[0];
// replacedert
replacedert.Equal(expectedNextTask, actualNextTask);
// Act
response = await client.PutAsync(url, null);
// replacedert
response.EnsureSuccessStatusCode();
#endregion
#region Upload form data during Task_2
// Arrange
url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/data/{dataGuid}";
// Act
response = await client.PutAsync(url, null);
// replacedert: Upload for data during step 2
replacedert.Equal(HttpStatusCode.Forbidden, response.StatusCode);
#endregion
#region Validate Task_2 before valid time
// Arrange
url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/validate";
// Act
response = await client.GetAsync(url);
string responseContent = await response.Content.ReadreplacedtringAsync();
List<ValidationIssue> messages =
(List<ValidationIssue>)JsonConvert.DeserializeObject(responseContent, typeof(List<ValidationIssue>));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Single(messages);
replacedert.Equal(ValidationIssueSeverity.Error, messages[0].Severity);
#endregion
#region Validate Task_2 after valid time
// Arrange
url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/validate";
// Act
Thread.Sleep(new TimeSpan(0, 0, 12));
response = await client.GetAsync(url);
responseContent = await response.Content.ReadreplacedtringAsync();
messages = (List<ValidationIssue>)JsonConvert.DeserializeObject(
responseContent,
typeof(List<ValidationIssue>));
replacedert.Equal(HttpStatusCode.OK, response.StatusCode);
replacedert.Empty(messages);
#endregion
#region Complete process
// Arrange
url = $"/{org}/{app}/instances/{instanceOwnerId}/{instanceGuid}/process/completeProcess";
// Act
response = await client.PutAsync(url, null);
ProcessState endProcess =
JsonConvert.DeserializeObject<ProcessState>(await response.Content.ReadreplacedtringAsync());
// replacedert
response.EnsureSuccessStatusCode();
replacedert.NotNull(endProcess);
#endregion
}
19
Source : FollowingStrategy.cs
with MIT License
from altskop
with MIT License
from altskop
public void run()
{
while (new Random().NextDouble() < confidence)
{
var targetPos = map.gamePosToMeshPos(targetPlayer.position);
var distance = Vector2.Distance(navigator.botPos, targetPos);
if (distance > 15)
{
// follow them
navigator.followPlayer(targetPos);
confidence -= 0.005;
found = true;
}
else
{
// stand still
System.Threading.Thread.Sleep(300);
confidence -= 0.005;
found = true;
}
/*
else
{
// search for them
if (points.Count == 0)
{
points.AddRange(map.places);
}
var nextPoint = getClosestPoint(points);
navigator.followPlayer(new Vector2(nextPoint.x, nextPoint.y));
distance = Vector2.Distance(navigator.botPos, targetPos);
if (Vector2.Distance(navigator.botPos, new Vector2(nextPoint.x, nextPoint.y)) < 15)
{
points.Remove(nextPoint);
}
if (distance < 20)
{
found = true;
}
if (found)
{
confidence -= 0.005;
}
confidence -= 0.0003;
}
*/
}
}
19
Source : PanicStrategy.cs
with MIT License
from altskop
with MIT License
from altskop
public void run()
{
while (Vector2.Distance(navigator.botPos, new Vector2(625, 145)) > 10)
navigator.setDestination(new Vector2(625, 145));
var taskInput = new TaskInput();
taskInput.pressE();
System.Threading.Thread.Sleep(500);
taskInput.mouseClick(new Vector2(960, 540));
}
19
Source : TaskDoingStrategy.cs
with MIT License
from altskop
with MIT License
from altskop
private void doTask()
{
System.Threading.Thread.Sleep(500);
taskPositions = new TaskManager().getTaskPositions();
var task = getClosestTask(taskPositions);
if (task != null)
{
//Console.WriteLine($"{task.position.x},{task.position.y}");
navigator.setDestination(task.position);
currentTaskIdentifier = new TaskIdentifier();
currentTaskIdentifier.doTask();
System.Threading.Thread.Sleep(500);
doneTasks.Add(task);
}
confidence -= 0.1;
}
19
Source : GasSolver.cs
with MIT License
from altskop
with MIT License
from altskop
public void Solve(DirectBitmap screen)
{
TaskInput taskInput = new TaskInput();
taskInput.mouseDown(new Vector2(1459, 880));
System.Threading.Thread.Sleep(6500);
taskInput.releaseMouse();
}
19
Source : SimonSaysSolver.cs
with MIT License
from altskop
with MIT License
from altskop
public void Solve(DirectBitmap screen)
{
TaskInput taskInput = new TaskInput();
// first reset the state
foreach (KeyValuePair<Vector2, Vector2> entry in buttonLocations)
{
taskInput.mouseClick(entry.Value);
System.Threading.Thread.Sleep(20);
}
System.Threading.Thread.Sleep(460);
for (int i=0; i<5; i++)
{
List<Vector2> buttons = new List<Vector2>();
while (buttons.Count < i+1)
{
if (varAbort) return;
Vector2 button = Vector2.Zero;
while (button.x == 0)
{
screen = GameCapture.getGameScreen(new System.Drawing.Rectangle(357, 196, 599, 676));
button = indicatedButton(screen);
}
buttons.Add(button);
Vector2 emptyScreen = button;
while (emptyScreen.x != 0)
{
screen = GameCapture.getGameScreen(new System.Drawing.Rectangle(357, 196, 599, 676));
emptyScreen = indicatedButton(screen);
}
}
System.Threading.Thread.Sleep(50);
foreach (var button in buttons)
{
System.Threading.Thread.Sleep(20);
taskInput.mouseClick(button);
}
}
}
19
Source : TaskIdentifier.cs
with MIT License
from altskop
with MIT License
from altskop
public void doTask()
{
new TaskInput().pressE();
System.Threading.Thread.Sleep(600);
screen = GameCapture.getGameScreenAsImage();
taskSolver = getTaskSolver();
if (taskSolver != null)
{
taskSolver.Solve(GameCapture.getGameScreen());
}
screen.Dispose();
System.Threading.Thread.Sleep(500);
}
19
Source : TrashSolver.cs
with MIT License
from altskop
with MIT License
from altskop
public void Solve(DirectBitmap screen)
{
TaskInput taskInput = new TaskInput();
taskInput.dragMouseNoRelease(new Vector2(1255, 417), new Vector2(1255, 673));
System.Threading.Thread.Sleep(2000);
taskInput.releaseMouse();
}
19
Source : BehaviorDriver.cs
with MIT License
from altskop
with MIT License
from altskop
public void run()
{
while (gameDataContainer == null)
{
System.Threading.Thread.Sleep(1500);
}
while (gameDataContainer.players.Count == 0)
{
System.Threading.Thread.Sleep(1500);
}
System.Threading.Thread.Sleep(8000);
inEmergencyMeeting = false;
talked = false;
roundMemory.generatePlayerSightings(gameDataContainer.players);
while (true)
{
while (!inEmergencyMeeting && !botInfo.isDead)
{
talked = false;
currentStrategy = selectStrategy();
currentStrategy.run();
roundMemory.addNewStrategy(currentStrategy);
if (currentStrategy is TaskDoingStrategy)
{
TaskDoingStrategy taskDoingStrategy = (TaskDoingStrategy)currentStrategy;
roundMemory.addTasks(taskDoingStrategy.doneTasks);
remainingTasks = taskDoingStrategy.taskPositions.Count;
}
else if (currentStrategy is TaskFakingStrategy)
{
TaskFakingStrategy taskDoingStrategy = (TaskFakingStrategy)currentStrategy;
roundMemory.addTasks(taskDoingStrategy.doneTasks);
remainingTasks = taskDoingStrategy.taskPositions.Count;
}
}
while (!inEmergencyMeeting && botInfo.isDead && !botInfo.isImposter && remainingTasks > 0)
{
var taskDoingStrategy = new TaskDoingStrategy(navigator, map);
taskDoingStrategy.run();
remainingTasks = taskDoingStrategy.taskPositions.Count;
}
while (inEmergencyMeeting && !botInfo.isDead)
{
if (!talked)
{
new MeetingTalker(botInfo, gameDataContainer).tellTheMemory(roundMemory, reportedBody, map);
talked = true;
roundMemory.refresh();
this.navigator = new Navigator(map);
new VotingDriver().vote(this.gameDataContainer.getLivingPlayers().Count);
}
System.Threading.Thread.Sleep(500);
}
while (inEmergencyMeeting && botInfo.isDead)
{
System.Threading.Thread.Sleep(500);
roundMemory.refresh();
}
while (botInfo.isDead && botInfo.isImposter)
{
System.Threading.Thread.Sleep(500);
}
while (botInfo.isDead && remainingTasks == 0)
{
System.Threading.Thread.Sleep(500);
}
}
}
19
Source : TaskInput.cs
with MIT License
from altskop
with MIT License
from altskop
public void pressQ()
{
inputSimulator.Keyboard.KeyPress(VirtualKeyCode.VK_Q);
System.Threading.Thread.Sleep(50);
}
19
Source : TaskInput.cs
with MIT License
from altskop
with MIT License
from altskop
public void dragMouse(Vector2 position, Vector2 destination)
{
moveMouse(position);
System.Threading.Thread.Sleep(20);
inputSimulator.Mouse.LeftButtonDown();
System.Threading.Thread.Sleep(20);
moveMouse(destination);
System.Threading.Thread.Sleep(20);
inputSimulator.Mouse.LeftButtonUp();
System.Threading.Thread.Sleep(20);
}
19
Source : TaskInput.cs
with MIT License
from altskop
with MIT License
from altskop
public void dragMouseNoRelease(Vector2 position, Vector2 destination)
{
moveMouse(position);
System.Threading.Thread.Sleep(20);
inputSimulator.Mouse.LeftButtonDown();
System.Threading.Thread.Sleep(20);
moveMouse(destination);
System.Threading.Thread.Sleep(20);
}
19
Source : VotingDriver.cs
with MIT License
from altskop
with MIT License
from altskop
public void vote(int livingPlayers)
{
System.Threading.Thread.Sleep(30000);
List<VotingVector> options = votingButtons.GetRange(0, livingPlayers+1);
int randomIndex = new Random().Next(options.Count);
VotingVector randomChoice = options[randomIndex];
var taskInput = new TaskInput();
taskInput.mouseClick(randomChoice.initialButton);
System.Threading.Thread.Sleep(500);
taskInput.mouseClick(randomChoice.confirmButton);
}
19
Source : Cheese.cs
with MIT License
from altskop
with MIT License
from altskop
static void _ObserveShipStatus()
{
while (Tokens.ContainsKey("ObserveShipStatus") && Tokens["ObserveShipStatus"].IsCancellationRequested == false)
{
Thread.Sleep(250);
shipStatus = Cheese.GetShipStatus();
if (prevShipStatus.OwnerId != shipStatus.OwnerId)
{
prevShipStatus = shipStatus;
onChangeShipStatus?.Invoke(shipStatus.Type);
Console.WriteLine("OnShipStatusChanged");
}
else
{
}
}
}
19
Source : PlayerData.cs
with MIT License
from altskop
with MIT License
from altskop
public void StartObserveState()
{
if(Tokens.ContainsKey("ObserveState"))
{
Console.WriteLine("Already Observed!");
return;
}
else
{
CancellationTokenSource cts = new CancellationTokenSource();
Task.Factory.StartNew(() =>
{
while (true)
{
if (PlayerInfo.HasValue)
{
if (observe_dieFlag == false && PlayerInfo.Value.IsDead == 1)
{
observe_dieFlag = true;
onDie?.Invoke(Position, PlayerInfo.Value.ColorId);
}
}
System.Threading.Thread.Sleep(25);
}
}, cts.Token);
Tokens.Add("ObserveState", cts);
}
}
19
Source : Program.cs
with MIT License
from altskop
with MIT License
from altskop
static void Main(string[] args)
{
if(args.Length != 0)
{
Console.WriteLine(args[0]);
HamsterCheese.StructGenerator.Generator.Generate(args[0], args[1]);
return;
}
Console.WriteLine(args[0]);
HamsterCheese.StructGenerator.Generator.Generate(@"C:\Users\shlif\OneDrive\Doreplacedents\GitHub\AmongUsMemory\AmongUsMemory\XmlStructs", null);
System.Threading.Thread.Sleep(99999);
}
19
Source : TaskFakingStrategy.cs
with MIT License
from altskop
with MIT License
from altskop
private void doTask()
{
var task = getClosestTask(taskPositions);
navigator.setDestination(task.position);
System.Threading.Thread.Sleep(task.fakeTime+500);
doneTasks.Add(task);
confidence -= 0.25;
}
19
Source : InspectSampleSolver.cs
with MIT License
from altskop
with MIT License
from altskop
public void Solve(DirectBitmap screen)
{
TaskInput taskInput = new TaskInput();
taskInput.mouseClick(new Vector2(1261, 936));
System.Threading.Thread.Sleep(300);
taskInput.closeTask();
}
See More Examples