text:
Q: Android Dynamic Feature modules with Dagger Hilt I have built a Dynamic feature module sample with Fragments, sub components and dependent components based on plaid app, if you wish to check out here is the link. Now, i'm trying to convert it to Dagger Hilt using the official android document.
In core module which is the library module, app module and dynamic feature modules depend on
@Singleton
@Component(modules = [CoreModule::class])
interface CoreComponent {

    /*
        Provision methods to provide dependencies below to components that depends on
        CoreComponent
     */
    fun coreDependency(): CoreDependency

    fun coreCameraDependency(): CoreCameraDependency

    fun corePhotoDependency(): CorePhotoDependency

    fun coreActivityDependency(): CoreActivityDependency

    @Component.Factory
    interface Factory {
        fun create(@BindsInstance application: Application): CoreComponent
    }

}

and it's module
@Module(includes = [CoreProvideModule::class])
abstract class CoreModule {
    @Binds
    abstract fun bindContext(application: Application): Context
}

@Module
object CoreProvideModule {

    @Singleton
    @Provides
    fun provideCoreDependency(application: Application) = CoreDependency(application)

    @ActivityScope
    @Provides
    fun provideCoreActivityDependency(context: Context) = CoreActivityDependency(context)

    @Provides
    fun provideCoreCameraDependency(): CoreCameraDependency = CoreCameraDependency()

    @Provides
    fun provideCorePhotoDependency(): CorePhotoDependency = CorePhotoDependency()

}

How is CoreComponent migrated? Do provision methods still stay and i only change
@Singleton
@DefineComponent

or
@Singleton
@DefineComponent(parent = ApplicationComponent.class)

for CoreModule i guess i only change
@EntryPoint
@InstallIn(CoreComponent::class)

or is this for adding provision methods in CoreComponent?
How do i create sub-component in app module?
If anyone has a sample with dynamic feature fragments and hilt, or tutorial to build, it would be more than welcome. I'm just working on it at the moment, if i figure it out i would post an answer

A: I finally figured it out.
For an app structure
FeatureCamera  FeaturePhotos  (Dynamic Feature Modules)
|         |    |
|         ----App
|              |
core(android-library)

Camera dynamic feature module dependencies from core module, Photo dynamic feature module dependencies from app.
First create a CoreModule in library module
@InstallIn(ApplicationComponent::class)
@Module
class CoreModule {

    @Singleton
    @Provides
    fun provideCoreDependency(application: Application) = CoreDependency(application)

    @Provides
    fun provideCoreActivityDependency(context: Application) = CoreActivityDependency(context)

    @Provides
    fun provideCoreCameraDependency(): CoreCameraDependency = CoreCameraDependency()

    @Provides
    fun provideCorePhotoDependency(): CorePhotoDependency = CorePhotoDependency()
}

An interface with @EntryPoint is required to with provision methods defined in this interface, if you don't define a method for that dependency you cannot inject it even though there is a @Provides method for it. These are mock dependencies that take application or context as only parameter.
@EntryPoint
@InstallIn(ApplicationComponent::class)
interface CoreComponent {

    /*
        Provision methods to provide dependencies to components that depend on this component
     */
    fun coreDependency(): CoreDependency

    fun coreActivityDependency(): CoreActivityDependency

    fun coreCameraDependency(): CoreCameraDependency

    fun corePhotoDependency(): CorePhotoDependency

}

In camera dynamic feature module, create another module for the dependency based inside of this dynamic feature module.
@InstallIn(FragmentComponent::class)
@Module(includes = [CameraBindModule::class])
class CameraModule {

    @Provides
    fun provideCameraObject(context: Context) = CameraObject(context)
}

@InstallIn(FragmentComponent::class)
@Module
abstract class CameraBindModule {
    @Binds
    abstract fun bindContext(application: Application): Context
}

And component to inject dependencies to Fragments or Activities in this DFM.
@Component(
        dependencies = [CoreComponent::class],
        modules = [CameraModule::class]
)
interface CameraComponent {

    fun inject(cameraFragment1: CameraFragment1)
    fun inject(cameraFragment2: CameraFragment2)

    fun inject(cameraActivity: CameraActivity)

    @Component.Factory
    interface Factory {
        fun create(coreComponent: CoreComponent, @BindsInstance application: Application): CameraComponent
    }

}

If injected to Activity call in `onCreate()`

      DaggerCameraComponent.factory().create(
                EntryPointAccessors.fromApplication(
                        applicationContext,
                        CoreComponent::class.java
                ),
                application
        )
                .inject(this)

For injecting to Fragment call in `onCreate()`

    DaggerCameraComponent.factory().create(
            EntryPointAccessors.fromApplication(
                    requireActivity().applicationContext,
                    CoreComponent::class.java
            ),
            requireActivity().application
    )
            .inject(this)

The trick is here to get dependency interface annotated with `@EntryPoint`
using `EntryPointAccessors.fromApplication()`

Also created Activity based dependencies in app module

**MainActivityModule.kt**

    @InstallIn(ActivityComponent::class)
    @Module(includes = [MainActivityBindModule::class])
    class MainActivityModule {

        @Provides
        fun provideToastMaker(application: Application) = ToastMaker(application)

        @ActivityScoped
        @Provides
        fun provideMainActivityObject(context: Context) = MainActivityObject(context)

    }

    @InstallIn(ActivityComponent::class)
    @Module
    abstract class MainActivityBindModule {

        @Binds
        abstract fun bindContext(application: Application): Context

    }

And only intend to inject these dependencies to Photos dynamic feature module so named it as `PhotoDependencies`

    @EntryPoint
    @InstallIn(ActivityComponent::class)
    interface PhotoModuleDependencies {

        fun toastMaker(): ToastMaker

        fun mainActivityObject(): MainActivityObject
    }

In Photos dynamic feature module create dagger module named `PhotoModule`

    @InstallIn(FragmentComponent::class)
    @Module(includes = [PhotoBindModule::class])
    class PhotoModule {

        @Provides
        fun providePhotoObject(application: Application): PhotoObject = PhotoObject(application)

    }

    @InstallIn(FragmentComponent::class)
    @Module
    abstract class PhotoBindModule {
        @Binds
        abstract fun bindContext(application: Application): Context
    }

And component

    @Component(
            dependencies = [PhotoModuleDependencies::class],
            modules = [PhotoModule::class]
    )
    interface PhotoComponent {

        fun inject(photosFragment1: PhotoFragment1)
        fun inject(photosFragment2: PhotoFragment2)

        @Component.Factory
        interface Factory {
            fun create(photoModuleDependencies: PhotoModuleDependencies,
                       @BindsInstance application: Application): PhotoComponent
        }
    }

And inject to fragments with

    DaggerPhotoComponent.factory().create(
            EntryPointAccessors.fromActivity(
                    requireActivity(),
                    PhotoModuleDependencies::class.java
            ),
            requireActivity().application
    )
            .inject(this)

The trick here is to get `EntryPointAccessors.fromActivity` instead of fromApplication.

You can check out [this link][1] if you wish to experiment yourself.

If you wish to add `ViewModel` to dynamic feature modules with hilt you can check out my answer [here][2].

  [1]: https://github.com/SmartToolFactory/Dagger2-Tutorials/tree/master/Tutorial10-1DFM-DaggerHilt
  [2]: https://stackoverflow.com/questions/63671489/how-to-create-viewmodel-in-dynamic-feature-module-with-dagger-hilt


text:
Q: How to validate JWT token in other project when you have separate project for Identity using asp.net identity I've two projects in solution. One is for Identity management using asp.net identity generating JWT tokens. In Second project there are API's that are secure and validating token that are generated from identity project but token validation not working.
I'm getting this error when calling api store route in postman. I'm passing token in Authorization header.

An unhandled exception occurred while processing the request.
  HttpRequestException: Response status code does not indicate success:
  404 (Not Found).
  System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
IOException: IDX20804: Unable to retrieve document from: '[PII is
  hidden]'.
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string
  address, CancellationToken cancel)
InvalidOperationException: IDX20803: Unable to obtain configuration
  from: '[PII is hidden]'.
  Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
  cancel)
Stack Query Cookies Headers HttpRequestException: Response status code
  does not indicate success: 404 (Not Found).
  System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string
  address, CancellationToken cancel)
Show raw exception details System.Net.Http.HttpRequestException:
  Response status code does not indicate success: 404 (Not Found).    at
  System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()    at
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String
  address, CancellationToken cancel) IOException: IDX20804: Unable to
  retrieve document from: '[PII is hidden]'.
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(string
  address, CancellationToken cancel)
  Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(string
  address, IDocumentRetriever retriever, CancellationToken cancel)
  Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
  cancel)
Show raw exception details System.IO.IOException: IDX20804: Unable to
  retrieve document from: '[PII is hidden]'. --->
  System.Net.Http.HttpRequestException: Response status code does not
  indicate success: 404 (Not Found).    at
  System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()    at
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String
  address, CancellationToken cancel)    --- End of inner exception stack
  trace ---    at
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String
  address, CancellationToken cancel)    at
  Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String
  address, IDocumentRetriever retriever, CancellationToken cancel)    at
  Microsoft.IdentityModel.Protocols.ConfigurationManager`1.GetConfigurationAsync(CancellationToken
  cancel) InvalidOperationException: IDX20803: Unable to obtain
  configuration from: '[PII is hidden]'.
  Microsoft.IdentityModel.Protocols.ConfigurationManager.GetConfigurationAsync(CancellationToken
  cancel)
  Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  Microsoft.AspNetCore.Authentication.AuthenticationHandler.AuthenticateAsync()
  Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext
  context, string scheme)
  Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
  context)
  Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
  context)
Show raw exception details System.InvalidOperationException: IDX20803:
  Unable to obtain configuration from: '[PII is hidden]'. --->
  System.IO.IOException: IDX20804: Unable to retrieve document from:
  '[PII is hidden]'. ---> System.Net.Http.HttpRequestException: Response
  status code does not indicate success: 404 (Not Found).    at
  System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()    at
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String
  address, CancellationToken cancel)    --- End of inner exception stack
  trace ---    at
  Microsoft.IdentityModel.Protocols.HttpDocumentRetriever.GetDocumentAsync(String
  address, CancellationToken cancel)    at
  Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectConfigurationRetriever.GetAsync(String
  address, IDocumentRetriever retriever, CancellationToken cancel)    at
  Microsoft.IdentityModel.Protocols.ConfigurationManager1.GetConfigurationAsync(CancellationToken
  cancel)    --- End of inner exception stack trace ---    at
  Microsoft.IdentityModel.Protocols.ConfigurationManager1.GetConfigurationAsync(CancellationToken
  cancel)    at
  Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  at
  Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler.HandleAuthenticateAsync()
  at
  Microsoft.AspNetCore.Authentication.AuthenticationHandler`1.AuthenticateAsync()
  at
  Microsoft.AspNetCore.Authentication.AuthenticationService.AuthenticateAsync(HttpContext
  context, String scheme)    at
  Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext
  context)    at
  Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext
  context)

This is my Startup.cs class in Identity project.
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cosmonaut;
using Cosmonaut.Extensions.Microsoft.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Identity;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Triverse.Identity.Models;
using Triverse.Identity.Services;
using IdentityRole = Microsoft.AspNetCore.Identity.DocumentDB.IdentityRole;

namespace Triverse.Identity
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var endPointUri = Configuration.GetValue<string>("AppSettings:EndpointUri");
            var primaryKey = Configuration.GetValue<string>("AppSettings:PrimaryKey");
            var databaseId = Configuration.GetValue<string>("AppSettings:DatabaseId");
            var collectionId = Configuration.GetValue<string>("AppSettings:CollectionId");

            var client = new DocumentClient(new Uri(endPointUri), primaryKey);
            services.AddSingleton<IDocumentClient>(client);

            // make sure the database exists!
            var db = client.CreateDatabaseQuery().Where(d => d.Id == databaseId).AsEnumerable().FirstOrDefault()
                     ?? client.CreateDatabaseAsync(new Database { Id = databaseId }).Result;

            var databaseLink = db.SelfLink;

            services.AddIdentityWithDocumentDBStores<ApplicationUser, IdentityRole>(
                dbOptions =>
                {
                    dbOptions.DocumentUrl = endPointUri;
                    dbOptions.DocumentKey = primaryKey;
                    dbOptions.DatabaseId = databaseId;
                    dbOptions.CollectionId = collectionId;
                },
                identityOptions =>
                {
                    identityOptions.User.RequireUniqueEmail = true;
                });

            var cosmosSettings = new CosmosStoreSettings(databaseId, endPointUri, primaryKey);
            services.AddCosmosStore<ApplicationUser>(cosmosSettings);

            services.AddScoped<IAccountRepository, AccountRepository>();
            services.AddTransient<ITokenService, TokenService>();

            services.AddAuthentication(options =>
                {
                    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                    options.DefaultSignInScheme = JwtBearerDefaults.AuthenticationScheme;
                })
                .AddJwtBearer(cfg =>
                {
                    cfg.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidIssuer = Configuration["Tokens:Issuer"],
                        ValidAudience = Configuration["Tokens:Audience"],
                        IssuerSigningKey =
                            new SymmetricSecurityKey(Encoding.UTF8.GetBytes(Configuration["Tokens:Key"])),
                        ValidateLifetime = true
                    };

                    cfg.Events = new JwtBearerEvents
                    {
                        OnAuthenticationFailed = context =>
                        {
                            if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
                            {
                                context.Response.Headers.Add("Token-Expired", "true");
                                context.Response.Headers.Add("access-control-expose-headers", "Token-Expired");
                            }

                            return Task.CompletedTask;
                        }
                    };
                });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();
        }
    }
}

This is my appsettings.json in Identity project.
"Tokens": {
    "Key": "4343@!#ewewq",
    "Issuer": "http://localhost:44376/",
    "Audience": "http://localhost:44385/",
    "ExpiryMinutes": "55",
    "ValidateLifetime": true
  }

This is my Startup.cs class in Store project.
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cosmonaut;
using Cosmonaut.Extensions.Microsoft.DependencyInjection;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using Store.API.Services;

namespace Store.API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var endPointUri = Configuration.GetValue<string>("AppSettings:EndpointUri");
            var primaryKey = Configuration.GetValue<string>("AppSettings:PrimaryKey");
            var databaseId = Configuration.GetValue<string>("AppSettings:DatabaseId");

            var client = new DocumentClient(new Uri(endPointUri), primaryKey);
            services.AddSingleton<IDocumentClient>(client);

            var db = client.CreateDatabaseQuery().Where(d => d.Id == databaseId).AsEnumerable().FirstOrDefault()
                     ?? client.CreateDatabaseAsync(new Database {Id = databaseId}).Result;

            var databaseLink = db.SelfLink;

            var cosmosSettings = new CosmosStoreSettings(databaseId, endPointUri, primaryKey);
            services.AddCosmosStore<Models.Store>(cosmosSettings);

            services.AddScoped<IStoreRepository, StoreRepository>();

            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            }).AddJwtBearer(options =>
            {
                options.Authority = "http://localhost:44376/";
                options.RequireHttpsMetadata = false;
                options.Audience = "http://localhost:44385/";
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseAuthentication();

            app.UseMvc();
        }
    }
}

This is my controller method in Store project.
[HttpGet]
[Authorize]
public async Task<IActionResult> GetStores()
{
  var stores = new
  {
     Id = 1,
     Name = "T-Shirt",
     Price = "120.00"
  };

  return Ok(stores);
}

This is my JWT token generated from Identity project.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzaGFAZG9tYWluLmNvbSIsImp0aSI6IjFjYjNkNjA2LWI4MGQtNGNlZC1hMWFjLThlYmUzNzc1ZGViOSIsIlVuaXF1ZUlkIjoiZjU1ZTM2MWQtYjFkYy00MDg4LTlmYjQtMDg3ZTI4OTFjNWI1IiwidW5pcXVlX25hbWUiOiJzaGFAZG9tYWluLmNvbSIsImZpcnN0TmFtZSI6IlNoYXduIiwibmJmIjoxNTY0OTkwMjA1LCJleHAiOjE1NjQ5OTM1MDUsImlzcyI6Imh0dHA6Ly9sb2NhbGhvc3Q6NDQzNzYvIiwiYXVkIjoiaHR0cDovL2xvY2FsaG9zdDo0NDM4NS8ifQ.ZBK8Fi14QUc9ObZx7ojg7LPcl8Qs2vrQyhZi7Dbk4Gg

A: Asp.NET Identity is not intended for this use case all by itself. You might want to look something like Identity Server which extends the functionality of Identity. It allows you to validate tokens in several ways,

*

*It has an endpoint for validating tokens

*It exposes a well known configuration endpoint that provide (along with a lot of other things) the public key of RSA certificate used to sign the token. So if you want, you can verify the signature yourself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unity. Function call after a certain period of time How can I make an object invisible (or just delete) after a certain period of time?
Use NGUI.
My example (for changes):
public class scriptFlashingPressStart : MonoBehaviour
{
    public GameObject off_Logo;
    public float dead_logo = 1.5f;

    void OffLogo()
    {
        off_Logo.SetActive(false);
    }

    //function onclick button
    //remove item after a certain time after pressing ???
    void press_start()
    {
        InvokeRepeating("OffLogo", dead_logo , ...);
    }
}

A: Use Invoke rather than InvokeRepeating.
check Invoke function here
 public class scriptFlashingPressStart : MonoBehaviour
    {
        public GameObject off_Logo;
        public float dead_logo = 1.5f;
        bool pressed = false;

    void OffLogo()
    {
       //do anything(delete or invisible)
        off_Logo.SetActive(false);
         pressed = false;
    }

   //use Invoke rather than InvokeRepeating
    void press_start()
    {
        if(!pressed)
        {
          pressed = true;
          Invoke("OffLogo", dead_logo);
        }
        else
        {
          Debug.Log("Button already pressed");
        }
    }
}

A: try
StartCoroutine(SomeFunctionAfterSomeTime);

IEnumerator SomeFunctionAfterSomeTime()
{
    ... //Your own logic
    yield return new WaitForSeconds(SomeTime);
}

A: You can destroy an object in a given time by simply calling Destroy.
public static void Destroy(Object obj, float t = 0.0F);

Parameters

*

*obj  The object to destroy.

*t    The optional amount of time to delay
before destroying the object.

See http://docs.unity3d.com/Documentation/ScriptReference/Object.Destroy.html


text:
Q: Having two serperate const with information and matching them up This is my first post, and i just started developing, so this question is properly stupid.
I am currently creating an application that pulls two sets of data.
1) All the contact information on business that went out of business in Denmark.
2) All of the customers at the firm i work at.
So the functionality is that every time one of our customers goes bankrupt we get a notification.
I have "successfully" made the query that gets the right information in two separate consts.
But how do i math up the numbers i want?
i will describe it like this in plain english, just so you understand what i mean.
Select every firm where "Employer Identification Number" matches up in the two consts.
I use suquel pro as the database, and adonis js for as the programming language


text:
Q: Read file from position FileStream infile = new FileStream(@"C:\Users\John\Desktop\ProjectNew\nov.txt",     FileMode.Open, FileAccess.Read);
        int position = x.Length;
        infile.Seek(position, SeekOrigin.Begin);

But Seek method returns number. How to read the file 'infile' from position to end in a string?

A: Is this what you're after? Assuming you wanted to start reading from position 100...
       using (FileStream fs = new FileStream(@"file.txt", FileMode.Open, FileAccess.Read))
        {
            fs.Seek(100, SeekOrigin.Begin);

            byte[] b = new byte[fs.Length - 100];
            fs.Read(b, 0, (int)(fs.Length - 100));

            string s = System.Text.Encoding.UTF8.GetString(b);
        }

A: The Seek method is supposed to return a number, the new position in the stream. Now just call whatever Read function you want.

A: Seek() only places the file pointer somewhere else. If you do a read before the seek, it will read from the beginning of the file. If you read after the seek, it will start reading from position.
So to read the file from position to the end, do Seek(), followed by Read() or ReadToEnd().


text:
Q: Why is my kernel configuration option not set in resulting defconfig after running bitbake -c savedefconfig virtual/kernel? I have made some adjustments to the kernel source so that I can use a custom logo on the kernel splash screen. In particular, the changes I have made allow the custom logo to be chosen as a kernel configuration option when I run the following bitbake command:
bitbake -c menuconfig virtual/kernel

and then navigate to the Device Drivers > Graphics support -> Bootup logo. I set the Bootup logo to the custom logo, save my changes & exit menuconfig. At this point, the generated .config file is at tmp/work/imx6ul_var_dart-fslc-linux-gnueabi/linux-variscite/4.9.88-r0/build/.config and I confirm that my logo has been configured as the boot logo in the following line from the .config file:
CONFIG_LOGO_CUSTOM_CLUT224=y

All is good up to this point. Now, I want to save the .config file in a defconfig format so that I can overwrite the default configuration in the source tree and replace it with the generated defconfig file. To do this I run the following command:
bitbake -c savedefconfig virtual/kernel

At this point, the generated defconfig file is at tmp/work/imx6ul_var_dart-fslc-linux-gnueabi/linux-variscite/4.9.88-r0/build/defconfig. But, when I search the generated defconfig file...I do not find the following line:
CONFIG_LOGO_CUSTOM_CLUT224=y

Why am I not seeing this configuration option in the defconfig file even though it was set in the .config file it is being generated from?
Edit (adding extra info):
I will describe the precise changes made to the kernel source. Firstly, I added the logo (logo_custom_clut224.ppm) to drivers/video/logo. I then modified drivers/video/logo/Kconfig to include the following entry inside if LOGO and the corresponding endif :
config LOGO_CUSTOM_CLUT224
    bool "224-color Custom logo"
    default y

I then added the following logic to drivers/video/logo/logo.c inside the if (depth >= 8) block:
#ifdef CONFIG_LOGO_CUSTOM_CLUT224
    logo = &logo_custom_clut224;
#endif

I then added the following statement to include/linux/linux_logo.h:
extern const struct linux_logo logo_custom_clut224;

Lastly, I modified the drivers/video/logo/Makefile to include an entry for the custom logo:
obj-$(CONFIG_LOGO_CUSTOM_CLUT224 += logo_custom_clut224.o

I would also like to note that the logo I am trying to use is 800x480.


text:
Q: Gradle sync failed: Failed to create parent directory "path" when creating directory I have a problem with my Gradle and Android Studio. I reinstalled Android studio and Im working with libGDX then when I try to compile my project, the terminal says me that.

FAILURE: Build failed with an exception.

*

*What went wrong:
  Could not create service of type ScriptPluginFactory using BuildScopeServices.createScriptPluginFactory().
  Could not create service of type CrossBuildFileHashCache using BuildSessionScopeServices.createCrossBuildFileHashCache().

*Try:
  Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
BUILD FAILED in 1s
  Failed to create parent directory 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Android Studio.gradle' when creating directory 'C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Android Studio.gradle\4.0\fileHashes'

This error appear with this:

13:19:16: Executing task 'desktop:run'...
Download https://services.gradle.org/distributions/gradle-4.0-bin.zip (67.52M)
  [ 97%] [ =====================================================> ] 66.07M
Download https://services.gradle.org/distributions/gradle-4.0-bin.zip succeeded, took 8s 734ms
  Unzipping ...

My version of Gradle: 4.4
My version of Android Studio: 3.1.2
If you need more information said me to put that.
Thanks!

A: *

*please try to run Android Studio as admin,

*if no result try check and create the path manually

Bests )


text:
Q: Add class and display block on click menu item i have html menu with submenu for ex:

                    Auto

Reno яхту

Audi

When i make mouseover on menu Auto, i need to replace for ul fadeOut to fadeIn and add to style="display:block" and after mouseout add to style="display:none" and to class add fadeOut to ul element?

A: You can try to achieve this only with css and  element+element selector
https://www.w3schools.com/cssref/sel_element_pluss.asp
eg:
.sf-with-ul:hover + .sub-menu {
  display: block;
  opacity: 1;
}

however this might not be the effect you want as the moment you mouse out of anchor element with class sf-with-ul trying to click on some of the sub menu items the whole sub menu will go back to "display:none; state"
maybe better apply this to the whole parent li like
.menu-item.has-children-3:hover .sub-menu {
  display: block;
  opacity: 1;
}


text:
Q: How might i go about making links to images automatically display the image in my chat? Right. So I've created a javascript based chat room, and it works great, but i'd love to implement 2 main things: the ability to have temporary profile pictures (uploaded each time the page is refreshed) to send along with member's messages, and automatically displaying links to images as the image in the chat.
My HTML:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <link href="style.css" rel="stylesheet">

-

-

  <form class="message-form" onsubmit="return false;">
    <input class="message-form__input" placeholder="Type a message.." type="text"/>
    <input class="message-form__button" value="Send" type="submit"/>
  </form>

<h7>MCTC-CHAT</h7>
  <h14>By Cole Chancellor</h14>

My javascript:
const CLIENT_ID = 'V1NQJG9DJAnWZnGd';

const drone = new ScaleDrone(CLIENT_ID, {
  data: { // Will be sent out as clientData via events
    name: window.prompt("Enter your name"),
    color: getRandomColor(),
  },
});

let members = [];

drone.on('open', error => {
  if (error) {
    return console.error(error);
  }
  console.log('Successfully connected to Scaledrone');

  const room = drone.subscribe('observable-room');
  room.on('open', error => {
    if (error) {
      return console.error(error);
    }
    console.log('Successfully joined room');
  });

  room.on('members', m => {
    members = m;
    updateMembersDOM();
  });

  room.on('member_join', member => {
    members.push(member);
    updateMembersDOM();
  });

  room.on('member_leave', ({id}) => {
    const index = members.findIndex(member => member.id === id);
    members.splice(index, 1);
    updateMembersDOM();
  });

  room.on('data', (text, member) => {
    if (member) {
      addMessageToListDOM(text, member);
    } else {
      // Message is from server
    }
  });
});

drone.on('close', event => {
  console.log('Connection was closed', event);
});

drone.on('error', error => {
  console.error(error);
});

function getRandomName() {
  const adjs = ["autumn", "hidden", "bitter", "misty", "silent", "empty", "dry", "dark", "summer", "icy", "delicate", "quiet", "white", "cool", "spring", "winter", "patient", "twilight", "dawn", "crimson", "wispy", "weathered", "blue", "billowing", "broken", "cold", "damp", "falling", "frosty", "green", "long", "late", "lingering", "bold", "little", "morning", "muddy", "old", "red", "rough", "still", "small", "sparkling", "throbbing", "shy", "wandering", "withered", "wild", "black", "young", "holy", "solitary", "fragrant", "aged", "snowy", "proud", "floral", "restless", "divine", "polished", "ancient", "purple", "lively", "nameless"];
  const nouns = ["waterfall", "river", "breeze", "moon", "rain", "wind", "sea", "morning", "snow", "lake", "sunset", "pine", "shadow", "leaf", "dawn", "glitter", "forest", "hill", "cloud", "meadow", "sun", "glade", "bird", "brook", "butterfly", "bush", "dew", "dust", "field", "fire", "flower", "firefly", "feather", "grass", "haze", "mountain", "night", "pond", "darkness", "snowflake", "silence", "sound", "sky", "shape", "surf", "thunder", "violet", "water", "wildflower", "wave", "water", "resonance", "sun", "wood", "dream", "cherry", "tree", "fog", "frost", "voice", "paper", "frog", "smoke", "star"];
  return (
    adjs[Math.floor(Math.random() * adjs.length)] +
    "_" +
    nouns[Math.floor(Math.random() * nouns.length)]
  );
}

function getRandomColor() {
  return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16);
}

//------------- DOM STUFF

const DOM = {
  membersCount: document.querySelector('.members-count'),
  membersList: document.querySelector('.members-list'),
  messages: document.querySelector('.messages'),
  input: document.querySelector('.message-form__input'),
  form: document.querySelector('.message-form'),
};

DOM.form.addEventListener('submit', sendMessage);

function sendMessage() {
  const value = DOM.input.value;
  if (value === '') {
    return;
  }
  DOM.input.value = '';
  drone.publish({
    room: 'observable-room',
    message: value,
  });
}

function createMemberElement(member) {
  const { name, color } = member.clientData;
  const el = document.createElement('div');
  el.appendChild(document.createTextNode(name));
  el.className = 'member';
  el.style.color = color;
  return el;
}

function updateMembersDOM() {
  DOM.membersCount.innerText = `${members.length} users in room:`;
  DOM.membersList.innerHTML = '';
  members.forEach(member =>
    DOM.membersList.appendChild(createMemberElement(member))
  );
}

function createMessageElement(text, member) {
  const el = document.createElement('div');
  el.appendChild(createMemberElement(member));
  el.appendChild(document.createTextNode(text));
  el.className = 'message';
  return el;

}

function addMessageToListDOM(text, member) {
  const el = DOM.messages;
  const wasTop = el.scrollTop === el.scrollHeight - el.clientHeight;
  el.appendChild(createMessageElement(text, member));
  if (wasTop) {
    el.scrollTop = el.scrollHeight - el.clientHeight;
  }
}

my css:
    body {
      box-sizing: border-box;
      margin: auto;
      width: 50%;
      padding: 13px;
      display: flex;
      flex-direction: column;
      max-height: 100vh;
      font-family: serif;

    }

    .members-count,
    .members-list,
    .messages {
      border: 8px solid #BDF0D7;
      padding: 15px;
      margin-bottom: 15px;
      max-width: 350px;
    }

    .messages {
      flex-shrink: 1;
      overflow: auto;
      max-width: 350px;
    }

    .message {
      padding: 5px 0;
      max-width: 350px;
      font-size: 13px;
    }
    .message .member {
      display: inline-block;
      max-width: 350px;
      font-size: 16px;
    }

    .member {
      padding-right: 10px;
      position: relative;
      max-width: 350px;
    }

    .message-form {
      display: flex;
      flex-shrink: 0;
      max-width: 350px;
    }
    .message-form__input {
      flex-grow: 1;
      border: 1px solid #dfdfdf;
      padding: 10px 15px;
      font-size: 10px;
      max-width: 350px;
    }
    .message-form__button {
      margin: 9px;
      max-width: 350px;
    }
    #menu {
    background: #0099CC;
    background: linear-gradient(to bottom,  #0099CC,  #FF99CC);
    color: #FFF;
    height: 45px;
    padding-left: 18px;
    border-radius: 10px;
    border: 5px double #6D6D6D;
}
#menu ul, #menu li {
    margin: 0 auto;
    padding: 0;
    list-style: none
}
#menu ul {
    width: 100%;
}
#menu li {
    float: left;
    display: inline;
    position: relative;
}
#menu a {
    display: block;
    line-height: 35px;
    padding: 0 14px;
    text-decoration: none;
    color: #FFFFFF;
    font-size: 10px;
}
#menu a.dropdown-arrow:after {
    content: "\25BF";
    margin-left: 5px;
}
#menu li a:hover {
    color: #0099CC;
    background: #F2F2F2;
}
#menu input {
    display: none;
    margin: 0;
    padding: 0;
    height: 45px;
    width: 100%;
    opacity: 0;
    cursor: pointer
}
#menu label {
    display: none;
    line-height: 35px;
    text-align: center;
    position: absolute;
    left: 35px
}
#menu label:before {
    font-size: 1.6em;
    content: "\2261";
    margin-left: 20px;
}
#menu ul.sub-menus{
    height: auto;
    overflow: hidden;
    width: 170px;
    background: #444444;
    position: absolute;
    z-index: 99;
    display: none;
}
#menu ul.sub-menus li {
    display: block;
    width: 100%;
}
#menu ul.sub-menus a {
    color: #FFFFFF;
    font-size: 10px;
}
#menu li:hover ul.sub-menus {
    display: block
}
#menu ul.sub-menus a:hover{
    background: #F2F2F2;
    color: #444444;
}
@media screen and (max-width: 800px){
    #menu {position:relative}
    #menu ul {background:#111;position:absolute;top:100%;right:0;left:0;z-index:3;height:auto;display:none}
    #menu ul.sub-menus {width:100%;position:static;}
    #menu ul.sub-menus a {padding-left:30px;}
    #menu li {display:block;float:none;width:auto;}
    #menu input, #menu label {position:absolute;top:0;left:0;display:block}
    #menu input {z-index:4}
    #menu input:checked + label {color:white}
    #menu input:checked + label:before {content:"\00d7"}
    #menu input:checked ~ ul {display:block}
}
.column {
  float: left;
  width: 33.33%;
  column-gap: 25px;
  column-rule: 6px dotted #3366FF;
}
.row:after {
  content: "";
  display: table;
  clear: both;
}
img {
    display: block;
    margin-left: auto;
    margin-right: auto;
    width: 40%;
}
.column {
  float: left;
  width: 33.33%;
}
.row:after {
  content: "";
  display: table;
  clear: both;
}
@media screen and (max-width: 600px) {
  .column {
    width: 100%;
  }
}
.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
  background-color: #f9f9f9;
  min-width: 160px;
  box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
  padding: 12px 16px;
  z-index: 1;
}

.dropdown:hover .dropdown-content {
  display: block;
}
#other {
    color: blue;
    background-color: lightblue;
}
output{
  width: 100%;
  min-height: 150px;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  gap: 15px;
  position: relative;
  border-radius: 5px;
}

output .image{
  height: 150px;
  border-radius: 5px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.15);
  overflow: hidden;
  position: relative;
}

output .image img{
  height: 100%;
  width: 100%;
}

output .image span {
  position: absolute;
  top: -4px;
  right: 4px;
  cursor: pointer;
  font-size: 22px;
  color: white;
}

output .image span:hover {
  opacity: 0.8;
}

output .span--hidden{
  visibility: hidden;
}

my json file:
{
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true
    }
  },
  "rules": {
    "semi": "error",
    "comma-dangle": "off",
    "no-console": "off",
    "keyword-spacing": "warn",
    "max-len": "warn",
    "key-spacing": "error",
    "prefer-const": "error",
    "space-before-function-paren": ["error", "never"],
    "eqeqeq": ["error", "smart"],
    "no-constant-condition": "off",
    "curly": "error",
    "no-var": "warn",
    "object-shorthand": "warn"
  },
  "extends": [
    "eslint:recommended"
  ],
  "env": {
    "browser": true,
    "commonjs": true,
    "es6": true,
    "node": true,
    "jquery": true
  },
  "globals": {
    "ScaleDrone": false,
    "sendMessage": false
  }
}

I've tried a lot of vaguely related solutions online but they're never for the specific issue, and being new to Javascript, I'm unsure how to properly modify them to work.
Edit: the I want the links to display like they would in, say, discord
Edit 2: i've gotten the links to display as images successfully, now i only need help with uploading profile pictures and referencing them there
updated section of code that worked:
function createMessageElement(text, member, myImage) {
 const el = document.createElement('div');
 el.appendChild(createMemberElement(member));
 el.appendChild(document.createTextNode(text));
 el.appendChild(myImage = new Image);
myImage.src = (text);
el.appendChild(document.body.appendChild(myImage));
 el.className = 'message';
 return el;

}

function addMessageToListDOM(text, member, myImage) {
 const el = DOM.messages;
 const wasTop = el.scrollTop === el.scrollHeight - el.clientHeight;
 el.appendChild(createMessageElement(text, member, myImage));
 if (wasTop) {
   el.scrollTop = el.scrollHeight - el.clientHeight;
 }
}


text:
Q: Are 'belie' and 'hide' interchangable?
*

*Her energetic activities in the function belied her old age.

*He could not belie his identity with all the makeover.
Is the usage of belie correct?

A: In those examples, belie and hide are interchangeable because they can share a common meaning of giving a false impression of.
Hide can also mean to conceal (in the sense of giving a false impression). Hide is more the physical act of avoiding being found. For example, the following sentence would not be a synonym of belie.

The boy hides in the bushes.

A: Belie is a verb with two distinct meanings, and one of those has many different senses. Essentially it means "to tell a lie about something". But the sense you are interested in here is OED sense 3c - as follows:

3c. To disguise (a person or thing); to conceal the true character or
  identity of; to conceal the fact of. Chiefly literary.
1610   G. Fletcher Christs Victorie 35   A painted face, belied with
  vermeyl store.
1634   Bp. J. Hall Contempl. Hist. New Test. (STC 12640.7) i. 435   If
  we had been on the Scaffold to see a man challenging the dogs in the
  disguise of a Bears-hide, would we have said, Now two beasts are
  fighting? The Shape therefore may well belie the Substance.
1697   Dryden Alexander's Feast ii. 2   A Dragon's fiery Form bely'd
  the God: Sublime on Radiant Spires He rode.
1725   E. Fenton in Pope et al. tr. Homer Odyssey I. iv. 618   A
  Boar's obscener shape the God belies.
1730   Pope Temple of Fame in Wks. III. 154   His horn'd head bely'd
  the Libian God.
1759   J. Fortescue Diss., Ess. & Disc. I. xxiii   Flow'ry deceit, and
  dark-designing fraud; Hypocrisy, with cherub-face belied, Mask'd
  hatred, quer'lous strife, and envy rude.
1810   A. Cunningham et al. Remains Nithsdale & Galloway Song 280   To
  belie the form of God in the unholy semblance of cats.
1863   M. Oliphant Rector & Doctor's Family viii. 146 in Chrons.
  Carlingford   Spring had begun to show faintly in the lengthening
  days—spring, that so often belies itself, and comes with a serpent's
  tooth.
1970   L. Deighton Bomber (1972) xi. 151   The grimy condition of the
  coasters was belied by the fresh rain that had glossed their decks and
  given their hulls the polish of old jackboots.

A: My impression is that while the second sentence appears to be grammatically sound, it isn't idiomatic:

#He could not belie his identity with all the makeup.

In the usage I've seen, the object of belie is never a person, but rather a thing, a concept, or an attribute.  For example, we have (from this article)

[H]is actions in the following weeks belied his apology.

which has the meaning "his actions in the following weeks made his apology seem to be a lie."  However, the sentences

#He belied his apology with his actions in the following weeks.
#He belied his apology by his actions in the following weeks.

do not seem like something an American English speaker would say.
That said, I have been unable to find a citation describing this usage, so it's possible that I'm off-base.  I will report back if I find anything definitive.


text:
Q: Python concatenate arrays based on information from a list I have a list with about 500 elements in it. For illustration I have:
list3 = [ 'a', 'b', 'c', 'a' ]

Where 'a', 'b', 'c' is name of the arrays as:
a = np.random.normal( 0, 1, ( 500, 20 ) )
b = np.random.normal( 0, 1, ( 500, 30 ) )
c = np.random.normal( 0, 1, ( 500, 30 ) )

I want to concatenate the arrays in the list in the order present in the list.
So, for my example I want to obtain:
C = np.concatenate( ( a, b, c, a ), 1 )

I don't have an idea how to approach this other than to store the arrays in a dictionary and then do a string search and concatenation in a for loop. Is there an elegant way to do this ?

A: If you want to be compact:
np.concatenate([dict(a=a, b=b, c=c)[x] for x in list3], 1)

Or to avoid the redundant dictionary creation:
by_label = dict(a=a, b=b, c=c)
np.concatenate([by_label[x] for x in list3], 1)

A: You can use the globals object to get the arrays based on name.
globals()["a"] # array a

So can do
np.concatenate(tuple(globals()[x] for x in list3),1)

A: You can use the locals() dictionary to access the variables by name
d = locals()
np.concatenate([d[x] for x in list3], 1)

A: You can easily get such a dictionary of all local variables by calling the locals() function. For example, to look up a variable named 'a':
var = 'a'
locals()[var]

Since np.concatenate appears to take a tuple, you could use:
lc = locals()
C = np.concatenate(tuple(lc[var] for var in list3), 1)

A: Why don't you store directly the variables instead of their names ?
Like :
list3 = [a, b, c, a]
C = np.concatenate(list3, axis=1)

Or you can use eval() (which don't seems to be recommanded most of the time) :
list3 = ['a', 'b', 'c','a']
CC = np.concatenate([eval(i) for i in list3], axis=1)


text:
Q: iOS React 16.8.0 site not loading anchored to the top of the page When loading my React 16.8.0 site on an iOS device, it is not anchored to the top when it renders the first time.  Every other page is scrolled to the top and even after you logout and navigate back to the homepage.
My developer believes there is an issue with the react-helmet package we are using.
React 16.8.0
React-router-dom 5.2.0
Site: newlifeame.faithmo.com
Tried using a ScrollToTop javascript element to handle this.
Scroll to top


text:
Q: How to properly add a break in JSX file for displaymessage? handleNotFound() {
    this.setState({
        displayMessage:
            'It looks like the link you are trying to reach does not exist.\n      ' +

            'If you clicked this link , please leave a comment within the article that contained the link so the author can be notified.\n       ' +

            'If you clicked this link from a location outside of __, please contact the _to open a ticket with the application where this link is referenced .\n      ' +

            'The link you were trying to reach:     ' +
            url
    });

The display message ends up coming out in one sentence, how do i properly add a break between each sentence?

A: handleNotFound() {
    this.setState({
        displayMessage: `
          something went wrong.
          I think you should use html tags
          to render your error message if it is in the dom
        `
    });

// Jsx won't break your paragraphs but you have two options

*

*Wrap the displayMessage in pre tag.
`{this.state.displayMessage}

*Split, map & trim the string.
render(){
  return this.state.displayMessage.split("\n").map(sentence => (

{sentence.trim()}

  ))

}

A: For things like standard messages I would be more inclined to have them in a configuration file rather than state. The config file can include anything: objects, arrays, functions that return arrays...
The latter is what I've used in this code because you need to fill out the url at some point. The function accepts a url argument, and fills that out when the array is returned. You can then map over the array and display each line.

const { Component } = React;

const config = {
  displayMessage: function (url) {
    return [
      'It looks like the link you are trying to reach does not exist.',
      'If you clicked this link , please leave a comment within the article that contained the link so the author can be notified.',
      'If you clicked this link from a location outside of __, please contact the _to open a ticket with the application where this link is referenced.',
      `The link you were trying to reach: ${url}`
    ]
  }
}

class Example extends Component {

  constructor() {
    super();
    this.url = 'http://www.google.com';
  }

  render() {
    return (

        {config.displayMessage(this.url).map(line => {
          return
{line}
;
        })}

    );
  }

};

ReactDOM.render(
  <Example />,
  document.getElementById('react')
);


text:
Q: Loop through string get key and value using regex key matches Javascript I have a string like
> var temp =
> "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green),"

For information, this string is generated automatically by kibana (I recover it through the url).
My question is :
There is any solutions to extract keys and values from this string and get a result in a array or an object like this :
>  var result = {
>                  "alias" : "!n",
>                  "apply" : "!t",
>                  "disabled" : "!f",
>                  "key": "stockInfo.raw",
>                  "negate": "!f",
>                  "value": "green",
>               }

Thanks

A: I think you're searching something like this:

var meta = "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green),"

var result = {}

meta.substr(0, meta.length - 2).substr(5).split(',').forEach(function(item) {
  var split = item && item.split(':')
  if (split.length) {
    result[split[0]] = split[1];
  }
})

console.log(result)

Split the string by , character and then split by : to identify key and value of object

A: same as other but with some es6 syntax :D

const result = document.getElementById("result");
const input = document.getElementById("input");

// string: data from url, return only the portion from the parenthesis
const extract_meta_values = string => {
 const EXTRACTOR = /^meta\(([^\)]+)\)/g;
 return EXTRACTOR.exec(string)[1];
}

// string: is a string of key:values separated by a comma
const meta_values_to_array_of_objects = string => string.split(',').map( tuple => {
  const [key, value] = tuple.split(':');
  return { [key]: value };
});

const meta_values = extract_meta_values(input.value);
const final = meta_values_to_array_of_objects(meta_values);

// print out
result.innerText = JSON.stringify(final, null, 2);
pre {
  display: block;
  border: 1px solid darkgray;
}

<input value="meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green)," id=input />

A: Substring to within parenthesis, split by comma, loop through, split by colon and add to an object.

var temp = "meta(alias:!n,apply:!t,disabled:!f,index:'index_*',key:stockInfo.raw,negate:!f,value:green)";
var t = {};
temp
  .substr(temp.indexOf("(") + 1, temp.indexOf(")") - temp.indexOf("(") - 1)
  .split(",")
  .forEach(function(a) {
    var b = a.split(":");
    t[b[0]] = b[1];
  });
console.log(t);


text:
Q: SubSonic 3.0.0.3 | SimpleRepository | saving byte[] to varbinary I have a Model, with a property of type byte[], with corresponding field equivalent on SQL Server of type varbinary(128).
Saving went well. but the problem is my password field is always NULL.
guser.Password = Encoding.ASCII.GetBytes("sample");
repo.Add(guser);

Is this a bug or a user error?


text:
Q: ValueError: If your data is in the form of symbolic tensors, you cannot use `validation_split`                 images = images / 255.0

                model = tf.keras.Sequential([
                keras.layers.InputLayer(input_shape=(227, 227, 3)),
                keras.layers.Conv2D(96, [7, 7], [4, 4], data_format='channels_last'),
                keras.layers.MaxPooling2D(pool_size=(3, 2), padding="same"),
                keras.layers.Conv2D(2566, [5, 5], [1, 1], data_format='channels_last'),
                keras.layers.MaxPooling2D(pool_size=(3, 2), padding='same'),
                keras.layers.Conv2D(384, [3, 3], [1, 1], data_format='channels_last'),
                keras.layers.MaxPooling2D(pool_size=(3, 2), padding='same'),
                keras.layers.Flatten(),
                keras.layers.Dense(512),
                keras.layers.Dropout(1 - pkeep),
                keras.layers.Dense(512),
                keras.layers.Dropout(1 - pkeep),
                ])

                prune_low_magnitude = tfmot.sparsity.keras.prune_low_magnitude

                batch_size = 128
                epochs = 2

                # Compute end step to finish pruning after 2 epochs.

                validation_split = 0.1 # 10% of training set will be used for validation set.

                num_images = int(images.shape[0]) * (1 - validation_split)
                end_step = np.ceil(num_images / batch_size).astype(np.int32) * epochs

                # Define model for pruning.
                pruning_params = {
                      'pruning_schedule': tfmot.sparsity.keras.PolynomialDecay(initial_sparsity=0.50,
                                                                               final_sparsity=0.80,
                                                                               begin_step=0,
                                                                               end_step=end_step)
                }

                model_for_pruning = prune_low_magnitude(model, **pruning_params)

                # `prune_low_magnitude` requires a recompile.
                model_for_pruning.compile(optimizer='Adadelta',
                              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
                              metrics=['accuracy'])

                model_for_pruning.summary()

                callbacks = [
                  tfmot.sparsity.keras.UpdatePruningStep(),
                ]

                model_for_pruning.fit(images,
                  batch_size=batch_size, epochs=epochs, validation_split=validation_split, steps_per_epoch=100,
                  callbacks=callbacks)

        with tf.variable_scope('output') as scope:

            weights = tf.Variable(tf.random_normal([512, nlabels], mean=0.0, stddev=0.01), name='weights')
            biases = tf.Variable(tf.constant(0.0, shape=[nlabels], dtype=tf.float32), name='biases')
            output = tf.add(tf.matmul(model.output, weights), biases, name=scope.name)

        return output

How do I fix images so it's not a symbolic tensor? Images is a tensor input for the preprocessed image size, with the input images being from the Adience benchmark.
The error says I can't use validation_split with a symbolic tensor. I tried converting the symbolic tensor to a variable and a numpy array, but the program still throws that the input images is a symbolic tensor.
Python 3.7
Keras 2.2.3
Tensorflow 1.14.0


text:
Q: List Client Side Printers How to list a client side printer in asp.net using c#?
My code: This will list the printers connected to the server.
ManagementScope scope = new ManagementScope(@"\root\cimv2");
scope.Connect();
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");
foreach (ManagementObject printer in searcher.Get())
{
    string printerName = printer["Name"].ToString().ToLower();
    Response.Write("chethann            ");
    Response.Write(printerName);
}

A: PrinterInformation info = new PrinterInformation();
var printers = info.GetPrinters();
foreach (var printer in printers)
{
Response.Write(string.Format("Machine Name : {0} - Printer Name: {1}", Environment.MachineName, printer.DeviceName));
}


text:
Q: chrome extension chome.tabs.onUpdate running twice? //In background.js
chrome.tabs.onUpdated.addListener(function(tabid, info, tab) {
    console.log(info);
});

I'm try to set it up so onUpdate runs once every time a youtube video page loads. I want wait for load after a youtube video loads. When I load directly from a url I get what I expect, but when I navigate to a suggested video, there are 2 loading/complete cycles. One for the current video, One for the next video.

This is the output for a direct url youtube video.

This is what happens if I navigate to a youtube video while watching another youtube video.
In my manifest I have a simple background.js script, permission for webNaviagtion and Tabs.
I don't know why it's running twice.

A: tabs.onUpdated is invoked for each frame/iframe, the Youtube watch page loads one.
webNavigation API provides frameId to the event listeners, the main page has frameId == 0.
Note that Youtube doesn't reload the page when the user goes from one video to another or from the main Youtube page to a video page so to detect these changes you may use chrome.webNavigation.onHistoryStateUpdated event listener or a content script that will listen to the DOM events used by the site, namely "spfdone".


text:
Q: jQuery Mobile data-role=page within a data-role=page I have a parent div with data-role="page" and its content has its own data-role="page" as well. Is it possible to navigate within the content area's data-role="page" without making the parent div navigate?
For example,

title goes here

 content goes here

 content goes here

Basically I want to navigate only between #content_1 and #content_2 while #main will just stay put/remain as well as the Title.

A: Perhaps just hide/show the 2 subpage divs via jQuery based on your particular page logic i.e. on click or some other event $('#content_1').toggle(); $('#content_2').toggle(); remember to also add #content_2{display:none;} as CSS to begin with.
Also, if you want the native transitions etc that you get with loading between normal pages you shoudl consider the plugin/widget found here https://github.com/ToddThomson/jQuery-Mobile-Subpage-Widget


text:
Q: partman configuration in preseed.cfg to ignore multiple drive warning I can't find the parameter that could ignore the "multiple disks found" warning. This is what my partman part looks like:
d-i partman-auto/disk string /dev/sdb
d-i partman-auto/purge_lvm_from_device boolean true
d-i partman-auto/method string lvm
d-i partman-lvm/device_remove_lvm boolean true
d-i partman-md/device_remove_md boolean true
d-i partman-lvm/confirm boolean true
d-i partman-partitioning/confirm_write_new_label boolean true
d-i partman/choose_partition select finish
d-i partman/confirm boolean true

The goal is to create the LVM partitions on /dev/sdb whithout raising any warnings. Do I have an order problem or something?

A: To answer to myself,
I've looked through the /var/og/installer/cdebconf/questions.dat file after a handmade install
It's a pretty useful file and all the question you ever asked is inside this file.
I Just had to had the question that was bothering me (a note type) and that was good to go

A: Seems that, at least in Jessie, the path of this file changed to /var/lib/cdebconf/questions.dat


text:
Q: Can't install software or perform Windows Updates For the last long while Windows Update has been failing on 99% of updates and (certain) software won't install. I have seen the error 0x8007010B in both cases. Why is this happening? How can it be fixed? I've searched all over for answers but I haven't gotten anywhere. I am using 32-bit Vista SP2.
Update:
I found this really helpful looking page http://support.microsoft.com/fixit/ and downloaded a thing to fix windows updates and it said it found an issue where the location for updates had been changed and it said it fixed it but updates still don't work.

A: The error, 0x8007010B, is caused by the file directory being invalid. Locate and download the update or updates directly from Microsoft's Download Center. After you download the update or updates follow the steps below. (Credit: MowGreen's Post)
Perform a clean boot of the computer and then install the update
To manually perform a clean boot of your computer in Windows 2000, Windows XP, or Windows   Server 2003, follow these steps:

*

*Click Start, click Run, type msconfig, and then click OK.

*On the General tab, click Selective Startup, and then click to clear the following       check boxes:

*

*Process SYSTEM.INI File

*Process WIN.INI File

*Load Startup Items

*On the Services tab, click to select the Hide All Microsoft Services check box, and then click Disable All.

*Click OK, and then click Restart to restart your computer.

*Run Microsoft Update or Windows Update. If the update does not run successfully, go to Method 4.

Note: You'll find more information on this topic and the source at this Microsoft Support page.

A: Error 0X8007010b is caused by damaged windows files or broken system structures. This is a critical problem that can cause an unstable operating system, which is typically caused by improper management of the computer.
Use Windows Repair tool to diagnose and fix the cause of your problem.
1: Download and install the tool.
2: Open it and scan the PC for problems.
3: Click on fix all Button.
Hope it will help you.


text:
Q: c4458 warning - how to find which variable is used I need to port an old project to the latest visual studio but it has some very awful code in it that I don't know how to resolve.
if have this function:
void CBuffer::AddData( LPBYTE lpData, u_long uDataSize, u_long &uRemnant )
{
    int cb;
    LPBYTE ptr  = GetWritableBuffer( (int *)&cb );

    cb  = ( cb < uRemnant? cb: uRemnant );
    ASSERT( ptr + cb <= m_lpBufMax );
    memcpy( (void*)ptr, &lpData[uDataSize - uRemnant], cb );
    m_pTail = ptr + cb;
    uRemnant    -= cb;
}

which prompts
buffer.cpp(90): warning C4458: declaration of 'cb' hides class member

here int cb overwrite u_long cb defined by the class CBuffer.
Is there a way to tell which cb should be used after this?
LPBYTE ptr  = GetWritableBuffer( (int *)&cb );

A: Local variables always shadow class member variables or global variables. So, in this method, always the local variable int cb is used.


text:
Q: Automatically create matching braces in vim How do I automatically create matching braces in vim?
It should work as follows: If I input an open brace the closing one should
appear automatically and the cursor should be placed in between. To jump out
of the brace pair the combination Ctrl-j is used.
There are plenty of plugins providing automatic brace insertion. But they

*

*either use a different key combination than Ctrl-j to jump out of the brace pair or

*interfere with the UltiSnips key
bindings.

The following works as expected
:inoremap ( ()<Esc>:let leavechar=")"<CR>i
:imap <C-j> <Esc>:exec "normal f" . leavechar<CR>a

But with these settings the UltiSnips snippets don't work any more. So I used
UltiSnips to insert the closing brace:
inoremap ( (<C-R>=UltiSnips_Anon('($1)$0', '(')<CR>

This almost works. The matching brace is inserted and I can skip the closing
one with Ctrl-j. This, however, works only if there is a space in
front of the open brace.
main () // works, the closing parentheses is added
main(   // fails without a space

My solutions either require a different key binding to jump over the closing
brace or require a space in front of the open one. How to fix this?
Note: I used parentheses as an example. It should work with parentheses,
braces, brackets and less-than signs and not interfere with the UltiSnips
plugin.

A:
How do I automatically create matching braces in vim?

This problem is non-trivial, as you will see. The simple answer is: Use a plugin, like autoclose or smartinput. Just naively remapping the ( [ .. keys will present you with edgecases in a couple of lines, that is why these plugins are made, and why they usually are quite complex (if they are any good).

So I used UltiSnips to insert the closing brace

You could try this instead (which is different from my original suggestion):
inoremap ( ()<CR>=UltiSnips_Anon('$1)$0', ')')<CR>

Where UltiSnips will split the line on ( instead of including main in the match. The problem with using a snippet plugin for this is that they (usually) don't support nesting, so they will forget any jump positions when the next (nested) snippet is inserted.

To jump out of the brace pair the combination Ctrl-j is used.

You can remap Ctrl-j for either UltiSnips or the conflicting plugin. If the mappings are not listed in the documentation, you can use :map/imap/nmap <key> to show the mapping. If you want Ctrl-j to pick and choose and do the work of both plugins, you are asking for:

*

*something a lot more advanced than I suspect you might think

*something I suspect you do not really want

Consider this bash loop:
while (( ${arr1[i]} < ${arr2[i<CURSOR>]} )); do
  [next_snippet_position_marker]
done

In this case, you'll need to press Ctrl-j 5 times to get to the loop body. Using the closing braces to jump out of a corresponding pair gives you much more control of where you actually want the cursor to move. You could implement a stack to keep track of inserted pairs and use Ctrl-j to pop and move, but then you'll run into problems if you start manually deleting braces without removing them from the stack. So you'll start solving problems which the brace-plugins are trying to solve. This is a hard wheel to reinvent.
Expanding on this, you can get what you initially asked for, using Ctrl-j to jump out of braces and snippets. If you use some dummy value to represent snippets positions and push them onto the stack in addition to the closing braces, with dynamic remapping of Ctrl-j to correspond to handing of snippets or braces. But then you'll need to implement some fairly advanced heuristics to figure out what magic should happen, since you are essentially taking on two problems at once, which is currently being solved by the creators of snippet insertion plugins and brace matching plugins separately, and re-solving these problems again, on top of their solutions, to achieve convenience and, well, magic.
It comes down to control vs convenience. I think control will serve you better in this case, meaning you should keep these problems and their associated plugins and keysmappings separate. If you still want convenience, it's doable, but it's hard.

A: Personally I use smartinput for auto insertion of brackets and quotes. For example typing { anywhere will produce {} with your cursor in the middle. To leave the { bracket group you just type the } when next to the inserted }.
However this does support your requirement of tabstops and jumping to outside the bracket. It also does not create a new between your brackets, but you just need one extra key for that anyway - <CR>.
You could map <C-J> to jump to the next line down:
:inoremap <C-J> <C-O>j

or if you wanted to move to the start of the next line:
:inoremap <C-J> <C-O>+

A: I have found autoclose adding a bit of lag, and also interfering with my setup (Ultisnips and Supertab), but I like its approach of emulating Eclipse CDT.
I use delimitMate with the following maps to help with the navigation and indentation, trying to get the same results:
imap <C-F> <C-G>g           " To jump out brackets in same line.
inoremap <C-K> <ESC>ki<TAB> " To move and insert an indent on the line before the current cursor (assuming empty line)

I use it this way: insert opening { <CR><CR><C-K> and start writing in the indented inner line.

A: Something like this might work out for you.
inoremap {      {}<Left>
inoremap {<CR>  {<CR>}<Esc>O
inoremap {{     {
inoremap {}     {}

A: I think delimitMate does what you need.
It automatically closes parentheses or quotes and puts your cursor in between.
To jump out of a parentheses pair (while being in insert mode) you'd do Ctrl-g + g but you can remap this to be Ctrl-j by adding this to your vimrc:
% Jump out of a block of parentheses (uses delimitMate)
imap <C-j> <C-g>g

A: Actually, Ultisnips can do it almost perfectly (this may be new). Slightly modifying answers given above, I have good success with
inoremap () ()<C-R>=UltiSnips#Anon('($1)$0', '()', 'double parentheses', 'i')<CR>
One has to type () which find better but that can be changed to ( as well. Then, the additional optional arguments to UltiSnips#Anon are a description and the modifier i which allows in-word expansion.
Jumping out of the parentheses with <c-j> works, also nested within other snippets. However, invoking nested () parentheses seems to break this feature, which is not a big deal.


text:
Q: Problems with sign in with Rails 4, Devise and CanCan I'm pretty new to Rails and Devise.  I'm having problems signing in/up.  When trying to signin, I get the following error:
ActiveRecord::RecordNotFound in UsersController#show
Couldn't find User with 'id'=sign_in

The show action in Users Controller is the following:
def show
  authorize! :show, current_user
  render 'profile_page'
end

Any help would be greatly appreciated.
Here's my route.rb:
    Rails.application.routes.draw do
get 'users/:id' => 'users#show'
resources :users
get 'users/edit'

controller :static_pages do
  get :home
  get 'show' =>'users/show'
end

resources :posts do
  resources :comments
end
scope '(:locale)' do
  resources :posts
end

devise_for :users do
 get '/users/sign_out' => 'devise/sessions#destroy', :as => :destroy_user_session
 get 'users/:id' => 'users#show'
end

authenticated :user do
   root :to => 'posts#index', as: :authenticated_root
end

resources :contacts, only: [:new, :create] do
  root :to => 'static_pages#home'
end

controller :static_pages do
  get :home
  get 'about' =>'static_pages#about'
  get 'about_class' => 'static_pages#about_class'
  get 'schedule_class' =>'static_pages#schedule_class'
end

end

A: Rails is looking for users/:id likely with the users#show action when you are probably entering users/sign_in into your browser. Your routes need to be adjusted.


text:
Q: Passing dynamic data to javascript It is good idea not to hardcode anything that may change in javascript. For example I want to have url generated by php.
I may write
echo "
<script ...>
    var anUrl = $urlFromPHP;
</script>";

and then:
<script ...>
    // some code
    $.ajax({ url: anUrl ... });
</script>";

Is there any better way to do it? Does anybody know if there is any built-in mechanism in yii framework?

A: I personally like the conversion between php variables (arrays,...) to javascript object by json_encode. It is easy to use for complex arrays for example.
<?php
// From manual:
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);

echo json_encode($arr);
?>
// results
{"a":1,"b":2,"c":3,"d":4,"e":5}

A: That's a perfectly good way to do it. Although you'll probably need quotes around the javascript url string:
var anUrl = '$urlFromPHP';


text:
Q: JavaScript IntelliSense with Reference Path in Visual Studio 2019 no more working As I noticed, IntelliSense with "Reference Path"-File comment's are no longer supported in Visual Studio 2019. We recently switched from 2017 to Version 2019.
Reference Path example: /// <reference path="../Messages.js" />
Unfortunately, my Team and I working still a lot with plain JavaScript files.
Is there any chance to enable the old IntelliSense behavior?


text:
Q: Remove ONLY the childrens with LINQ to SQL? I want to delete ONLY the childrens of an item selected in a datagridview with LINQ to SQL and it doesn't work. I don't know if it's possible to do this. I don't know how to proceed, can you please check at my code and tell me what I do wrong?
Here's my code :
private void cmdSupprimer_Click(object sender, EventArgs e)
{
    try
    {
        var catAct = (from catA in tbCategories.Categories
                               where catA.CategorieID == (int)dgCategories.Rows[0].Cells[0].Value
                               select catA).Single();

        for (int i = 0; i < catAct.Jeuxes.Count(); i++)
        {
            for (int j = 0; j < catAct.Jeuxes[i].Personnages.Count(); j++)
            {
                tbPersos.Personnages.DeleteOnSubmit(catAct.Jeuxes[i].Personnages[j]);
            }
            tbJeux.Jeuxes.DeleteOnSubmit(catAct.Jeuxes[i]);
        }
        tbCategories.Categories.DeleteOnSubmit(catAct);

        tbCategories.SubmitChanges();

        dgCategories.DataSource = null;
        dgCategories.DataSource = (from cats in tbCategories.Categories
                                   select new CategorieDisplay()
                                   {
                                       CategoryID = cats.CategorieID,
                                       CategoryNom = cats.CategorieNom
                                   }).ToList();

        MessageBox.Show("Les enfants de cette catégorie ont été supprimés");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

A: Make your datasource a variable called data.  Then you can delete rows from the data and the datagridview will also get updated.
var data = (from cats in tbCategories.Categories
                                   select new CategorieDisplay()
                                   {
                                       CategoryID = cats.CategorieID,
                                       CategoryNom = cats.CategorieNom
                                   }).ToList();

dgCategories.DataSource = data;


text:
Q: Adding shadow to UIView that is positioned using SnapKit I have positioned a UIView using SnapKit and need to find a way to add a shadow. Because I positioned the view relative to other UIViews, I do not have the height, width, or starting coordinate of the view. How can I add a shadow to this UIView positioned using SnapKit auto layout. The code to position the UIView is this:
tableViewBackground.snp.makeConstraints{ (make) -> Void in
        make.width.lessThanOrEqualToSuperview()
        make.height.lessThanOrEqualToSuperview()
        make.right.equalToSuperview().offset(-20)
        make.left.equalToSuperview().offset(20)
        make.bottom.equalToSuperview().offset(-20)
        make.top.equalTo(poiLabel.snp.bottom).offset(20)
}

A: Moved the creation of the shadow layer from viewDidLoad to viewDidLayoutSubviews


text:
Q: How to disable the new debug window in VS2017 I'm using Visual Studio 2017 RC and getting very frustrated with the new Chrome window that pops up when you click Debug.
Issues with the Debug Chrome Window:

*

*Takes ages to start/"attach" website (I think it's attaching all the javascript debugging which I don't need because I use Chrome DevTools for that anyway)

*Not dockable (as a tab) with other Chrome windows

*Doesn't remember form history. If I'm testing out forms I can't autocomplete form data, so I have to type the whole lot out every time

*Doesn't remember url history. If I'm testing a specific page on my site, I can't quickly select the url from Chrome url bar dropdown. Have to type the url in full

*Extensions aren't enabled so I can't use my ruler or color picker extensions

*Chrome window closes when debugging stops so I have to open up a new window to keep browsing the local site

Does anyone know how to disable this new Debug style window and go back to how it was in VS 2015?

A: In VS menu click:
Tools > Options > search for "browser projects" > untick the last option "Stop debugger when browser window is closed.
this will do the job.

A: For thoose, who have the 15.7 update and unchecking the JavaScript options doesn't do the trick, found a solution here:
https://blogs.msdn.microsoft.com/webdev/2016/11/21/client-side-debugging-of-asp-net-projects-in-google-chrome/
Tools > Options > Projects and Solutions > Web Projects, uncheck "Stop debugger when browser window is closed"

A: This is not an issue, rather a new feature in VS 2017. Previously we could only debug JS and TypeScript using IE in debug mode (of VS). But now they have introduced debugging JS and TS inside VS using Remote Debugging feature of Chrome. If you are running your application in debug mode (pressing F5) and Chrome is selected browser, Visual studio 2017 will try to open a remote debugging session with Chrome on a dedicated port. With remote debugging,

*

*The browser is launched in plain mode, i.e. no extension and no history etc. Remote debuggin doesnt work with an existing instance of Chrome already running.

*You always see this window for a while. At this point, VS is trying to attach the remote debugger to VS

*To go back to VS 2015 experience of debugging, change the debugging target from Chrome to IIS Express.

This post describes this feature in detail. https://blogs.msdn.microsoft.com/webdev/2016/11/21/client-side-debugging-of-asp-net-projects-in-google-chrome/

A kind of quick work around is to press F5 and launch the debug
  session and forget about the newly opened Chrome window. Go to your
  normal Chrome instance and just open your site in new tab. You will
  still be able to debug and do everything because IIS Express will
  still be running your app at that port.

Update:
The answer given below by @Steveadoo is the right way going forward. The option shown in his screenshot controls how chrome is launched for debugging. Uncheck it if you want to stick to your regular Chrome instance.
Hope this helps.

A: Debug > Options > Debugging > General > (uncheck) Enable JavaScript debugging for ASP.Net (Chrome and IE).
Tools > Options > Projects and Solutions > Web Projects, uncheck "Stop debugger when browser window is closed"
works for me, visual studio professional 2017, v 15.7.3

A: I'm not sure if this came with the latest VS 2017 Update, but inside Debug -> Options you can disable it now.
Just uncheck the highlighted one:

A: For VS 2017, Go to Tools -> Options -> Projects and solutions-> web projects and uncheck the last option as shown in image.
Also you can refer here: https://www.johanbostrom.se/blog/how-to-disable-the-built-in-chrome-from-starting-when-debugging-in-visual-studio-2017

A: Here is the Microsoft blog about this new functionality, and how to revert.
https://blogs.msdn.microsoft.com/webdev/2016/11/21/client-side-debugging-of-asp-net-projects-in-google-chrome/
Here is the path I followed to disable:
Debug > Options > Debugging > General > (uncheck) Enable JavaScript debugging for ASP.Net (Chrome and IE).

A: I'm using Visual Studio 2017, and what worked for me is a combination of these two options:

*

*Disable JavaScript debugging in Debug -> Options -> Debugging -> General Enable JavaScript debugging for ASP.Net.

*Disable stop debugging when browser is closed in Debug -> Options -> Projects and Solutions -> Web Projects -> Stop debugger when browser windows is closed, close browser when debugging stops.

When I used only one of these two it did not work.

A: if you look to JavaScript case
For Enabling and Disabling JavaScript Debugging in VisualStudio is the same on all versions

*

*Tools menu

*Options...

*Debugging -> General

*Uncheck "Enable JavaScript debugging for ASP.NET"

A: In Visual Studio 2017:

If it prompts you again to turn JS debugger on again, choose another option (It will continue to prompt you if you have breakpoints in your script code):


text:
Q: python prime numbers in one liner Do you think this is the kind of fastest way to get the prime numbers below the specified number in one liner:
[p for p in xrange(3,1000000) if p%2 != 0 and 0 not in (p%d for d in xrange(3,int(p**0.5)+1))]

A: I think that lines are cheap, and that you should write readable code, on multiple lines where necessary.
In this case, it's necessary. Also, if you need to use this for anything other than a Project Euler problem, you should use a Prime sieve found in a library.

A: You're confusing compact code with efficient code. There are ways to increase the efficiency of the above code, but it won't matter if you do it in one line or in 10 lines. Python compiles the human readable code to bytecode before execution. You have no control over how many bytecode instructions your code is converted to.
It's true that list comprehensions are generally faster than for loops but not universally true. It's also generally true that using implied loops such as map() are usually faster.  The timeit and dis modules are your friends. That way, you can find out for yourself whether a certain piece of code is faster than another.
Premature optimization is foolishness. Identify the bottlenecks in your code before you start tinkering. Can  you identify which part of the above code is likely to be slowing it down the most?

A: Yeah yeah yeah, you shouldn't do this in one line. For reasons. But I like a good challenge.
Here's what I came up with as a one liner, that is 'reasonably' fast. Its a wonderfully convoluted mess, but it works. It can be 'shorter', but I found that the 'if step%3 or step==3' actually sped things up by eliminating a third of the work.. And using set comprehensions.. If you don't care if the list is sorted, you can shave some by removing the sorted() call.
[2] + sorted(set(xrange(3,max,2)) - { x for step in xrange(3, int(max**0.5) + 1, 2) if step %3 or step==3 for x in xrange(step * 3, max, step * 2)} )

A: Was wondering the same... Why not just:
[2] + [x for x in xrange(3,max,2) if not [y for y in xrange(3,int(x**0.5)+1,2) if x%y==0]]


text:
Q: Order attribute names in xml using t-sql I need to order attribute names in alphabetic order and I've created following code, but it left xml as it is:
DECLARE @xml XML = N'<tt>
       <cpost s="a" cena="0.0000" cpost_id="16385" flprt="1" moq="0"
    valuta_id="2" nmatr_id="14117" norg_id="1791" />

       </tt>'

    SELECT
        t.query('.')
    FROM @xml.nodes('*/*') AS t(t)
    ORDER BY t.value('local-name(.)','nvarchar(max)')
    FOR XML PATH(''), TYPE, ROOT('tt')

Where did I make mistake?

A: Not pretty, but this is where my thinking takes me.
dbFiddle
Example
DECLARE @xml XML = N'
<tt>
    <cpost s="a" cena="0.0000" cpost_id="16385" flprt="1" moq="0" valuta_id="2" nmatr_id="14117" norg_id="1791" />
</tt>'

Declare @S varchar(max) = ''

Select @S = @S + concat(Item,'="',Value,'" ')
 From (
        Select Top 1000
               Item   = attr.value('local-name(.)','varchar(100)')
              ,Value  = attr.value('.','varchar(max)')
         From  @XML.nodes('/tt/cpost') as A(r)
         Cross Apply A.r.nodes('./@*') AS B(attr)
         Order By attr.value('local-name(.)','varchar(100)')
      ) A

Select convert(xml,'<tt><cpost '+@S+'/></tt>')

Returns
<tt>
  <cpost cena="0.0000" cpost_id="16385" flprt="1" moq="0" nmatr_id="14117" norg_id="1791" s="a" valuta_id="2" />
</tt>

EDIT - Added an In-Line Approach

DECLARE @xml XML = N'
<tt>
    <cpost s="a" cena="0.0000" cpost_id="16385" flprt="1" moq="0" valuta_id="2" nmatr_id="14117" norg_id="1791" />
</tt>'

Select convert(xml,'<tt><cpost '+Stuff((Select  ' ' +concat(Item,'="',Value,'" ')
 From (
        Select Top 1000
               Item   = attr.value('local-name(.)','varchar(100)')
              ,Value  = attr.value('.','varchar(max)')
         From  @XML.nodes('/tt/cpost') as A(r)
         Cross Apply A.r.nodes('./@*') AS B(attr)
         Order By attr.value('local-name(.)','varchar(100)')
      ) A
 For XML Path ('')),1,1,'') +'/></tt>')


text:
Q: How to append values to ES6 Map I am trying to learn about ES6 Map data structures and am having difficulty understanding some of their behaviour. I would like to create a Map with an Array as a value and append (push) new values onto the current value of the Map. For example:
let m = new Map()

m.set(1, []) // []

m.set(1, m.get(1).push(2)) // [[1, 1]]

I am confused as to why I do not get [2] as the value of m.get(1) above. How can I append values to the array in my map?

A: That's because the method push returns the size of the array after the insertion.
You can change your code to the following to append to an array:
m.get(1).push(2);
And it'll update the value in the map, there's no need to try to re-set the value again as the value is passed back as reference.

A: The best way to define a Map according to your need is to explicitly tell the Map, what kind of data you want to deal with.
in your case you want values in an array, we could get using a "string id" for example
In this case you will have this :
let map = new Map<String, Array<any>>

Then you can create items like map["key"] = ["lol", 1, null]

A: There is two thing. First as @Adriani6 said the push method do not returns a pointer to the array but the size of the array.
Secondly, you do not need to do an other m.set, because your push will affect directly the array behind the reference returned by m.get

function displayMap(m) {
  m.forEach(function(val, key) {
    console.log(key + " => " + val);
  });
}

let m = new Map();

m.set(1, []);

displayMap(m);

m.get(1).push(20);

displayMap(m);

A: It fails, because the return of push() is the size of the array after push.

*

*You can push the content after doing a get().
m.get(1).push(2);

*If you want to test set() then write a a self executable function like this:

let m = new Map()

m.set(1, []) // []

console.log(m.get(1))

m.set(1, (() => {m.get(1).push(2);return m.get(1);})());

console.log(m.get(1))

A: Here's a working example of what you are trying to do (open console)
Have a look here. As you can see the push method returns the new length of the array you just mutated, hence your result.


text:
Q: XAML errors using an assembly name different from the namespace I have a project with the Namespace: Product.Main and the Assembly: Product
In XAML, I have: xmlns:local="clr-namespace:Product.Main"
Everything works fine when both Namespace and Assembly are the same.  When they are different, and I go to the XAML designer, everytime I call local: I get an error:
The name "ContentView" does not exist in the namespace "clr-namespace:Product.Main".
and I get Invalid Markup in designer when I try to view a control using local.  I use local many times, so my Error list lists an error for every time I use it.  Everything builds and runs successfully, it is just annoying that I can't view my controls in designer and all the errors that are listed every time I build.
Is there a way to circumvent these errors and get designer to work when I use an Assembly name that is different than the namespace?  I don't want my output to be Product.Main.exe
Any help is appreciated!

A: Try  this since your assembly does not match your namespace.
xmlns:local="clr-namespace:Product.Main;assembly=Product"
http://msdn.microsoft.com/en-us/library/ms747086(v=vs.110).aspx

A: From my comment earlier.

Not to sound cliche, have you tried to clean your solution or try
  restarting VS or machine? I have had a similar problem before.


text:
Q: How to run background service in ionic? i want to start background service when app is launch and after restart the service is automatically start
document.addEventListener('deviceready', function() {
   myService = cordova.plugins.myService;;
  upload();
},

true);

A: you will need this service injected to your controller
.controller('myCtl', myCtl);

function myCtl(LoginService) {

   $scope.username = null;
   $scope.password = null;

   $scope.doLogin = LoginService.loginUser;

}

and then in your view
<div ng-controller="myCtl">
   ...

   <input type="text" ng-model="username">
   <input type="password" ng-model="password">

   <button type="button" ng-click="doLogin(username, password)">
      Login
   </button>

   ...
</div>


text:
Q: Map container is already initialized In Leaflet, I want all my markers to be hidden at the same time and show on the click of a checkbox.
Here is my code:
var cordnt=this.coordinates;
var overlayMarker = {};
 console.log("testing coodinates", cordnt)
var layerGroup = L.layerGroup().addTo(map)
for (i = 0; i < cordnt.length; i++) {
  newMarker = new L.marker([cordnt[i][0], cordnt[i][1]]).bindPopup(notation.desc);
  newMarker.openPopup()
   layerGroup.addLayer([newMarker])
  Object.assign(overlayMarker, {'Markers': layerGroup});
}

console.log("testing latlong",layerGroup)
L.control.layers(null, overlayMarker).addTo(map);

How can I achieve this?

A: Sounds like you want to read a file and create markers, and these markers should be in a layergroup so Leaflet handles them as one layer. Here is something similar to your code that I used.
$.getJSON(url, function(data) {
    for (i = 0; i < data.length; i++) {
        var lng = data[i].coordinates[0];
        var lat = data[i].coordinates[1];
        var Line1 = data[i].addressLine1;
        var Line2 = data[i].addressLine2;
        MCDs = L.marker([lat,lng]).bindPopup("<b>Address: </b>" + Line1 + "<br />Region: " + Line2);
        mcd.addLayer(MCDs);
    }
});

//mcd.addTo(map);  //uncomment if you want to layergroup drawn when the map draws, //leave commented if you want it unchecked in the layer control.

var overlayMaps = {
    "JSON Layer Group":mcd
};

//Add layer control
var layerControl = L.control.layers(baseMaps, overlayMaps).addTo(map);


text:
Q: WSO2 API-Manager with Postgres database is not working properly I have shifted the default h2 database to Postgresql for WSO2 API Manager by following this documentation: https://apim.docs.wso2.com/en/latest/install-and-setup/setup/setting-up-databases/changing-default-databases/changing-to-postgresql/
Creating a new API on throws:

"Something went wrong while getting the Revisions!"

On server found this error

ERROR - ApiMgtDAO Failed to get API Revision deployment mapping details for api uuid: a96f7266-c340-49b6-bbe1-cb252b49860e
org.postgresql.util.PSQLException: ERROR: UNION types integer and boolean cannot be matched

Any help would be greatly appreciated... Thanks...


text:
Q: OpenCV: Unable to correctly pass data to a function Compiling on Windows with MSVS2010
In the following code I have tried to use Line iterator and then after extracting the pixel values along the line, I am trying to pass the extracted data to a function foo():
The image is a single channel 16 bit png.
int foo(unsigned short int *values,  unsigned int nSamples)
{
    cout<<"address in PlotMeNow"<<endl;
    cout<<&values[0]<<endl;
    cout<<"values in PlotMeNow"<<endl;

    for(int i=0;i<5;i++){
        cout<<values[i]<<endl;
    }
    return 0;
}

unsigned short int * IterateLine(Mat image)
{
    LineIterator it(image, Point(1,1), Point(5,5), 8);
    vector<ushort> buf;

    for(int i = 0; i < it.count; i++, it++){
        buf.push_back(image.at<ushort>(it.pos()));
    }

    std::vector<ushort> data(5);
    data=buf;

    cout<<"the  address in the iterateLine() is"<<endl;
    cout<<&data[0]<<endl;

    cout<<"values in IterateLine"<<endl;
    for(int i=0;i<5;i++){
        cout<<data[i]<<endl;
    }
     return &data[0];
}

int main()
{

    Mat img = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);
    unsigned short int * x ;
    //Iterate through the line
    x =  IterateLine(img);

    int n=5;
    foo(&x[0], n);

    cout<<"The address in main() is"<<endl;
    cout<<x<<endl;
    cout<<"values in main are"<<endl;

    for(int i=0;i<5;i++){
        cout<<x[i]<<endl;
    }
    getch();
    return 0 ;
}

The output of the program is:
the address in the iterateLine() is
001195D8
values in IterateLine
40092
39321
39578
46003
46774
address in foo()
001195D8
values in foo()
56797
56797
56797
56797
56797
The address in main() is
001195D8
values in main() are
56797
56797
56797
56797
56797

As can be seen the values foo() and main() are wrong. It should be same as that reported by IterateLine().  Since address are passed correctly (see in the output ) so using pointers I should get same data from any function.  But its not happening.
Why is this happening and how do I correctly pass data to foo()?

A: void IterateLine( const Mat& image, vector<ushort>& linePixels, Point p1, Point p2 )
{
    LineIterator it(image, p1,p2, 8);

    for(int i = 0; i < it.count; i++, it++){
        linePixels.push_back(image.at<ushort>(it.pos()));
    }
}

int main()
{

    Mat img = imread("sir.png", CV_LOAD_IMAGE_ANYCOLOR | CV_LOAD_IMAGE_ANYDEPTH);

    vector<ushort> linePixels;        // initially empty
    IterateLine( img, linePixels, Point(1,1), Point(5,5) );

    foo( &linePixels[0], linePixels.size() );

    return 0 ;
}