text:
Q: mutiple variable outliers with different condition With regards hope you all are doing well.
I have a data frame as below I want to flag different variables as an outlier with different conditions.
Basically, I want to check some columns that have values more than threshold as I mention them in the bottom  I will group_by id and flag those outlies and select id,question_name, outlier value as text_answer and count number of occurrences of particular value entered by a particular id. The problem is I can get only the required output for a single variable with my code but I want to have all of them at one go.
raw_data <- data.frame(
id=c(1,2,1,2,3,4,4,3),
shelter_number=c(3,2,3,2,11,15,15,11),
question_name=c("A","B","C","A"),
size=c(12,11,12,10,9,15,18,14),
shelter_age=c(20,35,50,55,62,44,70,65)
)

What  I am trying is
raw_data <- raw_data %>% filter(shelter_number>=10 )

outliers <- raw_data %>% select(id,shelter_number) %>%
  pivot_longer(cols = -id,
               names_to = "Question_name", values_to= "Value",
               values_drop_na = TRUE) %>%
  count(id, Question_name, Value) %>% rename(text_answer=Value,count=n)

What I want is as below
expected_output <- data.frame(
  id=c(3,4,1,2,2,3,4,4,1,2,3,3,4),
  question_name=c("shelter","shelter","size","size","size","size","size","size","shelter_age","shelter_age","shelter_age","shelter_age","shelter_age"),
  text_answer=c(11,15,12,10,11,14,15,18,50,55,62,65,70),
  count=c(2,2,2,1,1,1,1,1,1,1,1,1,1)
)

Thresholds are as  below
shelter_age >50
shelter_number>10
size>10

Thanks in advance

A: Is this what you want?
raw_data %>%
  select(-question_name) %>%
  pivot_longer(-id, names_to = "question_name", values_to = "text_answer") %>%
  filter(
    question_name == "shelter_number" & text_answer > 10 |
      question_name == "shelter_age" & text_answer > 50 |
      question_name == "size" & text_answer > 10
  ) %>%
  count(id, question_name, text_answer, name = "count")


text:
Q: How to change text color & font of QComboBox I'm trying to change text color of QComboBox.
I've been used stylesheet or palette.
But, they changed the color of all text item in dropbox.
I want to change the color and font of only currently selected text of combobox, not dropbox.
Please help me how to change them and show me some example code.
Thank you.
// It is my code:
QStringList itemList;
itemList << "item1" << "item2" << "item3" << "item4" << "item5";

ui->comboBox->addItems(itemList);
ui->comboBox->setCurrentIndex(2);
ui->comboBox->setItemData(2, QColor(Qt::red), Qt::TextColorRole);

// this is the ways to use stylesheet
// ui->comboBox->setStyleSheet("QComboBox { color: blue; font-weight: bold; }");

// this is the ways to use QPalette
QPalette pal = ui->comboBox->palette();
pal.setColor(QPalette::Text, Qt::blue);
ui->comboBox->setPalette(pal);

redpajama_set_name: RedPajamaStackExchange


text:
Q: put each chunk of smaller array inside each row I have a large array which I converted into multidimensional array of 7 smaller chunks/groups. now I want each off these group to show in each row of table, having number of td's equal to number of items in each chunk. for example my array is:
var arr = ["OH","2090923","14 Dec 2017","01 Jan 2018","01 Jan 2018","1.0","Approval","CL","105452","31 Jan 2018","07 Feb 2018","07 Feb 2018","0.5","Approval","CL","2100909","06 Feb 2018","06 Feb 2018","06 Feb 2018","0.5","Approval","CL","105452","06 Feb 2018","16 Mar 2018","16 Mar 2018","1.0","Approval","ML","2100909","09 Feb 2018","09 Feb 2018","09 Jul 2018","151.0","Approval","PL","2130989","09 Feb 2018","12 Feb 2018","16 Feb 2018","5.0","Approval"]

Now I divided it into chunks of 7 each, but want to display in table as:

        OH
        2090923
        14 Dec 2017
        01 Jan 2018
        01 Jan 2018
        1.0
        Approval

        CL
        105452
        31 Jan 2018
        07 Feb 2018
        07 Feb 2018
        0.5
        Approval

but my code is displaying as:

        OH,2090923,14 Dec 2017,01 Jan 2018,01 Jan 2018,1.0,Approval

        CL,105452,31 Jan 2018,07 Feb 2018,07 Feb 2018,0.5,Approval

        CL,2100909,06 Feb 2018,06 Feb 2018,06 Feb 2018,0.5,Approval

        CL,105452,06 Feb 2018,16 Mar 2018,16 Mar 2018,1.0,Approval

        ML,2100909,09 Feb 2018,09 Feb 2018,09 Jul 2018,151.0,Approval

        PL,2130989,09 Feb 2018,12 Feb 2018,16 Feb 2018,5.0,Approval

each chuck is coming inside a full  , please help.
fsfiddle:https://jsfiddle.net/23ojbmkp/3/

A:

 var createGroupedArray = function(arr, chunkSize) {
        var groups = [], i;

        for (i = 0; i < arr.length; i += chunkSize) {
            groups.push(arr.slice(i, i + chunkSize));
        }
        return groups;
    }
    var arr = ["OH","2090923","14 Dec 2017","01 Jan 2018","01 Jan 2018","1.0","Approval","CL","105452","31 Jan 2018","07 Feb 2018","07 Feb 2018","0.5","Approval","CL","2100909","06 Feb 2018","06 Feb 2018","06 Feb 2018","0.5","Approval","CL","105452","06 Feb 2018","16 Mar 2018","16 Mar 2018","1.0","Approval","ML","2100909","09 Feb 2018","09 Feb 2018","09 Jul 2018","151.0","Approval","PL","2130989","09 Feb 2018","12 Feb 2018","16 Feb 2018","5.0","Approval"]

    var groupedArr = createGroupedArray(arr, 7);

    for(i=0;i < groupedArr.length;i++){

      var temp = '';
      for(var j = 0; j < groupedArr[i].length; j++)
        temp += '' + groupedArr[i][j] + '	';
      $(".tbl").append('
' + temp + '
');
}

*

*You don't need var result = JSON.stringify(groupedArr); and var res=JSON.parse(result);.

*i<=res.length should be i < res.length.

*Use nested for loops.

*Can be done in one for loop if you refactor the createGroupedArray function.

A: You need to loop over the elements in the nested array, and append them each as a  to the current
.

var createGroupedArray = function(arr, chunkSize) {
  var groups = [],
    i;
  for (i = 0; i < arr.length; i += chunkSize) {
    groups.push(arr.slice(i, i + chunkSize));
  }
  return groups;
}
var arr = ["OH", "2090923", "14 Dec 2017", "01 Jan 2018", "01 Jan 2018", "1.0", "Approval", "CL", "105452", "31 Jan 2018", "07 Feb 2018", "07 Feb 2018", "0.5", "Approval", "CL", "2100909", "06 Feb 2018", "06 Feb 2018", "06 Feb 2018", "0.5", "Approval", "CL", "105452", "06 Feb 2018", "16 Mar 2018", "16 Mar 2018", "1.0", "Approval", "ML", "2100909", "09 Feb 2018", "09 Feb 2018", "09 Jul 2018", "151.0", "Approval", "PL", "2130989", "09 Feb 2018", "12 Feb 2018", "16 Feb 2018", "5.0", "Approval"]
var groupedArr = createGroupedArray(arr, 7);
var table = $(".tbl");
$.each(groupedArr, function() {
  var row = $("
");
  $.each(this, function() {
    row.append($("", {
      text: this
    }));
  });
  table.append(row);
});


text:
Q: Plot a function including an integral I would like to curve a function v defined as follows:
u<-function(x){log(x^2+1)}

v<-function(x){integrate(v,0,x)}

When I use the command curve(v,1,2,10), the result is
Error in curve(v, 1, 2, 10) :
  'expr' did not evaluate to an object of length 'n'

Please help me to plot the curve of the function v.

A: You have a typo, it should be integrate(u, ...), not v.
And you must have function v return a vector. Like this:
u <- function(x){log(x^2+1)}

v <- function(x){
    sapply(x, function(.x) integrate(u, 0, .x)$value)
}

curve(v, from = 1, to = 2, n = 10)


text:
Q: What is meant by symptom based monitoring and cause based monitoring? In SRE context, what is meant by symptom and cause-based monitoring? why it is so important? And which tools are used for these kinds of monitoring?

A:
Symptoms Versus Causes

Your monitoring system should address two questions: what's broken,
and why?
The "what's broken" indicates the symptom; the "why" indicates a
(possibly intermediate) cause. Table below lists some hypothetical
symptoms and corresponding causes.
"What" versus "why" is one of the most important distinctions in
writing good monitoring with maximum signal and minimum noise.

Example
+--------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------+
|                        Symptom                         |                                                      Cause                                                      |
+--------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------+
| I'm serving HTTP 500s or 404s                          | Database servers are refusing connections                                                                       |
|--------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| My responses are slow                                  | CPUs are overloaded by a bogosort, or an Ethernet cable is crimped under a rack, visible as partial packet loss |
|--------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| Users in Antarctica aren't receiving animated cat GIFs | Your Content Distribution Network hates scientists and felines, and thus blacklisted some client IPs            |
|--------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------|
| Private content is world-readable                      | A new software push caused ACLs to be forgotten and allowed all requests                                        |
+--------------------------------------------------------+-----------------------------------------------------------------------------------------------------------------+

Source
Tools used for monitoring depends on your platform, what and how you want to monitor. For example, Azure Monitor is for the applications and infrastructure hosted in Azure, Amazon CloudWatch for those in AWS, and so the list goes on.


text:
Q: Starting a new room planner web application So I'm learning Python and beginning to grasp the fundamentals. I want to start a project that seems slightly over ambitious for my current knowledge level but I think I can do it bit by bit and it will look good in my portfolio.
Basically, I'd like to create a web application that generates a grid and allows the user to create rooms to scale. Dragging and dropping pieces of furniture to visualise how much space they will have between various pieces of furniture and checks if pieces will fit. Also I'd like the user to be able to save real furniture for example, using the Ikea website that will, when they're finished, generate a basket containing links and pictures to the items they have chosen and give them an idea of total cost.
It feels daunting starting out, what modules/libraries would I use to get this going? I'd like it to be a web app that is mobile friendly ideally?
Thanks in advance.

A: Making interactive web apps like that are not really within Python's capability.
On the web, Python (via Django) is good for back-end things and making websites, but for client-side interactivity like you are suggesting, you need to use Javascript.
There is a tool called Brython that lets you write client-side Python and then it will convert it into Javascript for you, but it is quite complicated.
I would suggest picking another project for Python (here is a great list), or if you want to continue with that furniture idea, then picking up some JS, React, and using a library like react-dnd would be a good starting point.


text:
Q: ASP.NET User-based Templates Is there anyway to let users write their own aspx templates with my defined dynamic variables?   Note that I don't want to use Web Forms (so there are no tags like <asp:button> etc).
In addition, I'd need a security solution so users can't change the system or do dangerous things like this.
Thanks.

A: Personally I would avoid using the ASPX engine for this.  I would probably use either a really simple custom formatting solution (such as just a text file with %%VAR_NAME%% allowed for dynamic values), or I would look at a templating language such as Markdown (used by StackOverflow and others).  BBCode is another option in a similar vein.
Allowing people to create ASPX templated pages on the fly seems like to much of a security issue to me.  It would be hard to make sure you have closed all the possible attack vectors once they have direct access to the ASP.NET engine.
Since you didn't specify, I'm just guessing at your needs, so depending on the exact problem this may or may not be your best bet.  If you include more details about the problem you are solving it would be easier to make suggestions.


text:
Q: can not convert implicitly from string to int In C#, I have used Enum to get the drop down values:
class Enum
{
    public enum Fields
    {
        AssignedTo = "Assigned To",
        CloseReason = "Close Reason",
        CustomerId = "Customer ID",
        CustomerName = "Customer Name",
        CompanyID = "Company ID",
        CompanyName = "Company Name",
    }
}

When I build the solution. I am getting the error: cannot implicitly convert type 'string' to 'int'.
I have removed the double quotes but still it shows the same error. What do I do wrong?

A: In C# string are not allowed types for enums.
Quote from MSDN https://msdn.microsoft.com/en-us/library/sbbt4032.aspx

The approved types for an enum are byte, sbyte, short, ushort, int,
  uint, long, or ulong

If will have to do some kind of conversion (i.e. using [DisplayName] attribute) to use enum in dropdown.

A: this is syntactically invalid in c#
https://msdn.microsoft.com/en-us/library/sbbt4032.aspx
you will need a workaround to create string enum in c#
https://www.google.com/?gfe_rd=cr&ei=sBwXV_XZDKO_wQOjmaqABw&gws_rd=ssl#q=string+enum+in+c%23

A: It is giving this error because by default the enum expects you to assign an integer value to the fields inside an enum.
public enum Fields
{
    AssignedTo = 1,
    CloseReason = 2,
    CustomerId = 3,
    CustomerName = 4,
    CompanyID = 5,
    CompanyName = 6
}

If you skip the assigning part , it will by default start assign the fields starting from integer 0.

A: i am not sure if it is because you are trying to display string to the enum  then is because enum only use int 16 and 32 so we have to create an extension to make it show strings and then use the int value to call it
using System.Reflection;

  public static class EnumExtensions
{

    public static string DisplayName(this Enum value)
    {
        FieldInfo field = value.GetType().GetField(value.ToString());

        EnumDisplayNameAttribute attribute
                = Attribute.GetCustomAttribute(field, typeof(EnumDisplayNameAttribute))
                    as EnumDisplayNameAttribute;

        return attribute == null ? value.ToString() : attribute.DisplayName;
    }
}

public class EnumDisplayNameAttribute : Attribute
{
    private string _displayName;
    public string DisplayName
    {
        get { return _displayName; }
        set { _displayName = value; }
    }
}
class Enum
  {
         public enum Fields
{
    [EnumDisplayName(DisplayName = "Assigned To"
    AssignedTo,
    [EnumDisplayName(DisplayName = "Close Reason"
    CloseReason,
    [EnumDisplayName(DisplayName = "Customer ID"
    CustomerId,
    [EnumDisplayName(DisplayName = "Customer Name"
    CustomerName,
    [EnumDisplayName(DisplayName = "Company ID"
    CompanyID,
    [EnumDisplayName(DisplayName = "Company Name"
    CompanyName ,
}
}

just like i did for my group description for listview

A: I do not think you want to be using enum for a drop down. Try looking into Dictionary or DataTable or some other structures. Maybe we could help if you give us more detail about what exactly are you trying to do.
EDIT: Here is a simple example of using List<string> as data source for ComboBox
List<string> dsList = new List<string>();
dsList.Add("Assigned To");
dsList.Add("Close Reason");
dsList.Add("Customer ID");
dsList.Add("Customer Name");
dsList.Add("Company ID");
dsList.Add("Company Name");

comboBox1.DataSource = dsList;

Also, you can dynamicaly change the List based on what options you want to display to the user


text:
Q: Do status effect particles still show while the player is invisible? Will other players still see the particles from a player that drank a Potion of Invisibility?

A: Yes it's easily detectable and also you will be outlined when hit by certain arrows.

A: The particles are visible unless the server has a plugin for it. You could also hope that the other players have gone into settings, and turned particles to none, which should disable them for their screen.


text:
Q: Simple Consequence of Sylow Theorem I am having a hard time understanding what should be a simple consequence of the Sylow theorems. If $P$ is the unique Sylow p-subgroup of a group $G$ then $P$ is normal in $G$. The argument goes that since $P$ is the only Sylow p-subgroup of $G$ then  for all $g$ in $G$, $gPg^{-1} = P$. However, if I recall the theorem goes that all Sylow p-subgroups conjugate in G. So I thought that this would imply that there exists at least one g in G such that $gPg^{-1} = P$, but does not necessarily imply that all $g$ in $G$ achieve this task. Otherwise this would imply that we can find all Sylow p-subgroups by picking one and conjugating it with all the elements of g, each time getting another Sylow p-subgroup, which I know is correct. I just dont understand how the theorem says that. Thanks.

A: Show that for any $g\in G$,$|gPg^{-1}|=|P|$ and $gPg^{-1}$ is a subgroup of $P$. Hence $gPg^{-1}$ is a Sylow $p$-subgroup of $G$. Then use the hypothesis of your question.

A: The theorem says that if $P$ and $Q$ are both Sylow $p$-subgroups of a group $G$, you can find a $g \in G$ with $P^g=Q$. In other words, $G$ works transitively on the set of all Sylow $p$-subgroups by conjugation. Hence, if there is only one Sylow $p$-subgroup $P$, any conjugate of $P$  is this subgroup $P$ itself, whence the normality.

A: Re: "So I thought that this would imply that there exists at least one $g$ in $G$ such that g$Pg^{-1} = P$, but does not necessarily imply that all $g$ in $G$ achieve this task. "
It actually does imply that all $g$ achieve that.
Note that for any $g\in G$, $|gPg^{-1}|=|P|$, i.e. $gPg{-1}$ is a Sylow $p$-subgroup.
Since there is only one Sylow $p$-subgroup, $gPg^{-1}=P$, that is, $P$ is a normal subgroup.


text:
Q: AngularJS Filter performs search by value attribute only and not text of html elements? I am trying to understand the angularJS filter mechanics to try and extend its initial functionality. Currently from what I can tell, when you perform the filter, it will search the value attribute on each html element for a match. This works all great in most cases. Where this falls apart is dropdown lists. If you set the text of an option to Hello world and the value = 1, the search is looking at the value attribute of the <option> instead of the text. This breaks the expected results thus why I need to find a way to make the filter include the Text properties of dropdown lists. Looking for advice on how to handle this or just further details of the filter function underneath. Below is the code i am trying to apply this too.

Search:<input id="txtSearch" ng-model="search" type="text" placeholder="Search" />

@using (Html.BeginForm("CategoryFieldApprovers", "Maintenance", FormMethod.Post))
{

                    Category Field
                    Approver

                        <input type="hidden" name="CategoryFieldApprovers[{{$index}}].CategoryFieldApproverID" ng-model="categoryFieldApprover.CategoryFieldApproverID" value="{{categoryFieldApprover.CategoryFieldApproverID}}" />
                        <input type="hidden" id="hdnIsDirty" name="CategoryFieldApprovers[{{$index}}].IsDirty" value="{{categoryFieldApprover.IsDirty}}" />

                        <input class="hdnCategoryFieldID" type="hidden" name="CategoryFieldApprovers[{{$index}}].CategoryFieldID" value="{{categoryFieldApprover.CategoryFieldID}}" />
                        <select ng-model="categoryFieldApprover.CategoryFieldID" ng-options="categoryField.CategoryFieldID as categoryField.Name for categoryField in categoryFields | filter:{Name :search}"></select>

                        <input class="hdnApproverOneUserID" type="hidden" name="CategoryFieldApprovers[{{$index}}].ApproverOneUserID" value="{{categoryFieldApprover.ApproverOneUserID}}" />
                        <select ng-model="categoryFieldApprover.ApproverOneUserID" ng-options="user.UserID as user.DisplayName for user in users | filter:{DisplayName :search}"></select>

                        <input type="button" ng-click="remove($index)" ng-show="categoryFieldApprover.ShowRemove" value="Remove" />

        <dir-pagination-controls max-size="5"
                                 direction-links="true"
                                 boundary-links="true">
        </dir-pagination-controls>

        Add Field Approver
        <input class="btn-primary btn-sm" ng-click="save()" type="button" value="Save" />

}

UPDATES: Removed the |filter:search from the tr element. Then added the filter:{Name: search} for each dropdown. It will now correctly filter and show/hide rows for those that pass the check. The only remaining problem now is that when the filter function executes, if the dropdowns selected item fails the test, it sets the selected index to 0 which is the blank item. How can I prevent it from changing the selection just because it failed to be included from the filter?

A: Please see this small demo here. If you are looking for same functionality then you just need to specify property inside filter which you want to search.

filter:{Name :search}

e.g.
<select ng-model="categoryFieldApprover.CategoryFieldID" ng-options="categoryField.CategoryFieldID as categoryField.Name for categoryField in categoryFields | filter:{Name :search}"></select>


text:
Q: Retrieve Data From Database : Spring Boot I understand that there are so many ways we can get data from the Db, one is using JPA or Typed/Named Query.
Wish to know on an Enterprise level do we use JpaRepository or custom repository and if custom what exactly do we use to fetch data is it Stream API or Criteria API or something else .
I have tried to use JpaRepository, getById() and also Stream API filter

A: I have been doing enterprise programming for a long time and the best choice for me was JPA because JPA allows you to avoid writing DML in the database specific dialect of SQL. JPA allows you to load and save Java objects  without any DML language at all. When you do need to perform queries JPQL allows you to express the queries in terms of the Java entities rather than the (native) SQL tables and columns.
Also many helpful annotations like @DynamicUpdate and @DynamicInsert help ORM to create more efficient queries.


text:
Q: Select Random Products magento 2.3 I want to display random products on my homepage.
I have been using this $collection->clear()->getSelect()->order('rand()');.
My aim is the products should be displayed randomly on every page refresh.
But here, this happens only after i clear cache and then refresh my page.
Without cache flush, it displays same products

A: Add This Block In Home Page And Check :-
{{block class="Magento\Catalog\Block\Product\ProductList\Random" template="product/list.phtml" num_products="12"}}

A: Add this line in your collection
$collection->getSelect()->orderRand();

If you are facing the cache issue, you can use in your layout file

cacheable="false";

Blocks can be set as non-cacheable by setting the cacheable attribute false in layout XML files. For example
<block class="Block\Class" name="blockname" cacheable="false" />

A: $productsCol = $this
        ->getCategory($id)
        ->getProductCollection()
        ->addAttributeToSelect('*')
        ->setPageSize(3);

$productsCol->getSelect()->orderRand();

$products = $productsCol->getItems();

Please check with this whole code.
I hope it will help you.

A: The best idea to Ajax, On the load of this page, call a page with a POST request and return Magento\Catalog\Block\Product\ProductList\Random  block content.
As Magento does calculate post request as cacheable request, So don't get any issue with the cache.
Controller Class RandomList.php
<?php

namespace StackExchange\Magento\Controller\Example;

use Magento\Framework\App\ResponseInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\View\Result\Layout;
use Magento\Framework\Controller\ResultFactory;

class RandomList  extends \Magento\Framework\App\Action\Action
{

    public function execute()
    {
        $this->resultFactory->create(ResultFactory::TYPE_LAYOUT);
    }

}

layout files {routeID}_example_randomList.xml and code is
And code:
<?xml version="1.0"?>

<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/layout_generic.xsd">
    <container name="root">
        <block class="MStackExchange\Magento\Block\Product\ProductList\Random" name="product.info.random.prp" as="products_random" template="Magento_Catalog::product/list/items.phtml" />
          <arguments>
                    <argument name="type" xsi:type="string">new</argument>
                </arguments>
    </container>
</layout>

Block Class
<?php
namespace StackExchange\Magento\Block\Product\ProductList;

use Magento\Catalog\Api\CategoryRepositoryInterface;

/**
 * Catalog product random items block
 *
 * @SuppressWarnings(PHPMD.LongVariable)
 */
class Random extends \Magento\Catalog\Block\Product\AbstractProduct implements
    \Magento\Framework\DataObject\IdentityInterface
{

    /**
     * @var \Magento\Catalog\Model\Product\Visibility
     */
    private $catalogProductVisibility;

    /**
     * Product collection factory
     *
     * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
     */
    protected $_productCollectionFactory;

    /**
     * @var CategoryRepositoryInterface
     */
    protected $categoryRepository;

    /**
     * @param \Magento\Catalog\Block\Product\Context $context
     * @param \Magento\Framework\Data\Helper\PostHelper $postDataHelper
     * @param CategoryRepositoryInterface $categoryRepository
     * @param \Magento\Framework\Url\Helper\Data $urlHelper
     * @param \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory
     * @param array $data
     */
    public function __hconstruct(
        \Magento\Catalog\Block\Product\Context $context,
        \Magento\Framework\Data\Helper\PostHelper $postDataHelper,
        CategoryRepositoryInterface $categoryRepository,
        \Magento\Framework\Url\Helper\Data $urlHelper,
        \Magento\Catalog\Model\Product\Visibility $catalogProductVisibility,
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,
        array $data = []
    ) {
        $this->_productCollectionFactory = $productCollectionFactory;
        parent::__construct($context, $data);
        $this->catalogProductVisibility = $catalogProductVisibility;
    }

    /**
     * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
     */
    protected function _getProductCollection()
    {
        if ($this->_productCollection === null) {
            /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
            $collection = $this->_productCollectionFactory->create();
            $collection->setVisibility($this->_catalogProductVisibility->getVisibleInCatalogIds());
             $collection = $this->_addProductAttributesAndPrices(
            $collection
             );
            $collection->getSelect()->order('rand()');
            $collection->addStoreFilter();

            $collection->setPage(1, 10);

            $this->_productCollection = $collection;
        }
        return $this->_productCollection;
    }

    /**
     * Return identifiers for produced content
     *
     * @return array
     */
    public function getIdentities()
    {
        return ['ran_products'];
    }
    /**
     * Prepare collection with new products
     *
     * @return \Magento\Framework\View\Element\AbstractBlock
     */
    protected function _beforeToHtml()
    {
        $this->setProductCollection($this->_getProductCollection());
        return parent::_beforeToHtml();
    }
}


text:
Q: When using VS2022 (v17.0.1.0), the complier can not recognize "string", and sends me an error. When I replace the string by const char*, it works I have tried searching on Google, only to find nothing.
And it seems the manual also doesn't work.
Here is my code:
account.h
#include <string>
#include "Date.h"

class SavingsAccount
{
public:
    void show();
    void deposit(Date now_date, double money, string ways);
    void withdraw(Date now_date, double money, const char* ways);
    void settle(Date new_date);
    SavingsAccount(Date date_new, const char* id_new, double rate_new);
    void accountshow();
    static double getTotal();
    static SavingsAccount* point;
    static int sum_account;
    static double sum_money;
private:
    const char* id;
    double balance = 0;
    double rate = 0;
    int lastDate = 0;
    Date date;
    double interest = 0;
};

account.cpp
#include <iostream>
#include <string>
#include "account.h"
#include "Date.h"
using namespace std;

double SavingsAccount::sum_money = 0;

void SavingsAccount::deposit(Date now_date, double money, string ways)   //<--- here is the problem
{
    interest += balance * (now_date - date) * rate / 366;
    date = now_date;
    date.show();
    cout << "\t#" << id << "\t" << money << "\t" << money + balance << "\t"<<ways << endl;
    balance += money;
    sum_money += money;
}

void SavingsAccount::withdraw(Date now_date, double money, const char* ways)   //取款
{
    interest += balance * (now_date - date) * rate / 366;
    date = now_date;
    date.show();
    cout << "\t#" << id << "\t-" << money << "\t" << balance - money << "\t" << ways << endl;
    balance -= money;
    sum_money -= money;
}

void SavingsAccount::settle(Date new_date)     //结算利息
{
    interest += balance * (new_date - date) * rate / 366;
    interest = (int(interest * 100 + 0.5)) / 100.0;
    sum_money += interest;
    date = new_date;
    date.show();
    cout << "\t#" << id << "\t" << interest << "\t" << interest + balance << " interest"<<endl;
    balance += interest;
    interest = 0;
}

void SavingsAccount::accountshow()
{
    this->date.show();
    cout << "\t" << "#" << id << " created" << endl;
}

void SavingsAccount::show()
{
    cout << id << "\tBalance: " << balance;
}

SavingsAccount::SavingsAccount(Date date_new, const char* id_new, double rate_new) : id(id_new)
{
    date = date_new;
    rate = rate_new;
    //sum_account++;
    balance = 0;
    interest = 0;
    accountshow();
}

double SavingsAccount::getTotal()
{
    return sum_money;
}

bank.cpp:
#include "account.h"
#include <iostream>
using namespace std;

int main()
{
    Date date(2008, 11, 1);
    SavingsAccount accounts[] = {
        SavingsAccount(date, "S3755217", 0.015),
        SavingsAccount(date, "02342342", 0.015)
    };

    const int n = sizeof(accounts) / sizeof(SavingsAccount);
    string works = "salary";
    accounts[0].deposit(Date(2008, 11, 5), 5000, works);
    accounts[1].deposit(Date(2008, 11, 25), 10000, "sell stock 0323");
    accounts[0].deposit(Date(2008, 12, 5), 5500, "salary");
    accounts[1].withdraw(Date(2008, 12, 20), 4000, "buy a laptop");
    cout << endl;
    for (int i = 0; i < n; i++) {
        accounts[i].settle(Date(2009, 1, 1));
        accounts[i].show();
        cout << endl;
    }
    cout << "Total: " << SavingsAccount::getTotal() << endl;
    return 0;
}

Because of the limited length for this, I did not show the Date.h and Date.cpp, and there is nothing wrong with it. But I will show it to you if you need.
Here is the problem, and I translate the error the VS tells me into English:

VS also says:

'void SavingsAccount::deposit(Date,double,std::string)' there is no overloading member function declared in SavingsAccount

But when I replace the string by const char*, just like what I write in the withdraw() function, it works without any problem.

So, could you please tell me how can I use string to finish this problem? Because const char* is so uncomfortable to be used.

A: In account.h, you have #include <string>, but you do not have using namespace std; (and rightly so), so the compiler doesn't know what string is.  You have to use std::string instead, eg:
void deposit(Date now_date, double money, std::string ways);

Or, use using std::string, at least (not recommended in a header, though):
using std::string;
...
void deposit(Date now_date, double money, string ways);

In account.cpp and bank.cpp, you have using namespace std; after #include <string>, so the compiler can work out what string is without needing you to  qualify it with std::.


text:
Q: Using concat or append to add an column in Python Here is what I have pulled in thus far and it ends with not appending correctly
I want to add my count column to
Here's the objective: What are the countries that have more than 4 cities listed in the cities table, and what is the minimum, average, and maximum populations of those countries, as well as the number of cities in each country? Order the result from the country with the most cities to the one with the fewest cities.
import psycopg2
import sqlalchemy
import pandas as pd

engine = sqlalchemy.create_engine('postgresql://dsa_ro_user:readonly@pgsql/dsa_ro')

connection = engine.connect()

df = pd.read_sql_query("SELECT * FROM cities", connection)

connection.close()

df.head()
import numpy as np
new_frame=df.groupby("country")
new_frame=new_frame["population"].agg([np.sum,np.mean,np.std])
new_frame.reset_index(inplace=True)

 new_df=df.groupby(["country"]).count()
new_df.columns.values[0]= "count"
new_df
new_df.reset_index(inplace=True)
new_frame2=new_df.groupby(["count"]).count()
new_frame2
new_frame2.reset_index(inplace=True)
new_frame2=new_frame2[new_frame2["count"]>4]
new_frame2
del new_frame2["population"]
new_frame2
##new_frame2.reset_index(inplace=True)
del new_frame2['country']
new_frame2

new_frame=new_frame.append(new_frame2, ignore_index=True ,sort=True)
new_frame
new_frame=new_frame.sort_values(by="count", ascending=False)
new_frame

A: Since I couldn't access your data I have used data from https://simplemaps.com/data/world-cities, but based on your code your data should look the same (country, city and population columns):
df = pd.read_csv('worldcities.csv')
df = df[["city_ascii", "population", "country"]].rename(columns = {'city_ascii':'city'})

Your new_frame and new_df data frames are good, you have the summary stats in new_frame and the city counts per country in new_df.
The next step is to filter for countries with more than 4 cities and put that into a new data frame:
#create a df of countries with more than 4 cities and remove population column
cities_gt_4=new_df[new_df['count'] > 4].drop(columns=["population"])

Now we want to join this data frame with our summary stats new_frame, based on country names. We can use pandas' merge function to join the two data frames together, based on the values of the country column in each data frame (we define based on which columns we want to join using the left_on and right_on arguments). We are using a left join (how = "left"), which means we will only keep rows for country values that exist in the left data frame (cities_gt_4). This means all country rows with <= 4 cities will be dropped, producing the desired final data frame. Then we sort using sort_values().
merged_df=pd.merge(left = cities_gt_4, right = new_frame, how = "left", left_on = "country", right_on = "country")

merged_df=merged_df.sort_values('count', ascending=False)


text:
Q: Install Kivy Garden Flowers in Pycharm How does one install flowers from the kivy garden within PyCharm (2019.1) such as Graph and matplotlib flowers? I already installed the kivy.garden package.

A: On kivy website specifies the new format to install garden flowers. It changed since version 1.11.0
Garden flowers can now be installed with the pip tool like a normal python package. Given a flower that you want to install, lets use graph as an example. You can install master directly from github with:
python -m pip install https://github.com/kivy-garden/graph/archive/master.zip
Full instructions on kivy website:
https://kivy.org/doc/stable/api-kivy.garden.html?highlight=install%20garden
Hope this helps


text:
Q: Does Software Updater update apps installed by Software Center I just want to know if I could install a bunch of apps through the Software Center and not have to add individual repositories to update every single app.

A: *

*If the application was installed originally from Software Center, then yes you have it in repositories already (although some apps might have other updated version outside ubuntu official repositories).

*If an application was installed by a method other than Software Center, then maybe or maybe not you have its repository automatically added during installation (you need to check software sources or sources.list file for that).

*Other application - MySQL workbench for example, have an in app tool to check for an update, and might direct you directly to update process.

A: If the repositories contains the update for a particular package then software updater updates that package.
Installing package via software-center does the same function as installing package via apt-get.
Yes, software updater updates packages installed via software-center only if the corresponding package had an update in enabled repositories.


text:
Q: How to install Android Studio from cli I am curling the latest Android Studio dmg file, mounting the image and copying the .app directory into the Applications directory. When I attempt to open the directory I receive this warning, and when I query the application state, I also receive the code below. Any idea how I can generically install Android Studio from the cli?
Warning:
"Android Studio" is damaged and can't be opened. You should move it to the Trash. Google Chrome.app downloaded this file on
...
| => spctl -a /Applications/Android\ Studio.app/
/Applications/Android Studio.app/: a sealed resource is missing or invalid

...
| => codesign --display --verbose=4 /Applications/Android\ Studio.app/
Executable=/Applications/Android Studio.app/Contents/MacOS/studio
Identifier=com.google.android.studio
Format=app bundle with Mach-O universal (i386 x86_64)
CodeDirectory v=20200 size=537 flags=0x0(none) hashes=11+3 location=embedded
OSPlatform=36
OSSDKVersion=657664
OSVersionMin=657408
Hash type=sha256 size=32
CandidateCDHash sha1=4456b3e77035b4318af16276667c88f7b7d4f9ac
CandidateCDHash sha256=6d95335c6815111d93abd1e87b9fd4648d991bdd
Hash choices=sha1,sha256
Page size=4096
CDHash=6d95335c6815111d93abd1e87b9fd4648d991bdd
Signature size=8948
Authority=Developer ID Application: Google, Inc. (EQHXZ8M8AV)
Authority=Developer ID Certification Authority
Authority=Apple Root CA
Timestamp=Dec 1, 2016, 4:57:25 PM
Info.plist entries=22
TeamIdentifier=EQHXZ8M8AV
Sealed Resources version=2 rules=12 files=11250
Internal requirements count=1 size=188

Android Install Script
#!/usr/bin/env bash

echo "Installing Android Studio"

ANDROID_STUDIO_DMG=$(curl -0 https://developer.android.com/studio/index.html | grep -o --regexp='https://dl.google.com/dl/android/studio/install/[a-zA-Z0-9./?=_-]*/android-studio-ide-[a-zA-Z0-9./?=_-]*-mac.dmg')

./dmginstall.sh $ANDROID_STUDIO_DMG

DMG Install Script - (Modified:https://gist.github.com/rahulgautam/6695872)
#!/usr/bin/env bash

# Downloads and install a .dmg from a URL
#
# Usage
# $ dmginstall [url]
#
# For example, for installing android-studio-ide
# $ dmginstall https://dl.google.com/dl/android/studio/install/2.2.3.0/android-studio-ide-145.3537739-mac.dmg
#
# TODO
# - currently only handles .dmg with .app folders, not .pkg files
# - handle .zip files as well

if [[ $# -lt 1 ]]; then
  echo "Usage: dmginstall [url]"
  exit 1
fi

url=$*

# Generate a random file name
tmp_file=/tmp/`openssl rand -base64 10 | tr -dc '[:alnum:]'`.dmg

# Download file
echo "Downloading $url..."
curl -# -L -o $tmp_file $url

echo "Please copy and paste the Volumes directory you would like to use"
echo "-----------------------------------------------------------------"
hdiutil mount $tmp_file

IFS= read -r -p "Enter volume: " volume
echo "$volume"

# Locate .app folder and move to /Applications
app=`find "$volume" -name *.app -maxdepth 1 -type d -print0`
echo "Copying `echo $app | awk -F/ '{print $NF}'` into /Applications..."
cp -rv "$app" '/Applications'

# Unmount volume, delete temporal file
echo "Cleaning up..."
hdiutil unmount "$volume"
rm "$tmp_file"

echo "Done!"


text:
Q: ObjectInputStream hanging The client-side of my "Socket to ServerSocket"-implementation looks like this, but it never gets past the ObjectInputStream-initialization. I have tried commenting out the line, and the following print-statement is then executed. The connection is (at least initially) successful, and the ServerSocket reports of a successful connection.
Client
try(
    Socket socket = new Socket("localhost", 4444);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    ObjectInputStream in = new ObjectInputStream(socket.getInputStream());
) {
    System.out.println("Connection and IO established");

} catch (IOException e) {
    e.printStackTrace();
}

Server
while (true) {
    Socket clientSocket = serverSocket.accept();
    System.out.println("Client has connected!");         // This always prints
    new Thread(new ServerThread(clientSocket)).start();
    System.out.println("ServerThread has started");      // This as well
}

A: The ObjectInputStream blocks waiting for the construction of the peer's ObjectOutputStream. Clearly the peer isn't constructing one, or possibly needs to flush it immediately after construction if you have a BufferedOutputStream in the stack.
Or possibly it is itself hung up constructing an ObjectInputStream because your client isn't constructing an ObjectOutputStream. The solution to that is to always construct and flush the ObjectOutputStream before the ObjectInputStream.


text:
Q: Link all tags within content variable I want to link all tags inside content variable, I can achieve it with foreach, but if one tag is car wash and another is car it's creating link inside link, how to avoid that ?
My code:
$tags = Tag::all();

foreach ($tags as $tag) {
    if(stripos($content, $tag->name) !== false) {
        $content = str_ireplace($tag->name, 'id, slug($tag->name)]) . '" target="_blank">' . $tag->name . '', $content);
    }
}

One of the solutions would be sorting tags by length, from small to larg, but nah, I need a better solution
EDIT: Storing already matched tags in a new array and checking with foreach and strpos if they contain substring before replacing, will be a solution for that, but another issue, strpost ans str_replace will match partial words like, if tag is car and content contains caring, there will be a partial match and it will also get replaced, how to avoid partial match ?
EDIT 2: Thanks @Kinglish for help, final code:
$tags = Tag::orderByRaw('CHAR_LENGTH(name) DESC')->get();

$linkedTags = [];
foreach ($tags as $tag) {
    foreach ($linkedTags as $linkedTag) {
        if(stripos($linkedTag, $tag->name) !== false) {
            continue 2;
        }
    }

    if(stripos($content, $tag->name) !== false) {

        $pos = stripos($content, $tag->name);
        $disallowedCharacters = [
            '-',
            '/',
            '@',
            '\\',
            '#',
            '*',
            '&'
        ];

        if ($pos != 0) {
            $charBefore = substr($content, $pos -1, 1);
            if (ctype_alpha($charBefore) || ctype_digit($charBefore) || in_array($charBefore, $disallowedCharacters)) {
                continue;
            }
        }

        $charAfter = substr($content, $pos + strlen($tag->name), 1);
        if (ctype_alpha($charAfter) || ctype_digit($charAfter) || in_array($charAfter, $disallowedCharacters)) {
            continue;
        }

        $linkedTags[] = $tag->name;
        $content = str_ireplace($tag->name, 'id, slug($tag->name)]) . '" target="_blank">' . $tag->name . '', $content);
    }
}

A: Well here's an idea that might work for you...
Store the found tags in an array and remove from content so they don't get picked up twice. Then reassemble the content at the end...
    // sort array from longest to shortest
function sort($a,$b){
    return strlen($b)-strlen($a);
}

usort($tags,'sort');

$found=array();
foreach ($tags as $tag) {
    if(stripos($content, $tag->name) !== false) {
        // test the string for partial match
        $pos = stripos($content, $tag->name);
        // test the character before
        if ($pos != 0) {
            $charBefore = substr($content, $pos -1, 1);
            if (ctype_alpha($charBefore)) {
               // its a partial, the character before the string is a letter
               continue;
            }
        }
        // test the character after
        $charAfter = substr($content, $pos + strlen($tag->name), 1);
            if (ctype_alpha($charAfter)) {
               // its a partial, the character after the string is a letter
               continue;
            }

        $storedlink = 'id, slug($tag->name)]) . '" target="_blank">' . $tag->name . '';
        $found[] = $storedlink;
        // get ref
        $ref = '[!'.count($found).'!]';
        $content = str_ireplace($tag->name, $ref, $content);
    }

    // reassemble
    $ctr=0;
    foreach ($found as $tag) {
        $content = str_replace('[!'.$ctr.'!]', $tag, $content) ;
        $ctr++;
    }
}

A: Here is my solution to make link tags, avoiding partial match:
$tags = Tag::all();
$space_order_tags = [];
foreach ($tags as $tag) {
    $space_order_tags[count(explode(' ', $tag->name))][] = $tag;
}

$replaced = [];
foreach (array_reverse($space_order_tags) as $tag_array) {
    foreach ($tag_array as $tag) {
        $replaced[$tag->name] = [$tag->id, hash('md5', $tag->name)];
        $content = preg_replace( "/\b$tag->name\b/", $replaced[$tag->name][1], $content);
    }
}

foreach (array_keys($replaced) as $tag_name) {
    $content = str_ireplace($replaced[$tag_name][1], '' . $tag_name . '', $content);
}

var_dump($content);


text:
Q: com.parse.ParseObject cannot be cast to I am developing application which having Parse Platform. To fetch data I am calling ParseCloud.callFunctionInBackground function.
I have registered the Parse and its sub class into the Application class like below :
public class App extends Application {
    @Override
    public void onCreate(){
        super.onCreate();
        Parse.setLogLevel(Parse.LOG_LEVEL_VERBOSE);
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        builder.networkInterceptors().add(httpLoggingInterceptor);
        ParseObject.registerSubclass(ParseMessage.class);
        Parse.initialize(new Parse.Configuration.Builder(this)
                        .applicationId("KEY")
                        .server("URL")
                        .build());
    }
}

I have below model class which extends ParseObject :
@ParseClassName("ParseMessage")
public class ParseMessage extends ParseObject {

    // Ensure that your subclass has a public default constructor
    public ParseMessage() {
        super();
    }

    public ParsePhoto getPhotos() {
        return (ParsePhoto) getParseObject("photos");
    }

    public void setPhotos(ParsePhoto value) {
        put("photos", value);
    }

    public String getCaption() {
        return getString("caption");
    }

    public void setCaption(String value) {
        put("caption", value);
    }

}

When I calling this below method from my Fragment :
HashMap<String, Object> params = new HashMap<String, Object>();
ParseCloud.callFunctionInBackground("MY_METHOD", params, new FunctionCallback<ArrayList<ParseMessage>>() {
            public void done(ArrayList<ParseMessage> mapObject, ParseException e) {
                if (e == null) {
                    ParseMessage object = mapObject.get(i);
                    }
                } else {
                }
    }
});

But I am getting below exception :

java.lang.ClassCastException: com.parse.ParseObject cannot be cast to
  com.example.ParseMessage

I already searched lots of thins from Google and Stackoverflow, but I did not get any solutions of it. Can anyone help me into this as I already spend a lot of time on this. Below response which I am getting from Parse :

A: The info you have provided is not very concrete, but from the debugger screen, it looks like you are trying to convert ParsePhoto into ParseMessage. ParsePhoto is subclass of ParseObject, and I believe this is causing the issue.


text:
Q: How to disable a div after click once in react in that case if you first time click show its show hello world its right but  again if you click on show its should not work. now its became a toggle but how can I do after one click its not working means after showing the hello world its should not again hide if you want to click again.
I'm also use pointer Event its also not working
import React, { useState } from "react";
export default function DropDown() {
  const [show,setShow]=useState(false)
  return (
    <>
      {show?
hello world
:null}

{setShow(!show);return false;}}>show

    </>
  )
}

A: You can simply modify your onClick with one time value set
onClick={()=>{setShow(true)}} //one time set

Full code
import React, { useState } from "react";
export default function DropDown() {
  const [show,setShow]=useState(false)
  return (
    <>
      {show?
hello world
:null}

{setShow(true)}}>show

    </>
  )
}

If you want to disable that button after show update, you can set disabled={show} to that button
import React, { useState } from "react";
export default function DropDown() {
  const [show,setShow]=useState(false)
  return (
    <>
      {show?
hello world
:null}

{setShow(true)}} disabled={show}>show

    </>
  )
}


text:
Q: Merge data based on some specific columns, pandas Assume I'm having two data frames, t1h and t2h. I want to merge that dataframe in such a way that for a specific list of columns if those rows seem to be similar, I need to perform addition operation with contents of the rest of the columns.
t1h
      timestamp           ip       domain http_status  \
0  1475740500.0  192.168.1.1  example.com         200
1  1475740500.0  192.168.1.1  example.com         200
2  1475740500.0  192.168.1.1  example.com         201
3  1475740500.0  192.168.1.1  example.com         201
4  1475740500.0  192.168.1.1  example.com         202

      test  b_count           b_sum  test_count  test_sum  data1  \
0    False       46  24742949931480          46     9.250      0
1     True       48  28151237474796          48     9.040      0
2    False       36  21702308613722          36     7.896      0
3     True       24  13112423049120          24     5.602      0
4    False       62  29948023487954          62    12.648      0

   data2
0      0
1      0
2      0
3      0
4      0

t2h
      timestamp           ip       domain http_status  \
0  1475740500.0  192.168.1.1  example.com         200
1  1475740500.0  192.168.1.1  example.com         200
2  1475740500.0  192.168.1.1  example.com         201
3  1475740500.0  192.168.1.1  example.com         201
4  1475740500.0  192.168.1.1  example.com         202

      test  b_count           b_sum  test_count  test_sum  data1  \
0    False       44  22349502626302          44     9.410      0
1     True       32  16859760597754          32     5.988      0
2    False       46  23478212117794          46     8.972      0
3     True       36  20956236750016          36     7.124      0
4    False       54  35255787384306          54     9.898      0

   data2
0      0
1      0
2      0
3      0
4      0

based on the below column list I need to get the output:
groupby_fields = ['timestamp', 'ip', 'domain', 'http_status', 'test']

pd.merge(t1h, t2h, on=groupby_fields)

      timestamp          ip        domain http_status  \
0  1475740500.0  192.168.1.1  example.com         200
1  1475740500.0  192.168.1.1  example.com         200
2  1475740500.0  192.168.1.1  example.com         201
3  1475740500.0  192.168.1.1  example.com         201
4  1475740500.0  192.168.1.1  example.com         202

      test  b_count_x         b_sum_x  test_count_x  test_sum_x  \
0    False         46  24742949931480            46       9.250
1     True         48  28151237474796            48       9.040
2    False         36  21702308613722            36       7.896
3     True         24  13112423049120            24       5.602
4    False         62  29948023487954            62      12.648

   data1_x  data2_x  b_count_y         b_sum_y  \
0        0        0         44  22349502626302
1        0        0         32  16859760597754
2        0        0         46  23478212117794
3        0        0         36  20956236750016
4        0        0         54  35255787384306

   test_count_y  test_sum_y  data1_y  data2_y
0            44       9.410        0        0
1            32       5.988        0        0
2            46       8.972        0        0
3            36       7.124        0        0
4            54       9.898        0        0

I want it in such a way that the output should look like:
Note: except the columns in groupby_fields every other column are of either type either int or float
      timestamp          ip        domain http_status  \
0  1475740500.0  192.168.1.1  example.com         200
1  1475740500.0  192.168.1.1  example.com         200
2  1475740500.0  192.168.1.1  example.com         201
3  1475740500.0  192.168.1.1  example.com         201
4  1475740500.0  192.168.1.1  example.com         202

      test  b_count           b_sum  test_count  test_sum  \
0    False       90  47092452557782          90    18.660
1     True       80  45010998072550          80    15.028
2    False       82  45180520731516          82    16.868
3     True       60  34068659799136          60    12.726
4    False      116  65203810872260         116    22.546

   data1  data2  \
0      0      0
1      0      0
2      0      0
3      0      0
4      0      0

Please let me know how can I achieve that in an optimized way.

A: Great use case for the groupby.agg() function
Assuming that t1h and t2h already exist, and have the same column names
groupby_fields = ['timestamp', 'ip', 'domain', 'http_status', 'test']

df = t2h.append(t2h, ignore_index = True)

agg_dict = {'b_count':'count',
        'b_sum':'sum',
        'test_count':'count',
        'test_sum':'sum',
        'data1':'sum',
        'data2':'sum'}

df.groupby(groupby_fields).agg(agg_dict).reset_index()


text:
Q: How to check Internet connection using Inno Setup I'm learning about Inno Setup to make a simple installer. I need to download a file from a website during the installation, so it's important check if there is Internet connection. How can I check or take some alert to connect Internet during the process of the installation?
Thanks!

A: The best check is to try to actually download the file.
"Internet" is hardly a real thing that you can connect to. So it's hard to test, if you are connected to "Internet". You actually do not need a connection to "Internet", you need a connection to your server. So test that.

See also

*

*How to check if internet connection is present in java?

*What is the best way to check for Internet connectivity using .NET?
An equivalent implementation in Inno Setup would be like:
function InitializeSetup(): Boolean;
var
  WinHttpReq: Variant;
  Connected: Boolean;
begin
  Connected := False;
  repeat
    Log('Checking connection to the server');
    try
      WinHttpReq := CreateOleObject('WinHttp.WinHttpRequest.5.1');
      { Use your real server host name }
      WinHttpReq.Open('GET', 'https://www.example.com/', False);
      WinHttpReq.Send('');
      Log('Connected to the server; status: ' + IntToStr(WinHttpReq.Status) + ' ' +
          WinHttpReq.StatusText);
      Connected := True;
    except
      Log('Error connecting to the server: ' + GetExceptionMessage);
      if WizardSilent then
      begin
        Log('Connection to the server is not available, aborting silent installation');
        Result := False;
        Exit;
      end
        else
      if MsgBox('Cannot reach server. Please check your Internet connection.',
                mbError, MB_RETRYCANCEL) = IDRETRY then
      begin
        Log('Retrying');
      end
        else
      begin
        Log('Aborting');
        Result := False;
        Exit;
      end;
    end;
  until Connected;

  Result := True;
end;


text:
Q: Hibernate Session Factory javax/xml/bind/JAXBException error I'm trying to make some kind of simple java + hibernate app. Somehow when i run the app there is an error.

CreateStudentDemo.java

package com.basicproject.hibernate.demo;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

import com.basicproject.hibernate.demo.entity.Student;
public class CreateStudentDemo {

    public static void main(String[] args) {

        // create session factory
        SessionFactory factory = new Configuration()
                .configure("hibernate.cfg.xml")
                .addAnnotatedClass(Student.class)
                .buildSessionFactory();

        // create session
        Session session = factory.getCurrentSession();

        try {
            // create a student object
            System.out.println("Creating new student object...");
            Student tempStudent = new Student("Luke", "Samson", "ls@bk.com");

            // start a transaction
            session.beginTransaction();

            // save the student object
            System.out.println("Saving the student...");
            session.save(tempStudent);

            // commit transaction
            session.getTransaction().commit();

            System.out.println("Done!");
        }
        finally {
            factory.close();
        }
    }

}

Student.java

package com.basicproject.hibernate.demo.entity;

import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table;

@Entity @Table(name="student") public class Student {

    @Id     @GeneratedValue(strategy=GenerationType.IDENTITY)   @Column(name="id")  private int id;

    @Column(name="first_name")  private String firstName;

    @Column(name="last_name")   private String lastName;

    @Column(name="email")   private String email;

    public Student() {

    }

    public Student(String firstName, String lastName, String email) {       this.firstName = firstName;         this.lastName = lastName;       this.email
= email;    }

    public int getId() {        return id;  }

    public void setId(int id) {         this.id = id;   }

    public String getFirstName() {      return firstName;   }

    public void setFirstName(String firstName) {        this.firstName = firstName;     }

    public String getLastName() {       return lastName;    }

    public void setLastName(String lastName) {      this.lastName = lastName;   }

    public String getEmail() {      return email;   }

    public void setEmail(String email) {        this.email = email;     }

    @Override   public String toString() {      return "Student [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";  }

}

And the error. It seems like i'm missing something but i can't realise that is it yet.

Error

Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/JAXBException     at org.hibernate.boot.spi.XmlMappingBinderAccess.<init>(XmlMappingBinderAccess.java:43)     at org.hibernate.boot.MetadataSources.<init>(MetadataSources.java:87)   at org.hibernate.cfg.Configuration.<init>(Configuration.java:123)   at org.hibernate.cfg.Configuration.<init>(Configuration.java:118)   at com.basicproject.hibernate.demo.CreateStudentDemo.main(CreateStudentDemo.java:14) Caused by: java.lang.ClassNotFoundException: javax.xml.bind.JAXBException  at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582)  at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185)   at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496)

Hopefully it can help resolve my problem. Thank You for help. There is also a lib folder in my project. Contains Hibernate's libs(required) and mysql connector.

A: I think you're attending the same online course as me! In previous lessons the instructor posted a solution to this problem :
This happens because of Java 9 and higher.
Java 9 and higher has removed java.xml.bind from its default classpath. That's why we get the class not found exception.  We have to explicitly add JAR files to the build path.

Solution
For Java 9 and higher, you need to additional JAR files.
You need to download the following JAR files:

*

*javax.activation-1.2.0.jar

*jaxb-api-2.3.0.jar

*jaxb-core-2.3.0.jar

*jaxb-impl-2.3.0.jar

*

*Download the files using links below:

http://search.maven.org/remotecontent?filepath=com/sun/activation/javax.activation/1.2.0/javax.activation-1.2.0.jar
http://search.maven.org/remotecontent?filepath=javax/xml/bind/jaxb-api/2.3.0/jaxb-api-2.3.0.jar
http://search.maven.org/remotecontent?filepath=com/sun/xml/bind/jaxb-core/2.3.0/jaxb-core-2.3.0.jar
http://search.maven.org/remotecontent?filepath=com/sun/xml/bind/jaxb-impl/2.3.0/jaxb-impl-2.3.0.jar

*Copy the JAR files to the lib folder of your project

*

*javax.activation-1.2.0.jar

*jaxb-api-2.3.0.jar

*jaxb-core-2.3.0.jar

*jaxb-impl-2.3.0.jar

Use the following steps to add the JAR files to your Java Build Path.

*Right-click your project, select Properties

*On left-hand side, click Java Build Path

*In top-center of dialog, click Libraries

*Click Classpath and then Click Add JARs ...

*Navigate to the JAR files /lib
Select the files:
javax.activation-1.2.0.jar
jaxb-api-2.3.0.jar
jaxb-core-2.3.0.jar
jaxb-impl-2.3.0.jar

*Click OK then click Apply and Close

Eclipse will perform a rebuild of your project and it will resolve the related build/runtime errors.

A: You miss jaxb-api-1.0.jar in your classpath.
if you are maven add the following dependency to your code:
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>1.0</version>
</dependency>

A: Please add the below jar in your project classpath.
http://central.maven.org/maven2/javax/xml/bind/jaxb-api/2.2.11/jaxb-api-2.2.11.jar

A: Please change the JRE from the STS/Eclipse to 8 version.
Don't use JRE 1.8 in JDK 16.

A: Changed to java 8 instead of java 9 and working perfectly fine.


text:
Q: How to dynamically access target of function object I have a vector of function objects (std::function) all derived from a common base class, base, as shown below. While iterating over the vector I would like access to and possibly change variables in the target -- for example test. At compile time, std::function::target() can return a pointer to the original target, but is there a way to do this at run-time -- i.e. dynamically access test? The vector of functors could be comprised of an arbitrary number of different target functions. Boost is not an option for this codebase.
#include <iostream>
#include <functional>
#include <vector>

typedef std::function<double(double)> Tfunc;

struct base { bool test; };

struct half : public base {
  template<typename T> T operator()(T x) { return x*0.5; }
};

struct square : public base {
  template<typename T> T operator()(T x) { return x*x; }
};

int main() {
  std::vector<Tfunc> v;
  v.push_back( half() );
  v.push_back( square() );

  v[0].target<half>()->test=false;
  v[1].target<square>()->test=true;

  for (auto &f : v)
    std::cout << f(2.0) << " " << f.target_type().name() << "\n";

  return 0;
}

Output:
1 4half
4 6square

A: Do you really need to put the test variable inside the functor using inheritance?  You could compose the functor and the test variable like this:
struct math_operation
{
     Tfunc f;
     bool  test;
};

std::vector<math_operation> v;
v.push_back( math_operation() );
v.push_back( math_operation() );
v[0].f = half();
v[1].f = square();
v[0].test = false;
v[1].test = true;


text:
Q: SQL Server not returning an error why? Could someone please explain why the following query runs and does not return an error in SQL server 2012? When column BADCOLUMN does not exist in Table sometable?
SELECT  et
       ,mdt
FROM csv_import as a
where et IN (2,73)
  AND siteid IN (
                 select BADCOLUMN
                 from sometable
                  where SN in ('a','b','c')
                )

If you run just the subquery
select BADCOLUMN
from sometable
where SN in ('a','b','c')

You will receive an error stating the column does not exist.  But if you run the full query
you will not receive an error and that section of the where clause gets ignored
To me the full query should not run as a section of it contains an error?
Opinions or Reasons?


text:
Q: PsychoPy Coder : text.stim or not text.stim
*

*Situation
I'm using the PsychoPy coder to create a random dot motion task in speed-accuracy trade-off situation. I want to have a letter for fixation point to inform subject if they are in "speed" condition or in "precision" (on every trial), so I first thought of simply drawing a text.stim (like "S" or "P"). But I heard that text.stim was pretty slow to draw and because of the dynamic nature of the RDK task if the text.stim needs to much time I'm afraid that it will impact the display of the dots.

*

*Question
I'm I right?
And if so what would be the best way to draw the "fixation letters"?

A: Well it seems that I found the answer in the TextStim reference manual so I put it here in case someone needs it:

Performance OBS: in general, TextStim is slower than many other visual stimuli, i.e. it takes longer to change some attributes. In general, it's the attributes that affect the shapes of the letters: text, height, font, bold etc. These make the next .draw() slower because that sets the text again. You can make the draw() quick by calling re-setting the text (myTextStim.text = myTextStim.text) when you've changed the parameters.

So the slowing seems to concern the changing of the attributes which is not my situation.

A: If you've just got one letter being drawn it shouldn't have a major impact on your RDK, but just check whether frames are being dropped. All these things depend on graphics card and CPU speed so you need to test individually for each machine/experiment


text:
Q: adding js code with razor I am generating some tabs dynamically. I end up with 4 tabs. The class of the tabs is beeing set in the foreach loop, and it is set to be the languageId, as you can see in the code below.

    @for (int i = 0; i < Model.NoteViewModel.NoteTextViewModels.Count(); i++)
    {
      var languageId = @Model.NoteViewModel.NoteTextViewModels[i].LanguageId;
      var imageName = string.Format("FlagSmall_{0}.gif", languageId);

    }

Now I introduce a new variable: var currentLanguage = new NotesController().LogonInfo.LanguageId; which holds the current language of the user logged in. What I want to do, is to set focus on the tab where href (or id or class) is the same as the currentLanguage. For this I guess I need js, but since I can't have js code with razor syntax, I'm stuck. So I want something like this:
@for (int i = 0; i < Model.NoteViewModel.NoteTextViewModels.Count(); i++)
{
  var languageId = @Model.NoteViewModel.NoteTextViewModels[i].LanguageId;
  var currentLanguage = new NotesController().LogonInfo.LanguageId;
  var imageName = string.Format("FlagSmall_{0}.gif", languageId);

  if (languageId == currentLanguage)
  {
    documentation.getElementById("currentLanguage").focus();
  }
}

How can I achieve this?

A:
I can't have js code with razor syntax

Sure you can, though you may need to explicitly tell the view engine that this is client-side content and not server-side code.  You can do this with the <text> tag.  It's not an HTML tag per se, but something the razor engine uses to specify static content.  Something like this:


text:
Q: Php code doesnt update in sql Can you help me find down what wrong is this code.
It say successed but in sql doesnt change.
it is something wrong with
$est = intval($_GET['est']);
Plz help.
?php

session_start();

require_once("lib/connection.php");

if (!isset($_SESSION['username'])) {
 header('Location: login.php');
}else {
 $ten = $_SESSION['username'];
 $sql = "select * from users where username = '$ten' ";
 $query = mysqli_query($conn,$sql);
 $data = mysqli_fetch_array($query);
 }
$est = intval($_GET['est']);

$query2 = "SELECT * FROM customerinfo where estimate_number = '$est'";

 $result = mysqli_query($conn,$query2);
 $row = mysqli_fetch_array($result);

 if (isset($_POST["xacnhan"])) {
   if (isset($_POST["estc"])){
     $estc = $_POST["estc"];
$sql = "UPDATE customerinfo SET estimate_number = '$estc' WHERE estimate_number = '$est'";
            mysqli_query($conn,$sql);
            echo "ban da doi thanh cong Name: $estc";
     }

      if(isset($_POST["namec"])){
 $namec = $_POST["namec"];
$sql = "UPDATE customerinfo SET name = '$namec' WHERE estimate_number = '$est'";
mysqli_query($conn, $sql);
echo "ban da doi thanh cong Name: $namec";

 }

 }

?>

A: $est = intval($_GET['est']);

You use $_GET['est'] without checking if this value exists. Try this:
if (!isset($_GET['est'])) {
    // error
} else {
    $est = intval($_GET['est']);
}

PS: You should definitely protect your code from SQL injections. It is the best known and easiest to exploit security issue of PHP. I could do an SQL injection within seconds using only a browser.


text:
Q: I want visible button has removed it text from TextView I want visible button has removed it text from TextView
i am making keyboard typing in text view I have 4 buttons b1,b2,b3,backspace.
when I clicking on b1 typing in textview "A" and b1 invisible
then when I clicking backspace button its remove last char but does not appear last button has clicked

my project

https://youtu.be/_pLEUevM8aA

java

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

        //my buttons
    Button b1,b2,b3,backspace;
        //my text view

    TextView txt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        txt = (TextView)findViewById(R.id.txt);
        b1 = (Button)findViewById(R.id.b1);
        b2 = (Button)findViewById(R.id.b2);
        b3 = (Button)findViewById(R.id.b3);
        backspace = (Button)findViewById(R.id.backspace);

        b1.setOnClickListener(this);
        b2.setOnClickListener(this);
        b3.setOnClickListener(this);
        backspace.setOnClickListener(this);

        }

      //on clike listener

    @Override
    public void onClick(View view) {

        switch (view.getId()){

              //b1 on click
            case R.id.b1:

                txt.setText(txt.getText().toString() + b1.getText());
                b1.setVisibility(View.INVISIBLE);

                break;

                  //b2 on click
            case R.id.b2:
                txt.setText(txt.getText().toString() + b2.getText());
                b2.setVisibility(View.INVISIBLE);

                break;

                     //b3 on click
            case R.id.b3:
                txt.setText(txt.getText().toString() + b3.getText());
                b3.setVisibility(View.INVISIBLE);

                break;

                //here is my problem last char has deleted button of that char must be get visible

                   //backspace on click
            case R.id.backspace:

                //I want visible button has removed it text from TextView
                //appear last button has clicked

               txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));

                break;
        }//end switch

    }                   //I hope get answer in this website
}
                    //thank for ALL helping

A: You can try this:
    case R.id.backspace:

    //try like this
    if(string.substring(string.length() - 1).equals(b3.getText()))
       b3.setVisibility(View.VISIBLE);
    ...

txt.setText(txt.getText().toString().substring(0,txt.getText().toString().length()-1));

A: You could create a Stack of pressed buttons, so that you would know in which order they are pressed:
public class MainActivity extends ... implements ...{
    Stack<View> pressedButtons = new Stack<>();
    ...
    @Override
    public void onClick(View view) {
        // If it is a number, not a backspace key - remember that we pressed it
        if(view.getId() != R.id.backspace) {
            pressedButtons.push(view);
            txt.setText(txt.getText().toString() + ((Button) view).getText());
            view.setVisibility(View.INVISIBLE);
        }
        else {  // backspace key
            String text = txt.getText().toString();
            if(text.isEmpty())
                return;  // do this to prevent crash
            txt.setText(text.substring(0, text.length() - 1));
            // make the button visible again
            View lastPressedButton = pressedButtons.pop();
            lastPressedButton.setVisibility(View.VISIBLE);
        }
    }
}


text:
Q: Child Automation run as step in Parent Automation? Any ideas on using this SSJS Automation Trigger (or some other method) to Trigger a Child Automation as a middle step in a Parent Automation that once complete continues to process?
I have a long (many steps) Automation that needs to be run during several different other Automations, I don't really want to put all the Child steps into each Parent from a readability and maintainability perspective.
I tried a do while loop in the linked SSJS code;
        do {
            // Keep getting the status until it changes from Running
            automationObject = GetAutomationObject(automationCustomerKey);
        } while (automationObject.Status == 3);
        // This should mean the Automation has completed running
        Write("Automation Complete");

But this didn't work, probably because it's horribly inefficient. There is no option to set a delay in SSJS for a polling interval last time I tried either.
Any genius ideas?

A: Although there is no way to accurately make what you are asking, if you instead break up each part into multiple automations to accomplish the same tasks, it can be possible.
For instance instead of:
Parent Automation
Step 1 - Step 2 - Step 3 - Step 4 (child) - Step 5 - Step 6 - Step 7 (child) - Step 8
It would be:
Auto 1
Step 1 - Step 2 - Step 3 - Step 4 (calls Auto 2)
Auto 2
Step 5 - Step 6 - Step 7 (calls Auto 3)
Auto 3
Step 8
In order to track this, I would have a fourth Automation that runs a script activity to verify that the other automations are running on schedule.  This could be attained a couple ways:

*

*API calls to get last run date, last instance status and current status and then take action to alert if there is issue (I would also log the results into a DE)

*Have an activity at the end of each Automation that inserts the current datetime into a DE and then do a script activity that looks there to validate that the datetime displayed there fits into the expected results. Then send an alert if this is not correct.

Example to call automation:

A: I cannot think of a way other than along the lines of what you are doing. That said, the problem I see with it is that, while waiting for the child automation, this script can timeout after 30 mins.
Overall I think the best way to handle this would be to have the child automation trigger a third automation to complete the remaining activities. There's not really a good way to keep a true parent process.

A: The 'do while' SSJS solution actually works when running this as a Script Activity instead of as a Cloud Page (since the Cloud Page times out quickly). Though I also used an external website with a simple custom page that could mimic a delay for polling the automation status with a reasonable frequency;
        var runRequestResult = RunAutomation(automationObject.ObjectID);
        if (runRequestResult == 'OK') {
            Write("
Automation Started.");
            var counter = 1;
            var waitms = 10000; // how long in ms to wait between polling the Automation
            do {
                // Wait for X ms, the counter parameter will prevent the page from being cached
                var req = new Script.Util.HttpGet("http://externalwebsite.com/wait.aspx?w=" + waitms + "&counter=" + counter);
                var resp = req.send();
                Write("
Waiting... " + counter);
                counter++;
                // Refresh the Automation Object
                automationObject = GetAutomationObject(automationCustomerKey);
            } while (automationObject.Status == 3); // Keep looping while the Automation is still running
            Write("
Automation Finished.");
        }

Note there is a 30 minute limit on Script Activities timing out, so the Child Automation must complete within that time.


text:
Q: Spring: Redirect depending the view I have 2 indentical forms (View A and View B) that use the same controller. I would like it when I do the post of view A, redirect me to a url x and when I do post view B redirects me to another url (y). Is this possible in this function
@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    CloseCaseFrom sendCloseCaseFrom = new CloseCaseFrom();
    sendCloseCaseFrom.setDetail(closeCaseFrom.getDetail());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdPanic(closeCaseFrom.getIdPanic());
    sendCloseCaseFrom.setIdCasePanic(closeCaseFrom.getIdCasePanic());
    sendCloseCaseFrom.setIdStaff(user.getIdStaff());
    sendCloseCaseFrom.setIdUserSession(user.getIdUser());
    sendCloseCaseFrom.setSessionToken(user.getToken());

    panic.mClosePanicCase(sendCloseCaseFrom);

    return "redirect:/alerts";

}

How can I know, which view trigger the controller?

A: You could add a hidden input element in each view with the same name but a different value. You then get that value in your controller and redirect based on that.
This input is in ViewA

<input type="hidden" name="destination" value="a" />

This input is in ViewB
<input type="hidden" name="destination" value="b" />

And in your controller

@RequestMapping(value = "/panics/closeCase", method = RequestMethod.POST)
public String closeCase(@RequestParam destination, @ModelAttribute("closeCaseFrom") CloseCaseFrom closeCaseFrom, Model model) {

    //..
    if (destination.equals("a")) {
        // a goes to urlx
        return "redirect:/urlx";
    if (destination.equals("b")) { // or just else {
        // b goes to urly
        return "redirect:/urly";

}

Or instead of values a or b you could have the actual destination as a value in the input fields and avoid using if, just plug that destination in your redirect.


text:
Q: XSL:Choose not working I have a checkbox field in the sharepoint list. Then i want to display the list in the list using Dataview webpart. The issue that i am having that the checkbox value is not returned as expected since it all returned value No although some record has a value yes.
This the xml that i have so far:
 <td class="ms-vb">
    <xsl:choose>
        <xsl:when test="@Within_x0020_Product_x003F_='1' or msxsl:string-compare(string(@Within_x0020_Product_x003F_),'Yes','','i')=0 or msxsl:string-compare(string(@Within_x0020_Product_x003F_),'True','','i')=0">Yes</xsl:when>
        <xsl:otherwise>No</xsl:otherwise>
    </xsl:choose>
 </td>

Please advise what i am doing wrong. Thank you

A: Try this
<xsl:choose>
    <xsl:when test="@Within_x0020_Product_x003F_=1">Yes</xsl:when>
    <xsl:otherwise>No</xsl:otherwise>
</xsl:choose>


text:
Q: Getting the bound type of templated column controls in gridView Hi I have following grid view
  <asp:GridView ID="grdSettings" runat="server" Height="400px" Width="100%"
                        AutoGenerateColumns="false" >
                        <Columns>
                            <asp:TemplateField HeaderText="XYZ"  BoundFieldName="XYZTypeName">
                                <ItemTemplate>
                                    <asp:Label ID="lblCustomerName" runat="server" Text='<%# Bind("CustomerName") %>'>
                                    </asp:Label>

                                        <asp:Label ID="lblCostumerId" runat="server" Text='<%#Bind("CustomerId") %>'></asp:Label>

                            </asp:TemplateField>
                        </Columns>
                     </asp:GridView>

Which is bound by List of Customer  ,class is as follows
Class Customer
{
  public string CustomerName { get; set; }
  public int CustomerId { get; set; }
}

Now on a method named GetGridStuff() , i need to iterate in every column and get the type that was bound to controls in template field. For example in case of the first control in the template field
 <asp:Label ID="lblCustomerName" runat="server" Text='<%# Bind("CustomerName") %>' >
                                    </asp:Label>

I need to know what type of property data it contains , in this case its CustomerName. I need to get this dynamically at run time as to write code in part of program which is not aware if this grid structure. I have the grid object with me and i can access all properties.

A: Let me try this, being away from coding for more than 5 years now and if I understand the problem correctly as you may want to handle it through server side code.
Look for an event called ItemBound (or similar forgive me for my memory), this gives you values of all the items in current row (Properties). You also need to declare temp control types (label,textbox etc) and assign corresponding value to these controls using e.FindControl with appropriate type casting, e.g. Label l = (Label)e.Findcontrol("Name")
downside of the approach you should avoid too much of process as it is going to execute on every row creating of the grid.
Let me know if you still want a precise code to handle the problem but otherwise this description should at least help you to look for Row Level Event to crack the prob and also encourage you to stick to tech forums :)


text:
Q: Angular 7 - how to style material menu to have items compacted closer to each other I am new to Angular and am wandering how to style a material design (MD) menus.
This menu would be intended mainly for a desktop app and should look something like menus in standard desktop apps (e.g. MS Excel).
I have searched the web but got no clear answers.
By default the Angular MD menu items are quite far apart - there is wide spacing between them. So they look like this (I am using text only for visualization here) :
Item A1

Item A2 >   Item A2-B1

Item A3     Item A2-B2

etc.        Item A2-B3 >     etc.

            etc.

How can we override the MD default styles and reduce the menu buttons - smaller fonts, smaller size, no or minimal gaps, so we get a small compact menu with taking minimum real-estate and fitting more items in the menu - e.g:
Item A1
Item A2 >   Item A2-B1
Item A3     Item A2-B2 >     etc.
etc.        Item A2-B3

Example menu.component.html file:
<div>
  <button mat-button [matMenuTriggerFor]="menu"
          class="myMenuItem">Menu</button>
  <mat-menu #menu="matMenu" [class]="myMenu" >
    <button mat-menu-item class="myMenuItem">Item 1</button>
    <button mat-menu-item class="myMenuItem">Item 2</button>
  </mat-menu>
</div>

Would you please outline the styles and if there is a possibility to modify/configure MD default styles for the nav and button components to control their sizes and appearance, please provide instruction or link. Thank you.

A: if it is angular material menu component? And if you want to solve it by css ? then try it
.mat-menu-item{
    line-height: 20px;
    height: 20px;
}

A: Here is the way of styling mat-menu or its menu-items . It is just a showcase . Please use your own CSS that fits the exact needs of your desktop-like app. Hope I was helpful .
menu.component.html
<button mat-button [matMenuTriggerFor]="menu" class="myMenuItem">Menu</button>
<mat-menu #menu="matMenu" [class]="myMenu" >
  <button mat-menu-item class="myMenuItem">Item 1</button>
  <button mat-menu-item class="myMenuItem"> Item 2</button>
</mat-menu>

menu.component.css
.myMenu {
  color : red;

  padding: 0px ;
  margin : 0px;
  height: auto;

}
.myMenuItem {
  display:  flex;
  color : red;
  font-size: 10px;
  padding: auto ;
  margin : auto;
  height: 30px;
 align-content: center ;
     align-items:  center ;
     align-self: center ;
}

A: Using Mihaylov's answer as a starting point, I've come up with the following:
styles.scss
/*
  Tight Menu - A normal material menu but more compact
  Usage:
  <mat-menu class="tight-menu">
    <button mat-menu-item>Your Button</button>
    <button mat-menu-item>Other Button</button>
  </mat-menu>
*/

.tight-menu .mat-menu-content {
  padding-bottom: 0px !important;
  padding-top: 4px !important;
}

.tight-menu button.mat-menu-item {
  display: flex;
  margin-bottom: 4px;
  height: 30px;
  align-items: center;
}
/* End of Tight Menu */


text:
Q: Are there any side effects with adding a method to a declerative class in sqlalchemy? I had asked this question How to create instance of a table entry but not added in ponyorm? where I was asking how I can create an instance of the class defined as a ponyorm table representation without immediately adding it. By using sqlalchemy where an explicit add is needed on a session instance I think I succeeded by using the following code.
I first create a class called AddInstance which has an add method, and then inherit from this in all my table definitions. This seems to work (ie I can create an instance of the class and add it only if I want to relatively easily)  but I'm not sure if there are any unintended side effects or this is very far from best practice.
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import Column, String, Integer

engine = create_engine('sqlite:///:memory:')
Base = declarative_base()
Session = sessionmaker(bind=engine)

class AddInstance:

    def add(self):
        session = Session()
        session.add(self)
        session.commit()

class Pizza(Base, AddInstance):
    __tablename__ = 'pizzas'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    toppings = relationship('Topping', back_populates='name')

class Topping(Base, AddInstance):
    __tablename__ = 'fruits'
    id = Column(Integer, primary_key=True)
    name = Column(String(50))
    pizzas = relationship('Pizza', back_populates='name')

Base.metadata.create_all(engine)

A: There will be no side effects, SQLAlchemy explicitly supports adding methods. It doesn't matter if those methods are defined on a mixin class or directly on the class derived from Base.
Quoting from the SQLAlchemy Object Relational Tutorial documentation section:

Outside of what the mapping process does to our class, the class remains otherwise mostly a normal Python class, to which we can define any number of ordinary attributes and methods needed by our application.

(bold emphasis mine).
There are plenty of examples of code bases that do exactly the same. Flask-SQLAlchemy provides a Model base class to add a query attribute (set when the declarative base is created), which lets you do Topping.query(...) directly from a model class, for example.
Your add() method does have downside: it creates a new Session() instance just to add and commit your object. This keeps it outside of the normal session state management semantics and if you wanted to do anything else with your newly created object you'd have to merge it into an existing session.
The normal, best practice for code involvig SQLAlchemy objects is to create a session to manage a transaction, a set of operations that together must succeed or fail. That includes creating objects; in many real-world applications you'd want to avoid creating extra rows in a database when other operations that rely on those rows fail. Your .add() method unconditionally commits each object in a separate transaction. You may want to revisit this pattern.


text:
Q: Git is showing files as changed, even though files are byte-for-byte identical Git is indicating that a file has changes. However, when I run git difftool and open the file in Beyond Compare, it shows the files as binary-identical. Even if I open Beyond Compare in hex-mode, it still shows the files as identical.
I'm running git 2.9.2.windows.1 on Windows 10. I see this issue both when I run git from PowerShell and from the msys git bash prompt.
Has anyone else ever seen this before? Note: I'm not talking about changes in line endings, since line ending differences would clearly be visible in a hex comparison of the files.

A: That could be a change in the file mode, aka Unix mode bits. Even on Windows (which does not have Unix mode bits) Git does track the file mode which could change e.g. by running git update-index --chmod=+x <filename>. You can double-check by running git status -v which in this case would display something like
$ git status -v
On branch version-defines
Your branch is up-to-date with 'origin/version-defines'.
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

        modified:   circle.yml

diff --git a/circle.yml b/circle.yml
old mode 100644
new mode 100755


text:
Q: How to extend a model with many optional models in django? Say I have a master model with several optional slave models:
   class Master(models.Model):
        field_m1 = models.IntegerField(default=0)
        field_m2 = models.IntegerField(default=0)

   class slave1(models.Model):
        field_s11 = models.OneToOneField(
        Master,
        on_delete=models.CASCADE,
        primary_key=True,
        )
        field_s12 = models.IntegerField(default=0)

   class slave2(models.Model):
        field_s21 = models.OneToOneField(
        Master,
        on_delete=models.CASCADE,
        primary_key=True,
        )
        field_s22 = models.IntegerField(default=0)

at first I create a createview and a updateview:
class MasterCreate(CreateView):
    model = Master

class MasterUpdate(UpdateView):
    model = Master

then I use them in template master_form.html
...
<form method="post">{% csrf_token %}
...
    {{form.field_m1 }}
    {{form.field_m2 }}
...
</form>
...

everything seems OK so far, but how to integrate the slave models into the master's model
so I can use these field in template just like use Master.field_m1 and Master.field_m2? since 2 slave models is optional, i can add them or not add in createview and add or delete them (or any of them) in updateview. Could it be implement using generic edit view?