/// <summary> создается поле, и забиваются расположения стен и всего остального /// </summary> internal Radar(Mind mind,IAPI api) { map = new Map (api.getMinX(),api.getMinY(), api.getMaxX()+1,api.getMaxY()+1); // создается поле для сканирования this.mind = mind; // добавляются ссылки для обратного вызова this.api = api; recycleSectors = new Queue<MapSector>(); ICoordinates xy = StepsAndCoord.Coordinates ( api.getMinX (),api.getMinY () ); for (int i = api.getMinX (); i <= api.getMaxX (); i++) { // проход по карте построчно for (int j = api.getMinY (); j <= api.getMaxY (); j++) { StepsAndCoord.otherPositionOfThis ( xy,i,j ); if (api.isNorm(xy)) { map[i, j] = new MapSector(); if (api.getTypeOfField(xy) == TypesOfField.WALL) { map[i, j].type = TypesOfField.WALL; map[i,j].xy = StepsAndCoord.Coordinates ( i,j ); } else { map[i,j].xy = StepsAndCoord.Coordinates ( i,j ); map[i,j].type = api.getTypeOfField ( xy ); } } } } xFunct (); }
/// <summary>/// Конструктор /// </summary> internal Radar(Mind mind,IAPI api) { map = new MapSector[api.getMaxX()+1,api.getMaxY()+1]; // создается поле для сканирования map.Initialize (); this.mind = mind; this.api = api; recycleSectors = new Queue<MapSector>(); ICoordinates xy = Helper.Coordinates ( api.getMinX (),api.getMinY () ); for (int i = api.getMinX (); i <= api.getMaxX (); i++) { for (int j = api.getMinY (); j <= api.getMaxY (); j++) { Helper.otherPositionOfThis ( xy,i,j ); if (api.isNorm(xy)) { map[i, j] = new MapSector(xy, xy, 0); if (api.getTypeOfField(xy) == TypesOfField.WALL) { map[i, j].type = TypesOfField.WALL; } else { map[i, j].type = TypesOfField.NOTHING; } } } } }
//Guess public static bool Guess(IAPI api) { AssertAPINotNull(ref api); do { Console.Write($"{api.GetLeftGuesses()} Gs left. Guess between {api.GetMax()} and {api.GetMin()}: "); try { if (TryAskInt(out int guess)) { if (api.Guess(guess)) { return(true); } break; } } catch (PropertyNotSetException) { Console.WriteLine("'Correct' or 'Allowed Guesses' has not been set"); } catch (ArgumentOutOfRangeException) { Console.WriteLine("Your guess was outside of Max and Min range"); } } while (true); return(false); }
public threadMsg(IAPI api, EventHandler <threadMsgEventArgs> on_message = null) { onMessageComplete = on_message; _api = api; _resetEvent = new ManualResetEvent(false); _threadEvent = new ManualResetEvent(false); _thread = new Thread(new ParameterizedThreadStart(delegate(object evt) { api.Init(); api.Open = true; app.postToAPI(_API.MEDIA, _API.MEDIA_KEY_INITED, null); threadMsgPara tm = (threadMsgPara)evt; while (_exit == false) { tm.ResetEvent.WaitOne(); if (_exit) { break; } else { msg m = api.Execute(_msg); //if (onMessageComplete != null) onMessageComplete.Invoke(this, new threadMsgEventArgs(m)); } tm.ResetEvent.Reset(); } })); _thread.Start(new threadMsgPara(_resetEvent)); }
private static void AssertAPINotNull(ref IAPI api) { if (api == null) { throw new ArgumentNullException(nameof(api)); } }
public Manager() { InitializeComponent(); cbTargetProtocol.SelectedItem = 0; Utils.EnableDisablePanel(spltCtrlArchive.Panel2, false); var clientChannel = new IpcChannel(); ChannelServices.RegisterChannel(clientChannel, true); //- Setup the legal Utils.SetupRtfBox(rtbLicence, "license.rtf"); _serverLink = (IAPI)Activator.GetObject(typeof(IAPI), "ipc://localhost:19888/API"); try { ReloadJobList(); } catch (RemotingException) { MessageBox.Show(this, "Unable to communicate with the CloudBackup service. Please check that the service is running, close this window and try again", "Unable to access service", MessageBoxButtons.OK); btnNewArchive.Enabled = false; } }
/** * 构建请求URL * */ private string BuildUrl(IAPI api, IAuth auth) { string url = null; if (auth == null) { throw new ArgumentNullException(nameof(auth)); } var method = api.GetHttpMethod(); var gatway = api.GetGateway(); var apiName = api.GetName(); var version = api.GetVersion(); IApiParams apiParams = api.GetAPIParams(); IDictionary <string, string> requestParams = apiParams.ToParams(); IDictionary <string, string> header = api.GetHeaders(); if (auth is Token) { var authToken = auth as Token; url = String.Format("{0}{1}{2}/{3}{4}{5}", gatway, "/api/", apiName, version, "?access_token=", authToken.GetToken()); } if (auth is Direct) { var authToken = auth as Direct; url = String.Format("{0}{1}{2}{3}/{4}", gatway, "/api/", "auth_exempt/", apiName, version); } return(url); }
static MP() { var mpAssembly = LoadedModManager.RunningMods .SelectMany(m => m.assemblies.loadedAssemblies) .FirstOrDefault(a => a.GetName().Name == "Multiplayer"); if (mpAssembly == null) { Sync = new Dummy(); return; } // This can fail in older MP versions halting mod loading try { Sync = (IAPI)mpAssembly .GetType("Multiplayer.Common.MultiplayerAPIBridge") .GetField("Instance") .GetValue(null); enabled = true; } catch (Exception e) { Log.Error("Multiplayer mod detected but it has no MPAPI Bridge\n\n" + e); } }
private T GetResponse <T>(IAPI api, IAuth auth, IDictionary <string, string> headers, List <KeyValuePair <string, string> > files) where T : YouZanResponse { var result = _YouZanClient.Invoke(api, auth, headers, files); return(JsonConvert.DeserializeObject <T>(result)); }
string IYouZanClient.Invoke(IAPI api, IAuth auth, IDictionary <string, string> headers, List <KeyValuePair <string, string> > files, bool isRichText = false) { { string url = null; if (api != null) { OAuthEnum oAuth = api.GetOAuthType(); switch (oAuth) { case OAuthEnum.TOKEN: url = BuildUrl(api, auth, isRichText); break; case OAuthEnum.SIGN: break; case OAuthEnum.DIRECT: url = BuildUrl(api, auth, isRichText); break; } var method = api.GetHttpMethod(); IApiParams apiParams = api.GetAPIParams(); IDictionary <string, string> requestParams = apiParams.ToParams(); IDictionary <string, string> header = api.GetHeaders(); string result = defaultHttpClient.Send(url, requestParams, header, files, isRichText); return(result); } return(null); } }
public AddProductViewModel(Product p, IAPI api) { this.api = api; this._productID = p.ProductID; this.ProductName = p.Name; this.ProductNumber = p.ProductNumber; this.MakeFlag = p.MakeFlag; this.FinishedGoodsFlag = p.FinishedGoodsFlag; this.Color = p.Color; this.SafetyStockLevel = p.SafetyStockLevel; this.ReorderPoint = p.ReorderPoint; this.StandardCost = p.StandardCost; ListPrice = p.ListPrice; Size = p.Size; SizeUnitMeasureCode = p.SizeUnitMeasureCode; WeightUnitMeasureCode = p.WeightUnitMeasureCode; Weight = p.Weight; DaysToManufacture = p.DaysToManufacture; ProductLine = p.ProductLine; Class = p.Class; Style = p.Style; ProductSubcategoryID = p.ProductSubcategoryID.HasValue ? api.GetSubcategoryNameByID(p.ProductSubcategoryID ?? 0) : null; ModelId = p.ProductModelID.HasValue ? api.GetModelNameByID(p.ProductModelID ?? 0) : null; this.SellStartDate = p.SellStartDate; this.SellEndDate = p.SellEndDate; fillLists(); Confirm = new CustomCommand(UpdateProductImplementation); }
public ProductListViewModel(IAPI api) { this.api = api; this.GetAllProducts(); this.AddProduct = new CustomCommand(AddProductImplementation, this); this.UpdateProduct = new CustomCommand(UpdateProductImplementation, this); this.DeleteProduct = new CustomCommand(DeleteProductImplementation, this); }
public static int GetRandom(this IAPI api) { if (api == null) { throw new ArgumentNullException(nameof(api)); } return(new Random().Next(api.GetMin(), api.GetMax() + 1)); }
void IConfigurator.Configure(IAPI api) { if (api == null) { throw new ArgumentNullException("api"); } api.APIKey = this.APIKey; }
private SearchArgs(IAPI api) { if (api == null) { throw new ArgumentNullException("api"); } this.api = api; }
public static void SetCorrectRandom(this IAPI api) { if (api == null) { throw new ArgumentNullException(nameof(api)); } api.SetCorrect(api.GetRandom()); }
public static int GetLeftGuesses(this IAPI api) { if (api == null) { throw new ArgumentNullException(nameof(api)); } return(api.GetAllowedGuesses() - api.GetUsedGuesses()); }
public ApiCacher(IAPI api, int cacheLifetime = 5 * 60 * 1000) { _api = api; _cacheTTL = cacheLifetime; var options = new MemoryCacheOptions(); _cache = new MemoryCache(options); }
/// <summary> /// Initializes a new instance of <see cref="ItemContext"/>. /// </summary> public ItemContext() { if (!_entities.Loaded) { _entities.Load(); } _api = new API(_entities); //TODO: extract dependency }
/// <summary> /// Constructs an instance of Core /// Registers handlers to catch ChatMessage events /// </summary> /// <param name="comm">CommHandler object to register with</param> public Core(ICommHandler comm) { CommHandler = comm; IAPIHandler = new IAPI(); MessageQueue = new Queue<ChatMessage>(); if (comm != null) { CommHandler.CoreListener += new ChatEventHandler(MessageHandler); } }
public TweetTail(IAPI api, string saveDir) { TwitterAPI = api; SaveDir = saveDir; Directory.CreateDirectory(saveDir); Account = new AccountManager(this); Blend = new BlendManager(this); Mute = new MuteManager(this); }
public void SetUp() { var ApiMock = new Moq.Mock <IAPI>(); ApiMock.Setup(a => a.AggregateExternalSources()).Returns(new Task(() => { apiCalls++; })); api = ApiMock.Object; var BotMock = new Moq.Mock <IBot>(); BotMock.Setup(a => a.NotifyRateChange()).Returns(new Task(() => { botCalls++; })); bot = BotMock.Object; logger = new Logger(); }
void Awake() { if (_clientSettings == null) { throw new System.Exception("[OmekaClient] Init failed, client settings is null"); } if (Api == null) { IAPI <DublicCoreVocabulary> api = new StandardApi <DublicCoreVocabulary>(); Api = api; api.SetRestEndPoint(_clientSettings.OmekaEndpoint); api.SetCredentials(_clientSettings.KeyIdentity, _clientSettings.KeyCredential); Debug.Log("[OmekaClient] Successfully Initialized"); } }
string IYouZanClient.Invoke(IAPI api, IAuth auth, IDictionary <string, string> headers, List <KeyValuePair <string, string> > files) { string url = null; if (api != null) { OAuthEnum oAuth = api.GetOAuthType(); switch (oAuth) { case OAuthEnum.TOKEN: url = BuildUrl(api, auth); break; case OAuthEnum.SIGN: break; case OAuthEnum.DIRECT: url = BuildUrl(api, auth); break; } var method = api.GetHttpMethod(); IApiParams apiParams = api.GetAPIParams(); IDictionary <string, object> requestParams = apiParams.ToParams(); IDictionary <string, string> header = api.GetHeaders(); string result = defaultHttpClient.Send(url, requestParams, header, files); if (YouZanConfig.SaveApiLogToDB) { YouZanLogger log = new YouZanLogger { ApiName = api.GetName(), ApiVersion = api.GetVersion(), ApiMethod = api.GetHttpMethod(), AuthType = oAuth.ToString(), RequestUrl = url, PostData = JsonConvert.SerializeObject(requestParams), Header = JsonConvert.SerializeObject(header), ResponseData = result, ClientId = api.GetClientId(), GrantId = api.GetGrantId() }; Task.Run(log.Save); } return(result); } return(null); }
public APIGateway(string type) { switch (type) { case "Console": _Type = new ConsoleApplication(); break; case "Database": _Type = new DatabaseApplication(); break; case "Mobile": _Type = new MobileApplication(); break; } }
private void Random_Id(object sender, RoutedEventArgs e) { //reset movie output lbMovies.ItemsSource = ""; Random rng = new Random(); int random_seed = rng.Next(0100000, 0500000); string random_string = random_seed.ToString(); Console.WriteLine(random_seed); api = apiFactory.createAPI("OMDB"); movies = api.search("IMDb ID", "tt" + "0" + random_string); lbMovies.ItemsSource = movies; }
public static bool IsOutOfGuesses(this IAPI api) { if (api == null) { throw new ArgumentNullException(nameof(api)); } int leftGuesses = api.GetAllowedGuesses() - api.GetUsedGuesses(); if (leftGuesses > 0) { return(false); } else if (leftGuesses == 0) { return(true); } throw new InvalidOperationException("LeftGuesses should not be less than 0"); }
public CState(IAPI Api) { API = Api; MapWidthVal = API.getMaxX() - API.getMinX() + 1; MapHeightVal = API.getMaxY() - API.getMinY() + 1; Map = new CMap(MapWidthVal, MapHeightVal, API.endAfterTime()); Map.ReadMap(API); MyHealth = API.myHealth(); MyPoints = API.myPoints(); MyCoord.Set(API.getCoordOfMe()); PredStep.Set(Steps.STEP, MyCoord); }
public void Init(IAPI api) { var hash = UInt160.Parse(whoami_scripthash); var hashex = UInt160.Parse(microblog_scripthash); plugin_whoami.api = api; Neo.Core.Blockchain.Notify += (s, e) => { if (e.Notifications[0].ScriptHash == hash) { notifys.Enqueue(e.Notifications[0].State); } else if (e.Notifications[0].ScriptHash == hashex) { notifyexs.Enqueue(e.Notifications[0].State); } }; }
public void LoadDlls(IAPI api, string path = "plugins", string searchPattern = "*.dll") { //loadplugin var files = System.IO.Directory.GetFiles(path, searchPattern); foreach (var file in files) { try { var dll = System.Reflection.Assembly.LoadFile(System.IO.Path.GetFullPath(file)); foreach (var t in dll.ExportedTypes) { var b = t.GetInterfaces().Contains(typeof(IPlugin)); if (b) { var plugin = t.Assembly.CreateInstance(t.FullName) as IPlugin; var name = plugin.Name; plugins.Add(name, plugin); } } } catch (Exception err) { string errstr = "error load:" + file + " err:" + err.Message; errors.Add(errstr); Console.WriteLine(errstr); } } foreach (var plugin in plugins) { try { plugin.Value.Init(api); } catch (Exception err) { string errstr = "error init:" + plugin.Key + " err:" + err.Message; failPlugin.Add(plugin.Key); Console.WriteLine(errstr); } } }
//AllowedGuesses public static void AskAllowedGuesses(IAPI api) { AssertAPINotNull(ref api); do { Console.Write("Enter Number of Guesses: "); try { if (TryAskInt(out int allowedGuesses)) { api.SetAllowedGuesses(allowedGuesses); break; } } catch (ArgumentOutOfRangeException) { Console.WriteLine("Number of guesses can only be whole numbers"); } } while (true); }
//Max public static void AskMax(IAPI api) { AssertAPINotNull(ref api); do { Console.Write("Enter Max Number: "); try { if (TryAskInt(out int max)) { api.SetMax(max); break; } } catch (ArgumentOutOfRangeException) { Console.WriteLine("Max value must be more than Min or Correct"); } } while (true); }
private void Search_OnClick(object sender, RoutedEventArgs e) { string searchType = cmbSearchType.Text; //reset movie output lbMovies.ItemsSource = ""; if (cmbDatabase.Text == "OMDB") { api = apiFactory.createAPI(cmbDatabase.Text); movies = api.search(searchType, SearchBar.Text); } if (cmbDatabase.Text == "TMDB") { api = apiFactory.createAPI(cmbDatabase.Text); movies = api.search(searchType, SearchBar.Text); } lbMovies.ItemsSource = movies; }
//Min public static void AskMin(IAPI api) { AssertAPINotNull(ref api); do { Console.Write("Enter Min Number: "); try { if (TryAskInt(out int min)) { api.SetMin(min); break; } } catch (ArgumentOutOfRangeException) { Console.WriteLine("Min value must be less than Max or Correct"); } } while (true); }
public threadMsg(IAPI api, EventHandler <threadMsgEventArgs> on_message = null) { onMessageComplete = on_message; _api = api; _resetEvent = new ManualResetEvent(false); _threadEvent = new ManualResetEvent(false); _thread = new Thread(new ParameterizedThreadStart(delegate(object evt) { threadMsgPara tm = (threadMsgPara)evt; while (_exit == false) { tm.ResetEvent.WaitOne(); if (_exit == false) { msg m = api.Execute(_msg); //if (onMessageComplete != null) onMessageComplete.Invoke(this, new threadMsgEventArgs(m)); } tm.ResetEvent.Reset(); } })); _thread.Start(new threadMsgPara(_resetEvent)); }
//Correct public static void AskCorrect(IAPI api) { AssertAPINotNull(ref api); do { Console.Write("Enter 'Correct' Number: "); try { if (TryAskInt(out int correct)) { api.SetCorrect(correct); break; } } catch (PropertyNotSetException) { Console.WriteLine("Max or Min hasn't been set yet."); } catch (ArgumentOutOfRangeException) { Console.WriteLine("Value must be less than max and more than min"); } } while (true); }
public void Init(IAPI api) { this.api = api; }
/// <summary> /// set api /// </summary> /// <param name="apiCall"></param> public void SetAPI( IAPI apiCall ) { m_iapi = apiCall; }
public SingleSend(IAPI api) { this.api = api; }
public LoLStats(IAPI Api) { this._Api = Api; }
/// <summary> /// set api /// </summary> /// <param name="api"></param> public void SetAPI( IAPI api ) { m_apiCall = api; m_innerFunc.SetAPI(m_apiCall); }
/// <summary> /// получение ссылки на реализацию методов интерфейсов /// </summary> public void Initialize(Interfaces.IAPI x_api) { m_api = x_api; mind = new Mind ( api.endAfterTime (),api.getCoordOfMe () ); radar = new Radar ( mind,api ); }
public static ISearchArgs Create(IAPI api) { return new SearchArgs(api); }
public void Initialize(IAPI Api) { API = Api; st = new CState(API); }
void IConfigurator.Configure(IAPI api) { api.APIKey = "Test"; }
public void ReadMap(IAPI api) { CCoord coord = new CCoord(); for (int x = 0; x < Width; x++) for (int y = 0; y < Height; y++) { coord.Set(x, y); this[x, y] = api.getTypeOfField(coord); } if (!MyCoord.EqualsXY(api.getCoordOfMe().X0, api.getCoordOfMe().Y0)) throw new Exception("Ошибка в API. Несоответствие данных"); CorrectEndTimeout(api.endAfterTime()); }