text:
Q: How to properly validate OpenIddict JWT access_token in API? I'm trying to implement an identity server based on OpenIddict. The use case we have is one large javascript application that needs to authenticate users to multiple back-end APIs. The javascript application gets a token from a dedicated OpenIddict server using the password flow. The token is then validated by the various APIs that are called by the front end.
I've implemented the server using ASP.NET Identity and EF, and can successfully retrieve a valid token. Our APIs are running in AWS Lambda, so we can't (or don't want to) use the standard .AddDataProtection methods. We use a self-signed certificate stored in S3 to generate the tokens and validate them.
Then problem is that when I send the access_token to the back-end APIs, they are not able to validate the token and provide access. I know the tokens are valid because I can manually decrypt them in Linqpad using a JwtSecurityTokenHandler and the self-signed certificate.
Here is my server configuration:
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddIdentity<ApplicationUser, IdentityRole>(options =>
            {
                options.ClaimsIdentity.UserNameClaimType = Claims.Name;
                options.ClaimsIdentity.UserIdClaimType = Claims.Subject;
                options.ClaimsIdentity.RoleClaimType = Claims.Role;
            })
            .AddEntityFrameworkStores<ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddOpenIddict()
            .AddCore(options =>
            {
                options.UseEntityFrameworkCore().UseDbContext<ApplicationDbContext>();
            })
            .AddServer(options =>
            {
                options.SetTokenEndpointUris("/connect/token");
                options.AllowPasswordFlow();
                options.AcceptAnonymousClients();
                options.AddEncryptionCertificate(MyCustomCertificate);
                options.AddSigningCertificate(MyOtherCustomCertificate);
                options.UseAspNetCore().EnableTokenEndpointPassthrough();
            });

            services.AddDbContext<ApplicationDbContext>(options =>
            {
                options.UseSqlServer(connectionString);
                options.UseOpenIddict();
            });

        }

I've tried two different confiugrations in the API, and neither of them work. Option 1, preferred, using the built-in OpenIddict token validation:
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();

            services.AddOpenIddict().AddValidation(
                options =>
                {
                    options.SetTokenValidationParameters(config =>
                    {
                        config.ValidateAudience = false; //just to make sure it's not a typo causing the problem
                        config.ValidateIssuer = false; //just to make sure it's not a typo causing the problem
                        config.TokenDecryptionKey = new X509SecurityKey(MyCustomCertificate);
                        config.IssuerSigningKey = new X509SecurityKey(MyOtherCustomCertificate);
                    });

                    options.UseAspNetCore();
                });

        }

This invariably results in {"error":"invalid_token","error_description":"The specified token is not valid."}, even though I can manually decrypt and validate the token. I've tried setting the default log level to Trace, but nothing else shows up in the log that might explain where the problem is.
Option 2, using built-in .NET token validation:
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
                .AddJwtBearer(options =>
                {
                    options.Authority = "https://openiddictserver";
                    options.Audience = "clientid";
                    options.RequireHttpsMetadata = false;
                    options.IncludeErrorDetails = true;
                    options.TokenValidationParameters = new TokenValidationParameters()
                    {
                        NameClaimType = OpenIdConnectConstants.Claims.Subject,
                        RoleClaimType = OpenIdConnectConstants.Claims.Role,
                        ValidateAudience = false, //just to make sure it's not a typo problem
                        ValidateIssuer = false, //just to make sure it's not a typo problem
                        TokenDecryptionKey = new X509SecurityKey(MyCustomCertificate),
                        IssuerSigningKey = new X509SecurityKey(MyOtherCustomCertificate)
                    };
                });

Option 2 just results in a 401 with no helpful info whatsoever.
Some more context:

*

*I can validate the signed id_token just fine. It's only when trying to use the encrypted access_token that I run into trouble

*I'm calling app.UseAuthentication() in the correct place and the [Authorize(AuthenticationScheme="something")] attributes are correct.

*I'm using the OpenIddict.AspNetCore package version 3.0.0 from the dedicated openiddict nuget feed.

I'm fairly certain it just comes down to not being able to decrypt the access_token in the proper way in the API.

A: The behavior you're seeing is caused by a limitation in the alpha bits of the OpenIddict validation handler, that checks whether TokenValidationParameters.IssuerSigningKeys is null, but not TokenValidationParameters.IssuerSigningKey.
To work around it, you can use:
config.IssuerSigningKeys = new[] { new X509SecurityKey(MyOtherCustomCertificate) };

Alternatively, you can use discovery to allow it to download the signing keys from the authorization server:
services.AddOpenIddict()
    .AddValidation(options =>
    {
        options.SetIssuer(new Uri("https://localhost:44365/"));
        options.AddEncryptionCertificate(AuthenticationExtensionMethods.TokenEncryptionCertificate());

        options.UseAspNetCore();
        options.UseSystemNetHttp();
    });

It's worth noting that the options.SetTokenValidationParameters() method will be removed very soon (as part of the introspection support addition). The new syntax for registering a static OIDC configuration will be something like that:
services.AddOpenIddict()
    .AddValidation(options =>
    {
        options.SetConfiguration(new OpenIdConnectConfiguration
        {
            Issuer = "https://localhost:44365/",
            SigningKeys = { new X509SecurityKey(AuthenticationExtensionMethods.TokenSigningCertificate()) }
        });

        options.AddEncryptionCertificate(AuthenticationExtensionMethods.TokenEncryptionCertificate());
    });


text:
Q: Convert an array of strings to a vector of numbers I have this:
d = {'2.5', '3.5'};
d =
'2.5'    '3.5'

How do I convert it to a vector of numbers?
d = 2.5   3.5

A: Given that you have a cell array of string values, you can use cellfun to apply str2num conversion on each entry. The output will be a vector/matrix of the converted values.
d = {'2.3','3.5'}
dVec = cellfun(@str2num, d);

However, you are better using str2double than str2num. From the documentation:

Note: str2num uses the eval function to convert the input argument.
  Side effects can occur if the string contains calls to functions.
  Using str2double can avoid some of these side effects.

dVec = cellfun(@str2double, d);

Update: As @yuk points out, you can call str2double() directly on the cell array for the same output.
dVec = str2double(d);

Note that the same call with str2num() will give the "must be a string or string array" error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a way to print integers normally that are assigned to a pointer array? I am creating a program that involves pointers and arrays and I have stumbled upon a problem.
Basically, I created three integers that would get its value from the user's input and later declared them all in an array in order to change all of their values in one single loop.
Then I declared a pointer which uses the array inside a loop in order to do that.
Expecting the pointer-array in the loop to print out the data in a normal order, rather, it had printed it backwards.
Mind you, I am a huge beginner to programming C++ and is still learning about pointers.
I have tried changing the index number in
pntr = &salary[3];

but 3 is the only one that prints out every input in the loop.
0 doesn't do the trick, same goes to 1, 2, 4 and so on and so forth.
I would like to have the new output to have the same syntax (salary1, salary2, salary3) and not reverse it (salary3, salary2, salary1) to have the inputted values be printed out.
Here is the code:
#include <iostream>
using namespace std;

int main() {
    int salary1, salary2, salary3;
    cout << "Enter salary for John: ";
    cin >> salary1;
    cout << "Enter salary for Mark: ";
    cin >> salary2;
    cout << "Enter salary for Nathan: ";
    cin >> salary3;
    cout << "Name \t Age \t Position \t Salary" << endl;
    cout << "John \t 16 \t Engineer \t " << salary1 << endl;
    cout << "Mark \t 16 \t Scouter \t " << salary2 << endl;
    cout << "Nathan \t 17 \t Manager \t " << salary3 << endl;
    int salary[3] = {salary1, salary2, salary3};
    int *pntr;
    pntr = &salary[3];
    for(int x = 0; x < 3; x++) {
        cout << "Enter new salary: " << endl;
        cin >> *(pntr + x);
        cout << "Salary 1:" << salary1 << endl;
        cout << "Salary 2:" << salary2 << endl;
        cout << "Salary 3:" << salary3 << endl;
    }
    cout << "Name \t Age \t Position \t Salary" << endl;
    cout << "John \t 16 \t Engineer \t " << salary1 << endl;
    cout << "Mark \t 16 \t Scouter \t " << salary2 << endl;
    cout << "Nathan \t 17 \t Manager \t " << salary3 << endl;
    return 0;
}

A: Your immediate issue is two-fold. You initialize your pointer and immediately point it out of the array. If you have an array of capacity 3, your indices are as follows:
 --- --- ---
| 0 | 1 | 2 |
 --- --- ---

Index 3 is not in your array, so your pointer is pointing outside of it. Change your initialization to: int* pntr = salary;.
Then, your other issue is that while you put the new salaries into the array, you never access the array again. Instead, you look at your three int variables again, which you never modified. The variables are also not needed for this exercise at all.
Here is a cut-down version of your code that fixes the immediate issue.
#include <iostream>

int main() {
  int salary1, salary2, salary3;

  std::cout << "Enter salary for John: ";
  std::cin >> salary1;
  std::cout << "Enter salary for Mark: ";
  std::cin >> salary2;
  std::cout << "Enter salary for Nathan: ";
  std::cin >> salary3;
  std::cout << "Name \t Age \t Position \t Salary" << '\n';
  std::cout << "John \t 16 \t Engineer \t " << salary1 << '\n';
  std::cout << "Mark \t 16 \t Scouter \t " << salary2 << '\n';
  std::cout << "Nathan \t 17 \t Manager \t " << salary3 << '\n';

  int salary[3] = {salary1, salary2, salary3};
  int *pntr = salary;  // CHANGED

  // CHANGE: Print the array
  for (auto i : salary) {
    std::cout << i << '\n';
  }

  for (int x = 0; x < 3; x++) {
    std::cout << "Enter new salary: ";
    std::cin >> *(pntr + x);
    std::cout << "Salary " << x + 1 << ": " << salary[x]
              << '\n';  // CHANGED: Access the array
  }

  // CHANGE: Print the array
  for (auto i : salary) {
    std::cout << i << '\n';
  }

  return 0;
}

It seems odd that you would have an array just for salaries. Here is a fresh take on your program that utilizes some C++ concepts that you likely haven't seen yet, but I hope you'll be able to appreciate how much simpler it makes your code. Note that I wouldn't call this code best practices by a long shot, but I think it serves its purpose of demonstrating some new principles.
The biggest design change is that instead of an array of just salaries, we have an array of people, and we can change their salaries if we need to.
#include <iomanip>
#include <iostream>
#include <vector>

struct Person {
  std::string name;
  int age;
  std::string title;
  int salary;
};

void print_table(const std::vector<Person>& emp) {
  std::size_t maxNameLength = 0;
  std::size_t maxTitleLength = 0;
  for (auto i : emp) {
    if (i.name.length() > maxNameLength) maxNameLength = i.name.length();
    if (i.title.length() > maxTitleLength) maxTitleLength = i.title.length();
  }

  std::cout << std::setw(maxNameLength + 1) << "Name"
            << "|Age|" << std::setw(maxTitleLength + 1) << "Title"
            << "|Salary\n";
  for (auto i : emp) {
    std::cout << std::setw(maxNameLength + 1) << i.name << "|" << std::setw(3)
              << i.age << "|" << std::setw(maxTitleLength + 1) << i.title << "|"
              << std::setw(6) << i.salary << '\n';
  }
}

int main() {
  std::vector<Person> employees{{"John", 16, "Engineer", 0},
                                {"Mark", 16, "Scouter", 0},
                                {"Nathan", 17, "Manager", 0}};

  for (int x = 0; x < 3; x++) {
    std::cout << "Enter new salary for " << employees[x].name << ": ";
    std::cin >> employees[x].salary;
  }

  print_table(employees);

  return 0;
}

Output:
Enter new salary for John: 34
Enter new salary for Mark: 45
Enter new salary for Nathan: 56
   Name|Age|    Title|Salary
   John| 16| Engineer|    34
   Mark| 16|  Scouter|    45
 Nathan| 17|  Manager|    56

A: If you want to change values of salary1, salary2, salary3, you should declare salary[3] for int*, not int!
int salary[3] = { salary1, salary2, salary3 };
to
int* salary[3] = { &salary1, &salary2, &salary3 };
then your pointer also should be double-pointer like:
int** pntr = salary;
finally you should dereference (pntr + x) double times because it's now double-pointer:
cin >> **(pntr + x);
whole code:
#include <iostream>
using namespace std;
int main() {
    int salary1, salary2, salary3;

    cout << "Enter salary for John: ";
    cin >> salary1;
    cout << "Enter salary for Mark: ";
    cin >> salary2;
    cout << "Enter salary for Nathan: ";
    cin >> salary3;
    cout << "Name \t Age \t Position \t Salary" << endl;
    cout << "John \t 16 \t Engineer \t " << salary1 << endl;
    cout << "Mark \t 16 \t Scouter \t " << salary2 << endl;
    cout << "Nathan \t 17 \t Manager \t " << salary3 << endl;

    int* salary[3] = { &salary1, &salary2, &salary3 };
    int** pntr = salary;

    for (int x = 0; x < 3; x++) {
        cout << "Enter new salary: " << endl;
        cin >> **(pntr + x);
        cout << "Salary 1:" << salary1 << endl;
        cout << "Salary 2:" << salary2 << endl;
        cout << "Salary 3:" << salary3 << endl;
    }

    cout << "Name \t Age \t Position \t Salary" << endl;
    cout << "John \t 16 \t Engineer \t " << salary1 << endl;
    cout << "Mark \t 16 \t Scouter \t " << salary2 << endl;
    cout << "Nathan \t 17 \t Manager \t " << salary3 << endl;

    return 0;
}

you might still have some question about the line
int** pntr = salary;
pntr is int** type and salary is int*[3] type,
array's address represents the array's first element's address,
so it's same with:
int** pntr = &salary[0];
you can easily find it same
just execute whole code with above two different initialization
you may write int** pntr = &salary[3]; if you don't have clear understanding
&salary[3] is representing salary[3]'s address,
and salary[3] is just an int* value, not an array "type"
it represents the array salary's third element's address, remember it
only in initialization index represents the size of array, after initialization index represents value

A: #include <iostream>

using namespace std;
int main() {
    int salary1, salary2, salary3;

    cout << "Enter salary for John: ";
    cin >> salary1;
    cout << "Enter salary for Mark: ";
    cin >> salary2;
    cout << "Enter salary for Nathan: ";
    cin >> salary3;
    cout << "Name \t Age \t Position \t Salary" << endl;
    cout << "John \t 16 \t Engineer \t " << salary1 << endl;
    cout << "Mark \t 16 \t Scouter \t " << salary2 << endl;
    cout << "Nathan \t 17 \t Manager \t " << salary3 << endl;

    int salary[3] = {salary1, salary2, salary3};

    for (int x = 0; x < 3; x++) {
      cout << "Enter new salary: " << endl;
      cin >> * (salary + x);
      cout << "Salary " << x << ": " << * (salary + x) << endl;
    }

    cout << "Name \t Age \t Position \t Salary" << endl;
    cout << "John \t 16 \t Engineer \t " << salary[0] << endl;
    cout << "Mark \t 16 \t Scouter \t " << salary[1] << endl;
    cout << "Nathan \t 17 \t Manager \t " << salary[2] << endl;
}

Perhaps you want something like this in the end ?
Things to note :

*

*arrays decay to pointer so you don 't need the extra pointer

*salary1, salary2, salary3 will not be overwritten as you probably expected as they are never touched.The memory in the salary array will be overwritten when you do cin >> *(salary+ x);

*So in the end you want to print what is in the array and not the salary1, 2, 3 variables (probably)


text:
Q: Fixing Traceback (most recent call last): in Bar code reader using Python I used the following code to get the reading from a USB bar code reader connected to a raspberry pi.
#!/usr/bin/python
import sys

def barcode_reader():
    hid = {4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f', 10: 'g', 11: 'h', 12: 'i', 13: 'j', 14: 'k', 15: 'l', 16: 'm',
           17: 'n', 18: 'o', 19: 'p', 20: 'q', 21: 'r', 22: 's', 23: 't', 24: 'u', 25: 'v', 26: 'w', 27: 'x', 28: 'y',
           29: 'z', 30: '1', 31: '2', 32: '3', 33: '4', 34: '5', 35: '6', 36: '7', 37: '8', 38: '9', 39: '0', 44: ' ',
           45: '-', 46: '=', 47: '[', 48: ']', 49: '\\', 51: ';', 52: '\'', 53: '~', 54: ',', 55: '.', 56: '/'}

    hid2 = {4: 'A', 5: 'B', 6: 'C', 7: 'D', 8: 'E', 9: 'F', 10: 'G', 11: 'H', 12: 'I', 13: 'J', 14: 'K', 15: 'L', 16: 'M',
            17: 'N', 18: 'O', 19: 'P', 20: 'Q', 21: 'R', 22: 'S', 23: 'T', 24: 'U', 25: 'V', 26: 'W', 27: 'X', 28: 'Y',
            29: 'Z', 30: '!', 31: '@', 32: '#', 33: '$', 34: '%', 35: '^', 36: '&', 37: '*', 38: '(', 39: ')', 44: ' ',
            45: '_', 46: '+', 47: '{', 48: '}', 49: '|', 51: ':', 52: '"', 53: '~', 54: '<', 55: '>', 56: '?'}

    fp = open('/dev/hidraw0', 'rb')

    ss = ""
    shift = False

    done = False

    while not done:
        # Get the character from the HID
        buffer = fp.read(8)
        for c in buffer:
            if ord(c) > 0:

                #  40 is carriage return which signifies

                if int(ord(c)) == 40:
                    done = True
                    break;

                #  use the hid2 characters.
                if shift:

                    # If it is a '2' then it is the shift key
                    if int(ord(c)) == 2:
                        shift = True

                    # if not a 2 then lookup the mapping
                    else:
                        ss += hid2[int(ord(c))]
                        shift = False

                #  If not shifted then use
                #  the hid characters

                else:

                    # If it is a '2' then it is the shift key
                    if int(ord(c)) == 2:
                        shift = True

                    # if not a 2 then lookup the mapping
                    else:
                        ss += hid[int(ord(c))]
    return ss

if __name__ == "__main__":
    try:
        while True:
            barcode_reader()
    except KeyboardInterrupt:
        pass

when this is executed, it get the following error message.
Traceback (most recent call last):
  File "C:\Users\buddhika\Desktop\barcode_test.py", line 66, in <module>
    barcode_reader()
File "C:\Users\buddhika\Desktop\barcode_test.py", line 16, in barcode_reader
    fp = open('/dev/hidraw0', 'rb')
FileNotFoundError: [Errno 2] No such file or directory: '/dev/hidraw0'

I tried the methods given in the internet to fix first error, but still the issue is there. The second error was corrected.
Why the first error message still comes and how to fix this.


text:
Q: Oracle query that can filter paired data I need some help with an Oracle query that can skip 'pairs' and only pick non paired data. Example:
Id      cost   hour type
123     $1.00  1    Input
123     $1.00  1    Output

234     $2.00  4    Input
345     $5.00  4    Output

236     $3.00  5    Input
236     $3.00  3    Output

In this example, the first two lines are a 'pair', since thir first 3 fields match; 3rd and 4th, and 5th and 6th lines are not a 'pair', since their first three fields do not match.

A: You may use window function and Partition by
select id, cost, hour, type
  from (
  select id, cost, hour, type,
         count(*) over(partition by id, cost, hour) as cn
  from mytable) t
where cn=1;

A: I changed column name "hour" to "hours" and "type" to "type_" (it is not good to use reserved Oracle words as object names, including column names). I assumed the cost is given as a number, not with the $ sign shown. (If it's a string, that's a bad idea to begin with.)
with
     input_data ( id, cost, hours, type_ ) as (
       select 123, 1.00, 1, 'Input'  from dual union all
       select 123, 1.00, 1, 'Output' from dual union all
       select 234, 2.00, 4, 'Input'  from dual union all
       select 345, 5.00, 4, 'Output' from dual union all
       select 236, 3.00, 5, 'Input'  from dual union all
       select 236, 3.00, 3, 'Output' from dual
     ),
     prep ( id, cost, hours, type_, rn, pairs ) as (
       select id, cost, hours, type_,
              row_number() over (partition by id, cost, hours, type_ order by null),
              least ( count(case when type_ = 'Input'  then 1 end)
                                        over (partition by id, cost, hours),
                      count(case when type_ = 'Output' then 1 end)
                                        over (partition by id, cost, hours)
                    )
       from input_data
     )
select id, cost, hours, type_
from   prep
where  rn > pairs
;

row_number() counts the rows for fixed id, cost, hours and type_ (I don't care in what order, I just need them "enumerated") and pairs counts how many pairs there are. In the final select, I just keep rows where the row_number is greater than pairs - that does exactly what you need.
        ID       COST      HOURS TYPE_
---------- ---------- ---------- ------
       234          2          4 Input
       236          3          3 Output
       236          3          5 Input
       345          5          4 Output

4 rows selected.

A: The lag() analytic function should suffice.
    select * from stackovf svf where id not in (select id from (select svf.*,
    (case when lag(id) over (partition by id,cost,hour order by 1)=id
    and lag(cost) over (partition by id,cost,hour order by 1)=cost
    and lag(hour) over (partition by id,cost,hour order by 1)=hour then 1
    else 0 end )as match_found
    from stackovf svf)
    where  match_found=1)


text:
Q: macro to email Access reports not as an attachment I don't know VBA.  Is there a way for me have the macro to send the email where the report would be in the body of the email and not as an attachment?  I currently use the "send-object" command and send it in html format.

A: This is how I did it with SendObject, it attaches the report as a RTF and puts it in the body of the email.
Private Sub btnEmail_Click()

    Dim IDnumber As Integer
    Dim Message As String
    Dim EmailTo As String
    Dim FileName As String

    'Get the current record's ID Number
    IDnumber = Me![ID]
    'set file name and path
    FileName = Environ("USERPROFILE") & "\My Documents\temp.html"
    'set email address
    EmailTo = "someone@domain.com"

    'get form to open a new record
    DoCmd.GoToRecord , , acNewRec

    'generate report for the current record entered
    DoCmd.OpenReport "ReportName", acPreview, , "[ID]=" & IDnumber, acHidden
    'create HTML file for the report
    DoCmd.OutputTo acOutputReport, "ReportName", acFormatHTML, FileName

    'open file
    Open FileName For Input As #1
    'read the file into a string
    Message = Input(LOF(1) - 1, 1)
    'close the file
    Close 1

    'generate email
    DoCmd.SendObject acSendReport, "ReportName", acFormatRTF, EmailTo, , , "Subject", Message
    'close the report
    DoCmd.Close acReport, "ReportName"

    'suppress errors if file is not there
    On Error Resume Next
    'remove file
    Kill FileName

End Sub

A: If you are using Outlook, you can write a report or query to disk and use either HTMLBody or RTFBody, it is a while since I tested this, I hope it is still useful.
Const ForReading = 1, ForWriting = 2, ForAppending = 3

Dim fs, f
Dim RTFBody
Dim MyApp As New Outlook.Application
Dim MyItem As Outlook.MailItem

DoCmd.OutputTo acOutputReport, "Report1", acFormatRTF, "Report1.rtf"
''DoCmd.OutputTo acOutputQuery, "Query1", acFormatHTML, "Query1.htm"

Set fs = CreateObject("Scripting.FileSystemObject")

Set f = fs.OpenTextFile("Report1.rtf", ForReading)
''Set f = fs.OpenTextFile("Query1.htm", ForReading)
RTFBody = f.ReadAll
''Debug.Print RTFBody
f.Close

Set MyItem = MyApp.CreateItem(olMailItem)
With MyItem
   .To = "abc@def.ghi"
   .Subject = "Subject"
   .RTFBody = RTFBody
   ''.HTMLBody = RTFBody
End With
MyItem.Display


text:
Q: Control does not exist in current context asp.net c# I have two files: FileGridCS.ascx and FileGridCS.ascx.cs
Within FileGridCS.ascx: I have added the control:
<asp:GridView ID="gvFiles" runat="server"></asp:GridView>

The header of this file is:
<%@ Control Language="C#" AutoEventWireup="true" CodeFile="FileGridCS.ascx.cs"
    Inherits="UserControls_FileGridCS" %>

Now, my class FileGridCS.ascx.cs is not recognising 'gvFiles'. I Get the following error:
Severity Code   Description  Project          File  Line    Suppression State
Error    CS0103 The name 'gvFiles' does not         137     Active
                exist in the current context

What am I doing wrong?, I am a little confused on why this happening when the control exists!
Thanks =)
UPDATE
Just to let you know, my class FileGrid.ascx.cs is a public partial class*

A: First You have to Specify the User Control on the .aspx Page
In which src is Location of that User Control....
In tagName with same name of .ascx in my case UserControl is GridControl.ascx and specify that tagName as GridControl
And also use TagPrefix as your choice...
<%@ Register Src="~/App_UserControls/GridControl.ascx" TagName="GridControl" TagPrefix="UC" %>

Then use as GridView Like Below Example...
<UC:GridControl ID="gvFiles" runat="server" />


text:
Q: Adding a portlet from one liferay container to another liferay portal I have two liferay portals. I have deployed few portlets on Portal A. I want to use them on Portal B.
What is the appropriate way to do this?

A: You cannot use them in each other.
REASON : You liferay portal is your web-application server, your portlets are the web apps of that server, you have deployed them on specific server.
So, you simply cannot use this like the way you are thinking (I think your wild guess would be sharing "webapps" across portal)
The following possible solutions you can use for that

*

*Use WSRP (Web Services for Remote Portlets), in this one, your one portal will host portlets and it can be used at remote portlets for another one.

*Use Liferay Services (service.xml and remote-service=true), in this one, one portal must host liferay services as remote service =true, another portal can consume this and done.

*Use Liferay Instance and not portals, Use a single Liferay portal server with 2 Liferay instances for 2 different web applications. This is possible, in this one, you can share all the resources on both the instance, and you can host them differently also.
Hope this helps!


text:
Q: wxpython TextCtrl segmentation fault on SetValue I'm building a small app with wxglade.
It is basically just a TextCtrl multiline and readonly.
I start a thread that reads a file and display the content into the TextCtrl.
After a bunch of execution I get a segmentation Fault.
Debian 9
Python 3.5.3
wxpython 4.0.7.post2
Any suggestion?
Thanks a lot!
Code
import wx, threading, pdb
import gettext

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((400, 300))
        self.text_ctrl_1 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.__set_properties()
        self.__do_layout()
        self.update_text()

    def update_text(self):
        print("update_text")
        text = ""
        try:
            f = open("test.txt", "r")
            text = f.read()
            f.close()
        except:
            print(_('Error opening test.txt file!'))
            text = _('Error opening test.txt file!')

        self.text_ctrl_1.SetValue(text)
        threading.Timer(1, self.update_text).start()

    def __set_properties(self):
        self.SetTitle(_("frame"))

    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        self.Layout()

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == "__main__":
    gettext.install("app") # replace with the appropriate catalog name

    app = MyApp(0)
    app.MainLoop()

Error

update_text
  update_text
  update_text
  update_text
(wxglade_out.py:5127): Gtk-WARNING **: Invalid text buffer iterator:
  either the iterator is uninitialized, or the
  characters/pixbufs/widgets in the buffer have been modified since the
  iterator was created. You must use marks, character numbers, or line
  numbers to preserve a position across buffer modifications. You can
  apply tags and insert marks without invalidating your iterators, but
  any mutation that affects 'indexable' buffer contents (contents that
  can be referred to by character offset) will invalidate all
  outstanding iterators
(wxglade_out.py:5127): Gtk-WARNING **: Invalid text buffer iterator:
  either the iterator is uninitialized, or the
  characters/pixbufs/widgets in the buffer have been modified since the
  iterator was created. You must use marks, character numbers, or line
  numbers to preserve a position across buffer modifications. You can
  apply tags and insert marks without invalidating your iterators, but
  any mutation that affects 'indexable' buffer contents (contents that
  can be referred to by character offset) will invalidate all
  outstanding iterators Segmentation fault

A: I don't believe that updating from within a thread will work properly.
Updates should be performed with the main GUI loop.
I don't know if this is related or not with gtk: Gtk +3 TextView application crashes
You can try updates via pubsub, some device of your own using variables or use a wx.Timer instead of a thread i.e.
import wx
import time

class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        kwds["style"] = kwds.get("style", 0) | wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.SetSize((400, 300))
        self.text_ctrl_1 = wx.TextCtrl(self, wx.ID_ANY, "", style=wx.TE_MULTILINE | wx.TE_READONLY)
        self.__set_properties()
        self.__do_layout()
        #self.update_text(None)
        self.timer = wx.Timer(self)
        self.Bind(wx.EVT_TIMER, self.update_text, self.timer)
        self.timer.Start(5000)

    def update_text(self, event):
        print("update_text")
        self.text_ctrl_1.Clear()
        wx.GetApp().Yield() # to see the clear occur release momentarily to the main loop
        try:
            with open("test.txt", "r") as f:
               text = f.read()
        except:
            print(_('Error opening test.txt file!'))
            text = _('Error opening test.txt file!')
        time.sleep(2)
        self.text_ctrl_1.SetValue(text)

    def __set_properties(self):
        self.SetTitle("My frame")

    def __do_layout(self):
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(self.text_ctrl_1, 1, wx.EXPAND, 0)
        self.SetSizer(sizer_1)
        self.Layout()

class MyApp(wx.App):
    def OnInit(self):
        self.frame = MyFrame(None, wx.ID_ANY, "")
        self.SetTopWindow(self.frame)
        self.frame.Show()
        return True

if __name__ == "__main__":
    app = MyApp()
    app.MainLoop()


text:
Q: jquery Curvy Corner plugin doesn't load after JSF ajax request We are using Curvy corners script (http://www.curvycorners.net) for the JSF buttons to have the curvy corners in IE.
In IE when we make a Ajax call ,in Ajax response this curvy corners doesn't executed so we tried to re-execute the curvy corner script .  as below in JSF ,but still the curvy corner is not refreshed ,how to reload the curvy corner in Ajax response
jsf.ajax.addOnEvent( function(data) {
if (data.status == "success") { // Can be 'begin', 'complete' and 'success'.
alert("curvy corner");
 var settings = {
 tl: { radius: 5 }, tr: { radius: 5 }, bl: { radius: 5 }, br: { radius: 5 },        antiAlias: true
    };
    $.getScript("jquery.curvycorners.min.js", function() {
    curvyCorners(settings, '.button-primary'); });

}

A: From the comments:

.getScript is not loading curvycorner script

Then the location which you specified in $.getScript() is just invalid. As you have specified it now (without a leading slash), it's relative to the current request URL. Imagine that you have opened the JSF page by http://localhost:8080/context/some/folder/some.xhtml, then the $.getScript("jquery.curvycorners.min.js") will try to load it from http://localhost:8080/context/some/folder/jquery.curvycorners.min.js. Your problem indicates that the file is actually not there at all, but on a different folder or something.
The callback function of  $.getScript() is only called when the script is successfully loaded. So you need to fix the location accordingly so that it get loaded properly.
But as you mentioned in the comments, you have this script already in the <head> and it is already working on page load. You don't need to load the whole script again by $.getScript() at all. Just invoke the callback function directly.
jsf.ajax.addOnEvent(function(data) {
    if (data.status == "success") {
        var settings = {
            tl: { radius: 5 }, tr: { radius: 5 }, bl: { radius: 5 }, br: { radius: 5 },        antiAlias: true
        };
        curvyCorners(settings, '.button-primary');
    }
}


text:
Q: AEM create package with 1 node only Is it possible in AEM to create a package for /home/users, but with ONLY 1 node under each user ?
Example, I have 100 users in AEM and every user has custom data in 1 node only. Can I fetch only this node for all the 100 users in a package ?
The structure of user nodes is like this:
/home/users/3/3_alphanumeric_id/customNode

I dont want to add 100 filters to the package as it will be a very long task.

A: ACS Commons has a Query Packager tool. The documentation on the page is pretty self explanatory.
If ACS Commons is not an option, another strategy would be to edit the filters of a content package on your machine, upload it, then build to pick up the nodes. The filters are configured in META-INF/vault/filter.xml and are in simple filter elements like <filter root="/home/users/3/3_alphanumeric_id/customNode"/>.
You can do the query to find all of your nodes in crxde, use the json it requests from the network traffic, and use a text editor to rewrite the json into the filter elements.


text:
Q: IronPython DataGridView: Get Value from One Key Press But Without Pressing 'Enter' and Move to the Next Cell I've been struggling with the difficulty for a few days. I've read on  http://www.ironpython.info/ and book 'IronPython In Action' by Michael and Christian, and DataGridView class on https://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview(v=vs.110).aspx, but I'm still lack of some knowledge and skills.
My question is how to get value from one key press but without pressing 'Enter' and Move to the next cell, which means when I press one number on keyboard but without pressing 'Enter', the number is passed into the first cell such as 3, and then the next cell is active. The sequence is meander, like row 1 col 1 -> row 1 col 2 -> ... -> row 1 col 12 -> row 2 col 12 -> row 2 col 11.
I tried many events of DataGridView such as 'CellEnter' and 'KeyPress', but failed.
If you could give some hints about it, I'll appreciate it very much.
The following is my code up to now:
import clr

clr.AddReference('System.Windows.Forms')
clr.AddReference('System.Drawing')

from System.Windows.Forms import Form
from System.Windows.Forms import DataGridView
from System.Windows.Forms import DataGridViewContentAlignment
from System.Windows.Forms import Application
from System.Windows.Forms import Control
from System.Windows.Forms import Clipboard
from System.Windows.Forms import DataFormats
from System.Windows.Forms import DataObject

from System.Drawing import Point
from System.Drawing import Size
from System.Drawing import Font
from System.Drawing import FontStyle
from System.Drawing import Color

from System import Text

from System.IO import MemoryStream

NUMROWS = 6
NUMCOLS = 12

data = [[-1 for x in range(NUMCOLS)] for x in range(NUMROWS)]

class DataGridForm(Form):
    def __init__(self, numcols, numrows):
        self.Text = 'DataGridView Cell Format Test'
        self.ClientSize = Size(98 * (numcols + 1), 25 * (numrows + 1))
        self.dgv = DataGridView()
        self.numcols = numcols
        self.numrows = numrows
        self.setupdatagridview()
        self.adddata()
        self.formatheaders()

    def setupdatagridview(self):
        self.dgv.Location = Point(0, 0)
        self.dgv.Size = Size(98 * (NUMCOLS + 1), 25 * (NUMROWS + 1))
        self.Controls.Add(self.dgv)
        # have to have columns defined before inserting rows
        self.dgv.ColumnCount = self.numcols
        # center all text in all data cells by default
        self.dgv.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
        #self.dgv.CellEnter += self.move
        #self.dgv.CellValueChanged +=self.move
        #self.dgv.Enter += self.move
        #self.dgv.CellStateChanged += self.move
        #self.dgv.ChangeUICues += self.move
        #self.dgv.EditingControlShowing += self.move
        #self.dgv.EditModeChanged += self.move
        #self.dgv.GotFocus += self.move
        #self.dgv.HandleCreated += self.move
        #self.dgv.KeyPress += self.move
        #self.dgv.KeyDown += self.move
        #self.dgv.KeyUp += self.move
        #self.dgv.MouseEnter += self.move
        #self.dgv.Move += self.move
        #self.dgv.TextChanged += self.move

        # add empty rows first
        for num in xrange(self.numrows):
            self.dgv.Rows.Add()
        # format empty cells
        self.dgv.AllowUserToAddRows = False
        self.dgv.AllowUserToDeleteRows = False
        self.dgv.ReadOnly = False
        self.dgv.ClearSelection()

    def formatheaders(self):
        for num in xrange(self.numcols):
            col = self.dgv.Columns[num]
            col.HeaderCell.Value = str(num + 1)
            # slightly left of center on headers
            col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
            # sets font and font style
            col.HeaderCell.Style.Font = Font(Control.DefaultFont, FontStyle.Bold)
            col.HeaderCell.Style.ForeColor = Color.MidnightBlue
        # put numbers on rows
        for num in xrange(self.numrows):
            row = self.dgv.Rows[num]
            # get sequential numeric label on side of row
            row.HeaderCell.Value = str(num + 1)
            # sets font and font style
            row.HeaderCell.Style.Font = Font(Control.DefaultFont, FontStyle.Bold)
            row.HeaderCell.Style.ForeColor = Color.Blue
        self.dgv.TopLeftHeaderCell.Value = 'Score'
        self.dgv.TopLeftHeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
        self.dgv.TopLeftHeaderCell.Style.Font = Font(Control.DefaultFont, FontStyle.Bold)
        self.dgv.TopLeftHeaderCell.Style.ForeColor = Color.Blue
        self.dgv.RowHeadersWidth = 60

    def adddata(self):
        for num in xrange(self.numrows):
            row = self.dgv.Rows[num]
            dat = (datax for datax in data[num])
            for cell in row.Cells:
                cell.Value = dat.next()
    """
    def move(self, sender, event):
        print 'move'
    """
dataGridForm = DataGridForm(NUMCOLS, NUMROWS)
Application.Run(dataGridForm)

A: I've found EditingControlShowing to evoke an event, and self.dgv.CurrentCell = self.dgv.Rows[currentRow].Cells[currentCol + 1] to move cell. However, I cannot get the input number and the table is none. My code of this part is as below.
def move(self, sender, event):
    currentCol = self.dgv.CurrentCellAddress.X
    currentRow = self.dgv.CurrentCellAddress.Y

    """
    print self.IsInputChar('a')
    if self.IsInputChar('a'):
        self.dgv.CurrentCell.Value = 8
    else:
        self.dgv.CurrentCell.Value = 10
    """

    if currentRow % 2 == 0 and currentCol != NUMCOLS - 1:
        self.dgv.CurrentCell = self.dgv.Rows[currentRow].Cells[currentCol + 1]
    elif currentRow % 2 == 0 and currentCol == NUMCOLS - 1:
        self.dgv.CurrentCell = self.dgv.Rows[currentRow + 1].Cells[currentCol]
    elif currentRow % 2 != 0 and currentCol != 0:
        self.dgv.CurrentCell = self.dgv.Rows[currentRow].Cells[currentCol - 1]
    elif currentRow % 2 != 0 and currentRow != NUMROWS - 1 and currentCol == 0:
        self.dgv.CurrentCell = self.dgv.Rows[currentRow + 1].Cells[currentCol]
    else:
        None

A: I found a way: firstly evoke EditingControlShowing event by "self.dgv.EditingControlShowing += self.keyPress"; and then evoke KeyPress by
def keyPress(self, sender, event):
        event.Control.KeyPress += self.move
And now I can get value by "self.dgv.CurrentCell.Value = event.KeyChar".
However, cell value and movement is not always correct, which needs to be resolved.

A: I finally work it out by myself. Use KeyPress event and set ReadOnly property true.


text:
Q: Issue with VBA else without if showing an error I am using the following VBA Else-If code:
If ActiveSheet.Range(range_name).Value < "8.50%" Then
   ActiveSheet.Shapes.Range(Array(shape_name)).Select
    With Selection.ShapeRange.Fill
        .Visible = msoTrue
        .ForeColor.RGB = RGB(192, 0, 0)
        .Transparency = 0
        .Solid
    End With
    ElseIf ActiveSheet.Range(range_name).Value < "9.70%" Then
     ActiveSheet.Shapes.Range(Array(shape_name)).Select
    With Selection.ShapeRange.Fill
        .Visible = msoTrue
        .ForeColor.RGB = RGB(255, 255, 0)
        .Transparency = 0
        .Solid
    Else
     ActiveSheet.Shapes.Range(Array(shape_name)).Select
    With Selection.ShapeRange.Fill
        .Visible = msoTrue
        .ForeColor.RGB = RGB(0, 255, 0)
        .Transparency = 0
        .Solid
    End With

When I run this, I receive an error: "Else without If ".
So, I changed the Else line to:
 ElseIf ActiveSheet.Range(range_name).Value >= "9.70%" Then

But still, it is giving me the same error, even though this Else has an If
Why is that? And the first code is also correct and shouldn't give an error in the first place. So why is this happening? Thanks in advance!

A: It's because you're missing an End With in the middle, i.e. this part
With Selection.ShapeRange.Fill
        .Visible = msoTrue
        .ForeColor.RGB = RGB(255, 255, 0)
        .Transparency = 0
        .Solid

A: add this:
End If

on the last line.
This is to terminate the if statement like what you did in your With statement.


text:
Q: Error trying to archive custom object in Xcode I am trying to use NSCoder to archive a custom object (my object is a library, as in a place to check out books) to the iPhone's file system.  However, I am getting an error "unrecognized selector sent to instance" when I attempt to call NSKeyedArchiver archiveRootObject.  The library declares the NSCoding protocol and implements the required methods. I'm at a loss.
The object Interface (library.h):
#import <Foundation/Foundation.h>
@interface Library : NSObject <NSCoding> {
int numCopies;
NSString *location;
NSString *locationInfo;
NSString *material;
NSString *library;
}
+ (id)library;
@property (nonatomic) int numCopies;
@property (retain) NSString *location;
@property (retain) NSString *locationInfo;
@property (retain) NSString *material;
@property (retain) NSString *library;
- (void)encodeWithCoder:(NSCoder *)encoder;
- (void)initWithCoder:(NSCoder *)decoder;
@end

The relevant part of object implementation (library.m):
#import "library.h"

@implementation Library

@synthesize numCopies;
@synthesize location;
@synthesize locationInfo;
@synthesize material;
@synthesize library;

+ (id)library
{
return [[Library alloc] init];
}

-(void)encodeWithCoder:(NSCoder *)encoder
{
    //for each instance variable, archive it under its variable name
    [encoder encodeObject:numCopies forkey:@"numCopies"];
    [encoder encodeObject:location forkey:@"location"];
    [encoder encodeObject:locationInfo forkey:@"locationInfo"];
    [encoder encodeObject:material forkey:@"material"];
    [encoder encodeObject:library forkey:@"library"];
}

Finally, the viewController (libTableViewController.m)
//try to archive the library object
NSString *savePath = pathInDocumentDirectory(@"lib.data");
NSLog(@"try to archive library to path: %@", savePath);
[NSKeyedArchiver archiveRootObject:this_lib toFile:savePath];

Here is the error:
2011-12-18 12:13:38.799 LibraryFiend2[12877:207] try to archive library to path: /Users/kclary/Library/Application Support/iPhone Simulator/4.3/Applications/71B11434-3307-449A-9E95-5E22034E7FA0/Documents/lib.data
2011-12-18 12:13:38.800 LibraryFiend2[12877:207] -[NSKeyedArchiver encodeObject:forkey:]: unrecognized selector sent to instance 0x4b1a130
2011-12-18 12:13:38.801 LibraryFiend2[12877:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSKeyedArchiver encodeObject:forkey:]: unrecognized selector sent to instance 0x4b1a130'
terminate called after throwing an instance of 'NSException'

If I substitute a simple array for my library object, it works.

A: You got exception because of this line [encoder encodeObject:numCopies forkey:@"numCopies"];
numCopies is not an object, it's a primitive and should be stored using encodeInt:forKey: method.


text:
Q: Is it possible to return empty row from Sql Server? Is this possible to return all columns in query as empty column (not null) or empty row, in case the actual query is returning no rows

A: If your objective is to return a query with no records, or with an empty recordset/dataset, the following should work without any previous knowledge on the original query:
SELECT * FROM (myOriginalQuery) as mySelect WHERE 0 = 1

A: Generally, if you must have an empty row returned..
If your original query is
select a,b,c from tbl

You can turn it into a subquery
select t.a,t.b,t.c
from (select 1 as adummy) a
left join (
    select a,b,c from tbl  -- original query
) t on 1=1

Which ensures the query will always have a rowcount of at least one.

A: Based on Richard's answer, you can use UNIONS to give you "something"...
select t.a, t.b, t.c
from (select null AS a, null AS b, null AS c
       union ALL
      select a, b, c from tbl)   -- original query
     ) AS t
on 1=1

The '1=1' is really what forces SQL to return something.

A: I can't comment due to Karma, so here is a more full answer addressing some of the other users' comments:
Accepted Answer
The accepted answer is of this form:
WITH data AS (
  ...your query...
), dummy AS (
  SELECT 1 AS dummy
) SELECT data.*
  FROM dummy
  LEFT JOIN data

This works because it joins your query's output rows against a single row then disregards the columns of that row. It is a LEFT JOIN, so when a contains rows and b does not, all rows of a will return with the b columns set to NULL.
This is great! Except this runs a JOIN the length of b which could be expensive.
Better answer
There is a better answer that doesn't rely on column names and will not scan the table, which as noted in a comment will give an extra row.
This following query builds on that and uses a WHERE NOT EXISTS to eliminate the extra row when it isn't needed.
WITH data AS (
  ...your query...
), nulls AS (
  SELECT
    null AS a,
    ...for each column output by your query...
) SELECT * FROM data
  UNION ALL
  SELECT * FROM nulls WHERE NOT EXISTS (SELECT * FROM data)

The major downside here is that you have to write out all of your columns as NULL, which will be hard in some situations.
Best answer
WITH data AS (
  ...your query...
), single_row AS (
  SELECT * FROM data LIMIT 1
), nulls AS (
  SELECT single_row.*
  FROM (SELECT 1 AS dummy) dummy
  LEFT JOIN single_row
  WHERE NOT EXISTS (SELECT * FROM single_row)
) SELECT * FROM data
  UNION ALL
  SELECT * FROM nulls

nulls will contain a row only when data does not. nulls gets its columns from a virtual row of data.


text:
Q: Log4J properties file not found I have a Java Project that was added to the Java Build Path of a Web Project.
On the first Java project I added the Log4J JAR file to the Java Build Path and since this project was added to the Java Build Project of the Web Project, the JAR file was automatically added to the Web Project Java Build Path also.
On the Web Project I have a Web Service that instantiates a class of the Java Project. That class has a simple Logger, and it works correctly.
Now, I am trying to create a properties file named log4j.properties to configure the Logger, Appender and LayoutPattern.
Whenever I try to call a method of the instantiaded class I get this error on the console:
log4j:ERROR Could not read configuration file [log4j.properties].
What am I doing wrong?
Here's the log4j properties file:
log4j.rootLogger=DEBUG, CA

log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n

Sorry but it was a false alarm...
Like I said, the project where the class that instantiates the logger resides is added as a dependency o a main project where the web services are defined.
As a result that project is published on a JAR file and with the suposed solution I mentioned:
PropertyConfigurator.configure(getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "log4j.properties");
I get a path like:
C:/project_path.jar/log4j.properties.
Obviously the propertied files still isn't found...
Sory... Still working on a solution

A: If using log4j 2.x, you need to have a file called log4j2.xml.
log4j.properties won't do it.

A: Place your log4j.properties file in your classes directory if using unpacked WAR, else place it in the src folder (root folder for your java classes).

A: The only way I found to solve this was to put the log4j.properties file in the src root folder.
Then on the class that instantiates the logger the following line:
PropertyConfigurator.configure("log4j.properties")
... had to be changed to:
PropertyConfigurator.configure(getClass().getProtectionDomain().getCodeSource().getLocation().getPath() + "log4j.properties");
And finally the file was found.
Thanks for the insight  Pål

A: Ok, sometimes the obvious answer is the one you least expect.
As it turned out I simply needed to remove the PropertyConfigurator.configure(xxx) line and place the log4j.properties file on the src folder of the dependency project.
Thanks


text:
Q: Can we define fundamental groups functorially for non-pointed path connected topological spaces? Let $\text{ppTop}$ denote the category of pointed and path connected topological spaces with morphisms base-preserve continuous maps. The fundamental group gives a functor $FG: \text{ppTop}\to \text{Gp}$ where GP is the category of groups.
Now we consider the category $\text{pTop}$ consisting of path-connected topological spaces and we can naturally define the fundamental groupoids instead of fundamental groups on $\text{pTop}$. If we want to define the fundamental group then we need to choose a base point. Notice that there is a forgetful functor $\text{For}:\text{ppTop}\to \text{pTop}$.

My question is: could we lift the functor $FG: \text{ppTop}\to \text{Gp}$ to a functor $\widetilde{FG}: \text{pTop}\to \text{Gp}$ such that $\widetilde{FG}\circ \text{For}=FG$? If not, how to construct a contradiction?

A: For any such lift $\widetilde{FG}:\mathrm{pTop}\to \mathrm{Gp}$ the induced map $pTop(X,Y)\to Gp(\widetilde{FG}(X),\widetilde{FG}(Y))$ must factor through the set of homotopy classes of the maps between $X$ and $Y$, for any spaces $X,Y$.
Indeed, consider the maps $\iota_0,\iota_1:X\rightrightarrows X\times[0,1]$ given by $\iota_a(x)=(x,a)$ for $a=0,1$. The morphisms $\iota_0,\iota_1$ are images of the morphism $\tilde\iota_0:(X,x)\to (X\times[0,1],(x,0))$ and $\tilde\iota_1:(X,x)\to (X\times[0,1],(x,1))$ in the pointed category. Since the functor $FG$ carries $\tilde\iota_0$ and $\tilde\iota_1$ to isomorphisms, so does the lift $\widetilde{FG}$ to the morphisms $\iota_0,\iota_1$. Analogously, the projection $p:X\times[0,1]\to X$ gets sent to an isomorphism. Since $p\circ\iota_0=p\circ\iota_1=id_X$, the induced morphisms $\widetilde{FG}(\iota_0),\widetilde{FG}(\iota_1):\widetilde{FG}(X)\to \widetilde{FG}(X\times[0,1])$ must be equal. In particular, the two compositions $$pTop(X\times[0,1],Y)\rightrightarrows pTop(X,Y)\to Gr(\widetilde{FG}(X),\widetilde{FG}(Y))$$ are equal which implies that any two homotopic maps $f_0,f_1:X\to Y$ induce the same maps between $\widetilde{FG}(X)$ and $\widetilde{FG}(Y)$.
Take now $X=S^1$ equipped with a base point $p\in S^1$. For any $(Y,y)\in ppTop$ the map induced by $FG$ sends a pointed morphism to its homotopy class$$ppTop((S^1,p),(Y,y))\twoheadrightarrow Gp(\mathbb{Z},\pi_1(Y,y))=\pi_1(Y,y)$$
By the above observation, a lifting $\widetilde{FG}$ would yield a factorization of this map through the set of homotopy classes of unpointed maps $S^1\to Y$.
[Corrected on 11/29 thanks to a comment by Achim Krause]:
However, the latter set is identified with the set of conjugacy classes in $\pi_1(Y,y)$, so taking $Y$ to be any space with a non-abelian fundamental group brings us to a contradiction.

For the sake of completeness, here is a proof of the last assertion.
Lemma For a path connected pointed topological space $(Y,y)$ the set $[S^1,Y]$ of homotopy classes of unpointed maps $S^1\to Y$ are in bijection with the set of conjugacy classes in $\pi_1(Y,y)$.
Proof. There is an evident map $\pi_1(Y,y)\to [S^1, Y]$. It is surjective because any unpointed map $f:S^1\to Y$ is homotopic to its conjugation by a path from $f(p)$ to $y$. Next, suppose that $f_0,f_1:S^1\to Y$ are pointed maps and $F:S^1\times[0,1]\to Y$ is an unpointed homotopy between them. The restriction $F|_{p\times[0,1]}$ induces a pointed map $g:S^1\to Y$ because $F((p,0))=f_0(p)=y=f_1(p)=F((p,1))$. We then have the equality $[f_0]=[g]^{-1}[f_1][g]$ in $\pi_1(Y,y)$. Indeed, a pointed homotopy between loops representing the sides of this equality is given by $$G(\alpha, t)=\begin{cases}g(3\alpha\cdot t),0\leq \alpha<\frac{1}{3}\\ F(3\alpha-1,t), \frac{1}{3}\leq\alpha <\frac{2}{3}\\ g(3(1-\alpha)\cdot t),\frac{2}{3}\leq\alpha\leq 1\end{cases}$$ (This formula defines a map $G:[0,1]\times [0,1]\to Y$ that factors through $S^1\times[0,1]$: the latter is the desired homotopy). Thus, any two elements of the fundamental group that can be represented by homotopic maps are conjugate, the converse is evident so the lemma is proven.

A: There is a more topological way. If you assume that $X$ admits a universal covering $\tilde X$ (so $X$ is path connected and semilocally simply connected, I believe) then the $G=\pi_1(X)$ is realized by the deck transformations, i.e. the self-homeomorphisms of $X$ that preserve the fibers of $p:\tilde X \to X$.
I am a bit worried, however, that my answer simply sweeps basepoints under the rug. They are certainly used in the construction I know of the universal cover $\tilde X$, but we can forget about them afterwards and simply use the covering map $p$.
**Edit: ** I still think this works, but I'm not sure if this construction is functorial in the sense you need.


text:
Q: why f_rename of fatfs is very slow? I'am developing a datalogger with an stm32L496 + FreeRtos + FatFs. The data logger save data to a buffer and when is full, the buffer is saved in a file on an SDcard with the help of fatfs and the SDMMC+DMA.
When the working file is too big (15Mo), this file is moved to another directory. But sometimes, I have overrun because of the very long time of f_rename (500ms). I can increase the buffer to hide the issue but I don't understand why this function takes so much time.
Anybody has this issue?
I'm using Fatfs R0.12c with FAT32 format.
I have found that the code takes a long time when the function call "follow_path", when checking if the new file exist and when it call "dir_find" with the variable "path" empty. (So when this is the last segment).
In f_rename :
/* At FAT12/FAT16/FAT32 */
mem_cpy(buf, djo.dir + DIR_Attr, 21);
mem_cpy(&djn, &djo, sizeof (DIR));
res = follow_path(&djn, path_new); // the problematic function
if (res == FR_OK) {
  res = (djn.obj.sclust == djo.obj.sclust && djn.dptr == djo.dptr) ?
     FR_NO_FILE : FR_EXIST;
}

And in follow_path:
for (;;) {
  res = create_name(dp, &path);  // if after this function, path == ""
  if (res != FR_OK) break;
  res = dir_find(dp); // this function can takes 500ms even @ 50Mhz
  ns = dp->fn[NSFLAG];

The code isn't faster if I increase the clock speed so I think this is a software issue.
Any idea ?
[EDIT]
Ok, I tried in exFat and I have the same issue but inconsistently. It happened maybe every 20 or 30 rename.
I found here https://github.com/greiman/SdFat/issues/250 that the SDMMC of STM32 could be the problem. The guy says :

The SDMMC controller causes the SD to need to copy data from partial
filled flash pages so there are occasional writes with many
milliseconds of latency

I someone can try the rename function with an stm32 or another microcontroler to measure the latency, it would be a big help.


text:
Q: Is there a way to identify the device data is being received from? (python) Summary
I have an MT4000 device connected to my computer using the serial port ttyS0. This is broadcasting data which is being received and read by a udp listener written in Python. I am also sending data manually through the terminal using a bash script I wrote.
The Goal
Is it possible to identify the device being used? The aim is for a web-page to allow the user to select which device they wish to see the data being sent. I would rather achieve this by directly identifying the device rather than saying anything from ttyS0, in case a different device is plugged in on that port.
The Answer
Is this possible, and if so, how? Everything I have found so far, is on identifying through a specific port.

A: Which specific device do you have? You may know this, but serial connections don't have any device identification built into the protocol.
I did find a technical manual for the MT4000 series that states that these devices are running an embedded RTOS, but doesn't mention any specifics. If they support ssh, I wonder if you could bring up a terminal and use an OS command to grab an identifier.


text:
Q: block ng-animate when going to the same state (Solution is on the bottom of this post).
Currently we've a problem in our project using ng-animate.
We've got two states, lets name them for now: State 1 and State 2. Both have their state name as a div class.
.
Now state1 should slide up to the top, and slide2 should slide in from the bottom. This is working fine when switching between slide1 and slide2. However, if a user clicks on another button that moves to state1 (when being on state1) then only the content should change and no animation should be done.
Currently we use: .state1.ng-leave { } for the leaving animation on the state1 div, and .state2.ng-enter { } on the entering state. As you can see, when I'm on state1 and clicking on a button that will give another page with state1 then still the .state1.ng-leave { } will get called and the animation will be done.
Anyone got a solution for us? The ng-leave {} for state1 should only be triggered as soon as state2 is entering.
State1/State2 flow
Things we've tried:

*

*We tried to add something to state('home.state1', { } to block the ng-animation for state1. When you enter state1, we never need an animation. We didn't find the solution using this. Probably there is something we can add to onExit: what we didn't try?

*We also tried to work with ng-animate in the div.

Preview In this plnkr I have made an example what is going wrong. If you click "state1", you can see that the page is sliding up, but we don't want that. We just want to "refresh" the page so you just get the page without animation. If you click state2 then the animation should be done (just like the example shows). I also added a button on the state2 page that shows how the page should load when going from state1 to state1. Please check my example below:
https://plnkr.co/edit/zaFcZFOEtCybRuXobYl0?p=preview
Edit - Solution:
The solution was kinda easy and I found it because of the accepted reaction below. In the .state() from state1 I added:
onEnter: function() { $('.pane-animated').removeClass('state1'); },

This removes the state1 class from the div (as state1 class is on the same div as "pane-animated". Just added that to remove the right class). As I applied the animation on
.state1.ng-leave { } it cannot do the animation anymore as it doesn't have this class anymore.
Tested it serveral times, and works great!

A: see in jquery when ever we use animate function then we first use STOP then animate for eg : $('cntrol').stop().animate(function(--
so i think you need to find some kind of stop function in angular also so that when ever you start animate first it stops the existing animate function.

A: Well here is the issue that i see. Any anchor tag with a # is taken as a redirect by angular so what it does as your route '/' is set to home page, angular redirects on that anchor click to home page and as the home page has a ng-leave animation applied. It does the animation.
In order to achieve what you want you just need to remove the # from the href and keep it empty as href="". Now that does not make sense as to why you would want a empty anchor but that gives you a dirty result but a result none the less (Hehe).
Now assuming you are wanting this to be done is to use the # anchor to navigate to a tag/element within the same page using hash linking. You can use the controller $anchorScroll() for it.
Example code:
yourapp.controller('yourControllername', function($scope, $location, $anchorScroll) {
  $scope.scrollTo = function(id) {
  $location.hash(id);
  $anchorScroll();
  }
});

Foo

Here you are

Hope this helps.
[Edit]
Ok after knowing your full requirement now based on your comment to this answer. I think i have come up with another solution to fit you needs. Its not perfect but it works until we find a good solution. Here is what you need to do (Keeping the sample code you shared in mind).
a) We make a new page and call it page-other.html. This will have same links buttons as home page with state 1 navigating to home using href="#" in anchor and state2 navigating to about as before. Just change the
Home
 to
Home- Other
 just to keep track where we are.
b) Add the page into the routeprovider but give it the same controller as mainController as follows:
.when('/other', {
        templateUrl: 'page-other.html',
        controller: 'mainController'
    })

c) Add the class page-no-animate in the css setting it just like home page with background color etc. except for the animation part will be none as follows:
.page-no-animate { background:#00D0BC; color:#00907c; }

.page-no-animate.ng-enter,
.page-no-animate.ng-leave,
.page-no-animate.ng-animate {
   animation:none 0s;
   -webkit-animation: none 0s;
}

d) Change your mainController code to as follows. What it does is it has a function named gotoOther which sets the pageClass to page-no-animate and redirects to the other page using $location.path("/other"). After this funtion we have if-else condition that check on which location we are to apply appropriate animation or no-animation pageClass value as we dont want the other page to animate when we click the state 1 again to come back:
animateApp.controller('mainController', ['$scope', '$location',
function($scope, $location) {
    $scope.gotoOther = function () {
        $scope.pageClass = 'page-no-animate';
        $location.path("other");
    };
    if ($location.path() == "/other")
    {
        $scope.pageClass = 'page-no-animate';
    }
    else
    {
        $scope.pageClass = 'page-home';
    }
}]);

e) In you page-home.html, in the "State1" anchor tag: empty the href attribute and add the ng-click attribute to call the gotoOther function we created in the controller as follows
State1


text:
Q: d3.js - Toggle attributes/styles on a  element based on its label relation StackBlitz demo - stackblitz is flaky in chrome, may not show preview. I use edge with stackBlitz, also fine on chrome for mobile.
I've created this force directed graph that has multiple labels attached to paths that sit on a <line>. When clicking these labels it updates the style of the <line> that it relates to. The issue is when another label on the corresponding path/line element is clicked the previous style state is not removed.
If this was one label the structure would be different and could toggle with a .selectall and target the .class attribute. But as these labels are looped with thier own paths and lines it becomes a little trickier.
Relevant code on line 286:
svg.selectAll('.edgelabel').on('click', function (d) {
  // arrow function will produce this = undefined
  _d3.selectAll('.nodeText').style('fill', 'black');
  _d3.selectAll('.edgelabel').style('fill', '#999');
  _d3.select(this).style('fill', 'blue');

  const thisLine = linkEnter.filter((e) => e.index === d.index);

  if (d.lineStyle === 'Confirmed') {
    console.log('Confirmed', d.lineStyle);
    thisLine.style('stroke', '#444');
    thisLine.style('stroke-dasharray', '0');
  } else if (d.lineStyle === 'Unconfirmed') {
    console.log('Unconfirmed', d.lineStyle);
    thisLine.style('stroke-dasharray', '8, 5');
  }
});

If a label has the value of confirmed it styles the line a part, then unconfirmed should style its own line another way, but at the same time the confirmed line needs to "disappear" styled so you can no longer see it.
StackBlitz demo


text:
Q: AutoMapping from a different source collection type Given the classes below, I need to establish the mapping from Person to PersonDTO. The problem I am having is that PersonDTO's address field mapping did not occur.
public class Address
{
    public int Id { get; set; }
    public string Value { get; set; }
}

public class RegisteredAddresses
{
    public int Id { get; set; }
    public List<Address> Addresses { get; set; }

    public RegisteredAddresses()
    {
        this.Addresses = new List<Address>();
    }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public List<RegisteredAddresses> AddressGroups { get; set; }

    public Person()
    {
        this.AddressGroups = new List<RegisteredAddresses>();
    }
}

public class PersonDTO
{
    public string Name { get; set; }
    public List<Address> Addresses { get; set; }

    public PersonDTO()
    {
        this.Addresses = new List<Address>();
    }
}

class Program
{
    static void Main(string[] args)
    {
        RegisteredAddresses registeredAddresses1 = new RegisteredAddresses();
        RegisteredAddresses registeredAddresses2 = new RegisteredAddresses();
        Person person = new Person();

        registeredAddresses1.Addresses.Add(new Address { Id = 1, Value = "address 1" });
        registeredAddresses1.Addresses.Add(new Address { Id = 2, Value = "address 2" });
        registeredAddresses1.Addresses.Add(new Address { Id = 3, Value = "address 3" });
        registeredAddresses1.Addresses.Add(new Address { Id = 4, Value = "address 4" });
        registeredAddresses1.Addresses.Add(new Address { Id = 5, Value = "address 5" });

        registeredAddresses2.Addresses.Add(new Address { Id = 1, Value = "address A" });
        registeredAddresses2.Addresses.Add(new Address { Id = 2, Value = "address B" });
        registeredAddresses2.Addresses.Add(new Address { Id = 3, Value = "address C" });
        registeredAddresses2.Addresses.Add(new Address { Id = 4, Value = "address D" });
        registeredAddresses2.Addresses.Add(new Address { Id = 5, Value = "address E" });

        person.Name = "person 1";
        person.AddressGroups.Add(registeredAddresses1);
        person.AddressGroups.Add(registeredAddresses2);

        Mapper.CreateMap<Person, PersonDTO>();

        // after this line....
        var personDto = Mapper.Map<Person, PersonDTO>(person);

        // .... personDTO.Addresses.Count() is zero; where it should be 10

    }
}

A: You need to tell AutoMapper how to map from the addresses contained in the AddressGroups to the addresses in PersonDTO.  Something like:
Mapper.CreateMap<Person, PersonDTO>()
      .ForMember(pd => pd.Addresses,
                 opt => opt.ResolveUsing(p => p.AddressGroups
                                               .SelectMany(ra => ra.Addresses)
                                        )
                );


text:
Q: content of div disappears after submitting I modified the content of a div element on my page with jQuery and inserted content from different page like this:
Page where content is inserted
<?php include('../includes/overall/overallHeader.php'); ?>

Einsatzliste

<?php include('../includes/overall/overallFooter.php'); ?>

Page where content is taken from
<?php include('../core/init.php'); ?>
<?php include('../core/db_connect.php'); ?>
<?php include('../core/init.php'); ?>

<form action="" method="post">

        Latitude
        <input type="text" name="latitude" id="latitude" autocomplete="off">

        Longitude
        <input type="text" name="longitude" id="longitude" autocomplete="off">

    <input type="submit" id="submit" value="Einsatz anlegen">
</form>

Sidebar Navigation content

Einsatzliste

The script correctly loads the content into the div "mainContent" as expected. This work fine. As soon as I hit the submit button the whole content in the div tags disappears. When I check with the Chrome dev tools the site structure, the tags are empty.
the php file does not contain any strange code to me that would call for that. I am relatively new to jQuery. How would I usefully check for an error or where should I start. I am not that experienced with debugging this.

A: I just found the answer. I was completely on the wrong track. The whole setup is completely fine and the script works as expected. The issue is the form input type of "submit". Submit causes a complete reload of the page. As I have not set the initial display of the incidents page when loaded the first time, the whole form "disappears". Eventually it just reloaded the index.php. Changing the type to button solved the issue.


text:
Q: Wrapping labels in a form I am trying to replicate this PDF form with TeX, with mixed success:

I am so far only good at rendering labels on one line like this:

My humble code uses \makebox for this, but apparently I cannot wrap labels with this approach:
            {\makebox[0.2\linewidth][l]{Position in Company: }}\uline{{<positionInCompany>}\hfill}{Nature of Business: }\uline{{<natureOfBusiness>}\hfill}\\

am I digging in the wrong direction?

A: I think using a table gives you the result you are looking for:
\documentclass{article}
\begin{document}

\begin{table}[h]
\begin{tabular}{lp{4cm}lp{4cm}}
\begin{tabular}[c]{@{}l@{}}Position in\\ Company:\end{tabular} &  &
\begin{tabular}[c]{@{}l@{}}Nature of\\ Business:\end{tabular} &  \\ \cline{2-2}
\cline{4-4}
\end{tabular}
\end{table}

\end{document}


text:
Q: How much does Azure APIM charge if I am using it for just an hour and then delete it? If I create an Azure API Management service in my subscription (I select SKU Developer that cost 48$/month via this official website)
I used it for 1 hour. And then I deleted my Azure APIM right away.
Question is:
Do I get charged for only 1 hour using Azure APIM ?
Or Do I have to pay a total of 48$ once I created APIM in my subscription?

A: If you delete API Management after one hour of deployment you'll only be charged for a single hour of use. In the US that's currently $0.07 / hour for the developer SKU. The Azure Pricing Calculator is great for pricing questions like this.


text:
Q: Admob Rewarded Video Ads Reporting Zero Revenue for a week For a week now, i have added admob rewarded video ads to my app to reward users with a point for each video ads watched. The users are watchig the videos and getting the rewards, but my admob dashboard always shows 0 as revenue.
Check attached picture.


text:
Q: How can I use bluebird-q in browser without browserify? I would like to use bluebird-q (https://github.com/petkaantonov/bluebird-q) as shim for Q in browser JS application. This is not possible out of the box as the bluebird-q library code starts with 2 NodeJS style requires:
var Promise = require("bluebird/js/main/promise")();
var scheduler = require("bluebird/js/main/schedule");

These 2 requires cannot be replaced by require of whole library (https://github.com/petkaantonov/bluebird/tree/v2.10.2#for-library-authors):
var Promise = require("bluebird");

Browserify solves the problem, but this solution is not convenient enough in my opinion: it requires build step, makes the code less readable, some static code scanners do not work as expected with browserified code and most important bluebird and bluebird-q cannot be referenced as separate script files.
Two questions about this topic:
1) What is the reason whole bluebird library cannot be included into bluebird-q as is?
2) Is there more elegant solution to use bluebird-q in browser without browserify?
P.S.: I know that bluebird itself is built for browsers using browserify: this build is properly tested. There is no official browserify build of bluebird-q.

A: As for now browser version of the library is attached to the npm package. It can be found here: https://unpkg.com/bluebird-q@2.1.1/q.js.


text:
Q: My result of $\lim\limits_{n \to \infty} \frac{n\log_2n}{\log_2 n!}$ is different than Wolfram, where had I made a mistake? I need to calculate:
$\lim\limits_{n \to \infty} \frac{n\log_2n}{\log_2 n!}$
Wolfram says it is 1. However I got different result:
First I will use Cesaro-Stolz to remove $n!$
$\lim\limits_{n \to \infty} \frac{n\log_2n}{\log_2 n!} = \lim\limits_{n \to \infty} \frac{(n+1)\log_2(n+1) - n\log_2n}{\log_2 (n+1)! - \log_2 n!} = \lim\limits_{n \to \infty} \frac{(n+1)\log_2(n+1) - n\log_2n}{\log_2 (n+1)}$
Now I can apply L'Hôpital's rule:
$\lim\limits_{n \to \infty} \frac{(n+1)\log_2(n+1) - n\log_2n}{\log_2 (n+1)}=\lim\limits_{n \to \infty} \frac{\log2(n+1)+\frac{1}{\ln2}-\log2n+\frac{1}{n\ln2}}{\frac{1}{(n+1)\ln2}}$
And I apply it again:
$\lim\limits_{n \to \infty} \frac{\log2(n+1)+\frac{1}{\ln2}-\log2n+\frac{1}{n\ln2}}{\frac{1}{(n+1)\ln2}} = \lim\limits_{n \to \infty} \frac{\frac{1}{(n+1)\ln2}-\frac{1}{n\ln2}-\frac{1}{n^2\ln2}}{\frac{1}{(n+1)^2\ln2}} = \lim\limits_{n \to \infty} \frac{(n+1)^2\ln2}{(n+1)\ln2}-\frac{(n+1)^2\ln2}{n\ln2}-\frac{(n+1)^2\ln2}{n^2\ln2} = \lim\limits_{n \to \infty} (n+1) - \frac{(n+1)^2}{n} - \frac{(n+1)^2}{n^2} = \lim\limits_{n \to \infty} \frac{n^3+n^2-n^3-2n^2-n-n^2-2n-1}{n^2} = \lim\limits_{n \to \infty} \frac{-2n^2-3n-1}{n^2} = -2$
I am probably missing something obvious, but having triple checked my calculation I don't see any obvious mistakes...
If there is an easier way to calculate that limit, I would gladly accept

A: Using Cesaro-Stolz:
$$\lim_{n\to \infty} \frac{n\log_2 n}{\log_2 n!} = \lim_{n\to \infty} \frac{(n+1)\log_2 (n+1)-n\log_2 n}{\log_2(n+1)}= 1+\lim_{n\to \infty}\frac{n\log_2(n+1)-n\log_2n}{\log_2(n+1)}$$$$=1+\lim_{n\to \infty} \frac{\log_2 (n+1)^n-\log_2n^n}{\log_2(n+1)}=1+\lim_{n\to \infty} \frac{\log_2 \left(1+\dfrac{1}{n}\right)^n}{\log_2(n+1)}=1+\frac{\log_2 e}{\infty}=1$$

A: I would start with $n!=1\cdot2\cdot3\cdot...\cdot n$, then $\log_2(n!)$ can be expressed as:
$\log_2(n!)=\log_2(1\cdot2\cdot3\cdot...\cdot n)=\log_2(1)+\log_2(2)+\log_2(3)+...+\log_2(n) \le n\log_2(n)$.
Hence, when $n\rightarrow\infty$ we will have $\log_2(n!) \approx n\log_2(n)$, so the limit will result with $1$.

A: $$ \frac{n\log_2(n)}{\log_2 (n!)}= \frac{n\log(n)}{\log( n!)}$$ Now using Stirling approximation
$$\log(n!)=n (\log (n)-1)+\frac{1}{2} \left(\log (2 \pi )+\log
   \left({n}\right)\right)+\frac{1}{12n}+O\left(\frac{1}{n}\right)$$ Then
$$\frac{\log( n!)}{n\log(n)}=1-\frac{1}{\log (n)}+\frac{\log (2 \pi  n)}{2 n \log (n)} \to 1$$
$$\frac{n\log(n)}{\log( n!)}=\frac 1 {\frac{\log( n!)}{n\log(n)} }\to 1$$


text:
Q: Cocos2d , hd retina display iPad Do you have to update to the latest cocos2d to get ipad retina display and what suffix do you use for retina display on iPad?

A: iPad retina is supported by both cocos2d 1.1 and 2.0
The suffix is

-ipadhd


text:
Q: Original service data is being modified by my component function - Angular 7 I am creating a weather app. My service made a call to the api and mapped the data to a global parameter. My component then accesses the global parameter and modifies the data to the correct format I need through a function.
The problem I am having is for some reason the function is mutating the original data.
As a work around I can create a new time property in my component parameter and the function won't modify the original data. But if I name the component property to time the original service data gets mutated.
Why is it doing this? Did I miss something?
Original mapped service data:
dailyForecast = [
0: {time: 1547618400}
1: {time: 1547704800}
2: {time: 1547791200}
];

weather.service.ts
@Injectable({
  providedIn: 'root'
})
export class WeatherService {

  // Weather parameters
  public dailyForecast: any;

  private weatherUrl = 'http://localhost:3000/weather/data';

  constructor(private http: HttpClient) {
  }

  getWeather(location) {
    return this.http.post(this.weatherUrl, location, httpOptions)
      .pipe(
        map((data: any) => {
          this.dailyForecast = data.daily;

          return data.currently;
        })
      );
  }

}

daily.component.ts
export class DailyComponent implements OnInit {

  dailyForecast: any;

  constructor(public weather: WeatherService) {
    this.dailyForecast = this.weather.dailyForecast.data;
  }

  ngOnInit() {
    this.convertUnixTime();
  }

  convertUnixTime() {
    console.log(this.weather.dailyForecast.data[0].time + ": original before loop")

    for(let i=0; i < this.dailyForecast.length; i++) {
      this.dailyForecast[i].time = this.weather.dailyForecast.data[i].time * 1000;

    console.log(this.weather.dailyForecast.data[0].time + ": original after loop")
    console.log(this.dailyForecast[0].time + ": component")
  }

console log printout
1547618400: original before loop
1547618400000: original after loop
1547618400000: component

If you notice the original number before and after the loop are different because for some reason the function is being applied to the original data.
If I however, change the function to create a new property called timeConverted:
for(let i=0; i < this.dailyForecast.length; i++) {
          this.dailyForecast[i].timeConverted = this.weather.dailyForecast.data[i].time * 1000;

the output is correct
1547618400: original before loop
1547618400: original after loop
1547618400000: component

What gives? Just trying to understand what is going on.


text:
Q: Angular2 Refresh Data After Action I have an Angular 2 application that I am supporting.  I am very, very green with Angular 2 but trying to take as many tutorials as possible.
The UI page typescript module calls a REST service and loads a table at init and displays the data.  I have an Angular component that is part of that UI page that calls another REST service that makes changes to the same data.  The update is controlled via a button on the page.  After that update occurs I need for the data being displayed to be refreshed.  Since the ts component that "drives" the entire page is separate from the component that makes the update I'm not sure how to make this happen.
I have a file called message.component.ts.  This file contains
import { OnInit, Component } from "@angular/core";
import { MessageService } from "./message.service";
import { ExchangeMessage } from "../shared/models/exchange-message";
import { HelperUtils } from "../shared/services/helper.service";

@Component({
    selector: "message-search",
    templateUrl: "./message.component.html"
})
export class MessageComponent implements OnInit {
    // Table config
    public messages: ExchangeMessage[];
    public selectedMessage: ExchangeMessage;
    public length: number = 0;
    public createdDateFrom: Date;
    public createdDateTo: Date;
    public constructor(private messageService: MessageService,
                       private preferenceService: PreferenceService) {
    }
    public ngOnInit(): any {
        this.searchForMessage();
    }
    public searchForMessage() {
        this.archivedSearch = this.searchForArchived;
        this.messageService.search(this.createdDateFrom, this.createdDateTo)
            .subscribe(messages => {
            this.messages = messages.data;
            this.length = messages.count;
        }, error => console.error(error));
    }
    public selectMessage(message: ExchangeMessage): void {
        this.selectedMessage = message;
    }
}

And the message.component.html file contains:

                Message Viewer

                                Message Search

                                <form (ngSubmit)="searchForMessage()" #messageSearchForm="ngForm">

                                                <date-range [(dateModel)]="createdDateFrom" [label]="'Created Date/Time From'" [isToDate]="false" [isRequired]="searchForArchived"></date-range>

                                                <date-range [(dateModel)]="createdDateTo" [label]="'Created Date/Time To'" [isToDate]="true" [isRequired]="searchForArchived"></date-range>

                                                <button type="submit" class="btn btn-primary" [disabled]="!messageSearchForm.valid">

                                                    Search
                                                </button>

                                </form>

Messages

                                    <message-actions [message]="selectedMessage"></message-actions>

                                                Message ID
                                                Message Type
                                                Inbound Message Format
                                                I/O
                                                Processing Status
                                                To
                                                From
                                                Retry Count
                                                Created Date/Time
                                                Last Updated Date/Time

                                                {{message.exchangeId}}
                                                {{message.messageType}}
                                                {{message.messageFormat}}
                                                {{message.incomingOutgoingIndicator}}
                                                {{message.processingStatus}}
                                                {{message.to}}
                                                {{message.from}}
                                                {{message.retryCount}} / {{maxRetryCount}}
                                                {{formatDate(message.createdDate)}}
                                                {{formatDate(message.updatedDate)}}

And the second component message-actions.component.ts which is used in the html as  contains:
import { Component, Input } from "@angular/core";
import { Action } from "../shared/manage-actions/action";
import { MessageService } from "./message.service";
import { ExchangeMessage } from "../shared/models/exchange-message";
import { NotificationService } from "../shared/services/notification.service";
import { ErrorDTO } from "../shared/models/error-dto";

@Component({
    selector: 'message-actions',
    template: '<manage-actions [actions]="messageActions"></manage-actions>'
})
export class MessageActionsComponent {
    private _message: ExchangeMessage;
    public messageActions: Array<Action> = [];
    constructor(private messageService: MessageService,
                private notificationService: NotificationService) {}
    @Input()
    set message(message: ExchangeMessage) {
        this._message = message;
        this.messageActions = [];
        if (this._message) {
            // Add Resubmit action
            this.messageActions.push(new Action('Resubmit', () => this.resubmitMessage());
        }
    }
    public resubmitMessage(): void {
        if (this._message) {
            this.messageService.resubmitMessage(this._message.exchangeId).subscribe(response => {
                    this.notificationService.success(response.message);
                },
                error => {
                    if (error.status === 400) {
                        let errorDto: ErrorDTO = error.json();
                        this.notificationService.error(errorDto.message);
                    } else {
                        console.error(error);
                    }
                });
        }
    }
    get message() {
        return this._message;
    }
}

When I select a row from the table the "Resubmit" button activates.  If I click that button it runs the resubmit method in message-actions.component which executes the message service that updates that entry on the database.  Once that happens I need to run the searchForMessage method in message.component.
I don't have a clue how to make that happen.  Please help.

A: Please have a look in the official Angular 2 cookbook: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#bidirectional-service
You should create a service that is shared between message-actions.component and message.component. Basically, message-actions.component will fire an event that message.component is subscribing to(read Subscriptions and Observables). Whenever an event is detected by message.component, it can then run the necessary code to refresh your data.


text:
Q: How to pass data(structure) as a message to a thread. How do I pass data to a thread from main application?
Inside the main application I created a thread for processing error messages. While processing data in the main application if there is an error, it generates an error message and fills it into a structure. This error message(structure) needs to be passed to the thread which will then process it further and the main application should continue its work. I am trying to do this in C on windows platform.
There will be only one thread running in my application. At the moment I have defined a global variable structure (myData) and I am passing that using  PostThreadMessage.
struct myData errorData;

From the main application post a message using
PostThreadMessage(ErrorLogId, THRD_MESSAGE_EXIT , 0 , (LPARAM)&errorData);

In the thread I have
MsgReturn = GetMessage(&msg, NULL, THRD_MESSAGE_SOMEWORK, THRD_MESSAGE_EXIT);

At the moment it is working fine. But if processing of error message takes more time, by that time main application might get new errors and update data in global structure errorData.
I could use locking mechanism but I cannot stop main application till the thread has finished processing. How do I pass data without having it as a global variable?

A: You might like to create a new instance of struct myData each time you are about to call PostThreadMessage().
The thread needs to free() this instance of struct myData when done with it.
Adding synchronization to your current approach would be against the asynchronous concept of spawning workers while the main task continues.
Anyway the threads still need to use synchronisation on their side in case of writing something to a shared log file for example.

A: A solution is to dynamically allocate a struct myData (using malloc()) each time, populate it and pass it to the thread for processing. The thread is responsible for free()ing it once it has completed processing it.
This approach removes any synchronization between threads on the global object errorData (as it is no longer required).

A: How about allocating the error message dynamically (with malloc()), filling it and passing a pointer to it to the thread in a message? Then the thread would work with the message and deallocate it (with free()).

A: Edit:
Didn't realize there was a message queue already, sorry, well then a dynamically allocated message will do of course.
Old answer for reference:
If you don't wish to wait until the thread finishes processing the error message, then you should use a synchronized queue for communications between the main thread and the worker thread. This is some pseudo code to explain what I mean:
Worker Thread:
while (queue_is_empty())
  wait;
lock(queue);
process_error(read(queue));
unlock(queue);

Main Thread:
if (error)
  lock(queue)
  write(queue, error)
  unlock(queue)
  //possibly signal thread

You don't have to implement that from scratch, you could use something like RabbitMQ


text:
Q: What does fetch in php do? I don't understand the concept of the fetch function.
I am doing a tutorial from 'PHP Solutions' book and i am using MySQL Improved to update something in the database.
Here is the code:
if (isset($_GET['article']) && !$_POST) {

$sql = 'SELECT article_id, title, article
    FROM journal WHERE article_id = ?';

$stmt = $conn->stmt_init();

 if ($stmt->prepare($sql)) {
    $stmt->bind_param('i', $_GET['article_id']);
    $stmt->bind_result($article_id, $title, $article);

   //execute the query, and fetch the result
   $OK = $stmt->execute();
   $stmt->fetch();
 }
}

So what is the fetch actually doing? I thought the execute() function is sending the information to the database and then it returns a true/false value to the $OK variable.
Is fetch() storing something in $stmt? Anybody have any idea what it is doing?

A: Hard to anticipate what was before this line in your example, but in general fetch function is for getting current row from result set you receive from database. You can read here


text:
Q: Flex3: Is it Possible to Embed only a Few Letters from a Font? Is there a way to embed only a few letters from a font instead of embedding the whole thing? I only need say 7 capital letters from a font. Thank you.
-Laxmidi

A: Yes, you CAN do that.  You just specify which characters or character ranges you want to embed from the font and only those characters get embedded:  http://www.adobe.com/livedocs/flex/3/html/help.html?content=fonts_07.html

A: Unfortunately this is not possible, but you can create your own fort and include only the needed chars you want to use.


text:
Q: How to add image with pdfmake I need to add an image in the header of the report generated by pdfmake. But when following the documentation I can't make this insertion, not even when converting the image to base64. Please suggest another solution
What was done:
import pdfMake from 'pdfmake/build/pdfmake';
import pdfFonts from 'pdfmake/build/vfs_fonts';

function epiPDF(epis){
    pdfMake.vfs = pdfFonts.pdfMake.vfs;

    const header = [
        {
            text: 'Description equipament',

            bold: true,
            fontFamily: 'Roboto',
            decoration: 'underline',

            margin: [0, 20, 0, 0],
            alignment: 'center',

            image: 'data:image/jpeg;base64,/9j/END_DATAURL_BASE64'

        }
    ];
    function Rodape(currentPage, pageCounf){
        return [
            {
                text: currentPage + ' / ' + pageCounf,
                alignment: 'right',
                fontSize: 9,
                margin: [0, 10, 20, 0]
            }
        ]
    }

    const docDefinitios = {
        pageSize: 'A4',
        pageMargins: [10, 50, 10, 40],

        header: [header],
        content: [infor, rec, details],
        footer: [Rodape]
    }
    pdfMake.createPdf(docDefinitios).download();
}

export default epiPDF;

when testing base64 code is correct

A: Could you please indicate what the browser errors are ?
Also I suggest you try again with the base64 encoded image specified in the pdfmake's playground

A: *

*Your docDef's header and footer should be functions instead of Arrays.

*Pdfmake elems have a specific structure, for example a text element cannot have an image (it must be 2 separated elems).
Your code should look something like this :
 const getHeader = (currPage, totalPage) => [
    {
        text: 'Description equipament',

        bold: true,
        fontFamily: 'Roboto',
        decoration: 'underline',

        margin: [0, 20, 0, 0],
        alignment: 'center',
    },
    {
     image: 'data:image...YOUR IMAGE',
     margin: [0, 20, 0, 0],
     alignment: 'center',
    }
  ]

 const docDefinitions = {
    pageSize: 'A4',
    pageMargins: [10, 50, 10, 40],

    header: getHeader,
    content: [infor, rec, details],
    footer: Rodape
}

Cheers


text:
Q: trouble with inserting php form data into mysql i have trouble inserting my with php into one table of mysql, i can insert in any other table but this one here is my code (is a test code)
This is the formulario.php code
    <form action="opformulario.php" method="POST">

        <input type="text" name="nombre" placeholder="Nombre" />

        <input type="text" name="apellido" placeholder="apellido" />

        <input type="text" name="correo" placeholder="correo" />

        <input type="text" name="nombre2" placeholder="Nombre" />

        <input type="text" name="apellido2" placeholder="apellido" />

        <input type="date" name="apellido3" placeholder="apellido" />

        <input type="submit" value="aceptar" />

and this is the op formulario code
include("conexion.php");

     $nombre = $_POST['nombre'];
     $apellido = $_POST['apellido'];
     $correo = $_POST['correo'];
     $nombre2 = $_POST['nombre2'];
     $apellido2 = $_POST['apellido2'];
     $apellido3 = $_POST['apellido3'];

     $FechaMySQL = implode( '-', array_reverse( explode( '/', $apellido3 ) ) ) ;

$query = " INSERT INTO cliente (nom_raz,nom_com,tel_cli,cel_cli,email_cli,fecha_reg) VALUES('$nombre','$apellido','$correo','$nombre2','$apellido2','$FechaMySQL')";

     $resultado = $conexion->query($query);

     if ($resultado){
        echo "Succesfull";

     }
     else{
        echo "Error:
".mysql_error();
     }

this is the table in  which i am trying to insert
Mysql 'cliente' table


text:
Q: Flutter TextFormField Prefix Icon Focus Color on Theme Change I have a TextFormField, which contains a prefix Icon that I would like to turn red when it is focused on.

To achieve that, I have wrapped the TextFormField with a Theme object (Relevant SO Question):
 Theme(data:ThemeData(colorScheme:
                    ThemeData().colorScheme.copyWith(primary:Colors.red)),
                    child: TextFormField()

This works great, but the problem arises when I switch to Dark mode inside my application.
Because I am using this setting (I am assuming), it turns the entire TextFormField to use the primary color which is black and then the entire TextFormField is black.

Other TextFormField elements which I have not wrapped with a Theme object, are styled correctly according to theme.

How would I go about fixing this?
What I would like to achieve is have the TextFormField appear like the others in Dark mode and be highlighted red when it is focused on, regardless of light or dark mode.
Would I need to define a custom application theme for this?

A: Tru to inherit from current theme by using copyWith method:
Theme(
    data: Theme.of(context).copyWith(
      primaryColor: Colors.red
    ),
      child: TextFormField(),
  )

UPDATE
Or alternatively, you can try using darkTheme property of the MaterialApp widget:
MaterialApp(
  darkTheme: Theme.of(context).copyWith(...),
  home: ...
)


text:
Q: Two output file names resolved to the same output path I have a project in VS2013, where I use the report from Telerik.
In the solution I have one report and a few classes. If I copy the first report rename it, Visual Studio reports error:
Two output file names resolved to the same output path: "obj\Debug\...

If I Remove the copied report and try to through the wizard add a new report to project, VS report me the same error.
Do you have someone with experience and someone you do not know the solution?
Thank you

A: I got this error when using entity frameworks code first migrations and had the same name for two of my migrations in the Migrations folder.
Two output file names resolved to the same output path: "obj\Debug\***.resources
I deleted the duplicate migration.cs file and the error went away. running add-migration again with the same name brought it back.

A: I had three files for a userControl, all sharing a common partial class, and this caused my issue; they were named ucPlate.cs, ucPlate.Map.cs, and ucPlate.Graphics.cs. When I changed ucPlate.Graphics userControl surface to DoubleBuffered, I got the compilation error, "Error  21  Two output file names resolved to the same output path: "obj\Debug\ASMS.Controls.ucPlate.resources" Reverting to DoubleBuffered = false did not fix it, nor did deleting the .resx file that was created when I turned on DoubleBuffered (previously, there was no .resx file).
The root cause was that turning on DoubleBuffered in the subsidiary partial class file auto-added InitializeComponent() to the bottom of my code for that file.  This method indicated the duplicate ucPlate name, forcing a .resx creation that already existed for the ucPlate.cs file.  I had expected it to be ucPlate.Graphics.resx.
private void InitializeComponent()
{
    this.SuspendLayout();
    //
    // ucPlate
    //
    this.Name = "ucPlate";
    this.ResumeLayout(false);
}

A: go to the solution explorer (if you rename a form e try to look at your error and delete the .resx file that have in your error)