text:
Q: ASP.NET MVC project with a section written in Angular2: a build error occurs when using MvcBuildViews Ok it could be a singular combination...
INTRODUCTION
I have an existing ASP.NET MVC 5 project.
It contains a private "Admin" area. I'm planning to change this area migrating it to Angular2 (+ WebAPI) :)
Due to some business requirements, I can't change the architecture of the original "Main" website (separating the Admin section into another website) so I must host inside it the new "Admin" area written in Angular2.
Main website url: http://www.example.com
Admin area url: http://www.example.com/admin
This is also true for the Visual Studio Project:
I created a folder "admin" and put all Angular2 stuff in it.
All works fine...
THE ISSUE
My ASP.NET project uses the MvcBuildViews parameter to build the MVC views on Release mode.
Now when I run the build in Release mode I receive this error:

\node_modules\selenium-webdriver\lib\test\data\web.config(29): error
  ASPCONFIG: It is an error to use a section registered as
  allowDefinition='MachineToApplication' beyond application level.  This
  error can be caused by a virtual directory not being configured as an
  application in IIS.

The error doesn't have sense for me...
MSBUILD has analyzed a web.config file inside the "node_modules".
The node_modules folder has been created in the project root folder after "npm install" (necessary to prepare angular2's stuff).
These folder should be ignored by msbuild... IMHO
HEY... node_modules IT IS NOT included in the VS project. MSBUILD is scanning the folder because it is only present inside the project...
WORKAROUNDS

*

*Give up the MvcBuildViews... but I think this setting is very useful to detect errors during development phase

*Hide the node_modules folder. This is the current workaround I'm using. I've added this pre-build event attrib +h "$(ProjectDir)node_modules"
Some other solution?
I've googled with no success...

A: I had the same issue recently. I found the solution to this issue in the following article:
Excluding node_modules folder from ASP.NET compilation
The article suggest to replace the AspNetCompiler task in your csproj for a direct call to aspnet_compiler.exe which support excluding folders. In the article, it does so by hardcoding the path to that .exe file. Which for most of the cases is Ok.
You may also use $(FrameworkDir) and $(FrameworkVersion) to avoid hardcoding the path or if you are unsure where the aspnet_compiler.exe may be:
<Target Name="MvcBuildViews" AfterTargets="AfterBuild" Condition="'$(MvcBuildViews)'=='true'">
    <Exec Command="$(FrameworkDir)\$(FrameworkVersion)\aspnet_compiler.exe -v temp -p $(WebProjectOutputDir) -x node_modules"/>
</Target>


text:
Q: dotnet publish doesn´t publish correct appsettings.{env.EnvironmentName}.json When I issue the following command in the command line:
dotnet publish -o "./../output" -c Release
The dotnetcli publishes the project correctly. However, it does not copy the appsettings.Production.json file, only the appsettings.json.
Why is this? I have googled around and read the official core docs, but haven't found how the correct environment appsettings.json is supposed to end up in the publish output.
Should I copy appsettings.Production.json manually to the published folder?

A: After Visual Studio 2017 15.3
Edit the .csproj file to manually exclude files/folder from being published
<ItemGroup>
  <Content Remove="appsettings.Development.json" />
</ItemGroup>

ref: https://www.danielcrabtree.com/blog/273/fixing-the-duplicate-content-error-after-upgrading-visual-studio-2017
original source

A: Discovered a three-step build in Visual Studio approach for publishing environment-specific appsetting files (Windows, PowerShell).

*

*appsettings.json

*appsettings.Development.json

*appsettings.Staging.json

*appsettings.Production.json

This approach will publish

*

*appsettings.json and

*appsettings.$(ASPNETCORE_ENVIRONMENT).json.

Step 1. Update csproj:
  <!-- App Settings -->
  <ItemGroup>
    <Content Remove="appsettings.json" />
    <Content Remove="appsettings.*.json" />
  </ItemGroup>
  <ItemGroup>
    <Content Include="appsettings.json" CopyToOutputDirectory="Always" />
    <Content Include="appsettings.$(ASPNETCORE_ENVIRONMENT).json" DependentUpon="appsettings.json" CopyToOutputDirectory="Always" />
  </ItemGroup>

Step 2. Set an environment variable in PowerShell:
  # Read
  [Environment]::GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "User")
  # Output: empty string if not set or 'Staging' in my case
  # Set environment variable "User" or "Machine" level
  [Environment]::SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Staging", "User")

Step 3. Then close and reopen Visual Studio solution to enable Visual Studio to see the environment variable and reload project structure accordingly.

*

*Now appsettings.json is a parent and appsettings.Staging.json is a nested file.

*If you set another environment (for example "Production") and then close and  Visual Studio and reopen your  solution, then you will appsettings.json as a parent and appsettings.Production.json as a nested file.

Final step. Run publishing.

Note: publishing profile environment variables do not affect publishing configuration. This approach uses PowerShell to set an environment variable and enables environment-specific publishing. Please see link for more details on environment variables.

A: In your project.json there is a section publishOptions. This lists all the files and folders that will be included when you publish. You will need to update yours to look something like this
{
  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings.json",
      "appsettings.Production.json",
      "web.config"
    ]
  },
}

You can also use globbing patterns, so you should find this works too (I haven't tested this one)
{
  "publishOptions": {
    "include": [
      "wwwroot",
      "Views",
      "appsettings*.json",
      "web.config"
    ]
  },
}

A: For the new csproj project format you have to add a new ItemGroup with the content
<ItemGroup>
  <Content Include="appsettings.json">
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  </Content>
  <Content Include="appsettings.Production.json">
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  </Content>
</ItemGroup>

In case you have multiple appsettings.{env}.json files simply repeat the Content tag inside the same ItemGroup and all your settings files will end up in the publish folder.
As mentioned in the comments an even cleaner solution is to use a wildcard include:
<ItemGroup>
  <Content Include="appsettings*json">
    <CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
  </Content>
</ItemGroup>

And all your appsettings files will be published!

A: Update:
For current (new) .csproj format the  CopyToPublishDirectory attribute should be used. It determines whether to copy the file to the publish directory and can have one of the following value:

*

*Always,

*PreserveNewest

*Never

So add next section into your .csproj:
<ItemGroup>
   <None Include="appsettings.Production.json" CopyToPublishDirectory="Always" />
</ItemGroup>

Look into @nover answer and SO Exclude or include files on publish for more information about file's control during publishing.

"In your project.json file you have the section publishOptions with subsection include, where you already have some files like "appsettings.json":
"publishOptions": {
  "include": [
    "appsettings.json",
    "hosting.json",
    "project.json",
    "web.config"
  ]
},

You should add "appsettings.Production.json" into this array.
Updates based on comments:

*

*Keep in mind, that all the appsettings.*.json files like appsettings.development.json, appsettings.staging.json and appsettings.production.json will always end up in all environments. You cannot simply handle this using project.json, as it does not support any condition rules. This will be changed in future, when project.json will be replaced back to msbuild and .csproj. If this is critical for your app, consider to use another configuration store, like Environment Variable, database, etc.

*Note, that order is important, as determine which settings will be applied if they exist in multiple locations. From documentation:

The order in which configuration sources are specified is important, as this establishes the precedence with which settings will be applied if they exist in multiple locations. In the example below, if the same setting exists in both appsettings.json and in an environment variable, the setting from the environment variable will be the one that is used. The last configuration source specified "wins" if a setting exists in more than one location. The ASP.NET team recommends specifying environment variables last, so that the local environment can override anything set in deployed configuration files.

A: VS 2019 (Version 16.4.1) has option to publish only the appsettings.json on right click on the file:

It will take your connection from the publish profile.

A: I found that you don't need to manually modify the project file to add in the items. Just set the "Build Action" to "Content" for these items in file properties. They get copied to the build output AND the publish folder. They're also included in the Application Files folder with the .deploy extension if you're publishing for ClickOnce.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Aura:Method with Parameters / Conditional Component Instancing I'm trying to make a component that can be used for many different scenarios. So I want to be able to use it in parent components. The idea is that the parent component would be used to create records and the child component would find related records based on criteria. Thus, I need the child component to only run/be instanced when I have a specific field populated in Lightning Data.
I have looked at a lot of references for Aura:Method, but I don't see/understand how to pass parameters from the parent to the method.
Here is a sample set of code that simplifies what I am trying to do. First the Method.
<aura:component controller="serverSideController" access="global">

<!-- Define the component as a Method to be called easier -->
<aura:method name="myMethod">

    <aura:attribute name="callback" type="Function" />

    <aura:attribute name="givenId" type="String" />
    <aura:attribute name="field2" type="String" />
    <aura:attribute name="field3" type="String" />
    <aura:attribute name="field4" type="String" />
    <aura:attribute name="field5" type="String" />

    <aura:attribute name="picklistValues" type="Object" />

    <!--
    <aura:handler name="init" value="{!this}" action="{!c.doInit}" />
    -->

</aura:method>

myMethodController
({
echoJunction : function(component, event) {
    var params = event.getParam('arguments');
    var callback;
    if (params) {
        callback = params.callback;
    }

    var action = component.get("c.junctionObjectRelLookupController");

    //Pass the parameters to the APEX class
    action.setParams({
        givenId: component.get("v.givenId"),
        givenIdFieldName: component.get("v.field2"),
        junctionObjectName: component.get("v.field3"),
        destinationObjectFieldName: component.get("v.field4"),
        destinationObject: component.get("v.field5")
    });

    //Give the results
    action.setCallback(this, function(response) {
        var state = response.getState();
        if (state === "SUCCESS") {
            //Return doesn't work for async server action call
            console.log("From server: " + response.getReturnValue());

            //call the callbackpassed into aura:method
            //I gave up right here and decided to ask how to proceed
        }

        var list = response.getReturnValue();
        component.set("v.picklistValues", list);
    })
    $A.enqueueAction(action);
}

And finally the serverside controller:
public class serverSideController {
@AuraEnabled
public static List<String> getRecordsIntoList(String givenId, String field2, String field3, String field4, String field5){
    //logic here
    return pickListValuesList;
}

So, if I am creating a record in a parent controller, how do I pass the parameters to the aura:method, and how do I get the values back in?
I had used something like this to pass the parameters and to have somewhere to hold the results:
<aura:attribute name="results" type="Object" />
<c:junctionObjectRelationshipLookup givenId="{!v.object.field}"
                                        field2="Specific String"
                                        field3="Specific String"
                                        field4="Specific String"
                                        field5="Specific String"
                                        picklistValues="{!v.results}" />

The key here is that my child component needs the givenId to function. Well, it needs all of them, clearly. I also want to use it twice in the same component, and I want the different instances to have different values in the other field names.

A: I am not sure you have configured correctly the components.
In your child component (lets call it childComponent) you need to define the aura:method and give it an action with a javascript method name, also I think Function type of attribute is not supported, but anyway I would make this a general object and pass it a json object so it can change easily as you please:
<aura:method name="methodOnChild" action="executeFromParent">
    <aura:attribute name="data" type="Object" />
</aura:method>

After that, to execute the method  - in your parent component you need to identify your childComponent so you can give it an aura:id when you are instantiating it, for example (you can do that in other ways):
<c:childComponent aura:id="childComponentId" />

Then in your parent component controller - you need to create the params to return, and then get the childComponent and execute the method like this:
var data = {
                givenId: component.get("v.givenId"),
                field2: component.get("v.field2"),
                field3: component.get("v.field3"),
                field4: component.get("v.field4"),
                field5: component.get("v.field5"),
                picklistValues: component.get("v.picklistValues")
            };

var childComponent = component.find("childComponentId");
childComponent.methodOnChild(data);

Finally on your childComponent you need to have the javascript method on your controller (the aura:method will call this method):
executeFromParent : function (component, event, helper) {
    var data = event.getParam('data');
    // now data contains your json - do whatever you want with it
}

A: I made a method to use as a utility for making toast messages
<aura:component description="AuraUtils">
<aura:method name="showToast" action="{!c.showToast}"  description="Used to show a toast message" >
    <aura:attribute name="title"    type="String"   description="title of toast" />
    <aura:attribute name="message"  type="String"   description="message inside of the toast"/>
    <aura:attribute name="type"     type="String"   description="error,warning,or success" />
    <aura:attribute name="mode"     type="String"   description="sticky, dismissible, or pester" />
</aura:method>

controller
showToast : function(component, event, helper) {
    var params = event.getParam('arguments');
    if (params) {
        var title = params.title;
        var message = params.message;
        var type = params.type;
        var mode = params.mode;
        helper.showToast(component, helper, title, message, type, mode);
    }
}

helper
showToast : function(component, helper, title, message, type, mode) {
    //helper.closeQuickActionPanel();
    let resultsToast = $A.get("e.force:showToast");
    let params = { "title": title, "message": message , "mode": mode, "type" : type};
    console.log('AuraUtils showToast params', params);
    resultsToast.setParams(params);
    resultsToast.fire();
}

I can call it like this
var AuraUtilsCmp = component.find("AuraUtils");
                if (AuraUtilsCmp) {
                    AuraUtilsCmp.showToast("", 'test message', 'message', "dismissible");
                }


text:
Q: get with csl equal product Id from xml in on row csv and sum size in one column I have an xml file and have to parse it to csv. In this case I like to delete all double parent_product_id and sum the size and stock_quantity in one column. Unfortunately I am not able to find a solution how to group it up when parent_product_id is equal and how to sum size and stock_quantity. Thanks for every help that I can get.

<?xml version="1.0" encoding="UTF-8" ?>
  <products>
   <product>
 <parent_product_id>RMA021-05J</parent_product_id>
        <brand_name>Regatta</brand_name>
        <colour>blauw</colour>
        <currency>EUR</currency>
        <rrp_price>29.95 EUR</rrp_price>
        <size>XXL</size>
        <stock_quantity>2</stock_quantity>
    </product>
  <product>
 <parent_product_id>RMA021-05J</parent_product_id>
        <brand_name>Regatta</brand_name>
        <colour>blauw</colour>
        <currency>EUR</currency>
        <rrp_price>29.95 EUR</rrp_price>
        <size>XL</size>
        <stock_quantity>4</stock_quantity>
    </product>
  </products>

<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
<xsl:output method="text" omit-xml-declaration="yes" encoding="UTF-8"/>
<xsl:strip-space elements="*"/>
<xsl:template match="products">
<xsl:for-each select="product">
<xsl:text>"</xsl:text>
 <xsl:value-of select="normalize-space(parent_product_id)"/><xsl:text>"|"</xsl:text>
 <xsl:value-of select="normalize-space(brand_name)"/><xsl:text>"|"</xsl:text>
 <xsl:value-of select="normalize-space(colour)"/><xsl:text>"|"</xsl:text>
 <xsl:value-of select="normalize-space(currency)"/><xsl:text>"|"</xsl:text>
 <xsl:value-of select="normalize-space(rrp_price)"/><xsl:text>"|"</xsl:text>
  <xsl:value-of select="normalize-space(size)"/><xsl:text>"|"</xsl:text>
 <xsl:value-of select="normalize-space(stock_quantity)"/><xsl:text>"|"</xsl:text>
<xsl:text>"
</xsl:text>
</xsl:for-each>
</xsl:template>
</xsl:stylesheet>

That's how my result look like now:

"RMA021-05J"|"Regatta"|"blauw"|"EUR"|"29.95 EUR"|"XXL"|"2"|""
"RMA021-05J"|"Regatta"|"blauw"|"EUR"|"29.95 EUR"|"XL"|"4"|""

The result that I need has to look like this:

"RMA021-05J"|"Regatta"|"blauw"|"EUR"|"29.95 EUR"|"XXL,XL"|"6"|""

A: Try this:
<xsl:template match="products">
    <xsl:for-each-group select="product" group-by="parent_product_id">
        <xsl:text>"</xsl:text>
        <xsl:value-of select="parent_product_id"/><xsl:text>"|"</xsl:text>
        <xsl:value-of select="brand_name"/><xsl:text>"|"</xsl:text>
        <xsl:value-of select="colour"/><xsl:text>"|"</xsl:text>
        <xsl:value-of select="currency"/><xsl:text>"|"</xsl:text>
        <xsl:value-of select="rrp_price"/><xsl:text>"|"</xsl:text>
        <xsl:value-of select="distinct-values(current-group()/size)" separator=","/><xsl:text>"|"</xsl:text>
        <xsl:value-of select="sum(current-group()/stock_quantity)"/><xsl:text>"|"</xsl:text>
        <xsl:text>"
</xsl:text>
    </xsl:for-each-group>
</xsl:template>

you can see transformation at https://xsltfiddle.liberty-development.net/94hvTyS


text:
Q: Merge two data frames based time range and unique ID So I have two data frames and I am trying to merge based on their unique IDs and dates, however some of the DF2 dates are sometimes one to two days off compared to DF1 for the same IDs. DF1 and DF2 are the sample dataframes and I want something like DF3 with the date column displaying either the date on DF1 or DF2
This is what I initially tried but I cannot think of a way to do joins based on dates that are not exact matches.
DF3 <- merge(x = DF1, y = DF2, by.x = c("ID1", "StartDate1"),
                    by.y = c("ID2", "StartDate2"), all = FALSE)

Sample data:
DF1
ID1       StartDate1      Gender
104382    2013-09-16        M
104382    2014-02-27        F
104382    2014-07-21        F
167623    2018-01-09        M

DF2
ID2       StartDate2      Gender
104382    2013-09-17        M
104382    2014-02-27        F
104382    2014-07-21        F
167623    2018-01-11        M

Desired result:
DF3
ID        StartDate      Gender
104382    2013-09-17       M
104382    2014-02-27       F
104382    2014-07-21       F
167623    2018-01-11       M

OR
DF3
ID        StartDate       Gender
104382    2013-09-16        M
104382    2014-02-27        F
104382    2014-07-21        F
167623    2018-01-09        M


text:
Q: Self Join a Table to Get a Pair of Value But Could Not Receive the Expected Results I am trying to self join the relation casts(movie_id,cast_id,cast_name). I want to query one pair of actors who have appeared in at least 1 movies together. The self pair must be excluded, and keep the mirror pair.
This is the relation table:

movie_id
cast_id
cast_name

12345
10
Trung

12340
10
Trung

12341
10
Trung

12342
10
Trung

12343
11
Thi

12340
12
Nhi

12341
12
Nhi

12342
12
Nhi

12343
12
Nhi

12340
13
David

12345
12
Nhi

This is what I've tried:
SELECT c.cast_id, c2.cast_id, c.movie_id
FROM casts c, casts c2
WHERE c.cast_id != c2.cast_id AND c.movie_id = c2.movie_id;

Instead of getting pairs of different cast_id, I got pairs of same cast_id.

cast_id
cast_id
movie_id

10
10
12345

10
10
12340

10
10
12340

10
10
12341

10
10
12342

11
11
12343

12
12
12340

12
12
12340

12
12
12341

12
12
12342

12
12
12343

13
13
12340

13
13
12340

12
12
12345

However, I got different pairs of actors if I try replace one of the attributes to cast_name like:
SELECT c.cast_name, c2.cast_id, c.movie_id
FROM casts c, casts c2
WHERE c.cast_id != c2.cast_id AND c.movie_id = c2.movie_id;

cast_id
cast_id
movie_id

Nhi
10
12345

David
10
12340

Nhi
10
12340

Nhi
10
12341

Nhi
10
12342

Nhi
11
12343

David
12
12340

Trung
12
12340

Trung
12
12341

Trung
12
12342

Thi
12
12343

Nhi
13
12340

Trung
13
12340

Trung
12
12345

Could you please explain the reason for this behavior and how to fix it to receive the expected results?
Thank you!

A: To resolve your issue, I did the the following (all of the code below is available on the fiddle here):
CREATE TABLE actor
(
  movie_id SMALLINT NOT NULL,
  cast_id  SMALLINT NOT NULL,
  cast_name TEXT NOT NULL
);

And populate it (note the pairs as comments - there are 7 pairs):
INSERT INTO actor VALUES

(12340, 13, 'David'),  -- David/Nhi, David/Trung, Nhi/Trung - ORDER BY cast_name
(12340, 12, 'Nhi'),
(12340, 10, 'Trung'),

(12341, 12, 'Nhi'),  -- Nhi/Trung
(12341, 10, 'Trung'),

(12342, 12, 'Nhi'),  -- Nhi/Trung
(12342, 10, 'Trung'),

(12343, 12, 'Nhi'),   -- Nhi/Thi
(12343, 11, 'Thi'),

(12345, 12, 'Nhi'),    -- Nhi/Trung
(12345, 10, 'Trung'),

--
--  Three extra records with actors who share a surname - added by me.
--

(12999, 25, 'Nguyen'), -- Nguyen(25)/Nguyen(26) - Nguyen(25)/Nguyen(27) - Nguyen(26)/Nguyen(27)
(12999, 26, 'Nguyen'),
(12999, 27, 'Nguyen');

There are 3 possible ways of doing this.
Method 1 (using cast_name):
SELECT
  a1.movie_id, a1.cast_name, a1.cast_id,
  a2.movie_id, a2.cast_name, a2.cast_id
FROM
  actor a1
JOIN actor a2
  ON  a1.movie_id = a2.movie_id
  AND a1.cast_name < a2.cast_name              -- note cast_name
ORDER BY a1.movie_id, a1.cast_name, a2.cast_name;

Result:
movie_id    cast_name   cast_id     movie_id    cast_name   cast_id
   12340        David        13        12340          Nhi        12
   12340        David        13        12340        Trung        10
   12340          Nhi        12        12340        Trung        10
   12341          Nhi        12        12341        Trung        10
   12342          Nhi        12        12342        Trung        10
   12343          Nhi        12        12343          Thi        11
   12345          Nhi        12        12345        Trung        10

The advantage of this method is that it presents the names in alphabetical order both down (ORDER BY) the records and across them (a1.cast_name < a2.cast_name) if this is desired. The major disadvantage is that the 3 duplicate Nguyens have disappeared!
Method 2 (using cast_id):
SELECT
  a1.movie_id, a1.cast_name, a1.cast_id,
  a2.movie_id, a2.cast_name, a2.cast_id
FROM
  actor a1
JOIN actor a2
  ON  a1.movie_id = a2.movie_id
  AND a1.cast_id < a2.cast_id                    -- note cast_id
ORDER BY a1.movie_id, a1.cast_name, a2.cast_name;

Result:
movie_id    cast_name   cast_id     movie_id    cast_name   cast_id
   12340          Nhi        12        12340        David        13
   12340        Trung        10        12340        David        13
   12340        Trung        10        12340          Nhi        12
   12341        Trung        10        12341          Nhi        12
   12342        Trung        10        12342          Nhi        12
   12343          Thi        11        12343          Nhi        12
   12345        Trung        10        12345          Nhi        12
   12999       Nguyen        25        12999       Nguyen        26
   12999       Nguyen        25        12999       Nguyen        27
   12999       Nguyen        26        12999       Nguyen        27

The advantage here is that we keep the Nguyen duplicates, but now the names aren't sorted alphabetically across the record.
Method 3 (complex):
SELECT
  a1.movie_id,
  CASE
    WHEN a1.cast_name = a2.cast_name THEN a1.cast_name
    ELSE LEAST(a1.cast_name, a2.cast_name)
  END AS l_name,
  CASE
    WHEN a1.cast_name = a2.cast_name THEN a1.cast_id
    ELSE
    (
      SELECT a.cast_id FROM actor a
      WHERE a.cast_name = LEAST(a1.cast_name, a2.cast_name)
      AND   a.movie_id = a1.movie_id
    )
  END AS c1_id,
  a2.movie_id,
  CASE
    WHEN a1.cast_name = a2.cast_name THEN a2.cast_name
    ELSE GREATEST(a1.cast_name, a2.cast_name)
  END AS g_name,
  CASE
    WHEN a1.cast_name = a2.cast_name THEN a2.cast_id
    ELSE
    (
      SELECT a.cast_id FROM actor a
      WHERE a.cast_name = GREATEST(a1.cast_name, a2.cast_name)
      AND   a.movie_id = a1.movie_id
    )
  END AS c2_id
FROM
  actor a1
JOIN actor a2
  ON  a1.movie_id = a2.movie_id
  AND a1.cast_id < a2.cast_id
ORDER BY a1.movie_id, l_name, g_name;

Result:
movie_id    l_name  c1_id   movie_id    g_name  c2_id
   12340     David     13      12340       Nhi     12
   12340     David     13      12340     Trung     10
   12340       Nhi     12      12340     Trung     10
   12341       Nhi     12      12341     Trung     10
   12342       Nhi     12      12342     Trung     10
   12343       Nhi     12      12343       Thi     11
   12345       Nhi     12      12345     Trung     10
   12999    Nguyen     25      12999    Nguyen     26
   12999    Nguyen     25      12999    Nguyen     27
   12999    Nguyen     26      12999    Nguyen     27
10 rows

Et voilà! Results sorted as per requirements and we have the duplicate Nguyen You can leave out fields as desired.
This final solution uses the LEAST() and GREATEST() functions (explained well here) which are two of the most under-utilised functions in the SQL arsenal!
In future, when asking questions like this one, could you please provide a fiddle with your table structure(s) and data.


text:
Q: Fit multiple linear regression without an intercept with the function lm() in R can you please help with this question in R, i need to get more than one predictor:
Fit multiple linear regression without an intercept with the function lm() to train data
using variable (y.train) as a goal variable and variables (X.mat.train) as
predictors. Look at the vector of estimated coefficients of the model and compare it with
the vector of 'true' values beta.vec graphically
(Tip: build a plot for the differences of the absolute values of estimated and true values).
i have already tried it out with a code i will post at the end but it give me only one predictor but in this example i need to get more than one predictor:
and i think the wrong one is the first line but i couldn't find a way to fix it :
i can't put the data set here it's large but i have a variable that stores 190 observation from a victor (y.train) and another value that stores 190 observation from a matrix (X.mat.trian)..  should give more than one predictor but for me it's giving one..
simple.fit = lm(y.train~0+ X.mat.train) #goal var #intercept # predictor
summary(simple.fit)# Showing the linear regression output
plot(simple.fit)
abline(simple.fit)

n <- summary(simple.fit)$coefficients
estimated_coeff <- n[ , 1]
estimated_coeff
plot(estimated_coeff)
#Coefficients: X.mat.train   0.5018
v <- sum(beta.vec)
#0.5369
plot(beta.vec)
plot(beta.vec, simple.fit)


text: Q: A "singular" Tischler theorem The Tischler theorem says that a compact manifold $M$ admitting a closed nowhere vanishing $1$-form $\alpha$ fibers over the circle. I was wondering if anything could be said about the case where $\alpha$ vanishes on some small (codimension-$1$? $0$-dimensional?) set, $sing(\alpha)$. I guess to hope for a fiber-bundle structure on $M/sing(\alpha)$ is too much, but maybe there are some extra conditions one could impose to get such a result?


text:
Q: FireMonkey draws blurred lines I try to display 1px thin lines in an Android app, but the FMX framework behaves strange: Lines are often drawn a little bit blurred, which can be seen on the screen. Even on a high resolution screens (tested on a Ascend Mate 7, which has a FullHD 1080x1920 on a 16 inch display) it is noticeable. It doesn't matter if I use a component, like a TLine or TRectangle (without sides - just Height=1) or if I draw a line myself on a canvas (e. g. with Canvas.Stroke.Thickness := 1.0 and Canvas.DrawLine()). Compiling as a Windows application shows 1px lines correctly, but on Android the lines are drawn as 2px or sometimes as 3px. Sometimes something between it, like one solid line and a second half transparent line.
It is also strange, that drawn line thickness seems to change when scrolling the view (at runtime) which contains the lines. Setting the thickness below the value 1.0 allows drawing lines really as 1px, but then the lines themself become transparent. No matter what I try - I cannot create a solid 1px thin completely opaque black line. And the above problems (e. g. while scrolling) still persists. Changing TForm.Quality does not help either. Native Android apps do not seem to have problems drawing thin lines.
Here is a native screenshots (zoom in to measure line thickness):

I tried some suggestions, like "moving" the lines: http://sourceoddity.com/blog/2013/10/using-tcanvas-in-delphi-for-android/. This helps a little bit with removing the bluring, but the lines are still drawn with more than 1px and I would like to solve the problem in one place (I cannot rewrite / redraw all of the hundreds of components in the framework).
Here is the sample project from the screenshot above: https://www.dropbox.com/s/le70jf601axd1xf/example.zip?dl=1
I tested this with version 10.1 (Berlin), but this strange behaviour occured in previous versions too (as long as I remember).

A: On android, you must take several think in account. First their is real pixel and virtual pixel (real pixel = virtual pixel x scale). this mean that when you ask to draw a 1px line on a XXhdpi device (with scale = 3) then you will have a 3px line that will be drawed. of course this not result in blured line, except if scale is for example 1.5
Second thing, connected to the first, if it's you don't start to draw you line on a real pixel. on android pos is a single, so you can draw you line everywhere, even on the middle of a real pixel. in this way of course the system will start to blur the line to draw it from the middle of one pixel to the middle of another pixel (because can't draw only half of a pixel). for avoid this always use Canvas alignToPixel function.
the other think you need to take care in account is that the firemonkey framework use an ugly designed parameter: form.quality. when you setup it to highquality the opengl used be firemonkey will be setuped to antialisased everything (including simple line), resulting in blur. to remove it you can setup it to normal, but in this way round corner / circle will be absolutely ugly on device with scale ratio of 1.
the option i personnally choose is to stay on form.quality = low (no anti aliased) and draw everything (including line, rectangle, etc) myself using the android api. You can take a look at this svn:  https://svn.code.sf.net/p/alcinoe/code/ or if you want to see directly load in android this demo : https://svn.code.sf.net/p/alcinoe/code/demos/ALFmxControls/Android/Release/ALFmxControls/bin/ALFmxControls.apk


text:
Q: Android Permission Denied when Writing files I am trying to create a file in the internal storage when I say internal storage it is not to keep safe data, it will be to save some images or public files I was trying everything but it is giving me error and I don't know why D:
CODE:
File file = new File(Environment.getDataDirectory() + File.separator
        + "test1111111.txt");
Log.e("ERROR", Environment.getDataDirectory() + File.separator
        + "testfile.txt");
try {
    file.createNewFile();
} catch (IOException e) {
    e.printStackTrace();
}
byte[] data1 = {
        1, 1, 0, 0
};
// write the bytes in file
if (file.exists())
{
    OutputStream fo = null;
    try {
        fo = new FileOutputStream(file);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    try {
        fo.write(data1);
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        fo.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    System.out.println("file created: " + file);

}

ERROR:
04-24 03:41:22.704    7797-7797/com.test.test W/dalvikvm﹕ VFY: unable to resolve virtual method 357: Landroid/content/res/Resources;.getDrawableForDensity (IILandroid/content/res/Resources$Theme;)Landroid/graphics/drawable/Drawable;
04-24 03:41:22.744    7797-7797/com.test.test E/ERROR﹕ /data/testfile.txt
04-24 03:41:22.744    7797-7797/com.test.test W/System.err﹕ java.io.IOException: open failed: EACCES (Permission denied)
04-24 03:41:22.744    7797-7797/com.test.test W/System.err﹕ at java.io.File.createNewFile(File.java:940)

MANIFEST:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.test.test" >

    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

In the emulator works fine but when I try with my phone it is giving me error.
EMULATOR:

DEVICE:
It is giving me error.
EDITED

A: Data directory is a system's directory, you can never have the permission to write in it.
Try for example :
File file = new File(Environment.getExternalStorageDirectory() + File.separator + "testfile.txt");

See this :
Data directory has no read/write permission in Android

A: You wont have the permission to write file under /data folder. Perhaps you can try SD card or Android Internal Storage instead.


text:
Q: Solve $x$ in $x = A^{x}$ for given $A$. I can see from graphing the problem that the equation $x = A^x$ will only have solutions when $A < 1.446...$ (approx).
For some value of $A$, say $k$, it will have exactly one solution, and then for $A < k$ it will have $2$ solutions.
How can we work out $k$? And how can we solve for the two values of $x$ given a specific $A < k$?

A: Without any special function, consider that you look for ther zero of
$$f(x)=A^x-x$$
It is simpler to take logarithms (assuming $x>0$) and consider
$$g(x)=x \log(A)-\log(x)$$
$$g'(x)=\log(A)-\frac 1 x \qquad \text{and} \qquad g''(x)=\frac 1 {x ^2} ~>0~\forall x$$
The minimum of the function occurs at
$$x_*=\frac 1{\log(A)}\implies g(x_*)=\log (\log (A))+1$$ In order to have two roots you need that
$$\log (\log (A))+1 <1 \implies  A < e^{\frac{1}{e}}=1.44467$$
Now, if $A< e^{\frac{1}{e}}$, the only explicit solutions are given in terms of Lambert function which is not elementary but simple. This function has a lot of applications (to give you an idea, just type Lambert of the search bar : $3932$ entries).
In the real domain the small and large solutions are
$$x_1=-\frac{W_0(-\log (A))}{\log (A)} \qquad \text{and}\qquad x_2=-\frac{W_{-1}(-\log (A))}{\log (A)} $$ In the linked page, you will find a series of approximations for their computation.


text:
Q: Trying to create my first node.js application: /bin/sh: 1: fpm: not found I have follow this steps to creae my first node.js application:
https://www.codementor.io/javascript/tutorial/how-to-create-cross-platform-desktop-apps-with-nwjs
The problem: I can not find anything at klout/dist directory after running gulp pack:linux64:deb, any help?
This is the output after gulp pack:linux64:deb:
https://gist.github.com/Ziiweb/ac0708acf689b7d6491d
and this is the output after gulp build:linux64
https://gist.github.com/Ziiweb/65104ee6f7f109f3a41e

A: According to logs you provided the fpm is missing. You have to install it globally for build to work by
npm install -g fpm


text:
Q: How can I display different menu items based on the user's role in angularjs? I'm using the meanjs stack to write a web application.  I need to display a dropdown menu to all users (logged in or not), then add more elements to the dropdown when a user is logged in.
For example, say you have a list of products.  You make a dropdown menu called "Products" that contains the element "List products".  This "List products" element appears if a user is logged in or not.  If a user is logged in, display another element in the dropdown called "Edit inventory".
The meanjs site says that the stack makes use of the "AngularJS Menus Service" and lists a little bit of documentation, but I can't find any more information on the usage of this service.  The linked docs mention the optional parameters isPublic and roles, but when I try to use them, there is no effect.
The code Menus.addMenuItem('topbar', 'Bios', 'bios', 'dropdown', '/bios(/create)?'); only shows this menu item when a user is logged in.
It has the same effect as Menus.addMenuItem('topbar', 'Bios', 'bios', 'dropdown', '/bios(/create)?', true);.  The optional isPublic parameter seems to make no difference.  What am I doing wrong?
I found this question, which is similar but not identical and also not answered satisfactorily.
To make use of the menus service in angular, is it necessary for a user to be logged in?

A: I just read the meanjs MenuService source code, this is addMenuItem:
 this.addMenuItem = function (menuId, menuItemTitle, menuItemURL, menuItemType, menuItemUIRoute, isPublic, roles) {
  // Validate that the menu exists
  this.validateMenuExistance(menuId);
  // Push new menu item
  this.menus[menuId].items.push({
    title: menuItemTitle,
    link: menuItemURL,
    menuItemType: menuItemType || 'item',
    menuItemClass: menuItemType,
    uiRoute: menuItemUIRoute || '/' + menuItemURL,
    isPublic: isPublic || this.menus[menuId].isPublic,
    roles: roles || this.defaultRoles,
    items: [],
    shouldRender: shouldRender
  });
  // Return the menu object
  return this.menus[menuId];
};

From this code, if you want to reset the isPublic, you should call the func with both menuItemUIRoute and the isPublic.
Cause if you don't pass the menuItemUIRoute. The parameters will be mixed up.
P.S This is Source Code in line 237, and the document is not right or this is a bug. Hope this can work for you. : )

A: This worked for me
in core menu service
**replace
// Define a set of default roles
 this.defaultRoles = ['user'];

with
 this.defaultRoles = ['user','admin'];**

And in articles config
For Main Menu
Menus.addMenuItem('topbar', 'Articles', 'articles', 'dropdown', '/articles(/create)?', true, ['admin']);
For Sub Menu
Menus.addSubMenuItem('topbar', 'articles', 'New Article', 'articles/create', 'menuItemUIRoute', true, ['admin']);


text:
Q: SQL Intersect not supported in Phoenix , alternative for intersect in phoenix? I have the following SQL expression:
SELECT SS_ITEM_SK AS POP_ITEM_SK
FROM (SELECT SS_ITEM_SK
FROM (SELECT SS_ITEM_SK,(ITEM_SOLD-ITEM_RETURNED) AS TOT_SOLD_QTY FROM (SELECT SS_ITEM_SK,COUNT(SS_ITEM_SK) AS ITEM_SOLD,COUNT(SR_ITEM_SK) AS ITEM_RETURNED FROM STORE_SALES1 right outer join STORE_RETURNS1 on SS_TICKET_NUMBER = SR_TICKET_NUMBER AND SS_ITEM_SK = SR_ITEM_SK GROUP BY SS_ITEM_SK)))

INTERSECT

SELECT CS_ITEM_SK AS POP_ITEM_SK FROM (SELECT CS_ITEM_SK
FROM (SELECT CS_ITEM_SK,(ITEM_SOLD-ITEM_RETURNED) AS TOT_SOLD_QTY FROM (SELECT CS_ITEM_SK,COUNT(CS_ITEM_SK) AS ITEM_SOLD,COUNT(CR_ITEM_SK) AS ITEM_RETURNED FROM CATALOG_SALES1 right outer join CATALOG_RETURNS1 on CS_ORDER_NUMBER = CR_ORDER_NUMBER and CS_ITEM_SK = CR_ITEM_SK  GROUP BY CS_ITEM_SK)))

INTERSECT

SELECT WS_ITEM_SK AS POP_ITEM_SK FROM (SELECT WS_ITEM_SK
FROM (SELECT WS_ITEM_SK,(ITEM_SOLD-ITEM_RETURNED) AS TOT_SOLD_QTY FROM (SELECT WS_ITEM_SK,COUNT(WS_ITEM_SK) AS ITEM_SOLD,COUNT(WR_ITEM_SK) AS ITEM_RETURNED FROM WEB_SALES1 right outer join WEB_RETURNS1 on WS_ORDER_NUMBER = WR_ORDER_NUMBER AND WS_ITEM_SK = WR_ITEM_SK GROUP BY WS_ITEM_SK)))

Apache phoenix is not supporting the keyword INTERSECT. Can somebody please help me to correct above query without using INTERSECT?

A: I think there are multiple ways you can do this:

*

*Join Method
select * from ((query1 inner join query2 on column_names) inner join query3 on column_names)

*Exists Method
(query1 where exists (query2 where exists (query3)) )

*In Method
(query1 where column_name in (query2 where column_name in (query3)) )

References: https://blog.jooq.org/2015/10/06/you-probably-dont-use-sql-intersect-or-except-often-enough/
and http://phoenix.apache.org/subqueries.html
Although I would use the exists/in over the join since if these queries return huge data then you might have to optimize your queries using this:
https://phoenix.apache.org/joins.html


text:
Q: How to always refresh file loaded by ajax, avoiding cached file First I load external JavaScript file with following code (it appends ext_chat.js script source to current DOM):
var protocol = ('https:' == document.location.protocol ? 'https://' : 'http://');
(function(d, t, p) {
   var g = d.createElement(t),
      s = d.getElementById('Chat_Script');
   g.src = p + 'mydomain.lc/js/ext_chat.js';
   s.parentNode.insertBefore(g, s.nextSibling);
}(document, 'script', protocol));

Inside the ext_chat.js. Here I'm including the CSS file:
function r(f) {
/in/.test(document.readyState) ? setTimeout('r(' + f + ')', 9) : f()
}

r(function () {
    includeCSSfile(getBaseUrl() + '/css/ext_chat.css')); // getBaseUrl() gives correct url
});

function includeCSSfile(href) {
    var head_node = document.getElementsByTagName('head')[0];
    var link_tag = document.createElement('link');
    link_tag.setAttribute('rel', 'stylesheet');
    link_tag.setAttribute('type', 'text/css');
    link_tag.setAttribute('href', href);
    link_tag.setAttribute('media', 'screen');
    head_node.appendChild(link_tag);
}

On first load, the CSS file is included fine. After the first time, when the page is loaded all changes to the ext_chat.css file are not reflected, and cached file is being used instead.
How can I force the CSS file to reload every time the page loads, instead of referring to the cached one?

A: First things first, don't use the eval version of setTimeout. Use .bind instead.
/in/.test(document.readyState) ? setTimeout(r.bind(null, f), 9) : f()

Now, to avoid a file caching you should just attach a random query string to the end of the URI. Usually you'll see ?v=123456789 or something to that effect. We can just use a timestamp in this case.
r(function () {
    includeCSSfile(getBaseUrl() + '/css/ext_chat.css?v=' + Date.now())); // getBaseUrl() gives correct url
});

Reading material:

*

*Function.prototype.bind()

*Date.now()


text:
Q: Apache Ignite : Transaction support and cache definition We are experimenting with Apache Ignite to use it as a Read and Write through caching layer for Distributed applications. The need is to weave a cache layer for the aggregates we depend on. Indiviual constituent entities that these aggregates comprise of, are managed entities maintained by EntityManager.
Two Questions:

*

*Does Apache Ignite participate in Container Managed Transaction out of box ?

*In order to understand solution to Q1 , I did a small experiment described below. Any insights on what induces below behaviour ?
Aggregates : Strategy and Strategy Parameter - one to many mapping.
Individual Entities : Strategy and StrategyParam (both managed by JPA/Hibernate).
CacheStore definition based on entitymanager : eg write method:
  @Override
public void write(Cache.Entry<? extends Long, ? extends StrategyAggregate> entry) throws CacheWriterException {
    em.merge(entry.getValue().getStrategy());
    entry.getValue().getStrategyParamList().forEach(strategyParam -> em.merge(strategyParam));
}

Now when we init first node with above cache definition, I see the transaction nature working alright i.e. post method completion I see both cache and database updated i.e. I can read the changes from cache.
But as soon as second node joins the cluster, the same api throws up error
"no entitymanager available ..." followed by stacktrace having transaction has been rolled back. Though Read from both cache and direct read from entity manager works fine.
Stacktrace
Caused by: javax.cache.integration.CacheWriterException: javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call
... 79 common frames omitted
Caused by: javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread - cannot reliably process 'merge' call
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:285) ~[spring-orm-4.3.25.RELEASE.jar:4.3.25.RELEASE]
at com.sun.proxy.$Proxy102.merge(Unknown Source) ~[na:na]
at StrategyAggregateCacheStore.write(StrategyAggregateCacheStore.java:47) ~[classes/:na]
at org.apache.ignite.internal.processors.cache.store.GridCacheStoreManagerAdapter.put(GridCacheStoreManagerAdapter.java:585) ~[ignite-core-2.11.0.jar:2.11.0]
... 78 common frames omitted


text:
Q: How get permission on WatchFace I have a application on Android Wear. App comprises only WatchFace.
How I can get permission without activity?
Permission added into manifest.

A: Go to Settings -> Permissions -> Select your app -> Turn on the permissions you have put in your manifest file

A: The easiest way is to create a little Activity solely for this purpose.

*

*Start it from your WatchFaceService (before trying to use the permission)

*Call requestPermissions() in its onCreate() method

*In onRequestPermissionsResult(), communicate the result back to your WatchFaceService, then call finish()
To keep this activity from being visible to the user while it does these things, declare it in your manifest as such:
    <activity android:name="com.mypackage.PermissionRequestor"
              android:theme="@style/NoDisplay"
        />

There's a bit more work if you're also going to support rationales, but I'll leave that as an exercise for the reader.


text:
Q: SQL get rows where column like In SQL is it possible to get only the rows of a table where the column name is like image? I've tried:
SELECT * FROM `projects` WHERE COLUMN LIKE '%image%' AND `id` = '125384332'

A: Can't add this as a comment due to not enough rep, but perhaps you can do something similar to what Fred -ii- was alluding to by getting the column names from the information schema columns table, then executed a prepared statement (which I think is roughly the MySQL equivalent of dynamic SQL, but I'm not certain) to create a query that will get you a query result with only those image columns selected.
Perhaps see also Selecting columns whose name matches a regular expression in PostgreSQL and How To have Dynamic SQL in MySQL Stored Procedure.


text:
Q: Free memory that sent to background child process as argument I have an exercise - to implement simple shell.
Since I have to implement the background operator ('&'), I can't send the arguments when they are on the buffer (because the new process maybe continue running after the next command and the buffer is overwritten). I allocate memory for each arg list, and because of the process is background and I don't wait for him, I don't know when to free the memory.
How I should do it?
Demonstrating (without buffer):
int main(){
  char **toSend = malloc(sizeof(char*) * 3 );
  toSend[0] = malloc(sizeof(char) * 3);
  strcpy(toSend[0], "ls");
  toSend[1] = malloc(sizeof(char) * 3);
  strcpy(toSend[1], "-a");
  toSend[2] = NULL;
  if( !fork() ){
    int devNull = open("/dev/null", O_WRONLY);
    dup2(devNull, STDOUT_FILENO);
    close(devNull);
    execvp(toSend[0], toSend);
  }
  free(toSend[0]); //???
  free(toSend[1]); //???
  free(toSend);    //???
  return EXIT_SUCCESS;
}

By the way, I will be happy to know if the using of the devNull pointer for create background process is correct.
Thanks in advance! and sorry for my bad English...

A: What you did is correct.
In the child process, after execvp(), its memory image is replaced by a new program, so you do not need to call free() in it. But you still need to call free() in the parent process, as you did in your example code.
Actually, because parent and child are different processes, you could define toSend as local buffer, instead of allocate memory for it dynamically.

A: free(toSend) will just free the address with it.First you free(toSend[0]) which frees all the address allocated using the first address till it encounters address which was not allocated by toSend pointer.


text:
Q: Beginner - How to print the external values of an array in Matlab? ## I want to write a function that receives an array as a parameter and then prints the array's external values better using loops.
e.g. If A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12]
Then the call printFrame(A) would display as in the code shows.
This is as far as I can get so that I obtain an array with only 0 in the middle, not sure if this way can lead me to the final purpose ---- printing the frame of the array##
% the text was not showing clear enough I want it to display like the following
1   2   3    4
5            8
9   10  11  12

function F = printFrame(A)
mat = [];
[m,n]=size(A);
for i=1:n
e = A(1,i);
mat = [mat,e];
end
for j=2:(m-1)
e = A(j,1);
mat = [mat,e];
   for k = 2:(n-1)
   A(j,k)=0;
   g = A(j,k);
   mat = [mat,g];
   end
e = A(j,end);
mat = [mat,e];
end
for i=1:n
h = A(end,i);
mat = [mat,h];
end

for l = 1:length(mat);
F = fprintf('%5d',mat(l));
 if rem(l,n) == 0
    fprintf('\n');
 end
end
fprintf('\n\n')
end

A: I believe something like this should be robust enough. I'm sure there's a more clever solution but this seems to work
A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12];
dims = size(A);

logicalmatrix = true(dims);
logicalmatrix(2:end-1, 2:end-1) = false;

A = A.'; % Transpose because MATLAB works column-wise
output = A(logicalmatrix);

EDIT, per your comment:
A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12];
dims = size(A);

A = arrayfun(@num2str, A, 'UniformOutput', 0).';
A(2:end-1, 2:end-1) = repmat({''}, dims - 2);

outstr = sprintf(strcat(repmat('%2s ', [1, dims(2)]), '\n'), A{:})

Returns:
outstr =

 1  2  3  4
 5        8
 9 10 11 12

As with my above answer, I'm sure there's a move clever solution. While more compact, I'm not sure if the arrayfun call is going to be any faster than a for loop. This should be fairly robust, the only thing that isn't robust is the the string output in the sprintf call (the %2s part) which I included to make sure the cells are uniformly padded, otherwise you'd get this:
outstr =

1 2 3 4
5   8
9 10 11 12

You'll have to change the value to the width of your largest number (with a negative sign if negative). I've been contemplating a couple robust solutions for this, but haven't quite settled on one that's elegant.

A: Use bsxfun to create a mask and apply that as a logical index. A needs to be transposed to get the order you want (rows first, then columns).
B = A.'; %'
mask = bsxfun(@or, [1 zeros(1,size(B,2)-2) 1], [1; zeros(size(B,1)-2,1); 1]);
result = B(mask).'; %'
disp(result)

A: This is as simple as I could make it. The resulting matrix contains strings instead of numeric values, but if you're just printing it out that should be okay.
A = [1, 2, 3, 4; 5, 6, 7, 8; 9, 10, 11, 12];
S = num2str(A);
S(2:end-1,2:end-1)=' ';
disp(S);

Output is:
1    2    3    4
5              8
9   10   11   12


text:
Q: Macro to generate function implementation by its definition? Would it be possible to automate writing the implementation for remote function?
If written by hand it would look like code below. Having both function declaration and implementation is important.
proc rcall*[A, B, R](fn: string, a: A, b: B, _: type[R]): R =
  echo (fn, a, b)

proc multiply(a, b: int): int

proc multiply(a, b: int): int =
  rcall("multiply", a, b, int)

I would like to automate it and write it as
proc rcall*[A, B, R](fn: string, a: A, b: B, _: type[R]): R =
  echo (fn, a, b)

proc multiply(a, b: int): int

remotefn multiply

And the remotefn macro should look at function definition and generate its implementation as rcall("multiply", a, b, int), is that possible?

A:
Would it be possible to automate writing the implementation ...

Yes, it would be possible to automate implementation of just about anything using nim macros that take typed argument (and then getTypeImpl)
import std/macros

macro dumpImpl(arg: typed): untyped =
  echo arg.getTypeImpl().treeRepr()

proc rcall*[A, B, R](fn: string, a: A, b: B, _: type[R]): R =
  echo (fn, a, b)

proc multiply(a, b: int): int

proc multiply(a, b: int): int =
  rcall("multiply", a, b, int)

dumpImpl multiply

Shows that multiply type (function signature) has the following structure:
ProcTy
  FormalParams
    Sym "int"
    IdentDefs
      Sym "a"
      Sym "int"
      Empty
    IdentDefs
      Sym "b"
      Sym "int"
      Empty
  Empty

Although it is important to keep in mind that overloaded procedures cannot be easily resolved based only on name (because, well, there are many implementations). The most obvious choice would be to still use typed argument, but pass some parameter to disambiguate the function call
import std/macros

macro dumpImpl(arg: typed): untyped =
  echo arg.treeRepr()

proc overload(a: string) = discard
proc overload(a: int) = discard

dumpImpl overload
# ClosedSymChoice - lists all possible overloads with their respective symbols
#   Sym "overload"
#   Sym "overload"

dumpImpl overload("123")
#Call
#  Sym "overload"
#  StrLit "123"

dumpImpl overload(123)
#Call
#  Sym "overload"
#  IntLit 123

As a small (personal) side note - when you are talking about nim macros the question should mostly be not "if this is even possible?" but rather "what is the most optimal way to do this?". It might require some knowledge of macro tricks, but it is possible to implement almost anything.
EDIT1 (add implementation code example, reply to question in comments):
import std/[macros]

proc rcall*[A, B, R](fn: string, a: A, b: B, _: type[R]): R =
  echo (fn, a, b)

macro remotefn(fn: typed) =
  let fname = fn.str_val()
  # `quote do` generates hygienic identifiers - i.e. all new
  # variables/functions introduced by it are unique and not visible in
  # global. To fix this you need to explicitly create identifier for your
  # procedure using `ident`

  let
    multId = ident("multiply") # < Function name identifier

    # Same goes for variables - nim does have a name-based overloading, so
    # you need to make sure function arguments use the same identifiers as
    # the original one
    aId = ident("a")
    bId = ident("b")

  result = quote do:
    proc `multId`(`aId`, `bId`: int): int =
      rcall(`fname`, 1, 1, int)

  echo result.toStrLit()

proc multiply(a, b: int): int
remotefn multiply


text:
Q: MVC5 OWIN ad and database I'm creating an MVC5 app.  It is an intranet app.  All users are already authenticated to the local Active Directory Domain.
We have an existing database that is currently used for a Windows app.
I want take the User's domain login name and use it to look up the roles and claims that are already configured in that database.
I will assume the the base project of ASP.NET / MVC5 / Authentication "Individual User Accounts" would be the starting point.
Please point me in the right direction.
Thanks

A: You do not want entire ASP.Net Identity. Instead, you can just use OWIN cookie authentication middleware.
Validate Credential via Active Directory
public bool ValidateCredentials(string userName, string password)
{
   using (var context = new PrincipalContext(ContextType.Domain))
   {
      return context.ValidateCredentials(userName, password);
   }
}

Authorize via Old Database
Once authenticated, you want to retrieve authorized role from old Database, and create claims.
private readonly HttpContextBase _context;
private const string AuthenticationType = "ApplicationCookie";

public OwinAuthenticationService(HttpContextBase context)
{
    _context = context;
}

public void SignIn(User user)
{
    IList<Claim> claims = new List<Claim>
    {
        new Claim(ClaimTypes.Sid, user.Id.ToString()),
        new Claim(ClaimTypes.Name, user.UserName),
        new Claim(ClaimTypes.GivenName, user.FirstName),
        new Claim(ClaimTypes.Surname, user.LastName),
    };

    // Get authorized roles from old database
    foreach (Role role in user.Roles)
    {
        claims.Add(new Claim(ClaimTypes.Role, role.Name));
    }

    ClaimsIdentity identity = new ClaimsIdentity(claims, AuthenticationType);

    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignIn(identity);
}

public void SignOut()
{
    IOwinContext context = _context.Request.GetOwinContext();
    IAuthenticationManager authenticationManager = context.Authentication;

    authenticationManager.SignOut(AuthenticationType);
}

Startup.cs
You also need to configure Startup for all those to happen.
[assembly: OwinStartup(typeof(YourApplication.Startup))]
namespace YourApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath = new PathString("/Account/Login")
            });
        }
    }
}

I hope you get the starting point.

A: The .NET OWIN Identity classes require that you authenticate through the CheckPasswordAsync() method of the ApplicationUserManager class.  This can be done by overriding the CheckPasswordAsync() method of class ApplicationUserManager. In your override you will need to call the ValidateCredentials() method of class System.DirectoryServices.AccountManagement to authenticate via Active Directory.  This will require the user to login to the application with their Windows username and password.  There are a few steps to get that to work though.
As you said, you start with a base project with "Individual User Accounts" authentication.
Step 1 - Update the ConfigureAuth() method in file App_Start\Startup.Auth.cs by adding the code below to the ConfigureAuth() method.
using System.DirectoryServices.AccountManagement;

//Add an Owin context for Active Directory principals
app.CreatePerOwinContext(() => new PrincipalContext(ContextType.Domain));

The rest of the updates are done in file App_Start\IdentityConfig.cs
Step 2 - Update the constructor for class ApplicationUserManager.
using System.DirectoryServices.AccountManagement;

//Add a PrincipalContext parameter to the constructor
public ApplicationUserManager(IUserStore<ApplicationUser> store, PrincipalContext principal) : base(store)
{
    this.principal = principal;
}

Step 3 - In the Create() method update the call to the constructor for class ApplicationUserManager.
//Add the PrincipalContext parameter
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<PortalIdentityDbContext>()), context.Get<PrincipalContext>());

Step 4 - Override the CheckPasswordAsync() method of class ApplicationUserManager.
//Override CheckPasswordAsync to login via Active Directory.
public override async Task<bool> CheckPasswordAsync(ApplicationUser user, string password)
{
    return await Task.FromResult(this.principal.ValidateCredentials(user.UserName, password, ContextOptions.Negotiate));
}

As for using your existing database, you will have to incorporate the OWIN Identity tables in it or vice-versa.  The Identity functionality requires those tables and you can't change that.  I would create a test project and get familiar with those tables.  Then figure out how you want to incorporate them into your existing database or vice-versa.  I heavily modify those tables for my custom functionality.  But the core tables and columns have to exist.


text:
Q: Disable dx aspxbutton I'm trying to set a button's enable/disable based on a checkbox being checked or not. Below is my javascript and asp code, which doesn't work. I am not sure if the function is not called at all, or something is wrong with how I disable the button.
<script type="text/javascript">

function OnChkAgreeChanged(chkAgree) {
    if (document.getElementById"chkAgree").checked)
        document.getElementById("btnSubmit").SetEnabled(true);
    else
        document.getElementById("btnSubmit").SetEnabled(false);
}
</script>

<asp:checkbox ID="chkAgree" runat="server"
    Text="blablabla" onchange="javascript:OnChkAgreeChanged(this);"/>

<dx:ASPxButton ID="btnSubmit" runat="server" Text="Submit"
    UseSubmitBehavior="true" AutoPostBack="true" Width="175px"
    CssClass="submitButton" OnClick="btnSubmit_Click" enabled="false">
</dx:ASPxButton>

A: chkAgree is an object not a string. You don't have to use document.getElementById. Try this...
<script type="text/javascript">

function OnChkAgreeChanged(chkAgree) {
    if (chkAgree.checked)
        document.getElementById("btnSubmit").disabled = null;
    else
        document.getElementById("btnSubmit").disabled = true;
}
</script>

Also, in onchange="javascript:OnChkAgreeChanged(this);" javascript: may not be required. Pls check ASP documentation.

A: DevExpress creates a client instance object for each one of it's various controls.  In this case it will create an ASPxClientButton for btnSubmit.  Since you haven't given btnSubmit a ClientInstanceName, you can access it like so:
window.aspxGetControlCollection().elements['<%= btnSubmit.ClientID %>'];

That means your entire handler function could look something like this:
function OnChkAgreeChanged(chkAgree)
{
    btnSubmit = window.aspxGetControlCollection().elements['<%= btnSubmit.ClientID %>'];
    if(!(btnSubmit === null || btnSubmit === undefined)) { btnSubmit.SetEnabed(chkAgree.checked); }
}

You could also make your life easier by defining the ClientInstanceName attribute like so:
<dx:ASPxButton ID="btnSubmit" ClientInstanceName="btnSubmit" runat="server" Text="Submit"
    UseSubmitBehavior="true" AutoPostBack="true" Width="175px"
    CssClass="submitButton" OnClick="btnSubmit_Click" enabled="false">
</dx:ASPxButton>

Then, you'd be able to use that directly in your handler:
function OnChkAgreeChanged(chkAgree)
{
    if(!(btnSubmit === null || btnSubmit === undefined)) { btnSubmit.SetEnabed(chkAgree.checked); }
}

You'll note that I like to check if that thing is null or not because if you set the display to none in the Code-Behind or otherwise disable it, it's very likely the DevExpress magic/voodoo (pick one) won't emit the JS creating that instance object.

A: JQuery Solution
$(document).ready(function () {
    $('#chkAgree').click(function () {
        if (this.checked) {
            $("#btnSubmit").prop('disabled', false);
        }
        else {
            $("#btnSubmit").prop('disabled', true);
        }
    });
});

Or if you want to do same thing using JavaScript can use solution suggested by mohkhan.

A: Use the ClientInstanceName and ClientEnabled (not the Enabled) properties for this purpose:
function OnChkAgreeChanged(chkAgree) {
    var checked = chkAgree.checked;
    btnSubmit.SetEnabled(checked);
}
</script>

<asp:checkbox ID="chkAgree" runat="server" Text="blablabla" onchange="OnChkAgreeChanged(this);"/>

<dx:ASPxButton ... ClientInstanceName="btnSubmit" ClientEnabled="False">
</dx:ASPxButton>


text:
Q: Javascript / ES6 find unique elements and count them in array Take an imaginary array of sold items where we oddly enough only are interested in the item title and value:
let items = [
    { title: "Trumping the Horns", value: 5.95 },
    { title: "Rocking about", value: 20.00 },
    { title: "Trumping the Horns", value: 5.95 }
]

I know I can get an array with the unique values rather easily:
const uniqueSales = [...new Set(items.map(item => item.title))];

But lets for instance say I want to know how many of each item I have sold, or the accumulated value of them? So:
[
    { title: "Trumping the Horns", amount: 2 },
    { title: "Rocking about", amount: 1 }
]

Is it possible to map those as well, without having to do some crazy sorting and iterating over that array? Preferebly in a one-liner. The main reason for not doing it server side is that I have a fair amount of different manipulations of the same data, and it seems most correct to just send it once and let the client handle the manipulations and presentations of the data.

A: You could use Map and store the reference to the new inserted objects of the result array.

var items = [{ title: "Trumping the Horns", value: 5.95 }, { title: "Rocking about", value: 20.00 }, { title: "Trumping the Horns", value: 5.95 }],
    result = items.reduce(
        (map => (r, a) => (!map.has(a.title) && map.set(a.title, r[r.push({ title: a.title, amount: 0 }) - 1]), map.get(a.title).amount++, r))(new Map),
        []
    );

console.log(result)

A: In ES6, we can get returned unique items from a single line of code as below,
// with arrays
const dupArr = [1, 1, 2, 3, 1];
const uniArr = [...(new Set(dupArr))];
// [1, 2, 3]

// with objects on a key.
const dupObj = [{ id: 1, value: 'a' }, { id: 2, value: 'b' }, { id: 1, value: 'c' }];
const uniKeys = [...(new Set(dupObj.map(({ id }) => id)))];
// [ '1', '2' ]

A:

let items = [{
    title: "Trumping the Horns",
    value: 5.95
  },
  {
    title: "Rocking about",
    value: 20.00
  },
  {
    title: "Trumping the Horns",
    value: 5.95
  }
];

console.log(items.reduce(function(countMap, item) {
  countMap[item.title] = ++countMap[item.title] || 1;
  return countMap;
}, {}));

A: Given the format you want in the end, I don't think it gets much shorter than using a Map to build up objects with the title and amount, then grabbing the Map's values:

const items = [
    { title: "Trumping the Horns", value: 5.95 },
    { title: "Rocking about", value: 20.00 },
    { title: "Trumping the Horns", value: 5.95 }
];
const map = new Map();
items.forEach(item => {
  const entry = map.get(item.title);
  if (!entry) {
    map.set(item.title, {title: item.title, amount: 1});
  } else {
    ++entry.amount;
  }
});
const uniqueSales = [...map.values()];
console.log(uniqueSales);

...preferably a one-liner...

The above can be shoehorned into fewer lines, but it doesn't improve speed, readability, or maintainability. Quite the opposite.

A: I would use a map rather than an array for storing your items, where the key of the map should be the title of the item, and the value should be the quantity of the sold items. Each time, before you add a new item to the map, you should check, whether the key already exist, and if it does, then increase the quantity, otherwise add a new key-value pair to the map.

A:  let array = [{title:"123"}, {title: "234"}, {title: "123"}]
 let sum = array.reduce((results, item, index) => {
                      let totalItem = results.find((element) =>
                            element.title == item.title)
                      if(totalItem){
                        totalItem.count += 1
                      }else {
                         results.push(Object.assign(item, {
                              count: 1
                            }))
                      }
                       return results
                     }, [])

use array reduce to generate new array

A: const ages = [3,1,1,2,3,4,1,2,3]
ages.sort();
console.log(ages);
const uniqueAges = ages.find((x, i) => {if(x!=ages[i-1]&&x!=ages[i+1]){
return x;
}} )
console.log(uniqueAges);

Output
4


text:
Q: VLOOKUP N/A Error I had a quick question about VLOOKUP in Excel.  Suppose I create a table of three rows and two columns with no headers.  Say that I supply the first column with the categories 'bad' 'okay and 'good' and the second with the numbers 0,1,2.  If I have a single column somewhere else in the worksheet containing 0s 1s and 2s I understand that my VLOOKUP should look as follows:
VLOOKUP(an entry in the column of 0s 1s and 2s, the table of three rows and two columns, 2, FALSE).
However, I get an N/A value.  Does anyone know why this might be?

A: For VLOOKUP to work you'd need the table to have the number column to the left of the text column (lookup range is always 1st column of the "table array"), so you either need to switch those and use VLOOKUP or leave the current setup and use INDEX/MATCH
=INDEX(1st column of table,MATCH(an entry in the column of 0s 1s and 2s, 2nd column of table,0))

A: VLOOKUP takes the entry (first part of function) and looks in column 1 of the table, that is, in your example, it is looking in the column containing 'Good', 'Okay' and 'Bad' and since it doesn't find anything (0, 1 or 2), it returns #N/A.
Turn around your table so that 0, 1 and 2 are first and then in the next column have 'Good', 'Okay' and 'Bad' and retype your formula in.


text:
Q: Anaconda Installation Failed on macOS Ventura I am trying to install Anaconda on my new MacBook which has Ventura 13.1 installed.
I am installing only for myself and the installation fails.
Can someone please help?
Edit 1
I have followed this link but I do not see that.
Edit 2
As it was a new setup, I erased the disk and was able to reinstall it.

A: As it was a new setup, I erased the disk and was able to reinstall it.
When I installed again, it asked that the installer wants access to Download folder.
Earlier, I may not have allowed it.
This time I did and it worked.

A: Directly running the sh script fixed the issue for me.


text:
Q: RegEx splitting multiple lines - grouped by ID I would like to create a regular expression to split a CSV file into multiple files based on an ID which can be found in each row. Here is an example:
ID,text,value
1,some text,5
1,other text,3
1,something,2
2,sample,4
3,john doe,2
3,jane doe,3
4,foo,1
4,bar,2
4,baz,3

The expected capturing groups would be
1,some text,5
1,other text,3
1,something,2

2,sample,4

3,john doe,2
3,jane doe,3

4,foo,1
4,bar,2
4,baz,3

What makes it even more complicated is that the ID might appear 1 or multiple times (like 2 above).
Here is what I tried:
^.*?\n(((\d+),.*?\n)(\2.*?){0,})

But it is not working as expected.

A: You can use this regex in MULTILINE mode to group individual blocks with same ID:
^(\d+).*[\r\n]+(?:\1.*[\r\n]+)*

RegEx Demo
RegEx Details:

*

*^: Start

*(\d+): Match 1+ digits and capture in group #1

*.*[\r\n]+: Match everything until end of line

*(?:\1.*[\r\n]+)*: Match same digit and rest of the line. Repeat this group 0 or more times


text:
Q: jQuery Modal Dialog I wonder whether someone could help me please.
I've been working on, and I've managed to put together this jQuery Modal Dialog box and it works fine.
What I'm now trying to do is to link this page to the dialog box via a button click, to be specific the 'Upload Image(s)' button.
On the button click, the dialog box correctly appears on screen, but rather than it hovering over the main page which it's called from, it appears on a seperate web browser page.
I've been working on this for days now and I just can't seem to get around the problem. I don't think the problem is with the dialog box code, but most likely in how I call the opening of it. i.e. having two submit buttons on the main form, means that I have called the page as shown below
because I wasn't sure how to deal with both of the 'submit' buttons for this particular scenario.
<form name="savemyfindstolocation" id="savemyfindstolocation" method="post" action="testdialog.php">

I just wondered whether someone could perhaps take a look at this please and let me know where I've gone wrong.
Many thanks and kind regards

A: You're going absolutely wrong mate. You have created a form with the action as testdialog.php which is the dialog form, if I'm not wrong.
You've given the button Upload Image as type="submit", which would SUBMIT the form ofcourse, as it is doing now.
To open a dialog, you will require to use either an input button with type="button" or a link/anchor with an onClick event.
Can you please tell where is your dialog located and how are you working with the dialog?


text:
Q: How to integrate Disqus in my Android App? I am developing an android app for a web-site. The web-site supports Disqus for commenting  service. I want to support the same in my application. I got APIs from Disqus docs but still I am not clear how to integrate them in my application. Please help me understand the implementation. Is anyone integrated Disqus comment service into their Android App?

A: Thanks ndgreen. Seeing your idea I created a something different without a PHP file necesity:
https://gist.github.com/bichotll/5563926
This script just create the html from a simple function and load th.

A: I ran into the same problem with having my web site disqus threads linked up with my android app. I wrote a little walkthrough if you are interested I will link to my walkthrough below. Basically in your android app you want to use a WebView and use a separate php file that can take your disqus identifier.
http://globeotter.com/blog/disqus-android-code/

A: You can use this code :
Google Login is working.
I did not tested Facebook yet.
static void setupDisqus(Context context, WebView disqus) {
    try {
        String URL = ""; // URL must be unique like identifier! Because Disqus, is using the url instead of identifier.
        String identifier = "";
        String shortName = "";
        String commentsUri = "https://captainsp.github.io/disqus_comments_dark_gray.html?" + "shortname=" + shortName +
                "&url=" + URLEncoder.encode(URL, "UTF-8") +
                "&title=" + URLEncoder.encode("Comments", "UTF-8") +
                "&identifier=" + URLEncoder.encode(identifier, "UTF-8");

        /*
         * You can use this colors in my Github Account:
         * disqus_comments_dark_gray.html
         * disqus_comments.html
         * disqus_comments_dark.html
         *
         *
         */

        disqus.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                new Handler().postDelayed(disqus::reload, 2000); // Reload Comments
                super.onReceivedError(view, request, error);
            }
        });
        CookieManager.getInstance().setAcceptThirdPartyCookies(disqus, true); // Accept Cookies to login (If you forget this part users need to login every single time)
        disqus.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); // Google / Facebook Login
        disqus.getSettings().setSupportMultipleWindows(true); // Google / Facebook Login
        CookieManager.getInstance().setAcceptCookie(true); // Accept Cookies to login 2
        disqus.setWebChromeClient(new WebChromeClient() {
            @SuppressLint("SetJavaScriptEnabled")
            @Override
            public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
                WebView newWebView = new WebView(context); // Create new WebView
                WebSettings webSettings = newWebView.getSettings();
                webSettings.setJavaScriptEnabled(true);
                webSettings.setUserAgentString(webSettings.getUserAgentString().replace("; wv", "")); // Hide WebView User Agent
                final Dialog dialog = new Dialog(context); // Create Dialog
                dialog.setContentView(newWebView);
                dialog.show();
                CookieManager.getInstance().acceptThirdPartyCookies(newWebView);
                newWebView.setWebViewClient(new WebViewClient());

                newWebView.setWebChromeClient(new WebChromeClient() {
                    @Override
                    public void onCloseWindow(WebView window) {
                        dialog.dismiss(); // Close the dialog after logged in
                    }
                });

                ((WebView.WebViewTransport) resultMsg.obj).setWebView(newWebView);
                resultMsg.sendToTarget();

                return true;
            }
        });
        disqus.getSettings().setJavaScriptEnabled(true); // Enable JavaScript
        disqus.getSettings().setAppCacheEnabled(true);
        disqus.getSettings().setDomStorageEnabled(true);
        disqus.loadUrl(commentsUri);
    } catch (Exception e) {
        e.printStackTrace();
    }

}

First create a new WebView or find it with findViewById(R.id.webView);
Then setup Disqus to your WebView: setupDisqus(this,webView);
More information : https://help.disqus.com/en/articles/1717165-javascript-embed-in-native-apps


text:
Q: Preloading of html web page or non-flash web applications? I believe that most of you have heard of preloading of images.
But is there anyone who knows how we can preload webpages?
For instance, when we are login to GMAIL, we will see a loading progress bar.
How do we preload html webpages/web applications (non-flash based )
as per what gmail is doing?
best Regards

A: Due to the stateless nature of the HTTP protocol, pre-loading webpages could be challenging. One way to achieve this would be to have a minimal HTML sent to the client initially and then progressively enhance parts of the site using AJAX. During the time those AJAX requests are being executed you could have some spinner on the page saying that the site is being loaded, but if you want to have real progress bars (such as the one GMail uses) things become even more challenging.

A: Google uses AJAX requests on GMail, you could do the same with jQuery. If you wanted to replace the entire code between  on a page.
function preload(url2load,anyDataIfAny) {
    $.ajax({
      type: 'POST',
      url: url2load,
      data: anyDataIfAny,
      success: function(data) {
        $(html).html(data);
      }
    });
}

This will show the user the loading screen until the page is loaded, then replace the loading screen with the requesting code.

A: Try this:
http://www.gayadesign.com/diy/queryloader-preload-your-website-in-style/

A: Depends alot on what you want to achieve..?
But generally, you could load the (next?) page into a hidden iframe.
- unveiling it when that becomes prudent..


text:
Q: Product of non-idempotent elements in a commutative monoid Assuming we have a commutative monoid $(M,\cdot)$ such that the non-trivial elements have no inverse. In addition, M contains no non-trivial idempotents. Considering two non-trivial elements $a_1$ and $a_2$. Is it possible to have a relation of the form $a_{1}^{n_1}a_{2}^{n_2} = a_{1}^{n_1^{'}}a_{2}^{n_2^{'}}$ with $(n_1,n_2) \neq (n_{1}^{'},n_{2}^{'})$?
I am suspecting the answer is a no. But so far I've only been able to show that  in the case where $n_1 > n_1^{'}$ and $n_2 > n_2^{'}$ we have an idempotent element $a_1^ta_2^m$ for some $t,m$. I have not been able to prove this when  $n_1 > n_1^{'}$ and $n_2 \leq n_2{'}$.

A: Take the monoid $M = \langle a, b \mid ab = ba, a^2b^2 = ab^3\rangle$. Its elements are of the form $a^n$ ($n \geq 0$), $b^m$ ($m > 0$), $ab^m$ ($m > 0$) or $a^2b$ and the unique idempotent is $1 = a^0$.


text:
Q: Режется HTML форматирование в multipart письме Пытаюсь сделать по аналогу другого письма multipart письмо. Но GMail режет все HTML теги и отображает письмо из второй части, но без форматирования. Как исправить это? Исходник письма:
Delivered-To: xxx@gmail.com
Received: by 10.79.105.193 with SMTP id e184csp1732294ivc;
        Tue, 31 May 2016 01:57:19 -0700 (PDT)
X-Received: by 10.25.210.205 with SMTP id j196mr3546366lfg.139.1464685039688;
        Tue, 31 May 2016 01:57:19 -0700 (PDT)
Return-Path: <webmaster@xxxx.com>
Received: from s05****.fastvps-server.com (s05***.fastvps-server.com. [2a03:f480:1:xxxxx])
        by mx.google.com with ESMTPS id qm4si72520lbb.68.2016.05.31.01.57.19
        for <xxx@gmail.com>
        (version=TLS1_2 cipher=ECDHE-RSA-AES128-GCM-SHA256 bits=128/128);
        Tue, 31 May 2016 01:57:19 -0700 (PDT)
Received-SPF: pass (google.com: domain of webmaster@xxxx.com designates 2a03:f480:1:xxxxx as permitted sender) client-ip=2a03:f480:1:xxxxx;
Authentication-Results: mx.google.com;
       dkim=pass header.i=@xxxx.com;
       spf=pass (google.com: domain of webmaster@xxxx.com designates 2a03:f480:1:xxxxx as permitted sender) smtp.mailfrom=webmaster@xxxx.com;
       dmarc=pass (p=NONE dis=NONE) header.from=xxxx.com
DKIM-Signature: v=1; a=rsa-sha256; q=dns/txt; c=relaxed/relaxed; d=xxxx.com; s=dkim;
    h=Date:Message-Id:List-Id:List-Unsubscribe:Content-Type:Reply-To:From:Subject:To; bh=DjWJSTXiHxh3erjnZcsVVDLhoKAx3FvkKujJ4BLQZXY=;
    b=06BOCMwbNIfb5Di3XDL8f7JIBn7n9bR+HAZsWRpGgihUmSag79//qOje+juwQpwDUmMOlMrcXGqQE3At1VZz15QRTQ+yKOvekH4LLoAkljqGw3yJTQtuK7T1UMPMHUadKEswGkum+1Gmw6TAuTZvenmJ3i05pXFFIE5dZGuIHWE=;
Received: from www-data by s05657567.fastvps-server.com with local (Exim 4.84_2)
    (envelope-from <webmaster@xxxx.com>)
    id 1b7fUF-0005jm-B4
    for xxx@gmail.com; Tue, 31 May 2016 11:57:19 +0300
To: xxx@gmail.com
Subject: Confirm Your Registration
From: XX XX <money@xxxx.com>
Reply-To: support@xxxx.com
Content-Type: multipart/alternative; boundary=ahQEtHYFz8RDrhtBhzK7raifn75e2T
List-Unsubscribe: <https://xxxx.com/unfollow?user_id=1&code=4iadh25Br5nYY543Q>
List-Id: <register-confirmation>
Message-Id: <E1b7fUF-0005jm-B4@s05657567.fastvps-server.com>
Date: Tue, 31 May 2016 11:57:19 +0300

--ahQEtHYFz8RDrhtBhzK7raifn75e2T
Content-Transfer-Encoding: quoted-printable
Content-Type: text/plain; charset=UTF-8
Mime-Version: 1.0

Please See English version below
---------------------------------
Пожалуйста, перейдите по https://xxxx.com/activateAccount?user_id=1&code=4iadh25Br5nYY543Q , чтобы подтвердить регистрацию. Вы подписываетесь на нашу рассылку, урегулировать которую вы можете в личном кабинете.
----------------------------------
Please, follow https://xxxx.com/activateAccount?user_id=1&code=4iadh25Br5nYY543Q , to confirm your account. That's also confirm subscription to our services.

Unfollow / Отписаться: https://xxxx.com/unfollow?user_id=1&code=4iadh25Br5nYY543Q

--ahQEtHYFz8RDrhtBhzK7raifn75e2T
Content-Transfer-Encoding: quoted-printable
Content-Type: text/html; charset=UTF-8
Mime-Version: 1.0

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>Confirm Your Registration</title>

https://xxxx.com/activateAccount?user_id=1&code=4iadh25Br5nYY543Q
Please See English version below

Пожалуйста, перейдите по следующей ссылке, чтобы подтвердить регистрацию. Вы подписываетесь на нашу рассылку, урегулировать которую вы можете в личном кабинете.

Please, follow this link, to confirm your account. That's also confirm subscription to our services.

Unfollow / Отписаться

--ahQEtHYFz8RDrhtBhzK7raifn75e2T--

A:
Content-Transfer-Encoding: quoted-printable

Не вижу ничего похожего на quoted-printable. Возможно, этот заголовок надо удалить. Либо наоборот привести содержимое к надлежащему виду.


text:
Q: Parsing a json datetime in revel I'm attempting to parse a Datetime in revel from a json request. The request looks something like this:
{
  "startedAt": "2017-06-01 10:39",
  ...
}

The struct it's being decoded into looks like this:
type MyStruct struct {
  StartedAt time.Time `json:"startedAt" bson:"startedAt"`
  ...
}

The decode line looks like this:
json.NewDecoder(c.Request.Body).Decode(&MyStruct)

Revel returns this error:
interface conversion: error is *time.ParseError, not *errors.Error

According to revel's documentation here, https://revel.github.io/manual/parameters.html
The SQL standard date time formats of 2006-01-02, 2006-01-02 15:04 are built in.

In the same document, they also say you can append formats like this:
func init() {
    revel.TimeFormats = append(revel.TimeFormats, "01/02/2006")
}

To verify the format was in the array, I tried this:
func init() {
    revel.TimeFormats = append(revel.TimeFormats, "2016-06-01 12:12")
}

In a final act of desperation I tried submitting it in the same format that revel will return json times in:
{
  "startedAt": "2017-06-22T12:22:16.265618819-05:00",
  ...
}

At this point I'm not sure where to go with this. Has anyone been able to get revel to parse a Datetime?

Update: I tried RickyA's solution below, but now there is a parsing error.
parsing time ""Mon, 02 Jan 2006 15:04:05 -0700"" as "Mon, 02 Jan 2006 15:04:05 -0700": cannot parse ""Mon, 02 Jan 2006 15:04:05 -0700"" as "Mon"

What's even stranger is that I implemented a bit of a hack to get this working in the interrum. I changed the request time field to a string, and gave it a ToX function which converted it. That function works, but when it's moved into the UnmarshalJSON function it fails.
Also, I can't tell if this is a bug or not:
func (t *AnyTime) UnmarshalJSON(b []byte) error {
  fmt.Println(time.RFC1123Z)
  fmt.Println(string(b))
  fmt.Println(reflect.TypeOf(time.RFC1123Z))
  fmt.Println(reflect.TypeOf(string(b)))
  ...

This outputs this:
Mon, 02 Jan 2006 15:04:05 -0700
"Mon, 02 Jan 2006 15:04:05 -0700"
string
string

Notice that only 1 of the string has double quotes. This is leading me to believe that some how the byte array passed to UnmarshalJSON has double quotes within its string.

Final Update: So I'm pretty sure the double quotes are intentional, and in a way it makes sense. The UnmarshalJSON is passing everything from the ':' through the ',' which includes the double quotes. I'm guessing this is done so that it can also support integers and booleans. I don't like the solution, but this is how I fixed it:
func (t *AnyTime) UnmarshalJSON(b []byte) error {
  var err error
  sTime := string(b)
  sTime = strings.TrimSuffix(sTime, "\"")
  sTime = strings.TrimPrefix(sTime, "\"")
  t.Time, err = time.Parse(time.RFC1123Z, sTime)
  ...

A: I had the same problem and ended up creating a custom type for time.Time
package genericfields

import (
    "encoding/json"
    "time"
    "strings"

    "gopkg.in/mgo.v2/bson"
)

// ANYTIME //

// AnyTime accepts any time format for its unmarshaling //
type AnyTime struct{ time.Time }

func (t AnyTime) MarshalJSON() ([]byte, error) {
    return json.Marshal(t.Time)
}

func (t *AnyTime) UnmarshalJSON(b []byte) error {
    err := json.Unmarshal(b, &t.Time)
    if err != nil { //assume non tz time input
        bstr := strings.Trim(string(b), `"`)
        t.Time, err = time.Parse("2006-01-02T15:04:05", bstr)
        if err != nil {
            return err //TODO add more formats to try
        }
    }
    return nil
}

func (t AnyTime) GetBSON() (interface{}, error) {
    return t.Time, nil
}

func (t *AnyTime) SetBSON(raw bson.Raw) error {
    var tm time.Time
    err := raw.Unmarshal(&tm)
    if err != nil {
        return err
    }
    t.Time = tm.UTC()
    return nil
}

func (t AnyTime) ToTime() time.Time {
    return t.Time
}

Usage:
type MyStruct struct {
  StartedAt genericfields.AnyTime `json:"startedAt" bson:"startedAt"`
  ...
}

You might need to tweak the input for time.Parse somewhat.


text:
Q: Can't able to open custom port in centos 7 launch AWS I have looked to this issue and notice when he ran netstat -ltpn he do have the 8080 port entry but in my case the desire port 8069 is not entered in this list.
Here was my step till now
sudo yum install firewalld -y
sudo systemctl start firewalld
sudo systemctl enable firewalld
sudo systemctl status firewalld

The output of the status is :
    ● firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2018-11-11 09:02:38 UTC; 6min ago
     Docs: man:firewalld(1)
 Main PID: 27702 (firewalld)
   CGroup: /system.slice/firewalld.service
           └─27702 /usr/bin/python -Es /usr/sbin/firewalld --nofork --nopid

Nov 11 09:02:37 ip-172-31-29-154.us-west-2.compute.internal systemd[1]: Start...
Nov 11 09:02:38 ip-172-31-29-154.us-west-2.compute.internal systemd[1]: Start...
Hint: Some lines were ellipsized, use -l to show in full

then I tried to open open port 8069:
sudo firewall-cmd --zone=public --add-port=8069/tcp --permanent
sudo systemctl stop firewalld

also I have added the inbound port 8069 in aws security group
Image
Here is the output of netstat -ltpn
[root@ip-172-31-29-154 ~]# netstat -ltpn
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      471/rpcbind
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1088/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      954/master
tcp6       0      0 :::111                  :::*                    LISTEN      471/rpcbind
tcp6       0      0 :::22                   :::*                    LISTEN      1088/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      954/master

And when I tried to run command in window command prompt
telnet "host public IP" 8069

then it say
Connecting To "host public IP"...Could not open connection to the host, on port 80: Connect failed

A: You have no service configured to respond on port 8069.
netstat shows only ports with services listening (waiting for requests) on these. With telnet it is the same, you can't just connect to any port and expect a response.
You have to find out how to configure the service that you are expecting to listen on that port to actually listen there.
And: If you enable a firewall you have to make absolutly sure that your SSH-Port (22) is allowed because otherwise you might shut yourself out!


text:
Q: Indirect questions - Identifying Subject / Object in indirect questions I'm struggling to identify subjects and objects in indirect questions.
Any rule of thumb to distinguish them apart?
Here is my thinking..
In the following question, which would be the subject and object?
"Could you explain what this is?

The subject of the sentence:

"you" or "this"?

Tips to help identify?
Correct me if I am wrong, please.
"this" is the Subject as the answer would start with what it is.
example:
"It" is a strange hat.
Any help would be appreciated. Thanks

A: Let us parse:
A good way to parse a question is to look at the corresponding statement. In most statements, the grammatical subject comes first:

You could explain what this is.

It is now clear that the subject is "you" the verb phrase is "could explain", and the object is a noun phrase "what this is"
That noun phrase is a clause with a subject "this" a verb "is" and complement "what" (the question word complement heads the phrase)
So both "this" and "you" are subjects.  One is the subject of the main verb "could explain" and one is the subject in the subordinate clause "what this is"


text:
Q: Raspberry PI Server/Client Socket in Python I am trying to set up a Python socket between my Raspberry Pi (running Raspbian) and my Macbook Pro (running Mavericks).
Both devices are connected to the same WiFi network in my appt.  I run the server code on my RPi and then the client code on my Macbook (I have also tried the reverse).  I think that I am missing a set up step because the code I am using I found on multiple sites, so I assume it works.  I also checked that my Macbook has firewall turned off.
Server Code:
from socket import *

host = "127.0.0.1"

print host

port = 7777

s = socket(AF_INET, SOCK_STREAM)

print "Socket Made"

s.bind((host,port))

print "Socket Bound"

s.listen(5)

print "Listening for connections..."

q,addr = s.accept()

data = raw_input("Enter data to be sent: ")

q.send(data)

Client Code:
from socket import *

host = "127.0.0.1"

print host

port=4446

s=socket(AF_INET, SOCK_STREAM)

print "socket made"

s.connect((host,port))

print "socket connected!!!"

msg=s.recv(1024)

print "Message from server : " + msg

I get the error:

Traceback (most recent call last):
  File "TCPclient.py", line 9, in <module>
    s.connect((host,port))
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/socket.py",

line 224, in meth
          return getattr(self._sock,name)(*args)
      socket.error: [Errno 61] Connection refused

My process for executing the code is:

*

*type "python TCPserver.py" into RPi terminal

*type "python TCPclient.py into Macbook terminal
Then I receive the error message on my Macbook, no error on the RPi
My questions are:

*

*Is 127.0.0.1 the proper input for "host"? (please note I also tried "localhost")

*Does the input for host have to be the same for the client and server code?

*Should the RPi and Macbook both be connected to the same WiFi network?

*Is there any set up that needs to be done on either the RPi or my Macbook in order for this to work (Please note my RPi is Model B, new, and I did not set up anything else on it before this)

*Do you know why I am receiving this error and how to fix it?

Your help is greatly appreciated!!

A: 127.0.0.1 is a special IP address for local machine.
You must set the real IP address (on your LAN) of you mac in the client code.
You should also bind on this IP on the server, or on 0.0.0.0 to bind on all available IP addresses.
You must also use the same port number on both client and server.

And to reply to your questions:

Is 127.0.0.1 the proper input for "host"? (please note I also tried "localhost")
127.0.0.1 is the same than localhost, it means the local machine. This will work if you run the client and the server on the same machine, else you need the real IP address of your mac. Try ifconfig in a console.

Does the input for host have to be the same for the client and server code?
Yes and no. On the server you bind to a port and an address, so you'll wait for connections on this port and address. You can use the IP address, or 0.0.0.0.

Should the RPi and Macbook both be connected to the same WiFi network?
Yes and no. It will work with the same WiFi network, but it will also work with two different WiFi networks if they are connected together directly or with a IP router. Most of the time though they are connected to the internet through a NAT (network address translator), and then it will not work.

Is there any set up that needs to be done on either the RPi or my Macbook in order for this to work (Please note my RPi is Model B, new, and I did not set up anything else on it before this)
I don't know much about the RPi but it looks like standard TCP sockets, that should work out of the box.

Do you know why I am receiving this error and how to fix it?
As I stated at the beginning: You try to connect to the RPi (127.0.0.1) on the wrong port.

A: You have created a listener on port 7777, then you connected on 4446 !!!!!
just connect on the same port you are listening to =)