text:
Q: Property of Lp spaces for infinite measures I'm currently having some trouble solving the following question.
Q. Suppose $X,M, \mu $ is a measure space for which $\mu(A) > 0 \Longrightarrow \mu(A) \geq 1$
Prove that if $1 \leq p < q \leq \infty $, then $ L^p \subset L^q$, and $\|f\|_{\infty } \leq \|f\|_{q} \leq \|f\|_{p} \leq \|f\|_{1}$
I'm aware that if $\mu(X) < \infty$, then $L^q \subset L^p$, but since this question does not assume that the measure is finite, I could not use the aforementioned property.
Would appreciate any hints/solutions to the question!

A: I will prove the last inequality and leave the rest to you. Suppose $\|f\|_1 \leq 1$. Then $1 \geq \int_{|f| >1} |f|> \mu \{x:|f(x)| >1\}\geq 1$ if $\mu \{x:|f(x)| >1\}>0$ (which is a contradiction). Hence, $|f| \leq 1$ a.e..  Now $\int |f|^{p}d\mu \leq \int |f| d\mu$ because $|f|^{p-1} \leq 1$. Hence $\int |f|^{p}d\mu \leq1$ and $\|f\|_p \leq 1$. We have proved that $\|f\|_1 \leq 1$ implies that $\int |f|^{p}d\mu \leq1$. This implies (by scaling) that $(\int |f|^{p}d\mu)^{1/p} \leq \|f\|_1 $.
Note: by an argument similar to the one above $\|f\|_r \leq 1$ for some $r\geq 1$ implies that $|f| \leq 1$ a.e.  This makes the first inequality very easy. Let me know if you need help with $\|f\|_q \leq \|f\|_q$. ,


text:
Q: EFCore Not recognizing Database Provider I have a .Net Core WebApplication Project in which the Context Class is in a Class Library. If I hard code the connection string in the OnConfiguring(DbContextOptionsBuilder optionsBuilder) method I can generate migrations. Since it is better to let dependency injection manage the context I would like to add this to the Startup Class. However when I do I get the following error:

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

DbContext Class:
public class CustomerManagerContext : IdentityDbContext<User, Role, long, UserClaim, UserRole, UserLogin, RoleClaim, UserToken>
{
    public CustomerManagerContext() { }
    public CustomerManagerContext(DbContextOptions<CustomerManagerContext> options) : base(options)
    {
    }

    //protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    //{
    //    base.OnConfiguring(optionsBuilder);
    //    optionsBuilder.UseSqlServer("SecretConnectionString");
    //}

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<User>().ToTable("Users");
        builder.Entity<Role>().ToTable("Roles");
        builder.Entity<UserClaim>().ToTable("UserClaims");
        builder.Entity<UserRole>().ToTable("UserRoles");
        builder.Entity<UserLogin>().ToTable("UserLogins");
        builder.Entity<RoleClaim>().ToTable("RoleClaims");
        builder.Entity<UserToken>().ToTable("UserTokens");

    }
}

Startup Class - ConfigureServices Method
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<CustomerManagerContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
    );

    services.AddEntityFrameworkSqlServer()
        .AddDbContext<CustomerManagerContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

    services.AddIdentity<User, Role>()
        .AddEntityFrameworkStores<CustomerManagerContext>()
        .AddDefaultTokenProviders();
}

A: This bit me hard, getting errors like:

*

*No database provider has been configured for this DbContext.

*No design-time services were found.

*The server was not found or was not accessible.
But I ended up with a fairly simple solution/work-around:

*

*Set the default startup-project in your solution (or in your command line)

*in your Startup.cs add the migration-project:
  public void ConfigureServices(IServiceCollection services)
  {
      var myDbContextAssemblyName = typeof(MyDbContext).Assembly.GetName().Name;
      var connectionString = Configuration.GetConnectionString(MyDbContext.ConnectionStringName);
      services.AddDbContext<MyDbContext>(options => options.UseSqlServer(
          connectionString,
          x => x.MigrationsAssembly(myDbContextAssemblyName)));
          // do more ...
      }

*in your connection-string use the IP-address and port-number (inspired by this corefx issue), instead of the server-name/dns (FWIW: query to get IP).
So now I have this in my appsettings.Development.json:
"ConnectionStrings": {
"MyConnectionStringName": "Data Source=10.1.2.3,1433; Initial Catalog=MyCatalog; Integrated Security=SSPI"
}
TLDR: other suggestions
I found a lot of other suggestions, and I will mention a few that seemed interesting.  Maybe it will help someone else:
Project-names in command-line
Mention startup-project and migration-project in command-line:
Update-Database -Verbose -Project x.Data -StartupProject x.Web

Addition (from the comments):  This also works from the dotnet CLI:
dotnet ef migrations add <MIGRATION_NAME> --project <DATABASE_PROJECT_DIR> --startup-project <STARTUP_PROJECT_DIR> dotnet ef database update --project <DATABASE_PROJECT_DIR> --startup-project <STARTUP_PROJECT_DIR>

Migrate from code
One can also call migrations at StartUp
, "for apps with a local database".  (I guess otherwise running on multiple nodes, may start multiple runtime migrations at the same time with concurrency issues?)
myDbContext.Database.Migrate();

Set DbContext in Main.cs
This EntityFrameworkCore issue states:

The problem is that when EF calls either CreateWebHostBuilder or
BuildWebHost it does so without running Main. (This is intentional
because EF needs to build the model and use the DbContext without
starting the application.) This means that when EF invokes on of these
methods the static IConfiguration property is still null--since it
is only set in Main. So, you'll need to either make sure that
IConfiguration is set/handled when EF calls one of these methods, or
use IDesignTimeDbContextFactory.

This is not necessary for me, I guess because .Net Core 2 loads the configuration behind the scenes.
Use IDesignTimeDbContextFactory with environment variable
This EntityFrameworkCore issue states:

The typical way to do this is to read a file, an environment variable, or similar inside IDesignTimeDbContextFactory.

This seems too much a hack to me.
DbContext-creation at design time
Microsoft documentation mentions:

Some of the EF Core Tools commands (for example, the Migrations
commands) require a derived DbContext instance to be created at design
time in order to gather details about the application's entity types
and how they map to a database schema.

They mention these ways to provide this design time DbContext:

*

*from application services: for an ASP.NET Core app as startup project:

The tools try to obtain the DbContext object from the application's
service provider. [...] The tools first try to obtain the service
provider by invoking Program.BuildWebHost() [JP: or
CreateWebHostBuilder] and accessing the IWebHost.Services
property.  The DbContext itself and any dependencies in its
constructor need to be registered as services in the application's
service provider. This can be easily achieved by having a constructor
on the DbContext that takes an instance of
DbContextOptions<TContext> as an argument and using the
AddDbContext<TContext> method.

*

*Using a constructor with no parameters

If the DbContext can't be obtained from the application service
provider, the tools look for the derived DbContext type inside the
project. Then they try to create an instance using a constructor with
no parameters. This can be the default constructor if the DbContext
is configured using the OnConfiguring method.

*

*From a design-time factory

You can also tell the tools how to create your DbContext by
implementing the IDesignTimeDbContextFactory<TContext> interface: If
a class implementing this interface is found in either the same
project as the derived DbContext or in the application's startup
project, the tools bypass the other ways of creating the DbContext
and use the design-time factory.

A: I was having the same issue when I when providing options along with dbcontext while adding dbcontext to services like:-
services.AddDbContext<TodoContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

then I added dbcontext without options like below and it fixed the problem for me
services.AddDbContext<TodoContext>();

also I had to add OnConfiguring method to dbcontext class so the context can access the connection string:-
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
    optionsBuilder.UseSqlServer("Server=(localdb)\\mssqllocaldb;Database=IdenDB;Trusted_Connection=True;MultipleActiveResultSets=true");
}

I am not sure if this is the right way of doing things since I just started with core but  here is an answer which explains this issue in a bit more detail

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prepare my document for submission to a paper I am preparing my document to be submitted to a journal via ScholarOne Manuscripts™. I have read in their online documentation Here, that I need to  do the following:

*

*Embed fonts

*Remove macros

*Remove local hyperlinks

*Embed Images and verify there are less than 100 embedded images in the file

*Remove Field Codes (placeholders in Microsoft Word for data that might     change in a document)

I have no idea what these mean and to do them. Could somebody please explain?

A: Your online documentation says that usually a PDF will be accepted. pdfLaTeX nowadays spills out PDFs, so all is well.
I assume that those rules apply to folks who use Word and the conversion to a PDF might be tricky. E.g. a large number of images in a Word file are a kind of challenge...


text:
Q: 404 page redirect issue for all subpages? I am using drupal7 404 page redirect to my custom page using htaccess.
I have to handle 404 error for all subpages. Example : www.example.com/one/two/(INVALID_URI) to my custompage.
I used this in .htacces Errordocument 404 /custom404.php this working only for www.example.com/(INVALID_URI). i need the rule for above example.
How to fix this redirect issue?


text:
Q: how to manipulate Joi messages by http request? I have a user schema like the code below:
const Joi = require("joi");
const message = require("./types/string");

const username = Joi.string()
  .regex(/^[A-Za-z0-9]+$/)
  .required()
  .min(5)
  .max(20)
  .messages(message);

const email = Joi.string()
  .regex(/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/)
  .required()
  .min(5)
  .max(255)
  .email()
  .messages(message);

const password = Joi.string()
  .regex(/^[A-Za-z0-9]+$/)
  .required()
  .min(5)
  .max(255)
  .messages(message);

const userSchema = Joi.object({
  username,
  password,
  email,
});

exports.userSchema = { route: "/users", object: userSchema };

and a schema validation like the code below that I have found at https://www.digitalocean.com/community/tutorials/how-to-use-joi-for-node-api-schema-validation:
const _ = require("lodash");
const { StatusCodes } = require("http-status-codes");
const { Schemas } = require("../joi-schema-validation");

exports.schemaValidator = function (useJoiError = false) {
  const _useJoiError = _.isBoolean(useJoiError) && useJoiError;
  const _supportedMethods = ["post", "put", "patch"];

  const _validationOptions = {
    abortEarly: false,
    allowUnknown: true,
    stripUnknown: true,
  };

  return (req, res, next) => {
    const route = req.route.path;
    const method = req.method.toLowerCase();

    const schema = Schemas.find(
      (schema) => schema.route === route.replace("/:id", "")
    );

    if (_.includes(_supportedMethods, method) && schema) {
      const { object } = schema;
      const { error, value } = object.validate(req.body, _validationOptions);

      if (error) {
        const JoiError = {
          status: "failed",
          validationErrors: {
            details: _.map(error.details, ({ message, context }) => ({
              [context.label]: req.t(message.replace(/['"]/g, "")),
            })),
          },
        };

        const CustomError = {
          status: "failed",
          error: "Invalid request data. Please review request and try again.",
        };

        return res
          .status(StatusCodes.BAD_REQUEST)
          .json(_useJoiError ? JoiError : CustomError);
      } else {
        req.body = value;
        return next();
      }
    }
    return next();
  };
};

Let's say I have two locales joi messages, one in english and one in spanish.
How can I switch to locale joi messages if "Accept-Language" header is "es-es" lcid?

A: After digging around and slept over it, I've manage to come up with an easy solution. In the beginning of the route handler middleware, i have a "messages" variable where I check the request header accept language. If the language LCID is "en" then I return the english error messages or return default error messages, in my case the dutch language error messages.
Before validating, I pass the return error messages into the messages method of my schema and then chain the validate function to it.
The updated code looks now like code underneath:
const _ = require("lodash");
const { StatusCodes } = require("http-status-codes");
const { Schemas } = require("../joi-schema-validation");

exports.schemaValidator = function (useJoiError = false) {
  const _useJoiError = _.isBoolean(useJoiError) && useJoiError;
  const _supportedMethods = ["post", "put", "patch"];

  const _validationOptions = {
    abortEarly: false,
    allowUnknown: true,
    stripUnknown: true,
  };

  return (req, res, next) => {
    const messages =
      req.headers["accept-language"] === "en"
        ? require("../joi-schema-validation/types/string")
        : require("../joi-schema-validation/types/string-nl");

    const route = req.route.path;
    const method = req.method.toLowerCase();

    const schema = Schemas.find(
      (schema) => schema.route === route.replace("/:id", "")
    );

    if (_.includes(_supportedMethods, method) && schema) {
      const { object } = schema;
      const { error, value } = object
        .messages(messages)
        .validate(req.body, _validationOptions);

      if (error) {
        const JoiError = {
          status: "failed",
          validationErrors: {
            details: _.map(error.details, ({ message, context }) => ({
              [context.label]: message.replace(/['"]/g, ""),
            })),
          },
        };

        const CustomError = {
          status: "failed",
          error: "Invalid request data. Please review request and try again.",
        };

        return res
          .status(StatusCodes.BAD_REQUEST)
          .json(_useJoiError ? JoiError : CustomError);
      } else {
        req.body = value;
        return next();
      }
    }
    return next();
  };
};

If there are any comments or alternatives for this solution, I'm more than happy to read about them.
Happy coding


text:
Q: Dynamic scrolling in combobox ext 4.0 I am using extjs 4.0 and having a combobox with queryMode 'remote'. I fill it with data from server. The problem is that the number of records from server is too large, so I thought it would be better to load them by parts. I know there is a standart paginator tool for combobox, but it is not convinient because needs total number of records.
Is there any way to add dynamic scrolling for combobox? When scrolling to the bottom of the list I want to send request for the next part of records and add them to the list. I can not find appropriate listener to do this.

A: The following is my solution for infinite scrolling for combobox, Extjs 4.0
Ext.define('TestProject.testselect', {
    extend:'Ext.form.field.ComboBox',
    alias: ['widget.testselect'],
    requires: ['Ext.selection.Model', 'Ext.data.Store'],

    /**
     * This will contain scroll position when user reaches the bottom of the list
     * and the store begins to upload data
     */
    beforeRefreshScrollTop: 0,

    /**
     * This will be changed to true, when there will be no more records to upload
     * to combobox
     */
    isStoreEndReached : false,

    /**
     * The main thing. When creating picker, we add scroll listener on list dom element.
     * Also add listener on load mask - after load mask is hidden we set scroll into position
     * that it was before new items were loaded to list. This prevents 'jumping' of the scroll.
     */
    createPicker: function() {
        var me = this,
        picker = me.callParent(arguments);
        me.mon(picker, {
            'render' : function() {
                Ext.get(picker.getTargetEl().id).on('scroll', me.onScroll, me);
                me.mon(picker.loadMask, {
                   'hide' : function() {
                      Ext.get(picker.id + '-listEl').scroll("down", me.beforeRefreshScrollTop, false);
                   },
                   scope: me
                });
            },
            scope: me
        });
        return picker;
    },

    /**
     * Method which is called when user scrolls the list. Checks if the bottom of the
     * list is reached. If so - sends 'nextPage' request to store and checks if
     * any records were received. If not - then there is no more records to load, and
     * from now on if user will reach the bottom of the list, no request will be sent.
     */
    onScroll: function(){
        var me = this,
        parentElement = Ext.get(me.picker.getTargetEl().id),
        parentElementTop = parentElement.getScroll().top,
        scrollingList = Ext.get(me.picker.id+'-items');
        if(scrollingList != undefined) {
            if(!me.isStoreEndReached && parentElementTop >= scrollingList.getHeight() - parentElement.getHeight()) {
                var multiselectStore = me.getStore(),
                beforeRequestCount = multiselectStore.getCount();
                me.beforeRefreshScrollTop = parentElementTop;
                multiselectStore.nextPage({
                    params: this.getParams(this.lastQuery),
                    callback: function() {
                            me.isStoreEndReached = !(multiselectStore.getCount() - beforeRequestCount > 0);
                        }
                });
            }
        }
    },

    /**
     * Took this method from Ext.form.field.Picker to collapse only if
     * loading finished. This solve problem when user scrolls while large data is loading.
     * Whithout this the list will close before finishing update.
     */
    collapse: function() {
        var me = this;
        if(!me.getStore().loading) {
            me.callParent(arguments);
        }
    },

    /**
     * Reset scroll and current page of the store when loading all profiles again (clicking on trigger)
     */
    doRawQuery: function() {
        var me = this;
        me.beforeRefreshScrollTop = 0;
        me.getStore().currentPage = 0;
        me.isStoreEndReached = false;
        me.callParent(arguments);
    }
});

When creating element, should be passed id to the listConfig, also I pass template for list, because I need it to be with id. I didn't find out more elegant way to do this. I appreciate any advice.
{
                    id: 'testcombo-multiselect',
                    xtype: 'testselect',
                    store: Ext.create('TestProject.testStore'),
                    queryMode: 'remote',
                    queryParam: 'keyword',
                    valueField: 'profileToken',
                    displayField: 'profileToken',
                    tpl: Ext.create('Ext.XTemplate',
                        '
<tpl for=".">',
                            '
',
                                '{profileToken}',
                            '
',
                        '</tpl>
'
                    ),
                    listConfig: {
                        id: 'testcombo-boundlist'
                    }
                },

And the store:
Ext.define('TestProject.testStore',{
    extend: 'Ext.data.Store',
    storeId: 'teststore',
    model: 'TestProject.testModel',
    pageSize: 13, //the bulk of records to receive after each upload
    currentPage: 0, //server side works with page numeration starting with zero
    proxy: {
        type: 'rest',
        url: serverurl,
        reader: 'json'
    },
    clearOnPageLoad: false //to prevent replacing list items with new uploaded items
});

A: Credit to me1111 for showing the way.
Ext.define('utils.fields.BoundList', {
    override:'Ext.view.BoundList',
    ///@function utils.fields.BoundList.loadNextPageOnScroll
    ///Add scroll listener to load next page if true.
    ///@since 1.0
    loadNextPageOnScroll:true,
    ///@function utils.fields.BoundList.afterRender
    ///Add scroll listener to load next page if required.
    ///@since 1.0
    afterRender:function(){
        this.callParent(arguments);

        //add listener
        this.loadNextPageOnScroll
        &&this.getTargetEl().on('scroll', function(e, el){
            var store=this.getStore();
            var top=el.scrollTop;
            var count=store.getCount()
            if(top>=el.scrollHeight-el.clientHeight//scroll end
               &&count<store.getTotalCount()//more data
              ){
                  //track state
                  var page=store.currentPage;
                  var clearOnPageLoad=store.clearOnPageLoad;
                  store.clearOnPageLoad=false;

                  //load next page
                  store.loadPage(count/store.pageSize+1, {
                      callback:function(){//restore state
                          store.currentPage=page;
                          store.clearOnPageLoad=clearOnPageLoad;
                          el.scrollTop=top;
                      }
                  });
              }
        }, this);
    },
});

A: You can implement the infinite grid as list of the combobox.
Look at this example to implement another picker:
http://www.sencha.com/forum/showthread.php?132328-CLOSED-ComboBox-using-Grid-instead-of-BoundList

A: If anyone needs this in ExtJS version 6, here is the code:
Ext.define('Test.InfiniteCombo', {
    extend: 'Ext.form.field.ComboBox',
    alias: ['widget.infinitecombo'],

    /**
     * This will contain scroll position when user reaches the bottom of the list
     * and the store begins to upload data
     */
    beforeRefreshScrollTop: 0,

    /**
     * This will be changed to true, when there will be no more records to upload
     * to combobox
     */
    isStoreEndReached: false,

    /**
     * The main thing. When creating picker, we add scroll listener on list dom element.
     * Also add listener on load mask - after load mask is hidden we set scroll into position
     * that it was before new items were loaded to list. This prevents 'jumping' of the scroll.
     */
    createPicker: function () {
        var me = this,
            picker = me.callParent(arguments);
        me.mon(picker, {
            'afterrender': function () {
                picker.on('scroll', me.onScroll, me);
                me.mon(picker.loadMask, {
                    'hide': function () {
                        picker.scrollTo(0, me.beforeRefreshScrollTop,false);
                    },
                    scope: me
                });
            },
            scope: me
        });
        return picker;
    },

    /**
     * Method which is called when user scrolls the list. Checks if the bottom of the
     * list is reached. If so - sends 'nextPage' request to store and checks if
     * any records were received. If not - then there is no more records to load, and
     * from now on if user will reach the bottom of the list, no request will be sent.
     */
    onScroll: function () {
        var me = this,
            parentElement = me.picker.getTargetEl(),
            scrollingList = Ext.get(me.picker.id + '-listEl');
        if (scrollingList != undefined) {
            if (!me.isStoreEndReached && me.picker.getScrollY() + me.picker.getHeight() > parentElement.getHeight()) {
                var store = me.getStore(),
                    beforeRequestCount = store.getCount();
                me.beforeRefreshScrollTop = me.picker.getScrollY();
                store.nextPage({
                    params: this.getParams(this.lastQuery),
                    callback: function () {
                        me.isStoreEndReached = !(store.getCount() - beforeRequestCount > 0);
                    }
                });
            }
        }
    },

    /**
     * Took this method from Ext.form.field.Picker to collapse only if
     * loading finished. This solve problem when user scrolls while large data is loading.
     * Whithout this the list will close before finishing update.
     */
    collapse: function () {
        var me = this;
        if (!me.getStore().loading) {
            me.callParent(arguments);
        }
    },

    /**
     * Reset scroll and current page of the store when loading all profiles again (clicking on trigger)
     */
    doRawQuery: function () {
        var me = this;
        me.beforeRefreshScrollTop = 0;
        me.getStore().currentPage = 1;
        me.isStoreEndReached = false;
        me.callParent(arguments);
    }
});

A: First of all thanks to @me1111 for posting the code for dynamic rendering on scroll. That code is working for me after doing a small change.
 tpl: Ext.create('Ext.XTemplate',
                    '
<tpl for=".">',
                        '
',
                            '{profileToken}',
                        '
',
                    '</tpl>
'
                ),
                listConfig: {
                    id: 'testcombo-boundlist'
                }

in code from
<tpl for="."> i have changed id to "testcombo-boundlist-items". as we defined id as 'testcombo-boundlist' in listConfig.
Before modification, in onScroll method scrollingList = Ext.get(me.picker.id + '-items'); i am getting scrollList as a null. because me.picker.id will return 'testcombo-boundlist' on this we are appending '-items' so it became 'testcombo-boundlist-items' but this id does not exists. so iam getting null.
After modification of id in
 we have a list object on "testcombo-boundlist-items". so i got a object.
Hope this small change will help.


text:
Q: EJB 2.0 - straighting it out for me I am working with EJB 2.0.
I have some gaps. mind helpoing me fill them?
A. when I creat an EJB project and write my code, I need to perform rmic. Then these generated files - I put them also in my client side?
B. I once heard of a phrase "skeleton" vs. "stub" - could you tell which is each.
B. Also, I have a project and I want to deploy it. I understand I need to create an EAR project automatically out of my EJB project. What do I need to do?
Thank you.

A: Here mentioned abstract purpose of each, but if you want to get more information on that, go through RMI documention.

*

*Stub : A stub for a remote object acts as a client's local representative or proxy for the remote object.

*Skeleton : The skeleton is responsible for dispatching the call to the actual remote object implementation. They are eliminated since version 1.2.
You can use build tool like Maven/ANT to build EAR project out of EJB project.
They can also be used to build client-side jars, so you don't have to manually look after generating them using rmic.


text:
Q: Visual Studio Professional 2013 32-bit versus 32-bit web installer When downloading Visual Studio Professional 2013, you have the option of downloading 32-bit and 32-bit web installer. What's the difference?

A: The web installer installs a small stub that then downloads the rest of the program. So you end up with Visual Studio installed but not a installer file (so nothing you could copy to another machine to install).
The web installer though may be quicker as it only downloads what you need based on your selection


text:
Q: Parse badly formatted HTML for table data I'm writing a c# console application to retrieve table info from an external html web page.
Example web page: (chessnuts.org)
I want to extract all <td> records for data,match,opponent,result etc - 23 rows in example link above.
I've no control of this web page which unfortunately isn't well formatted so options I've tried like the HtmlAgilityPack and XML parsing simply fail. I have also tried a number for RegEx's but my knowledge of this is extremely poor, an example I tried below:
string[] trs = Regex.Matches(html,
                             @"<tr[^>]*>(?<content>.*)</tr>",
                             RegexOptions.Multiline)
                    .Cast<Match>()
                    .Select(t => t.Groups["content"].Value)
                    .ToArray();

This returns a complete list of all <tr>'s (with many records I don't need) but I'm then unable to get the data from this.
UPDATE
Here is an example of the use of HtmlAgilityPack I tried:
 HtmlDocument doc = new HtmlDocument();

        doc.LoadHtml(html);
        foreach (HtmlNode table in doc.DocumentNode.SelectNodes("//table"))
        {

            foreach (HtmlNode row in table.SelectNodes("tr"))
            {
                foreach (HtmlNode cell in row.SelectNodes("td"))
                {
                    Console.WriteLine(cell.InnerText);
                }
            }
        }

A: I think you just need to fix your HtmlAgilityPack attempt. This works fine for me:
// Skip the first table on that page so we just get results
foreach (var table in doc.DocumentNode.SelectNodes("//table").Skip(1).Take(1)) {
    foreach (var td in table.SelectNodes("//td")) {
        Console.WriteLine(td.InnerText);
    }
}

This dumps a heap of data from the results table, one columns per line, to the console.

A: If you want a full program:). I looked for this for hours.
class ReadHTML
    {
    internal void ReadText()
    {
        try
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.RootFolder = Environment.SpecialFolder.MyComputer;//This causes the folder to begin at the root folder or your documents
            if (fbd.ShowDialog() == DialogResult.OK)
            {
                string[] files = Directory.GetFiles(fbd.SelectedPath, "*.html", SearchOption.AllDirectories);//change this to specify file type
                SaveFileDialog sfd = new SaveFileDialog();// Create save the CSV
                //sfd.Filter = "Text File|*.txt";// filters for text files only
                sfd.FileName = "Html Output.txt";
                sfd.Title = "Save Text File";
                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    string path = sfd.FileName;
                    using (StreamWriter bw = new StreamWriter(File.Create(path)))
                    {
                        foreach (string f in files)
                        {

                            var html = new HtmlAgilityPack.HtmlDocument();
                            html.Load(f);
                            foreach (var table in html.DocumentNode.SelectNodes("//table").Skip(1).Take(1))//specify which tag your looking for
                            {
                                foreach (var td in table.SelectNodes("//td"))// this is the sub tag
                                {
                                    bw.WriteLine(td.InnerText);// this will make a text fill of what you are looking for in the HTML files
                                }
                            }

                        }//ends loop of files

                        bw.Flush();
                        bw.Close();
                    }
                }
                MessageBox.Show("Files found: " + files.Count<string>().ToString());
            }
        }

        catch (UnauthorizedAccessException UAEx)
        {
            MessageBox.Show(UAEx.Message);
        }
        catch (PathTooLongException PathEx)
        {
            MessageBox.Show(PathEx.Message);
        }
    }//method ends
}


text: Q: Do prescription glasses augment or mitigate the effect of the sun on the skin around the eyes directly beneath them (assuming no UV blocking coating)? The question is about minus correction (nearsightedness), but would also be interesting to know how it differs for plus correction (farsightedness), cylinder correction (astigmatism), axis correction.


text:
Q: azureml history logging to output dir When running my Pytorch Estimator in the cloud, I get this output regarding the recommended way to save my training scripts output to a folder called './outputs'. This folder is created by my script, and is in the correct root-folder provided. It has output.
However the estimator returns this, while preparing the container:
Starting the daemon thread to refresh tokens in background for process with pid = 124
Warning: Unable to import azureml.history. Output collection disabled.
all I provide my estimator is my training script, conda env.yml and a compute target.
It completes the training script successfully, not errors.
Any ideas why I get this ?


text:
Q: Creating a rating system for randomised groups So I have this code that groups (1,2,3,4)(x4) into 4 groups, I was trying find a way to rate these groups. E.G. (1,1,1,1) is a good group since there are no other numbers (1,2,3,4) would be the worst group. So does anyone know a way to check the number of different values in a group e.g. (1111) have 1 value, where as (1,2,3,3) has 3 changes.
import numpy
import random
members, n_groups = 4, 4
participants=list(range(1,members+1))*n_groups
#print participants
random.shuffle(participants)

with open('myfile1.txt','w') as tf:
    for i in range(n_groups):
        group = participants[i*members:(i+1)*members]
        for participant in group:
            tf.write(str(participant)+' ')
        tf.write('\n')

with open('myfile1.txt','r') as tf:
    g = [list(map(int, line.split())) for line in tf.readlines()]
    print(g)
    print(numpy.mean(g, axis=1))

A: Using the above to create a simple function:
For input data of the format (31432123121) you can use:
def get_rating(group):
    group = str(group)  # needed to use set
    return len(set(group))

set will sort the number of unique elements into sets
>>> set("1111222233")
set(['1', '3', '2'])
>>>

then len just gets the length.
For input data like (1,2,3,1,2):
def get_rating(group):
    """
    (tuple of ints)->int
    """
    group_str = ""  # create an empty string to rep the nums
    for each_num in group:  # iterate through each of the numbers in the group
        group_str += str(each_num)  # convert each number to a string and append to group_str
    return len(set(group_str))  # return a count of the number of different elements in the input group

print get_rating((4,2,3,4,4,4,1,5))  # simple test for function

To use with many lists:
# global var
my_groups = [[3, 1, 3, 1], [2, 2, 4, 2], [3, 4, 3, 2], [4, 4, 1, 1]]

def get_rating(group):
    """
    (tuple of ints)->int
    """
    group_str = ""
    for each_num in group:
        group_str += str(each_num)
    return len(set(group_str))

# iterates through each list inside the main list.
# Note that lists and tuples can be treated the same except when you want
# to change the internal values
for each_grp in my_groups:
    print get_rating(each_grp),

Remove the comma on the last line of code if you want to print them on separate lines.


text:
Q: Error when passing additional ViewData to strongly typed Partial View My partial view isn't being loaded. Please find my code snippets, I can't figure out what is wrong.  Help please.
The error message is:

c:MvcUI\Views\Project\Details.ascx(42): error CS1950: The best overloaded Add method 'System.Web.Mvc.ViewDataDictionary.Add(System.Collections.Generic.KeyValuePair)' for the collection initializer

I am having In my view:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcUI.Models.ProjectModel>" %><%Html.RenderPartial("LabelsDetails", Model.Categories, new ViewDataDictionary{"labelsName", labelsName }); %>

My partialView
<%@ Control language="C#"Inherits="System.Web.Mvc.ViewUserControl<Models.ProjectModel>" %> <%int count = 0; %>
 <%var labelsName = ViewData["labelsName"];%>

            <%if (Model!=null) {%>

                 <%if (!String.IsNullOrEmpty(Model.Name))
                   {%>
                    <li>
                          <%: Html.Hidden((labelsName)+".Index", count.ToString())%>
                          <%: Html.TextBox((labelsName)+"[" + (count) + "].Name", Model.Name, new { Style = "width:280px" })%>
                          <%: Html.Hidden((labelsName)+"[" + (count++) + "].ID", Model.ID, new { Style = "width:280px" })%>
                        <input type="button" value = "Delete"/>
                    </li>
                    <%}
                     %>
                 <%} %>

                <li>
                     <%: Html.Hidden((labelsName) + ".Index", count.ToString())%>
                          <%: Html.TextBox((labelsName) + "[" + (count) + "].Name", "", new { Style = "width:280px" })%>
                          <%:  Html.Hidden((labelsName) + "[" + (count++) + "].ID", 0, new { Style = "width:280px" })%>
                    <input type="button"  value= "Add" />
                </li>

My projectModel
public class Label
{
    public String Name { get; set; }
    public int ID { get; set; }
}
 public List<Label> Categories { get; set; }

A: The syntax you are using to initialize the ViewDataDictionary is wrong. You need two {. Try like this:
<% Html.RenderPartial(
    "LabelsDetails",
    Model.Categories,
    new ViewDataDictionary {{ "labelsName", labelsName }}
); %>

A: Dariv code for renderpartial was helpful but there was an error on the partial view inherits which can be found on
http://sokhanh03.spaces.live.com/blog/cns!78F088CCD824626B!832.entry


text:
Q: Is random forest for regression a 'true' regression? Random forests are used for regression. However, from what I understand, they assign an average target value at each leaf. Since there are only limited leaves in each tree, there are only specific values that the target can attain from our regression model. Thus is it not just a 'discrete' regression (like a step function) and not like linear regression which is 'continuous'?
Am I understanding this correctly? If yes, what advantage does random forest offer in regression?

A: It is discrete, but then any output in the form of a floating point number with fixed number of bits will be discrete. If a tree has 100 leaves, then it can give 100 different numbers. If you have 100 different trees with 100 leaves each, then your random forest can theoretically have 100^100 different values, which can give 200 (decimal) digits of precision, or ~600 bits. Of course, there is going to be some overlap, so you're not actually going to see 100^100 different values. The distribution tends to get more discrete the more you get to the extremes; each tree is going to have some minimum leaf (a leaf that gives an output that's less than or equal to all the other leaves), and once you get the minimum leaf from each tree, you can't get any lower. So there's going to be some minimum overall value for the forest, and as you deviate from that value, you're going to start out with all but a few trees being at their minimum leaf, making small deviations from the minimum value increase in discrete jumps. But decreased reliability at the extremes is a property of regressions in general, not just random forests.

A: The answer will depend on what is your definition of regression, see Definition and delimitation of regression model.  But a usual definition (or part of a definition) is that regression models conditional expectation. And a regression tree can indeed be seen as an estimator of conditional expectation.
In the leaf nodes you predict the average of the sample observations reaching that leaf, and an arithmetical mean is an estimator of an expectation. The branching pattern in the tree represents the conditioning.

A: This is correct - random forests discretize continuous variables since they are based on decision trees, which function through recursive binary partitioning. But with sufficient data and sufficient splits, a step function with many small steps can approximate a smooth function. So this need not be a problem. If you really want to capture a smooth response by a single predictor, you calculate the partial effect of any particular variable and fit a smooth function to it (this does not affect the model itself, which will retain this stepwise character).
Random forests offer quite a few advantages over standard regression techniques for some applications. To mention just three:

*

*They allow the use of arbitrarily many predictors (more predictors than data points is possible)

*They can approximate complex nonlinear shapes without a priori specification

*They can capture complex interactions between predictions without a priori specification.

As for whether it is a 'true' regression, this is somewhat semantic. After all, piecewise regression is regression too, but is also not smooth. As is any regression with a categorical predictor, as pointed out in the comments below.

A: It's perhaps worth adding that Random Forest models can't extrapolate outside the range of the training data, since their lowest and highest values are always going to be averages of some subset of the training data; there is a nice graphical example here.


text:
Q: Turning a text file into JSON I'm trying to write a function that takes text file as input and turns it into the JSON tree format below so I can use it in my d3.js project.
The text file is really simple: Every line that starts with 'b' represents a bag and the following integer is the number of the bag. Each bag contains nodes.
So the first line is bag 1 with the nodes 1 and 2.
The lines that does not contain b represent the links between the bags. So bag 1 points to bag 2 for example.
Sample input:
b 1 1 2 3
b 2 2 3 4
b 3 4 5 6
1 2
1 3

Expected output:
const tree = {
  id: 1,
  name: '1, 2, 3',
  vertices: [1, 2, 3],
  children: [
    {
      id: 2,
      name: '2, 3, 4',
      vertices: [2, 3, 4],
    },
    {
      id: 3,
      name: '4, 5, 6',
      vertices: [4, 5, 6],
    },
  ],
};

code so far (help from tom):
function readTreeInput(evt) {
  const file = evt.target.files[0];
  const fileReader = new FileReader();

  fileReader.onload = function convertTreeToJSON() {
    const lines = this.result.split('\n');
    const res = {}; let current = res;

    for (let line = 0; line < lines.length; line++) {
      const textLine = lines[line];
      if (textLine.startsWith('c') || textLine.startsWith('s')) continue;

      if (textLine.startsWith('b')) {
        const bagId = parseInt(textLine[2], 10);
        const firstNode = textLine[4];
        const secondNode = textLine[6];
        const thirdNode = textLine[8];
        let vertices;

        if (secondNode === undefined) {
          vertices = [firstNode];
        } else if (thirdNode === undefined) {
          vertices = [parseInt(firstNode, 10), parseInt(secondNode, 10)];
        } else {
          vertices = [firstNode, secondNode, thirdNode];
        }
        current.id = bagId;
        current.name = vertices.join(', '); // bagLabel;
        current.vertices = vertices;
        current = (current.children = [{}])[0];
      }
    }
    removeExistingTree();
    drawTree(res);
  };
  fileReader.readAsText(file);
}

Not quite sure how to go from here to take care of the nesting, any advice? :)

A: Any problem there ? ;-) I prefer easier textLine.split(' ') but left most of your code untouched. And suppose FileReader would not work here.

var result = document.createElement('PRE');
result.innerText = x = JSON.stringify(
    convertTreeToJSON.call({ result: 'b 1 1 2\nb 2 2 3\nb 3 4 3\nb 4 5 4\n1 2\n2 3\n3 4' })
    , null, 1)
    .replace(/\[\n\s+(\d+),\n\s+(\d+)\n\s+]/g, '[$1, $2]')
    .replace(/\[\n\s+/g, '[').replace(/}\n\s+\]/g, '}]');
document.body.appendChild(result);
function convertTreeToJSON (x) {
    const lines = this.result.split('\n');
    const edges = [];
    const treeBags = [];
    const listOfIds = [];

    var res = {}; var current;

    for (let line = 0; line < lines.length; line++) {
        const textLine = lines[line];

        if (textLine.startsWith('c') || textLine.startsWith('s')) return;

        if (textLine.startsWith('b')) {
            const bagId = parseInt(textLine[2]);
            let bagLabel;
            let vertices;
            const firstNode = textLine[4];
            const secondNode = textLine[6];
            const thirdNode = textLine[8];

            if (secondNode === undefined) {
                vertices = [firstNode];
            } else if (thirdNode === undefined) {
                vertices = [parseInt(firstNode), parseInt(secondNode)];
            } else {
                vertices = [firstNode, secondNode, thirdNode];
            }

            if (res.id === undefined) {
                current = res;
            } else {
                current = res.children[res.children.push({}) - 1];
            }
            current.id = bagId;
            current.name = vertices.join(', '); // bagLabel;
            current.vertices = vertices;
            if (current == res) current.children = [];
        }
    }
    return res;
}


text:
Q: Reading strings of files I am really newbie in C and I want create a program that reads two input files which are only include strings. I have created for its related file's strings. I have dealing with some problem and I couldn't figure out, there is some segmentation fault in there. (asked by-ua)
Here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct linked_list {
    char my_data[256];
    struct linked_list *next_it;
} node_t;

int main(int argc, char *argv[]) {
    /*
    if(argc != 4) {
        fprintf(stderr, "Requiring 2 input 1 output file name to start!\n");
        exit(EXIT_FAILURE);
    }*/

    FILE *my_s;
    FILE *my_f;
    // FILE *my_o;
    bool mybool = true;
    int my_ch; // our char to read
    char my_buffer[256];
    bool check_all = true;

    node_t *set_a = malloc(sizeof(node_t));
    node_t *set_b = malloc(sizeof(node_t));
    my_f = fopen(argv[1], "r"); // first textfile to read
    my_s = fopen(argv[2], "r"); // second textfile to read

    if (my_f != NULL && my_s != NULL) {
        while (fgetc(my_f) != EOF && mybool != false && check_all != false) {
            my_ch = fgetc(my_f);
            int i = 0;
            while (my_ch >= 0) {
                my_buffer[i++] = my_ch;
                my_ch = fgetc(my_f);
            }
            strcpy(set_a->my_data, my_buffer);
            if (feof(my_f)) {
                mybool = false;
            } else {
                set_a->next_it = malloc(sizeof(node_t));
                set_a = set_a->next_it;
            }
        }
        mybool = false;
        printf("First File Copy Done!\n");
        while (fgetc(my_s) != EOF && mybool != true && check_all != false) {
            my_ch = fgetc(my_s);
            int i = 0;
            while (my_ch >= 0) {
                my_buffer[i++] = my_ch;
                my_ch = fgetc(my_s);
            }
            strcpy(set_b->my_data, my_buffer);
            if (feof(my_s)) {
                check_all = false;
            } else {
                set_b->next_it = malloc(sizeof(node_t));
                set_b = set_b->next_it;
            }
        }
        printf("Second File Copy Done!\n");
    } else {
        fprintf(stderr, "Cannot read from %s and %s\n", argv[1], argv[2]);
    }

    while (set_a != NULL) {
        int j = 0;
        printf("No: %d, Var: %s",j++, set_a->my_data);
        node_t *set_c = set_a;
        set_a = set_a->next_it;
        free(set_c);
    }
    while (set_b != NULL) {
        int j = 0;
        printf("No: %d, Var: %s",j++, set_b->my_data);
        node_t *set_c = set_b;
        set_b = set_b->next_it;
        free(set_c);
    }
    return 0;
}

A: You are not pointing the tail of the two linked lists to 'NULL' after reaching the end of file and you are not maitaining the heads of each linked list. You change the head each time reading a string. So at final stage 'set_a' and 'set_b' become the last node without a NULL tail

A: Your code has several problems:

*

*You initialize your list with an uninitialized first node.  There is no way to test anything in this node... Why not initialize an empty list as NULL.

*You test for end of file by reading the next byte from each file, but you do not store this byte... so it gets lost.  Later you check for feof(my_s), but this function does not do what you think it does. It is much better to check is fgetc() returns EOF, but store the byte it read.

*Why do you start every local variable name with my or my_, this is not helping, just use the short names, they are not supposed to designate anything global anyway.

*You do not keep a pointer to the head of each list, you set set_a and set_b to point to the next node, there is just no way to find the head of the lists anymore.

*You reset j to 0 in each iteration of the print and free loop, all nodes will print with number 0.

*You should use functions to load, print and free the lists, to avoid repeating the same code twice.

Here is an improved version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

typedef struct linked_list {
    char *data;
    struct linked_list *next;
} node_t;

node_t *load_lines(const char *filename) {
    node_t *head = NULL;
    FILE *fp = fopen(filename, "r");
    if (fp != NULL) {
        char buffer[256];
        size_t i = 0;
        int c;
        node_t **tailp = &head;

        for (;;) {
            c = fgetc(fp);
            if (c != EOF && c != '\n') {
                if (i < sizeof(buffer) - 1) {
                    buffer[i++] = c;
                }
                continue;
            }
            if (i > 0) {
                buffer[i] = '\0';
                /* allocate a new node */
                *tailp = malloc(sizeof(**tailp));
                (*tailp)->next = NULL;
                (*tailp)->data = strdup(buffer);
                tailp = &(*tailp)->next;
                i = 0;
            }
            if (c == EOF) {
                break;
            }
        }
        fclose(fp);
    }
    return head;
}

void print_word(node_t *np) {
    int j = 0;
    while (np != NULL) {
        printf("No: %d, Var: %s", j++, np->data);
        np = np->next;
    }
}

void free_words(node_t *np) {
    while (np != NULL) {
        node_t *next = np->next;
        free(np->data);
        free(np);
        np = next;
    }
}

int main(int argc, char *argv[]) {
    /*
    if (argc != 4) {
        fprintf(stderr, "Requiring 2 input 1 output file name to start!\n");
        exit(EXIT_FAILURE);
    }*/

    node_t *set_a, *set_b;

    if ((set_a = load_words(argv[1])) != NULL) {
        printf("First File Copy Done!\n");
    }
    if ((set_b = load_words(argv[2])) != NULL) {
        printf("Second File Copy Done!\n");
    }
    if (!set_a && !set_b) {
        fprintf(stderr, "Cannot read from %s and %s\n", argv[1], argv[2]);
    }

    print_words(set_a);
    free_words(set_a);
    print_words(set_b);
    free_words(set_b);
    return 0;
}


text:
Q: Group by in SQL using first two digits I have a column storing codes like 71xxxx, 78xxxx, 59xxxx, and so on. I need to run a query to find out all the records that have codes starting with 71.
I mean, all the rows where the the first two digits of the code column are 71. If anyone can share the SQL query for this, I would be really helpful.
Thanks.

A: You would use like in a where clause for the filtering:
where code like '71%'

This is pretty basic SQL.  If you are not familiar with it, you should study the language a bit more.

A: Try this
select substr(col, 1,2),count(*)  from ITEM group by substr(col, 1,2)


text:
Q: How do I compare two integers limit_speed = 50
current_speed = int(input("speed now :"))
def displayPenalty(limit_speed, current_speed):
        if current_speed - limit_speed == 0:
            print("no charge")
        elif current_speed - limit_speed == 20:
            print("charge 20 dollars")
        elif current_speed - limit_speed == 40:
            print("charge 40 dollars")

How do I make this function work so that it will check the difference between the 2 integers and print out based on it?

A: I think this is what you are looking for:
limit_speed = 50
current_speed = int(input("speed now :"))
def displayPenalty(limit_speed, current_speed):
        if current_speed <= limit_speed:
            print("no charge")
        else:
           print(f'charge: {current_speed - limit_speed}')

A: You can simply check if one value is greater than the other. (I think you would want this)...
def displayPenalty(limit_speed, current_speed):
    if current_speed>limit_speed: print(f"Charge {current_speed-limit_speed} dollars")
    else: print("no charge")

A: see below (I think this is what you are looking for)
limit_speed = 50

def displayPenalty(limit_speed, current_speed):
    delta = current_speed - limit_speed
    if delta == 0:
        print("no charge")
    elif 0 < delta <= 20:
        print("charge 20 dollars")
    elif 20 < delta:
        print("charge 40 dollars")

current_speed = int(input("speed now :"))
displayPenalty(limit_speed, current_speed)


text:
Q: Django, trouble deleting a record? I have a Django class-based delete view
It is called by a template (DetailsView, which has a button on the bottom which i want to be able to click in order to delete the record)
The code in the template is this:

  Edit

<form method="post" action="{% url 'delete_candidate' object.pk %}" class="inline">
  {% csrf_token %}
  <input type="hidden" name="object_pk" value="{{ object.pk}}">
  <button type="submit" name="delete" value="delete" class="link-button">
  </button>
</form>

The update_candidate works  using the object.pk... a page is displayed with the right object, but if i try and delete i get error

Request Method:   POST Request URL:
    http://127.0.0.1:8000/candidates/delete_candidate/1/ Django Version:
    2.0.6 Exception Type:   ImproperlyConfigured Exception Value:  DeleteCandidateView is missing a QuerySet. Define
  DeleteCandidateView.model, DeleteCandidateView.queryset, or override
  DeleteCandidateView.get_queryset().
POST Variable                     Value object_pk                     '1'
  csrfmiddlewaretoken
  'Vp3McmK88riynpBJ9U2yPRXNvI3i8ufeepY2FnRt1cktW7aw48p7JsYTnFWvk4kD'
delete                       'delete'

Does anyone have any ideas on how to fix this issue?

A: Message says that some of the views using a generic CBV DetailView or a DeleteView has the wrong setup, in this case probably DeleteCandidateView is missing some of the following required attributes:

*

*model,

*queryset,

or you need to override DeleteCandidateView.get_queryset

It depends on the Generic Class Based View you are using, but it will tipically look like:
class DeleteCandidateView(DetailView):

    model = DeleteCandidate # or whatever your model is called


text:
Q: Как сделать punycode url'a, не только домен Я нашел вариант как преобразовать punycode для домена, но не нашел скрипта, где это было бы для url'a
Примеры:
домен: президент.рф
url: http://президент.рф/help/faq.html
вот такой скрипт переводит домен:
#!/usr/bin/perl
use URI;
use URI::UTF8::Punycode;
use Encode;

my $domain = shift;
print puny_encode_domain($domain);

sub puny_encode_domain {
    my $domain = shift;

    my @puny_words = ();
    foreach my $d (split(/\./, $domain)) {
        if ($d !~ m/[a-zA-Z0-9*]/i) {
        $d = puny_enc($d) unless $d =~ m/^\d+$/;
        }
        push(@puny_words, $d);
    }
    my $result = join('.', @puny_words);
    return $result;

}

но если ввести http://президент.рф/help/faq.html не работает.

A: Конечно не работает, оно только части домена кодирует. Посмотрите на код функции puny_encode_domain(), в ней split выдаст вам такие части для целого адреса:
#!/usr/bin/perl

use Modern::Perl;
use DDP;
use utf8::all;

my @parts = split /\./, 'http://президент.рф/help/faq.html';
p @parts;

Вывод:
[
    [0] "http://президент",
    [1] "рф/help/faq",
    [2] "html"
]

Соответственно, все они проскочат мимо puny_enc().
Можно всё сделать проще, в модуле URI поддержка IDNA уже давно есть из коробки:
#!/usr/bin/perl

use Modern::Perl;
use utf8::all;
use URI;

my $uri = URI->new( 'http://президент.рф/help/faq.html' );
say $uri->canonical();

Вывод:
http://xn--d1abbgf6aiiy.xn--p1ai/help/faq.html

A: Еще 1 вариант с библиотекой Mojo::URL
#!/usr/bin/perl
use Mojo::URL;
binmode(STDOUT,':utf8');

    my $data = shift;
    my $url = Mojo::URL->new($data);
    my $path = $url->path;
    my $punyhost = $url->ihost;
    print "$punyhost"."$path"."\n";


text:
Q: How can I add KeyUp event for my UserControl? I have a user control that working like WatermarkPasswordBox and I want to add KeyUp event for my user control's PasswordBox's Key Up event. How can I do it?
 <UserControl
x:Class="Windows8.StoreApp.Common.CustomControls.WatermarkPasswordTextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Windows8.StoreApp.Common.CustomControls"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300"
d:DesignWidth="400">

<Grid>
    <PasswordBox x:Name="passwordB" GotFocus="PasswordBox_GotFocus" LostFocus="PasswordBox_LostFocus" PasswordChanged="passwordB_PasswordChanged" Style="{StaticResource AkbankControlStyleWatermarkPasswordBoxLoginFormInputPasswordBox}"></PasswordBox>
    <TextBlock x:Name="lblWaterMark" Tapped="lblWaterMark_Tapped" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,4,10,4" Opacity="0.8" FontFamily="Segoe UI" FontSize="16" Foreground="#FF8E8E8E" FontWeight="SemiBold"></TextBlock>
</Grid>

  public WatermarkPasswordTextBox()
    {
        this.InitializeComponent();
    }

    private void PasswordBox_GotFocus(object sender, RoutedEventArgs e)
    {
        lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
    }

    private void PasswordBox_LostFocus(object sender, RoutedEventArgs e)
    {
        if ((sender as PasswordBox).Password.Length == 0)
        {
            lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Visible;
        }
    }

    private void passwordB_PasswordChanged(object sender, RoutedEventArgs e)
    {
        if ((sender as PasswordBox).Password.Length != 0)
        {
            lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        }
    }

    private void lblWaterMark_Tapped(object sender, TappedRoutedEventArgs e)
    {
        lblWaterMark.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
        passwordB.Focus(Windows.UI.Xaml.FocusState.Pointer);
    }

    private string _watermark=String.Empty;
    public string Watermark
    {
        get
        {
            _watermark = lblWaterMark.Text;
            return _watermark;
        }
        set
        {
            SetProperty<string>(ref _watermark, value, "Watermark");
            lblWaterMark.Text = _watermark;
        }
    }

    private int _lenghtMax;
    public int LenghtMax
    {
        get
        {
            if (passwordB != null)
            {
                _lenghtMax = passwordB.MaxLength;
                return _lenghtMax;
            }
            else
            {
                return 0;
            }
        }
        set
        {
            if (passwordB != null)
            {
                SetProperty<int>(ref _lenghtMax, value, "LenghtMax");
                passwordB.MaxLength = _lenghtMax;
            }
        }
    }

    private string _passText = String.Empty;
    public string PassText
    {
        get
        {
            if (passwordB != null)
            {
                _passText = passwordB.Password;
                return _passText;
            }
            else
            {
                return String.Empty;
            }

        }
        set
        {
            if (passwordB != null)
            {
                SetProperty<string>(ref _passText, value, "PassText");
                passwordB.Password = _passText;
                passwordB_PasswordChanged(passwordB, null);
            }
            else
            {
                SetProperty<string>(ref _passText, value, "PassText");
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    private bool SetProperty<T>(ref T storage, T value, [CallerMemberName] String propertyName = null)
    {
        if (Equals(storage, value)) return false;

        storage = value;
        OnPropertyChanged(propertyName);
        return true;
    }

    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

I want to use like this;

and this Key_Up will equal to mycontrol's PasswordBox' key up event.
Thanks.

A: public event KeyEventHandler RelayedKeyUp
{
    add
    {
        passwordB.KeyUp += value;
    }
    remove
    {
        passwordB.KeyUp -= value;
    }
}


text:
Q: How to simulate the card click animation on the new Apple Store "Today" feed? When clicking on any card of the new Apple Store today feed, there's a really nice animation that first gives a sense of depth (card becomes smaller), and after the card expands, completely filling the view.
On the opposite direction, if the user slides his finger down, the view becomes the card again (everything back to normal).
Are there any libraries that do that? I've been trying using UIView.animate but my results have been horrible. Could someone give me some directions on how to tackle this problem?


text:
Q: Dismiss modal from a view in a tab bar view How can I dismiss a modal view opened from a view in a tab bar view and stays on that view?
I have a tab bar view after login in and there are two views on the tab view (Clients and Profile).
On clients I have a list of clients and I can open another view that shows invoices.
Tapping on an invoice, it shows me the details of a particular invoice.
On this view, there is an actionView with some buttons.
One of those button is "Make Payment".
When tapped on Make Payment, a modal windows is shown.
However, when I tap on a cancel button, it removes all the views and goes back to the login view (initial view)
Invoice View
@IBAction func showActionAlert(_ sender: Any) {
let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)

let payButton = UIAlertAction(title: "Make Payment", style: .default, handler: { (action) -> Void in

    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let controller = storyboard.instantiateViewController(withIdentifier: "MakePaymentViewController")
    self.present(controller, animated: true, completion: nil)

})

let voidButton = UIAlertAction(title: "Void", style: .destructive, handler: { (action) -> Void in
})

let deleteButton = UIAlertAction(title: "Delete", style: .destructive, handler: { (action) -> Void in
})

let cancelButton = UIAlertAction(title: "Cancel", style: .cancel, handler: { (action) -> Void in })
alertController.addAction(payButton)
alertController.addAction(voidButton)
alertController.addAction(deleteButton)
alertController.addAction(cancelButton)
self.navigationController!.present(alertController, animated: true, completion: nil)

}

Modal View
 @IBAction func cancelButton(_ sender: Any) {
     let tmpController :UIViewController! = self.presentingViewController;
     self.dismiss(animated: false, completion: {()->Void in
         tmpController.dismiss(animated: true, completion: nil);
     });
 }

A: The controller you're presenting it from is your navigationController in which your navigation stack is.
If you present several viewControllers from your navigationController and then dismiss all the presented Controllers from the parent/presentingViewController(which is navigationController) all viewControllers that are presented on are dismissed.
Instead of presenting it like this :
self.navigationController!.present(alertController, animated: true, completion: nil)

do this
self.present(alertController, animated: true, completion: nil)

And while dismissing do:
self.dismiss(animated: true, completion: nil)

A: I changed the cancelButton action and it worked:
@IBAction func cancelButton(_ sender: Any) {
    dismiss(animated: true, completion: nil)
}


text:
Q: Ruby Regex matching unexpected characters I am trying to write a script that parses filename of a comicbook and tries to extract info such as Seriesname, Publication year etc.In this case, I am trying to extract publication year from the name. Consider the following name, I would need to match and get value 2003. Below is the expression I had for this.
r = %r{ (?i)(^|[,\s-_])v(\d{4})($|[,\s-_]) }

However this matches the number irrespective of what character I have before the v or after the number
I expect the first two to not match and the third to match.

*

*010 - All Star Batman & Robin The Boy Wonder 01 - av2003

*010 - All Star Batman & Robin The Boy Wonder 01 - v2003t

*010 - All Star Batman & Robin The Boy Wonder 01 - v2003

What am I doing wrong in this case?

A: Inside character classes (ie. []s) the - character has a special meaning when it's between two other characters: it creates a range starting the character before and ending at the character after.
Here, you want it literally, so you should either escape the - or (more idiomatically in regex) put it as the first or last character in the [].
Also, btw, you have literal space characters, but no /x modifier, also you probably don't want to capture what's before and after the year, so the final pattern would be:
%r{(?i)(?:^|[,\s_-])v(\d{4})(?:$|[,\s_-])}

A: @smathy answered your question (rather nicely). I want to point out that you could write your regex without a capture group:
 r = /
     (?:         # begin a non-capture group
       ^|[,\s_-] # match the beginning of the string, a ws char or char in ',_-'
     )           # end the non-capture group
     v           # match v
     \K          # forget everything matched so far
     \d{4}       # match 4 digits
     (?=         # begin a positive look-ahead
       $|[,\s_-] # match the end of the string, a ws char or char in ',_-'
     )           # end positive lookahead
     /x

"010 - All Star Batman & Robin The Boy Wonder 01 - av2003"[r]
  #=> nil
"010 - All Star Batman & Robin The Boy Wonder 01 - v2003t"[r]
  #=> nil
"010 - All Star Batman & Robin The Boy Wonder 01 - v2003"[r]
  #=> "2003

*

*If you wish to match v or V, change the line v to [vV].

*If you wish the regex to be case independent, change /x to /ix (in which case there is no need to replace v with [vV]).

*If you wish to ensure the publication date is (say) in the 20th or 21st century, change \d{4} to [12]\d{3}.

*You could alternatively change the non-capture group to a positive lookbehind ((?<=^|[,\s_-])) and delete \K.


text:
Q: Use of undeclared identifier 'location' Am getting this error on several lines which I have commented out, and wonder why I am getting this problem? What is the best way to fix this?
Location is a CoreData entity and placemark is one of its attributes.
Thanks in advance.
LocationsViewController.m
#import "LocationsViewController.h"
#import "Location.h"

@interface LocationsViewController ()

@end

@implementation LocationsViewController{
    NSArray *locations;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];

    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Location" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:YES];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

    NSError *error;
    NSArray *foundObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (foundObjects == nil) {
        FATAL_CORE_DATA_ERROR(error);
        return;
    }

    locations = foundObjects;

}

- (void)viewDidUnload
{
    [super viewDidUnload];
    locations = nil;
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    // Return the number of rows in the section.
    return [locations count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Location"];

    UILabel *descriptionLabel = (UILabel *) [cell viewWithTag:100];
    descriptionLabel.text = @"If you can see this";

    UILabel *addressLabel = (UILabel *)[cell viewWithTag:101];
    addressLabel.text = @"%@ %@, %@",
    location.placemark.subThoroughfare, // Use of undeclared identifier 'location'
    location.placemark.thoroughfare, // Use of undeclared identifier 'location'
    location.placemark.locality ]; // Use of undeclared identifier 'location'

    return cell;
}

@end

A: In cellForRowAtIndexPath
You forgot
Location *location = locations[indexPath.row];


text:
Q: Excel VBA table entry validation I have a table created in excel (named WaterTable) and have a userform which allows data to be entered into it.  The columns are: YEAR, QUARTER, SOURCE, VOLUME.
Looking around on here and other locations I have managed to get sorted with code that allows users to enter data into the boxes on the form and submit - with the code adding a new row and entering their data.
However, where I am struggling is that at the moment a user could put in:
YEAR - QUARTER - SOURCE - VOLUME
2013 -    4    -  MAINS -   50

And that's no problem - BUT if they enter a wrong number and want to re-enter it will just create a new line, but retain the original entry.  This causes problems for presenting the data (multiple entries) and also means errors cannot be corrected.  I have managed to look around and put the following code in:
    Set sheet = ThisWorkbook.Worksheets("Raw Data")
    Set table = sheet.ListObjects.Item("WaterTable")
    Set EvalRange = table.DataBodyRange

If WorksheetFunction.CountIf(EvalRange, YearBox.Text) > 1 And WorksheetFunction.CountIf(EvalRange, QuarterBox.Text) > 1 And WorksheetFunction.CountIf(EvalRange, SourceBox.Text) > 1 Then
    MsgBox "Data Entry Already Present"
    Application.EnableEvents = False
    Else
    Call AddDataRow
End If

Which partially solves my problem - as now you can only enter one 'volume' data point for a particular year, quarter and source.  Which works to an extent - but what I really want is for the message box to give option to either replace the current data OR close.  So that wrongly entered data can be corrected.  Unfortunately I've come across a brick wall on that one and can't think what to use!
Hope that makes sense!
AS ADDITION FOLLOWING COMMENT MADE BELOW:
I've changed to using 'find' command, and come up with the following code to start me off:
SearchString = YearBox.Value
On Error Resume Next
Set bCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False).Offset(0, 3)
If Not bCell Is Nothing Then
       MsgBox "Checking data Validity"
    ReplaceData = bCell.Address
End If

Set aCell = oRange.Find(What:=SearchString, LookIn:=xlValues, _
            LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
            MatchCase:=False, SearchFormat:=False)

If Not aCell Is Nothing Then
    FoundAt = aCell.Address
   Select Case MsgBox("The entered exists: " & FoundAt & "   " & ReplaceData & "  Replace?", vbYesNo)
    Case vbNo
    MsgBox "data entry cancelled"
    Case vbYes
    Select Case MsgBox("This will replace data: Are You Sure?", vbYesNo)
        Case vbYes
        bCell = VolBox.Value
        Case vbNo
        Call CommandButton1_Click
    End Select
End Select
Else
    MsgBox "Unique Data Entry Confirmed - submit data?", vbOKCancel
    Call AddDataRow
End If

Not terribly elegant unfortunately (and I don't know why the first 'find' for bCell fails if the entry is not found - although the aCell which seems to be virtually the same works fine?? Hence the resume on error).
This however will only check one data point (in this case year) so I can find out if the year column matches and then make a change to the volume data if the user wants to or stop if they don't.  What I can't do is use multiple criteria.  I don't see a way to have 'AND' with this?

A: Think I might have solved it (albeit in a slightly clumsy way!)
I've added a hidden column to my table generated from data entry by:
lastRow.Cells(1, 1) = YearBox.Text & "-" & QuarterBox.Text & "-" & SourceBox.Text

This creates a row which includes the data from all three variables.
I've then modified my search string in the 'find' code I posted in my question to be the same as the above:
SearchString = YearBox.Text & "-" & QuarterBox.Text & "-" & SourceBox.Text

That way it is only searching one box, but checks all three criteria.
Thanks for the help Siddharth.


text:
Q: node.js list all active threads I am trying to teach myself about synchronous and asynchronous writing in node.js right now.
Just out of interest I wanted to check all active threads while trying to write a random line into a txt.-file using fs.writeFile(). If there is any way to do so, I'd be pleased with an answer that could help me understand this subject.

A: Rather than using multiple threads, it is much easier to use multiple processes in Node.js. For example, the cluster module can run the same js code in multiple processes.
For more information on cluster module : How to use clusters in node js?
For getting a list of all processes, please refer to this post : how to get the list of process.
For more information on threads in node.js refer to : https://nodejs.org/api/worker_threads.html


text:
Q: Large space between text and tables I'm seemingly seeing a lot of white space between the main body text and tables, perhaps because I am using a three part table.

I've included a picture of what I am seeing. You can see the sheer waste of white space between the main text body and the table. I was wondering if anyone knew of any obvious solutions to this?

A: Several solutions:

*

*If you're using \begin{figure}[H] as @egreg suggested, change [H] to [h];

*Put \raggedbottom in the preamble.  Downside of this is that there can be more space than you'd like at the bottom of the pages;

*Put \allowdisplaybreaks in the preamble.  This will help if you have long formulas by breaking them across pages, which you may or may not find objectionable.


text:
Q: I want to convert tbl_df to ts for time series analysis. I have done it but lost my (Month) column which is date in my data I am trying to convert my data set tbl_df into time series (ts) to perform the forecasting ARIMA model.
These are the first 5 rows of my original dataset;
   Month      count
   <date>     <int>
 1 2016-01-01   431
 2 2016-02-01   478
 3 2016-03-01   468
 4 2016-04-01   488
 5 2016-05-01   445

After a successful conversion I have lost the Month column and got a strange date.
I have used the following code for conversion into ts;
 crime_monthly1 <- as.ts(crime_monthly)

I got this with Month col changes into strange numbers;
   Month count
 1 16801   431
 2 16832   478
 3 16861   468
 4 16892   488
 5 16922   445

I have applied this code to convert the date and whole dataset into ts but could not helped;
crime_monthly1$Month <- as.Date(crime_monthly1$Month, format = "%m/%d/%Y")
ts(crime_monthly1[,-1], start = as.Date(crime_monthly1$Month[1]), frequency = 1)

I got the following error;
Error in crime_monthly1$Month : $ operator is invalid for atomic vectors

The other issue is that I am getting Frequency just 1. Though my dataset is having monthly temporal resolution with 36 months, which i think should be 12 as in 1 year there are 12 months.
Can anyone please tell me the complete procedure for doing this. I am really sorry but I new to R and I searched previous questions also but could not found the exact solution in my case.

A: The simplest approach is this.
crime_ts <- ts(crime_monthly$count, start=2016, frequency=12)

But you might find it better to use a tsibble object rather than a ts object.
library(tidyverse)
library(tsibble)

crime_monthly <- tribble(
    ~Month,      ~count,
    "2016-01-01",  431,
    "2016-02-01",  478,
    "2016-03-01",  468,
    "2016-04-01",  488,
    "2016-05-01",  445) %>%
  mutate(Month = as.Date(Month))

crime_tsibble <- as_tsibble(crime_monthly, index=Month) %>%
  mutate(
    Month = yearmonth(Month)
  )
crime_tsibble
#> # A tsibble: 5 x 2 [1M]
#>      Month count
#>      <mth> <dbl>
#> 1 2016 Jan   431
#> 2 2016 Feb   478
#> 3 2016 Mar   468
#> 4 2016 Apr   488
#> 5 2016 May   445

Created on 2020-02-23 by the reprex package (v0.3.0)
Tools for using tsibble objects are in the tsibble, feasts and fable packages.

A: Assuming the input shown reproducibly in the Note at the end, convert it to a zoo object z using the yearmon index class which represents year/months. Then as.ts will convert it to ts class with the correct frequency.
library(zoo)

z <- read.zoo(DF, FUN = as.yearmon)
tt <- as.ts(z)

tt
##      Jan Feb Mar Apr May
## 2016 431 478 468 488 445

frequency(tt)
## [1] 12

class(tt)
## [1] "ts"

Note
The input in reproducible form is assumed to be:
Lines <- "   Month      count
 1 2016-01-01   431
 2 2016-02-01   478
 3 2016-03-01   468
 4 2016-04-01   488
 5 2016-05-01   445"
DF <- read.table(text = Lines)


text:
Q: DIsplay 'data loading' while using sendAsynchronousRequest:queue:completionHandler: I am using this block method to load my data from the server...
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:[myString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]]
                                            cachePolicy:NSURLRequestUseProtocolCachePolicy
                                        timeoutInterval:60.0];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection
 sendAsynchronousRequest:urlRequest
 queue:queue
 completionHandler: ^( NSURLResponse *response,
                      NSData *data,
                      NSError *error)
 {
     [[mySingleton dictionaryUserDetail] removeAllObjects];
     [[mySingleton arrayUserDetail] removeAllObjects];

     if ([data length] > 0 && error == nil) // no error and received data back
     {
         NSError* error;
         NSDictionary *myDic = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
         [mySingleton setDictionaryUserDetail:[myDic mutableCopy]];

         NSArray *myArray = [myDic objectForKey:@"searchResults"];
         [mySingleton setArrayUserDetail:[myArray mutableCopy]];

         dispatch_async(dispatch_get_main_queue(), ^{
             [self userDetailComplete];
         });
     } else if
         ([data length] == 0 && error == nil) // no error and did not receive data back
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             [self serverError];
         });
     } else if
         (error != nil) // error
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             [self serverError];
         });
     }
 }];

I would like to be able to show the user a progress bar instead of just a spinner. If I were using delegates I assume I could have used the NSURLConnectionDelegate
connection:didReceiveData:

but I do not know how to do this with a block. Anyone have some genius insight?

A: If you want to display a progress bar that shows the actual download progress then you have to use the delegate-based methods of NSURLConnection. sendAsynchronousRequest and sendSynchronousRequest do not provide methods for that.


text:
Q: CMake find packages using find_package in submodules folder Root
  CMakeLists.txt
  Valyrie/
    CMakeLists.txt
  Submodules/
    CMakeLists.txt
    SubmodulePackage/
       CMakeLists.txt

I have a directory structure listed like above. However even if I add_subdirectory("submodules") so the submodule packages get added first cmake won't find the packages with find_package inside the Valkyrie cmakelists.txt. Is there a way to do that? I'd do relative path, but some submodules don't seem to get brought in correctly by just relative pathing their header files for some reason (header-only library).
Root Level Cmake
cmake_minimum_required (VERSION 3.8)

project (Valkyrie)

# Include sub-projects.
add_subdirectory("submodules")
add_subdirectory("Valkyrie")

Submodules CMake
cmake_minimum_required (VERSION 3.8)

set(GLFW_BUILD_DOCS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_TESTS OFF CACHE BOOL "" FORCE)
set(GLFW_BUILD_EXAMPLES OFF CACHE BOOL "" FORCE)

add_subdirectory("json")
add_subdirectory("spdlog")
add_subdirectory("glfw")
add_subdirectory("entt")
add_subdirectory("glm")

Valkyrie
cmake_minimum_required (VERSION 3.8)

find_package(Vulkan REQUIRED)
find_package(spdlog REQUIRED) #Error here

file(GLOB_RECURSE sources CONFIGURE_DEPENDS "*.cpp")
file(GLOB_RECURSE headers CONFIGURE_DEPENDS "*.h")

add_library(Valkyrie ${headers} ${sources})
target_compile_features(Valkyrie PUBLIC cxx_std_20)

target_include_directories(Valkyrie
    PUBLIC "../submodules/glfw/include"
    PUBLIC "../submodules/glm"
    PUBLIC "../submodules/entt/single_include"
    PUBLIC "../submodules/spdlog/include"
    PUBLIC ${Vulkan_INCLUDE_DIRS}
)

target_link_libraries(Valkyrie
"${CMAKE_BINARY_DIR}/submodules/glfw/src/glfw3.lib"
${Vulkan_LIBRARIES}
)


text:
Q: Why are parenthesis in my WHERE clause messing up the JOIN? (SQL) I'm working with DVM v1.1.0: https://www.ibm.com/docs/en/dvm/1.1.0?topic=reference-supported-sql-functions. When I try to use parenthesis in a WHERE statement within a UNION, and then JOIN it with another table, it gives me the following error:

Invalid keyword LEFT found in FROM list

I have 2 tables that I need to UNION (call them U_1 and U_2), and then a 3rd table that I have to LEFT OUTER JOIN (call it J_1).
U_1 and U_2 have 2 columns that I need to filter on: 1 column that has 1 desired value, 'G' (FILTER_1VAL), and 1 column that has 2 desired values, '1' or '2' (FILTER_2VAL).
I have this SQL call to UNION U_1 and U_2 with this filter:
SELECT *
FROM U_1
WHERE FILTER_1VAL = 'G' AND (FILTER_2VAL = '1' OR FILTER_2VAL = '2')

UNION

SELECT *
FROM U_2
WHERE FILTER_1VAL = 'G' AND (FILTER_2VAL = '1' OR FILTER_2VAL = '2')

This returns (as expected) every column of U_1 and U_2 that matches these filters.
I also have some skeleton syntax for a JOIN clause on a UNION of these tables:
SELECT *
FROM
    (SELECT * FROM U_1
     UNION
     SELECT * FROM U_2) full_union
LEFT OUTER JOIN
    J_1 joined ON full_union.field1 = joined.field1

This also works as expected; returning U_1 and U_2 together with data from J_1 where applicable.
Then, you can add some simple WHERE clauses in the nested UNION to do some data filtering:
SELECT *
FROM
    (SELECT *
     FROM U_1
     WHERE FILTER_1VAL = 'G' AND FILTER_2VAL = '1' OR FILTER_2VAL = '2'
     UNION
     SELECT *
     FROM U_2
     WHERE FILTER_1VAL = 'G' AND FILTER_2VAL = '1' OR FILTER_2VAL = '2') full_union
LEFT OUTER JOIN
    J_1 joined ON full_union.field1 = joined.field1

This runs fine and returns as expected.
However, when I add parenthesis to the WHERE clause to do more complicated filtering, and ensure that it's filtering based on the proper AND/OR logic that I want, it can't run the query:
SELECT *
FROM (
    SELECT *
    FROM U_1
    WHERE FILTER_1VAL = 'G'
      AND (
           FILTER_2VAL = '1'
        OR FILTER_2VAL = '2'
      )

    UNION
    SELECT *
    FROM U_2
    WHERE FILTER_1VAL = 'G'
      AND (
           FILTER_2VAL = '1'
        OR FILTER_2VAL = '2'
      )
  ) full_union
  LEFT OUTER JOIN J_1 joined ON full_union.field1 = joined.field1

13:20:33:643, 28 Jul 2021 - Error executing statement.
13:20:33:643, 28 Jul 2021 - [DV][JDBC Driver] Invalid keyword LEFT found in FROM list
13:20:33:643, 28 Jul 2021 - Stop SQL Execution (Iteration Time = 47  ms).

It really seems like the presence of () within the WHERE clause is what triggers this error to occur; why would this be? Is there any way to avoid this, or coerce the logical order of operations so I can achieve the filtering I want without using parenthesis?
EDIT 7/29:
See Power Mouse's comment below. Changing the query to:
SELECT *
FROM (
    SELECT *
    FROM U_1
    WHERE FILTER_1VAL = 'G'
      AND (
           FILTER_2VAL = '1'
        OR FILTER_2VAL = '2'
      )
      AND 1=1

    UNION
    SELECT *
    FROM U_2
    WHERE FILTER_1VAL = 'G'
      AND (
           FILTER_2VAL = '1'
        OR FILTER_2VAL = '2'
      )
      AND 1=1
  ) full_union
  LEFT OUTER JOIN J_1 joined ON full_union.field1 = joined.field1

Removed the error and returned the correct result. My best guess is an issue with the SQL parser in DVM.

A: I suspect that U_1, U_2, and J_1 are not your actual table names, and that the code in your question was not copied and pasted directly to the post.  You likely have mismatched parentheses, but you may have typed the query for the post correctly.
Write your SQL in a way that is readable and easy to troubleshoot.  Then it will be easier to see that you are missing a closing parenthesis at the end of your second WHERE clause.  (Technically, right after the subquery.)


text:
Q: How to represent a JSON object variable with Proto definition I want to define a request message in gRPC which should have a Json Object as a field
For e.g.
message UserRequest{
    string name = 1;
    string city = 2;
    string email = 3;
    metainfo = 4;//A Json Object variable which can have any number of elements
}

How do I represent the metainfo property within proto definition?
I have tried using below definition but it didn't work.
message UserRequest{
    string name = 1;
    string city = 2;
    string email = 3;
    google.protobuf.Any metainfo = 4;
}

A: I think you want a .google.protobuf.Struct, via struct.proto - this essentially encapsulates a map<string, Value> fields, and is broadly akin to what you would want to describe via JSON. Additionally, Struct has custom JSON handling, as mentioned in the file:

The JSON representation for Struct is JSON object.

So:
    .google.protobuf.Struct metainfo = 4;


text:
Q: How I can upload LZMA file format to AWS? I want to upload a file that LZMA Format(unity asset bundle) to Amazon server using PUT method but I always get an error said:
"errorMessage": "Expected params.Body to be a string, Buffer, Stream, Blob, or typed array object".
I try to buffer the file but it is not working so what is the best way to upload this type of file.
                    var aws = require('aws-sdk');
                    var s3 = new aws.S3();
                    var mime = require('mime-types');
                    //.....
                    var mimetype = mime.lookup(f.name);
                    if (mimetype == false) {
                        mimetype = 'application/octet-stream';
                    }
                  //is not working
                  //  var buffer = Buffer.from(new Uint8Array (f));
                  // fs.readFile(f, function (err, data)
                  s3.putObject({
                            Bucket: "my backet",
                            Key: f.name,
                            Body: f,
                            ContentType: mimetype,
                            CacheControl: 'no-cache',
                            Expires: 0
                        }, function(err, data) {
                            if (err) {
                                context.fail(err, "error");
                            }
                            console.log("success:" + f.name);
                        });


text:
Q: @ContentChild not working in directive applied to custom component I have a custom component that is a <h1> tag and an <input> tag. I want be be able to access the input from my custom directive however when I try to use Angular's @ContentChild attribute, it is always undefined.
If I apply my custom directive to a native <input>, it works fine.
I have set up a StackBlitz highlighting this issue here: https://stackblitz.com/edit/using-contentchild-in-directive
If you open the JavaScript console after the page has loaded, you will see:
Native Component: ElementRef {nativeElement: input}
Custom Component: undefined

How can I access the <input> within the custom component from the directive?

A: Well this behavior is because you are accessing contentChild with Template Reference Variable called control:
@ContentChild('control',null) public ctrlByName: any;

and it is only assigned to input element:
<input  #control name="Native Component" testDirective />

thats why test-component is not being detected by ContentChild
so you can actually assign el from ElementRef to your element and it will work fine, you wont need ContentChild:
constructor(private el: ElementRef) {
    this.name = el.nativeElement.attributes.name.value;
    this.ctrlByName = el;
}

Working DEMO


text:
Q: How do I use regex to split only on commas not in angle brackets? I have the string
DobuleGeneric<DoubleGeneric<int,string>,string>
I am trying to grab the 2 type arguments:
DoubleGeneric<int,string> and string
Initially I was using a split on ','. This worked, but only if the generic args are not themeselves generic.
My Code:
string fullName = "DobuleGeneric<DoubleGeneric<int,string>,string>";
Regex regex = new Regex( @"([a-zA-Z\._]+)\<(.+)\>$" );
Match m = regex.Match( fullName );
string frontName = m.Groups[1].Value;
string[] innerTypes = m.Groups[2].Value.Split( ',' );

foreach( string strInnerType in innerTypes ) {
        Console.WriteLine( strInnerType );
}

Question:
How do I do a regex split on commas that are not encapsulated in angle brackets?

A: Both commas are between angle brackets! Regex does a bad job when parsing a complex nested syntax. The question should be, how to find a comma, which is between angle brackets that are themselves not between angle brackets. I don't think that this can be done with regex.
If possible, try to work with Reflection. You might also use CS-Script to compile your code snippet and then use Reflection to retrieve the information you need.

A: To split the example you have given you can use the following. However, this is not generic; it could be made generic based on the other strings that you expect. Depending on the variation of the strings you have, this method could get complex; but I would suggest that the use of Roslyn here is overkill...
string fullName = "DobuleGeneric<DoubleGeneric<int,string>,string>";
Regex Reg =
    new Regex(@"(?i)<\s*\p{L}+\s*<\s*\p{L}+\s*,\s*\p{L}+\s*>\s*,\s*\p{L}+\s*>");
Match m = Reg.Match(fullName);
string str = m.ToString().Trim(new char[] { '<', '>' });
Regex rr = new Regex(@"(?i),(?!.*>\s*)");
string[] strArr = rr.Split(str);

I hope this helps.

A: The answers are correct, using Regex is the wrong approach.
I ended up doing a linear pass, replacing items encapsulated in brackets with ~s, and then doing a split.
static void Main( string[] args ) {

    string fullName = "Outer<blah<int,string>,int,blah<int,int>>";

    Regex regex = new Regex( @"([a-zA-Z\._]+)\<(.+)\>$" );
    Match m = regex.Match( fullName );
    string frontName = m.Groups[1].Value;
    string inner = m.Groups[2].Value;

    var genArgs = ParseInnerGenericArgs( inner );

    foreach( string s in genArgs ) {
        Console.WriteLine(s);
    }
    Console.ReadKey();
}

private static IEnumerable<string> ParseInnerGenericArgs( string inner ) {
    List<string> pieces = new List<string>();
    int angleCount = 0;
    StringBuilder sb = new StringBuilder();
    for( int i = 0; i < inner.Length; i++ ) {
        string currChar = inner[i].ToString();
        if( currChar == ">" ) {
            angleCount--;
        }
        if( currChar == "<" ) {
            angleCount++;
        }
        if( currChar == ","  &&  angleCount > 0 ) {

            sb.Append( "~" );

        } else {
            sb.Append( currChar );
        }

    }
    foreach( string item in sb.ToString().Split( ',' ) ) {
        pieces.Add(item.Replace('~',','));
    }
    return pieces;
}

A: Here is the regex I will use:
\<(([\w\.]+)(\<.+\>)?)\,(([\w\.]+)(\<.+\>)?)$

([\w\.]+) matches "DoubleGeneric".
(\<.+\>)? matches the possible generic args like DoubleGeneric<OtherGeneric<int, ...>>
The key point is that no matter how many nested generic args you have you will have only one ">," in the whole expression.
You can use m.Gruops[1] and m.Groups[4] to get the first and second Type.


text:
Q: Ildasm for .NET 4.5 I've been trying to use Unmanaged Export for project in .NET 4.5, but when compiling it says that:
Microsoft.Build.Utilities.ToolLocationHelper could not find ildasm.exe . And it is mostly true, as there is no folder bin with ildasm.exe at C:\Program Files (x86)\Microsoft SDKs\Windows\v8.1.
Although it is present in this location C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin, I've tried copying bin folder, but it doesn't work.
Do you know how can I achieve UnamanagedExport to work with .NET 4.5?

A: I'll just put this here if someone find this question.
To reinstall .NET 4.5 SDK in Visual Studio 2019 (in my case), you have to download and install Microsoft Build Tools 2015.
https://www.microsoft.com/en-us/download/confirmation.aspx?id=48159
HTH,
Edin


text:
Q: QT : attempting to reference a deleted function I know this question has been asked numerous time (there and there for example) but unfortunately, those solutions are not working for my case.
Background
Error message: 'ADACEL::SPEECH::SRA::StatusRow::StatusRow(const ADACEL::SPEECH::SRA::StatusRow &)': attempting to reference a deleted function
From my reading, I understand that the problem could be from the copy constructor of QObject, but I don't know how to fix this!

So, see my classe  :
namespace ADACEL
{
    namespace SPEECH
    {
        namespace SRA
        {
            class StatusRow: public QObject
            {
                Q_OBJECT
                Q_PROPERTY(QString name READ name WRITE setName NOTIFY nameChanged)
                Q_PROPERTY(QString icon READ icon WRITE setIcon NOTIFY iconChanged)

            public:
                StatusRow(QObject *parent = 0);
                StatusRow(const QString &name, const QString &color, QObject *parent = 0);
                //StatusRow(const StatusRow&) = delete;
                ~StatusRow(void) {};

                QString name() const;
                void setName(const QString &name);

                QString icon() const;
                void setIcon(const QString &icon);

                //StatusRow& operator=(const StatusRow&) = delete;

            Q_SIGNALS:
                void nameChanged();
                void iconChanged();

            private:
                QString m_name;
                QString m_icon;
            };
        }
    }
}

Q_DECLARE_METATYPE(ADACEL::SPEECH::SRA::StatusRow)

Instantiation of my classe:
StatusWindow::StatusWindow(GUIDataLayer* pUiDataLayer) : QDeclarativeView(0),
                                                         m_statusRows(0)
{
    setWindowModality(Qt::ApplicationModal);

    m_statusRows = new QList<StatusRow*>();
    m_statusRows->append(new StatusRow(TITLE_AUDIO_PROVIDER, ICON_OK));
    m_statusRows->append(new StatusRow(TITLE_ADAPTER, ICON_ERROR));

    rootContext()->setContextProperty("statusInfo", QVariant::fromValue(m_statusRows));
    rootContext()->setContextProperty("uiDataLayer", pUiDataLayer);
...
}

What I tried so far
I already tried this Q_DECLARE_METATYPE(ADACEL::SPEECH::SRA::StatusRow*) but then I have the error Type is not registered, please use the Q_DECLARE_METATYPE macro to make it known to Qt's meta-object system
Also, Q_DECLARE_METATYPE is only necessary when I am using a pointer into the QVariant.  The following is compiling without any problem :
QList<StatusRow*> statusRows;
statusRows.append(new StatusRow(TITLE_AUDIO_PROVIDER, ICON_OK));
statusRows.append(new StatusRow(TITLE_ASR_ENGINE, ICON_NONE));
statusRows.append(new StatusRow(TITLE_POST_PROCESSOR, ICON_NONE));
statusRows.append(new StatusRow(TITLE_ADAPTER, ICON_ERROR));
rootContext()->setContextProperty("statusInfo", QVariant::fromValue(statusRows));

A: I do not observe the error you indicate, I also prefer to use QVariantList instead of QList <T* > to export a list of QObjects:
main.cpp
using namespace ADACEL::SPEECH::SRA;

QVariantList statusRows;
statusRows.append(QVariant::fromValue(new StatusRow("TITLE_AUDIO_PROVIDER", "ICON_OK")));
statusRows.append(QVariant::fromValue(new StatusRow("TITLE_ASR_ENGINE", "ICON_NONE")));
statusRows.append(QVariant::fromValue(new StatusRow("TITLE_POST_PROCESSOR", "ICON_NONE")));
statusRows.append(QVariant::fromValue(new StatusRow("TITLE_ADAPTER", "ICON_ERROR")));

QQuickView view;
view.rootContext()->setContextProperty("statusInfo", QVariant::fromValue(statusRows));


text:
Q: Missing getSystemService(String) I can't use getSystemService(String) from the Context library I want to use it here, but it's missing.
I want this

A: Try to access with context object if you are accessing this method in non activity class.
  context.getSystemService(Context.POWER_SERVICE);