예제 #1
0
 public ActionRenderer(IHost host) : base(host)
 {
     _renderAction = this.GetType()
         .GetMethods(BindingFlags.NonPublic | BindingFlags.Instance)
         .Where(method => method.Name == "RenderAction")
         .ToArray();
 }
예제 #2
0
        public NServiceBusRoleEntrypoint()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException;

            var azureSettings = new AzureConfigurationSettings();

            var requestedProfiles = GetRequestedProfiles(azureSettings);
            var endpointConfigurationType = GetEndpointConfigurationType(azureSettings);

            AssertThatEndpointConfigurationTypeHasDefaultConstructor(endpointConfigurationType);

            var specifier = (IConfigureThisEndpoint)Activator.CreateInstance(endpointConfigurationType);

            if (specifier is AsA_Host)
            {
                host = new DynamicHostController(specifier, requestedProfiles, new List<Type> { typeof(Development) });
            }
            else
            {
                scannedAssemblies = scannedAssemblies ?? new List<Assembly>();
                host = new GenericHost(specifier, requestedProfiles,
                    new List<Type> { typeof(Development) }, scannedAssemblies.Select(s => s.ToString()));
            }

        }
예제 #3
0
 public ClientDatabaseViewer(IHost host)
     : base(host)
 {
     cachedItems = new List<ListViewItem>(256);
     InitializeComponent();
     ApplySettings();
 }
        public BindingWorkflow(IHost host, ConnectionInformation connectionInformation, ProjectInformation project)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            if (connectionInformation == null)
            {
                throw new ArgumentNullException(nameof(connectionInformation));
            }

            if (project == null)
            {
                throw new ArgumentNullException(nameof(project));
            }

            this.host = host;
            this.connectionInformation = connectionInformation;
            this.project = project;
            this.projectSystem = this.host.GetService<IProjectSystemHelper>();
            this.projectSystem.AssertLocalServiceIsNotNull();

            this.solutionBindingOperation = new SolutionBindingOperation(
                    this.host,
                    this.connectionInformation,
                    this.project.Key);
        }
예제 #5
0
		public Navigator(IPersister persister, IHost host, VirtualNodeFactory nodes, ContentSource sources)
		{
			this.persister = persister;
			this.host = host;
			this.virtualNodes = nodes;
			this.sources = sources;
		}
예제 #6
0
		public XmlInstallationManager(IHost host, IPersister persister, XmlContentRepository repository, ConnectionMonitor connectionContext, Importer importer, IWebContext webContext, ContentActivator activator)
            : base(connectionContext, importer, webContext, persister, activator)
        {
            this.host = host;
            this.persister = persister;
			this.repository = repository;
        }
예제 #7
0
        public CredentialStore(IPersister persister, IHost host)
        {
            _persister = persister;
            _host = host;

            DefaultRoles = new[] {"Everyone", "Members", "Editors", "Administrators"};
        }
예제 #8
0
 /// <summary>
 /// When the control is entered and get the focus, a textbox window control is added to the 
 /// windows host control.
 /// </summary>
 public override void OnEnter(IHost host)
 {
     if (box == null)
     {
         box = new TextBox();
         box.Font = Font;
         box.BorderStyle = BorderStyle.None;
         box.TextChanged += new EventHandler(box_TextChanged);
         box.KeyDown += new KeyEventHandler(box_KeyDown);
         box.KeyPress += new KeyPressEventHandler(box_KeyPress);
         box.GotFocus += new EventHandler(box_GotFocus);
         box.LostFocus += new EventHandler(box_LostFocus);
         box.BackColor = BackColor;
     }
     Rectangle r = HostBounds;
     r.Inflate((int)(3 * -ScaleFactor.Width), (int)-ScaleFactor.Height);
     box.Text = Text;
     int dy = (r.Height - box.Height) / 2;
     r.Y += dy;
     box.Bounds = r;
     host.AddControl(box);
     box.Focus();
     Invalidate();
     base.OnEnter(host);
 }
예제 #9
0
 private void Given_Engine()
 {
     this.host = mr.Stub<IHost>();
     engine = new OllyLang();
     engine.Host = host;
     engine.Debugger = new Debugger(null);
 }
예제 #10
0
        /// <summary>
        /// new
        /// </summary>
        /// <param name="connectionID"></param>
        /// <param name="socket"></param>
        /// <param name="host"></param>
        /// <exception cref="ArgumentNullException">socket is null</exception>
        /// <exception cref="ArgumentNullException">host is null</exception>
        public DefaultConnection(long connectionID, Socket socket, IHost host)
        {
            if (socket == null) throw new ArgumentNullException("socket");
            if (host == null) throw new ArgumentNullException("host");

            this.ConnectionID = connectionID;
            this._socket = socket;
            this._host = host;
            this._messageBufferSize = host.MessageBufferSize;

            try//f**k...
            {
                this.LocalEndPoint = (IPEndPoint)socket.LocalEndPoint;
                this.RemoteEndPoint = (IPEndPoint)socket.RemoteEndPoint;
            }
            catch (Exception ex) { Log.Trace.Error("get socket endPoint error.", ex); }

            //init for send...
            this._saeSend = host.GetSocketAsyncEventArgs();
            this._saeSend.Completed += new EventHandler<SocketAsyncEventArgs>(this.SendAsyncCompleted);
            this._sendQueue = new SendQueue();

            //init for receive...
            this._saeReceive = host.GetSocketAsyncEventArgs();
            this._saeReceive.Completed += new EventHandler<SocketAsyncEventArgs>(this.ReceiveAsyncCompleted);
        }
예제 #11
0
        public DiagnosticController(IContentItemRepository repository, IHost host, IDefinitionManager definitions,
            ILinkGenerator linkGenerator, IUrlParser parser, DatabaseSection config, IFlushable flushable, IReplicationStorage repstore, 
            IFileSystemFactory fileSystemFactory)
        {
            _repository = repository;
            _host = host;
            _definitions = definitions;
            _linkGenerator = linkGenerator;
            _parser = parser;
            _flushable = flushable;
            _tablePrefix = config.TablePrefix;

            _repstore = repstore;

            if (_forceWriteLockManager != null) return;

            // Create Force Write Lock Manager
            var storageConfig = (FileSystemNamespace) Enum.Parse(typeof (FileSystemNamespace),
                ConfigurationManager.AppSettings["AzureReplicationStorageContainerName"] ??
                "ReplicationStorageDebug");

            var fileSystem = fileSystemFactory.Create(storageConfig);
            _forceWriteLockManager = new ReplicationForceWriteLockManager(fileSystem);
            _writeLockManager = new ReplicationWriteLockManager(fileSystem);
        }
예제 #12
0
 HostManager(IHost host)
 {
     Host = host;
     Host.Start += HandleHostStart;
     Host.IncomingRequestReceived += HandleHostIncomingRequestReceived;
     Host.IncomingRequestProcessed += HandleIncomingRequestProcessed;
 }
예제 #13
0
        public bool SelectRootDirectory(IHost host, bool force)
        {
            string path = this.RootDirectory;
            string initDir;
            if (String.IsNullOrEmpty(path) || !Directory.Exists(path))
            {
                initDir = null;
            }
            else
            {
                initDir = path;
                if (!force && IsValidDir(initDir))
                {
                    return true;
                }
            }

            path = SimpleDialog.OpenFolder(initDir, "Please specify de4dot's root directory.");
            if (String.IsNullOrEmpty(path) || !Directory.Exists(path)) 
                return false;

            if (!IsValidDir(path)) 
                return false;

            this.RootDirectory = path;
            return true;
        }
예제 #14
0
 public DirectUrlInjector(IHost host, IUrlParser parser, IContentItemRepository repository, IDefinitionManager definitions)
 {
     this.host = host;
     this.parser = parser;
     this.repository = repository;
     this.definitions = definitions;
 }
		public DefaultDirectorySelector(IHost host, EditSection config)
		{
			this.host = host;
			mode = config.DefaultDirectory.Mode;
			defaultFolderPath = config.DefaultDirectory.RootPath;
			uploadFolders = new List<string>(config.UploadFolders.Folders);
		}
예제 #16
0
        public Statement(IHost host, string name, StatementTail statementTail)
            : this(host, name)
        {
            if (statementTail != null)
            {
                if (statementTail.Parameters != null)
                {
                    Parameters = statementTail.Parameters;
                }

                //AddAttributes(statementTail.Attributes);
                if (statementTail.Attributes != null)
                {
                    for (int i = 0; i < Attributes.Count; i++)
                    {
                        statementTail.Attributes.Add(Attributes[i]);
                    }
                    Attributes = statementTail.Attributes;
                }

                if (statementTail.Children != null)
                {
                    Children = statementTail.Children;
                }
            }
        }
예제 #17
0
 internal Statement(IHost host)
     : base(host)
 {
     Attributes = new AttributeList(host);
     Children = new StatementList(host);
     Parameters = new ParameterList(host);
 }
        public frmDeobf(IHost mainForm, string[] rows, string sourceDir)
        {
            InitializeComponent();

            InitForm(mainForm, rows, sourceDir);
            InitFormOnce();
        }
예제 #19
0
 public BitmapViewer(IHost host)
     : base(host)
 {
     DoubleBuffered = true;
     BackgroundImageLayout = System.Windows.Forms.ImageLayout.Center;
     ApplySettings();
 }
예제 #20
0
 public DocumentView(IHost host, IRendererFactory rendererFactory, IDictionary<string, object> documentHost, Document document)
 {
     DocumentHost = documentHost;
     _host = host;
     _rendererFactory = rendererFactory;
     _document = document;
 }
예제 #21
0
        public override bool OnStart()
        {
            var azureSettings = new AzureConfigurationSettings();
            var requestedProfileSetting = azureSettings.GetSetting(ProfileSetting);

            var endpointConfigurationType = GetEndpointConfigurationType(azureSettings);

            AssertThatEndpointConfigurationTypeHasDefaultConstructor(endpointConfigurationType);

            var specifier = (IConfigureThisEndpoint)Activator.CreateInstance(endpointConfigurationType);
            var requestedProfiles = requestedProfileSetting.Split(' ');
            requestedProfiles = AddProfilesFromConfiguration(requestedProfiles);

            //var endpointName = "Put somethingt smart here Yves"; // wonder if I live up to the expectations :)
            var endpointName = RoleEnvironment.IsAvailable ? RoleEnvironment.CurrentRoleInstance.Role.Name : GetType().Name;

            if (specifier is AsA_Host)
            {
                host = new DynamicHostController(specifier, requestedProfiles, new List<Type> { typeof(Development) }, endpointName);
            }
            else
            {
                host = new GenericHost(specifier, requestedProfiles, new List<Type> { typeof(Development), typeof(OnAzureTableStorage) }, endpointName);
            }

            return true;
        }
예제 #22
0
        public PanelDbManager(IHost host, PluginParameter data)
        {
			_host = host;
			_shellData = (Shell)data[0];
			_shellSqlConn = GetShellSqlConn();

			// init StrRes to translate string
			StrRes.SetHost(_host);
            Init();			

            //绑定事件
			_dbManager = new DbManager(_host, _shellData, _shellSqlConn.type);
			_dbManager.ConnectDbCompletedToDo += DbManagerConnectDbCompletedToDo;
			_dbManager.GetDbNameCompletedToDo += DbManagerGetDbNameCompletedToDo;
			_dbManager.GetDbTableNameCompletedToDo += DbManagerGetTableNameCompletedToDo;
			_dbManager.GetColumnTypeCompletedToDo += DbManagerGetColumnTypeCompletedToDo;
			_dbManager.ExecuteReaderCompletedToDo += DbManagerExecuteReaderCompletedToDo;
			_dbManager.ExecuteNonQueryCompletedToDo += DbManagerExecuteNonQueryCompletedToDo;

			RefreshServerStatus(false);


	        if (string.IsNullOrEmpty(_shellSqlConn.type) || string.IsNullOrEmpty(_shellSqlConn.conn))
	        {
		        MessageBox.Show("shell's sqlConnection is null or space");
	        }
	        else
	        {
				//连接数据库
				_dbManager.ConnectDb(_shellSqlConn.conn);
	        }
        }
예제 #23
0
 public void Edit(IHost host)
 {
     var editor = host.GetEditor<ClassDiagramEditor>(this, "Edit diagram");
     editor.DiagramNode = this;
     editor.LoadData();
     host.ShowEditor(editor);
 }
예제 #24
0
        public void ViewTableContent(IHost host)
        {
            try
            {
                //var db = Parent as DataBaseElement;
                //IDbConnection connection = db.GetConnection();
                //IDbCommand command = connection.CreateCommand();
                //command.CommandText = string.Format("select * from [{0}]", Name);
                //connection.Open();
                //IDataReader reader = command.ExecuteReader();


                //var dt = new DataTable();
                //dt.Load(reader);

                //reader.Close();
                //connection.Close();
                //var editor = host.GetEditor<TableDataView>(this, "View Table");
                //editor.Data = dt;
                //host.ShowEditor(editor);
            }
            catch (Exception)
            {
                MessageBox.Show("An error occured");
            }
        }
예제 #25
0
 private HostManager(IHost host)
 {
     this.Host = host;
     this.Host.Start += this.HandleHostStart;
     this.Host.IncomingRequestReceived += this.HandleHostIncomingRequestReceived;
     this.Host.IncomingRequestProcessed += this.HandleIncomingRequestProcessed;
 }
예제 #26
0
        public StringLiteral(IHost host, string value)
            : base(host)
        {
            base.Name = "string";

            if (IsWrappedInQuotes(value))
            {
                ValueType = ValueType.StringLiteral;
                //strip quotes

                int offset = StartsWith(value, '@') ? 2 : 1;
                value = new string(value.ToArray(), offset, value.Length - (offset + 1));
            }
            else if (value == "this")
            {
                ValueType = ValueType.Local;
            }
            else if (value == "null" || value == "true" || value == "false")
            {
                ValueType = ValueType.Keyword;
            }
            else
            {
                ValueType = ValueType.Property;
            }

            if (ValueType == ValueType.StringLiteral)
            {
                Values = Parse(value);
            }
        }
예제 #27
0
 public FileUploadOrDownload(IHost host, Shell shellData, string sourceFilePath, string targetFilePath)
 {
     _host = host;
     _shellData = shellData;
     _sourceFilePath = sourceFilePath;
     _targetFilePath = targetFilePath;
 }
예제 #28
0
 internal SandboxedHost(IHost host, IObjectAccessor accessor, MicroScheduler scheduler)
 {
     m_host = host;
     m_accessor = accessor;
     m_graphics = new SandboxedGraphics(host.Graphics);
     m_scheduler = scheduler;
 }
        public ActiveSolutionBoundTracker(IHost host, IActiveSolutionTracker activeSolutionTracker)
        {
            if (host == null)
            {
                throw new ArgumentNullException(nameof(host));
            }

            if (activeSolutionTracker == null)
            {
                throw new ArgumentNullException(nameof(activeSolutionTracker));
            }

            this.extensionHost = host;
            this.solutionTracker = activeSolutionTracker;

            this.solutionBindingInformationProvider = this.extensionHost.GetService<ISolutionBindingInformationProvider>();
            this.solutionBindingInformationProvider.AssertLocalServiceIsNotNull();

            this.errorListInfoBarController = this.extensionHost.GetService<IErrorListInfoBarController>();
            this.errorListInfoBarController.AssertLocalServiceIsNotNull();
            this.errorListInfoBarController.Refresh();

            // The user changed the binding through the Team Explorer
            this.extensionHost.VisualStateManager.BindingStateChanged += this.OnBindingStateChanged;

            // The solution changed inside the IDE
            this.solutionTracker.ActiveSolutionChanged += this.OnActiveSolutionChanged;

            this.IsActiveSolutionBound = this.solutionBindingInformationProvider.IsSolutionBound();
        }
예제 #30
0
 public MongoInstallationManager(MongoDatabaseProvider database, IHost host, IPersister persister, ConnectionMonitor connectionContext, Importer importer, IWebContext webContext, ContentActivator activator)
     : base(connectionContext, importer, webContext, persister, activator)
 {
     this.database = database;
     this.host = host;
     this.persister = persister;
 }
예제 #31
0
 private protected FilterBase(IHost host, IDataView input)
     : base(host, input)
 {
 }
예제 #32
0
 /// <include file='doc.xml' path='doc/members/member[@name="Whitening"]/*'/>
 /// <param name="env">The environment.</param>
 /// <param name="columns">Describes the parameters of the whitening process for each column pair.</param>
 internal VectorWhiteningEstimator(IHostEnvironment env, params ColumnOptions[] columns)
 {
     _host  = Contracts.CheckRef(env, nameof(env)).Register(nameof(VectorWhiteningEstimator));
     _infos = columns;
 }
예제 #33
0
        public OneHotHashEncodingEstimator(IHostEnvironment env, params ColumnInfo[] columns)
        {
            Contracts.CheckValue(env, nameof(env));
            _host = env.Register(nameof(ValueToKeyMappingEstimator));
            _hash = new HashingEstimator(_host, columns.Select(x => x.HashInfo).ToArray());
            using (var ch = _host.Start(nameof(OneHotHashEncodingEstimator)))
            {
                var binaryCols = new List <(string input, string output)>();
                var cols       = new List <(string input, string output, bool bag)>();
                for (int i = 0; i < columns.Length; i++)
                {
                    var column = columns[i];
                    OneHotEncodingTransformer.OutputKind kind = columns[i].OutputKind;
                    switch (kind)
                    {
                    default:
                        throw _host.ExceptUserArg(nameof(column.OutputKind));

                    case OneHotEncodingTransformer.OutputKind.Key:
                        continue;

                    case OneHotEncodingTransformer.OutputKind.Bin:
                        if ((column.HashInfo.InvertHash) != 0)
                        {
                            ch.Warning("Invert hashing is being used with binary encoding.");
                        }
                        binaryCols.Add((column.HashInfo.Output, column.HashInfo.Output));
                        break;

                    case OneHotEncodingTransformer.OutputKind.Ind:
                        cols.Add((column.HashInfo.Output, column.HashInfo.Output, false));
                        break;

                    case OneHotEncodingTransformer.OutputKind.Bag:
                        cols.Add((column.HashInfo.Output, column.HashInfo.Output, true));
                        break;
                    }
                }
                IEstimator <ITransformer> toBinVector = null;
                IEstimator <ITransformer> toVector    = null;
                if (binaryCols.Count > 0)
                {
                    toBinVector = new KeyToBinaryVectorMappingEstimator(_host, binaryCols.Select(x => new KeyToBinaryVectorMappingTransformer.ColumnInfo(x.input, x.output)).ToArray());
                }
                if (cols.Count > 0)
                {
                    toVector = new KeyToVectorMappingEstimator(_host, cols.Select(x => new KeyToVectorMappingTransformer.ColumnInfo(x.input, x.output, x.bag)).ToArray());
                }

                if (toBinVector != null && toVector != null)
                {
                    _toSomething = toVector.Append(toBinVector);
                }
                else
                {
                    if (toBinVector != null)
                    {
                        _toSomething = toBinVector;
                    }
                    else
                    {
                        _toSomething = toVector;
                    }
                }
            }
        }
예제 #34
0
        public static async Task RunWithTasksAsync(this IHost webHost, CancellationToken cancellationToken = default)
        {
            await webHost.Services.GetService <IStartupTask>().ExecuteAsync(cancellationToken);

            await webHost.RunAsync(cancellationToken);
        }
예제 #35
0
 public FunctionsV2HostWrapper(IHost innerHost)
 {
     this.innerHost        = innerHost ?? throw new ArgumentNullException(nameof(innerHost));
     this.innerWebJobsHost = (JobHost)this.innerHost.Services.GetService <IJobHost>();
 }
예제 #36
0
        public SharedSettings(IConfiguration configuration, ILogger <SharedSettings> logger, IHost host, IManagedTasks managedTasks, IMemoryCache memoryCache)
        {
            _logger       = logger;
            _host         = host;
            _managedTasks = managedTasks;
            _memoryCache  = memoryCache;

            SessionEncryptionKey = EncryptString.GenerateRandomKey();
            RemoteSettings       = configuration.Get <RemoteSettings>();

            var url = RemoteSettings.AppSettings.WebServer;

            if (url.Substring(url.Length - 1) != "/")
            {
                url += "/";
            }
            BaseUrl = url;

            _apiUri = url + "api/";

            CookieContainer = new CookieContainer();
            var handler = new HttpClientHandler
            {
                CookieContainer = CookieContainer
            };

            //Login to the web server to receive an authenticated cookie.
            _httpClient     = new HttpClient(handler);
            _loginSemaphore = new SemaphoreSlim(1, 1);
        }
예제 #37
0
 protected RowToRowMapperTransformBase(IHost host, IDataView input)
     : base(host, input)
 {
 }
예제 #38
0
        //public DummyApplication(ILogger<DummyApplication> logger, IConfiguration configuration)
        //{
        //    this.logger = logger ?? throw new ArgumentNullException(nameof(logger));
        //    this.configuration = configuration ?? throw new ArgumentNullException(nameof(configuration));

        //    DemoLogging();
        //} // public DummyApplication(...)


        public ServiceBaseHost(ILogger <ServiceBaseHost> logger, IHost host)
        {
            this.host   = host;
            this.logger = logger;
        }
        internal OneHotEncodingEstimator(IHostEnvironment env, ColumnOptions[] columns, IDataView keyData = null)
        {
            Contracts.CheckValue(env, nameof(env));
            _host = env.Register(nameof(OneHotEncodingEstimator));
            _term = new ValueToKeyMappingEstimator(_host, columns, keyData);
            var binaryCols = new List <(string outputColumnName, string inputColumnName)>();
            var cols       = new List <(string outputColumnName, string inputColumnName, bool bag)>();

            for (int i = 0; i < columns.Length; i++)
            {
                var        column = columns[i];
                OutputKind kind   = columns[i].OutputKind;
                switch (kind)
                {
                default:
                    throw _host.ExceptUserArg(nameof(column.OutputKind));

                case OutputKind.Key:
                    continue;

                case OutputKind.Binary:
                    binaryCols.Add((column.OutputColumnName, column.OutputColumnName));
                    break;

                case OutputKind.Indicator:
                    cols.Add((column.OutputColumnName, column.OutputColumnName, false));
                    break;

                case OutputKind.Bag:
                    cols.Add((column.OutputColumnName, column.OutputColumnName, true));
                    break;
                }
            }
            IEstimator <ITransformer> toBinVector = null;
            IEstimator <ITransformer> toVector    = null;

            if (binaryCols.Count > 0)
            {
                toBinVector = new KeyToBinaryVectorMappingEstimator(_host, binaryCols.Select(x => (x.outputColumnName, x.inputColumnName)).ToArray());
            }
            if (cols.Count > 0)
            {
                toVector = new KeyToVectorMappingEstimator(_host, cols.Select(x => new KeyToVectorMappingEstimator.ColumnOptions(x.outputColumnName, x.inputColumnName, x.bag)).ToArray());
            }

            if (toBinVector != null && toVector != null)
            {
                _toSomething = toVector.Append(toBinVector);
            }
            else
            {
                if (toBinVector != null)
                {
                    _toSomething = toBinVector;
                }
                else
                {
                    _toSomething = toVector;
                }
            }
        }
예제 #40
0
        public static TOut Train <TArg, TOut>(IHost host, TArg input,
                                              Func <ITrainer> createTrainer,
                                              Func <string> getLabel  = null,
                                              Func <string> getWeight = null,
                                              Func <string> getGroup  = null,
                                              Func <string> getName   = null,
                                              Func <IEnumerable <KeyValuePair <RoleMappedSchema.ColumnRole, string> > > getCustom = null,
                                              ICalibratorTrainerFactory calibrator = null,
                                              int maxCalibrationExamples           = 0)
            where TArg : LearnerInputBase
            where TOut : CommonOutputs.TrainerOutput, new()
        {
            using (var ch = host.Start("Training"))
            {
                ISchema schema  = input.TrainingData.Schema;
                var     feature = FindColumn(ch, schema, input.FeatureColumn);
                var     label   = getLabel?.Invoke();
                var     weight  = getWeight?.Invoke();
                var     group   = getGroup?.Invoke();
                var     name    = getName?.Invoke();
                var     custom  = getCustom?.Invoke();

                var trainer = createTrainer();

                IDataView view = input.TrainingData;
                TrainUtils.AddNormalizerIfNeeded(host, ch, trainer, ref view, feature, input.NormalizeFeatures);

                ch.Trace("Binding columns");
                var roleMappedData = new RoleMappedData(view, label, feature, group, weight, name, custom);

                RoleMappedData    cachedRoleMappedData = roleMappedData;
                Cache.CachingType?cachingType          = null;
                switch (input.Caching)
                {
                case CachingOptions.Memory:
                {
                    cachingType = Cache.CachingType.Memory;
                    break;
                }

                case CachingOptions.Disk:
                {
                    cachingType = Cache.CachingType.Disk;
                    break;
                }

                case CachingOptions.Auto:
                {
                    ITrainerEx trainerEx = trainer as ITrainerEx;
                    // REVIEW: we should switch to hybrid caching in future.
                    if (!(input.TrainingData is BinaryLoader) && (trainerEx == null || trainerEx.WantCaching))
                    {
                        // default to Memory so mml is on par with maml
                        cachingType = Cache.CachingType.Memory;
                    }
                    break;
                }

                case CachingOptions.None:
                    break;

                default:
                    throw ch.ExceptParam(nameof(input.Caching), "Unknown option for caching: '{0}'", input.Caching);
                }

                if (cachingType.HasValue)
                {
                    var cacheView = Cache.CacheData(host, new Cache.CacheInput()
                    {
                        Data    = roleMappedData.Data,
                        Caching = cachingType.Value
                    }).OutputData;
                    cachedRoleMappedData = new RoleMappedData(cacheView, roleMappedData.Schema.GetColumnRoleNames());
                }

                var predictor = TrainUtils.Train(host, ch, cachedRoleMappedData, trainer, "Train", calibrator, maxCalibrationExamples);
                var output    = new TOut()
                {
                    PredictorModel = new PredictorModel(host, roleMappedData, input.TrainingData, predictor)
                };

                ch.Done();
                return(output);
            }
        }
예제 #41
0
 public SpellTimerForm(IHost host)
 {
     InitializeComponent();
     _host = host;
     LoadSettings();
 }
예제 #42
0
 public void Connect(IHost hostApplication)
 {
     HostApplication = hostApplication;
 }
예제 #43
0
 /// <summary>
 /// Called first to allow filling some lists. Host is not fully set up at that moment.
 /// </summary>
 /// <param name="host"></param>
 public void PreInitalize(IHost _host)
 {
     host = _host;
 }
예제 #44
0
 public SymbolService(IHost host)
 {
     _host         = host;
     OnChangeEvent = new ServiceEvent();
 }
예제 #45
0
        internal static OneVersusAllModelParameters Create(IHost host, bool useProbability, TScalarPredictor[] predictors)
        {
            var outputFormula = useProbability ? OutputFormula.ProbabilityNormalization : OutputFormula.Raw;

            return(Create(host, outputFormula, predictors));
        }
예제 #46
0
 protected void SetComplete(IHost host)
 {
     _host = host;
 }
예제 #47
0
        private ParquetLoader(IHost host, ModelLoadContext ctx, IMultiStreamSource files)
        {
            Contracts.AssertValue(host);
            _host = host;
            _host.AssertValue(ctx);
            _host.AssertValue(files);

            // *** Binary format ***
            // int: cached chunk size
            // bool: TreatBigIntegersAsDates flag
            // Schema of the loader (0x00010002)

            _columnChunkReadSize = ctx.Reader.ReadInt32();
            bool treatBigIntegersAsDates = ctx.Reader.ReadBoolean();

            if (ctx.Header.ModelVerWritten >= 0x00010002)
            {
                // Load the schema
                byte[] buffer = null;
                if (!ctx.TryLoadBinaryStream(SchemaCtxName, r => buffer = r.ReadByteArray()))
                {
                    throw _host.ExceptDecode();
                }
                var strm   = new MemoryStream(buffer, writable: false);
                var loader = new BinaryLoader(_host, new BinaryLoader.Arguments(), strm);
                Schema = loader.Schema;
            }

            // Only load Parquest related data if a file is present. Otherwise, just the Schema is valid.
            if (files.Count > 0)
            {
                _parquetOptions = new ParquetOptions()
                {
                    TreatByteArrayAsString  = true,
                    TreatBigIntegersAsDates = treatBigIntegersAsDates
                };

                _parquetStream = OpenStream(files);
                DataSet schemaDataSet;

                try
                {
                    // We only care about the schema so ignore the rows.
                    ReaderOptions readerOptions = new ReaderOptions()
                    {
                        Count  = 0,
                        Offset = 0
                    };
                    schemaDataSet = ParquetReader.Read(_parquetStream, _parquetOptions, readerOptions);
                    _rowCount     = schemaDataSet.TotalRowCount;
                }
                catch (Exception ex)
                {
                    throw new InvalidDataException("Cannot read Parquet file", ex);
                }

                _columnsLoaded = InitColumns(schemaDataSet);
                Schema         = CreateSchema(_host, _columnsLoaded);
            }
            else if (Schema == null)
            {
                throw _host.Except("Parquet loader must be created with one file");
            }
        }
예제 #48
0
 internal static OneVersusAllModelParameters Create(IHost host, TScalarPredictor[] predictors)
 {
     Contracts.CheckValue(host, nameof(host));
     host.CheckNonEmpty(predictors, nameof(predictors));
     return(Create(host, OutputFormula.ProbabilityNormalization, predictors));
 }
예제 #49
0
 /// <summary>
 /// Constructor for deserialization.
 /// </summary>
 private GenericScorer(IHost host, ModelLoadContext ctx, IDataView input)
     : base(host, ctx, input)
 {
     Contracts.AssertValue(ctx);
     _bindings = Bindings.Create(ctx, host, Bindable, input.Schema);
 }
예제 #50
0
 public void Register(IHost host)
 {
     _host = host;
 }
        public static void RunAsService(this IHost host)
        {
            var hostService = new GenericServiceHost(host);

            ServiceBase.Run(hostService);
        }
예제 #52
0
 public bool Initialize(IHost hostApplication)
 {
     My = hostApplication;
     FeuerwehrCloud.Helper.Logger.WriteLine("|  *** ImagePrinter loaded...");
     return(true);
 }
예제 #53
0
        public static List <UserData> GetUserData(string rawData, IHost host)
        {
            var dic = GetRawUserData(rawData, host);

            return(dic.Values.ToList());
        }
 /// <summary>
 /// 作为服务器
 /// </summary>
 /// <param name="host">主机</param>
 /// <returns></returns>
 public static IServer AsServer(this IHost host)
 {
     return(host.Services.GetService <IEnumerable <IHostedService> >().OfType <IServer>().FirstOrDefault());
 }
예제 #55
0
        private TermTransform(IHost host, ModelLoadContext ctx, IDataView input)
            : base(host, ctx, input, TestIsKnownDataKind)
        {
            Host.AssertValue(ctx);

            // *** Binary format ***
            // for each term map:
            //   bool(byte): whether this column should present key value metadata as text

            int cinfo = Infos.Length;

            Host.Assert(cinfo > 0);

            if (ctx.Header.ModelVerWritten >= VerNonTextTypesSupported)
            {
                _textMetadata = ctx.Reader.ReadBoolArray(cinfo);
            }
            else
            {
                _textMetadata = new bool[cinfo]; // No need to set in this case. They're all text.
            }
            const string dir = "Vocabulary";

            TermMap[] termMap = new TermMap[cinfo];
            bool      b       = ctx.TryProcessSubModel(dir,
                                                       c =>
            {
                // *** Binary format ***
                // int: number of term maps (should equal number of columns)
                // for each term map:
                //   byte: code identifying the term map type (0 text, 1 codec)
                //   <data>: type specific format, see TermMap save/load methods

                Host.CheckValue(c, nameof(ctx));
                c.CheckAtModel(GetTermManagerVersionInfo());
                int cmap = c.Reader.ReadInt32();
                Host.CheckDecode(cmap == cinfo);
                if (c.Header.ModelVerWritten >= VerManagerNonTextTypesSupported)
                {
                    for (int i = 0; i < cinfo; ++i)
                    {
                        termMap[i] = TermMap.Load(c, host, this);
                    }
                }
                else
                {
                    for (int i = 0; i < cinfo; ++i)
                    {
                        termMap[i] = TermMap.TextImpl.Create(c, host);
                    }
                }
            });

#pragma warning disable MSML_NoMessagesForLoadContext // Vaguely useful.
            if (!b)
            {
                throw Host.ExceptDecode("Missing {0} model", dir);
            }
#pragma warning restore MSML_NoMessagesForLoadContext
            _termMap = new BoundTermMap[cinfo];
            for (int i = 0; i < cinfo; ++i)
            {
                _termMap[i] = termMap[i].Bind(this, i);
            }

            _types = ComputeTypesAndMetadata();
        }
예제 #56
0
        public static ArrayList GetStepsList(string textValue, ArrayList possibleAction, IHost host)
        {
            var ret = new ArrayList();

            if (textValue != null)
            {
                var xSteps = XElement.Parse(textValue);
                foreach (XElement element in xSteps.Descendants(Constants.STEP))
                {
                    var uiId = element.GetAttributeValue(Constants.UI_ID);
                    if (String.IsNullOrEmpty(uiId))
                    {
                        continue;
                    }

                    var sData = host.GetDataObject(uiId);
                    if (sData == null)
                    {
                        continue;
                    }

                    //var xData = sData.GetXElementFromDataObject();
                    var uiObject = element.GetAttributeValue(Constants.UI_OBJECT);
                    if (String.IsNullOrEmpty(uiObject))
                    {
                        continue;
                    }
                    var    enable           = Boolean.Parse(element.GetAttributeValue(Constants.ENABLE));
                    var    defaultDataValue = element.GetAttributeValue(Constants.DEFAULT_DATA);
                    var    dataName         = element.GetAttributeValue(Constants.DATA);
                    var    stepId           = element.GetAttributeValue(Constants._ID);
                    var    action           = element.GetAttributeValue(Constants.ACTION) ?? "";
                    string xpath;
                    xpath = getXPath(element);
                    var step = new Step
                    {
                        _id            = stepId,
                        Action         = action,
                        UIId           = uiId,
                        UIObject       = uiObject,
                        Enable         = enable,
                        DefaultData    = defaultDataValue,
                        Data           = dataName,
                        XPath          = xpath,
                        PossibleAction = possibleAction
                    };
                    ret.Add(step);
                }
            }
            return(ret);
        }
        /// <summary>
        /// Returns the feature selection scores for each slot of each column.
        /// </summary>
        /// <param name="host">The host.</param>
        /// <param name="input">The input dataview.</param>
        /// <param name="labelColumnName">The label column.</param>
        /// <param name="columns">The columns for which to compute the feature selection scores.</param>
        /// <param name="numBins">The number of bins to use for numeric features.</param>
        /// <param name="colSizes">The columns' sizes before dropping any slots.</param>
        /// <returns>A list of scores for each column and each slot.</returns>
        internal static float[][] TrainCore(IHost host, IDataView input, string labelColumnName, string[] columns, int numBins, int[] colSizes)
        {
            var impl = new Impl(host);

            return(impl.GetScores(input, labelColumnName, columns, numBins, colSizes));
        }
예제 #58
0
 public UnitTest03()
 {
     _host = CreateHostBuilder(null).Build();
 }
예제 #59
0
        private static async Task ApplyDbMigrationsWithDataSeedAsync(string[] args, IConfiguration configuration, IHost host)
        {
            var applyDbMigrationWithDataSeedFromProgramArguments = args.Any(x => x == SeedArgs);

            if (applyDbMigrationWithDataSeedFromProgramArguments)
            {
                args = args.Except(new[] { SeedArgs }).ToArray();
            }

            var seedConfiguration = configuration.GetSection(nameof(SeedConfiguration)).Get <SeedConfiguration>();
            var databaseMigrationsConfiguration = configuration.GetSection(nameof(DatabaseMigrationsConfiguration))
                                                  .Get <DatabaseMigrationsConfiguration>();

            await DbMigrationHelpers
            .ApplyDbMigrationsWithDataSeedAsync <IdentityServerConfigurationDbContext, AdminIdentityDbContext,
                                                 IdentityServerPersistedGrantDbContext, AdminLogDbContext, AdminAuditLogDbContext,
                                                 IdentityServerDataProtectionDbContext, UserIdentity, UserIdentityRole>(host,
                                                                                                                        applyDbMigrationWithDataSeedFromProgramArguments, seedConfiguration, databaseMigrationsConfiguration);
        }
예제 #60
0
 public StochasticTrainerBase(IHost host, SchemaShape.Column feature, SchemaShape.Column label, SchemaShape.Column weight = default)
     : base(host, feature, label, weight)
 {
 }