text:
Q: openshift set env jdk8 I have 2 Cartridges on openshift platform

*

*Tomcat 7 (JBoss EWS 2.0)

*PostgreSQL 9.2

I have also precompiled war file i want to deploy in the weapps/ directory in my openshift git repository (pushed into remote server).
Problem is war file is compiled to run in 1.8jre and the default jre is 1.7
I created simple executable shell script named start in repo in directory
.openshift/action_hooks/
#!/bin/bash

export JAVA_HOME=/etc/alternatives/java_sdk_1.8.0
export PATH=$JAVA_HOME/bin:$PATH

But still after restart app rhc app-restart myApp system variable JAVA_HOME is set back to jdk7.
Could you please point me out where is the problem?

A: The script you are using is correct and must work. In the action_hooks/start script, add below lines.
#!/bin/bash
export JAVA_HOME=/etc/alternatives/java_sdk_1.8.0
export PATH=$JAVA_HOME/bin:$PATH
echo $(java -version)
echo 'Starting application...'

You must see java 8. Anytime you start your application it should be same.


text:
Q: Call event with javascript I'm trying to call a event with a JavaScript.
But when I click the button that fire the event on the script drop me this error:

JavaScript runtime error: 'newButton_Click' is undefined

this is my script
<script>
    $(".btn-primary .outline .separate").click(function (e) {
        newButton_Click($(this), e)
    })
</script>

and this is the event that I want to fire:
protected void newButton_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);
            Button Btnclick = (Button)sender;
            var team = Btnclick.Text;
            string name = Btnclick.CommandArgument;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == team && x.STANDBY == 0).ToList();

            var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
            Grv_Eng.DataSource = ListOfToolsOk;
            Grv_Eng.DataBind();
        }

to fire the event I'm assigning an OnClientClick:
newButton.OnClientClick = "newButton_Click";

I'm using the class to find the button because the id is dynamically and I want that many dynamically buttons make the same event:
newButton.CssClass = "btn-primary outline separate";
[EDITED]
here is where I create the buttons:
protected void Page_Init(object sender, EventArgs e)
    {
        if (AssignClicked)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "showAndHide();", true);

            Button Btn_clic = (Button)sender;
            var name = Btn_clic.Text;

            List.ListUsers listArea = new List.ListUsers();
            List<Data.Area> Area = listArea.AreaList();

            List<Data.Area> ListOfEquiposOk = Area.Where(x => x.AREA == name && x.STANDBY == 0).ToList();

            var TeamFCH = ListOfEquiposOk.Select(x => x.TEAM).Distinct().ToList();

            foreach (var team in TeamFCH)
            {
                Button newButton = new Button();
                newButton.CommandName = "Btn" + Convert.ToString(team);
                newButton.ID = "Btn_" + Convert.ToString(team);
                newButton.Text = team;
                newButton.CommandArgument = name;

                newButton.Click += (se, ev) =>
                {

                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ModalGood();", true);
                    Button Btnclick = (Button)se;
                    var teams = Btnclick.Text;

                    List<Data.Area> ListOfToolsOk = Area.Where(x => x.AREA == name && x.TEAM == teams && x.STANDBY == 0).ToList();

                    var ToolArea = ListOfToolsOk.Select(x => x.TEAM);
                    Grv_Eng.DataSource = ListOfToolsOk;
                    Grv_Eng.DataBind();

                };

                pan1.Controls.Add(newButton);

                newButton.CssClass = "btn-primary outline separate";
            }
        }
    }

this is the event that fire the Page_Init
protected void DButton(object sender, EventArgs e)
        {
            AssignClicked = true;
            Page_Init(sender, e);
        }

The values to AssignClicked are those:
public bool AssignClicked
        {
            get
            {
                return Convert.ToBoolean(ViewState["AssignClicked"]);
            }
            set
            {
                ViewState["AssignClicked"] = value;
            }
        }

redpajama_set_name: RedPajamaStackExchange


text:
Q: not able to navigate between events of a object with dropdown box like visual studio 2019 in VS 2022 > I am not sure did they change it the way we can do it or is there any simpler way or they actually removed the option and limited us to use code instead
in vs 2019 if we double click the button we directly went to click event of a button and then from the upper right dropdown box we can easily move to any other event of a current object like double click or mouse over etc which automatically created the event handling SUB
but I am not able to do it in the VS 2022 so what happened with it?
as you can see in the attached images

A: I'm truly hoping that it's a bug in VS2022 because I'm really missing this function too. I've found a lot of topics in the official discussions and feeds and it seems that different older versions have the same issue, but they have already patched them. No info about 17.0.x version. :( I'll investigate further. Please report if somebody find a working solution.

A: Go to Options->Text Editor->(your language) and enable "Navigation Bar".
Previously answered here:
Visual Studio window which shows list of methods

A: well finally I found the answer to my question with thanks to mrtn
Microsoft finally found the bug and fixed the Asked Issue in question, so New update will solve this problem that was a bug from VS 2022
Additionally, I want to mention there is another way to create/edit Object's Events from Design view
Go to the design view and then click the Button with Lightning icon, a list of Events will Appear, and then go for the desired event and double click to add the event or edit it

A: This bug has been fixed in the latest version of the VS 2022 as per below post. Just tested and seems to be working as it used to!
https://developercommunity.visualstudio.com/t/event-drop-down-menu-in-the-upper-right-corner-of/1579215


text:
Q: How to install Patch SUPEE 8788 V2 I have got Magento version 1.9.2.0 I would like to install the new security patch 8788 v2. I have not installed the 8788v1 yet.
I know the installation process states, Revert SUPEE-8788 if you have already installed it, Revert SUPEE-1533 if you have already installed it, Deploy SUPEE-3941 if it hasn't already been installed.
My issue is I can not find out if SUPEE-1533 and SUPEE-3941 is installed because it is not in my app-etc-applied.patches.list and when I check on www.magereport.com, it does not indicate these patches.
I need advise on how to install this new patch successfully please.


text: Q: Disable jQuery Mobile Source Maps Although source maps are great for debugging, you don't really need to be sending these files to your end users. jQuery Mobile's source map is huge (222 kb, which is massive for a mobile website). Is there some way of disabling the request to get this map from the server? I have tried using jQuery's CDN and tried using a local include, but in both cases a request is visible in the Network tab of Chrome's DevTools.


text:
Q: How can i parse PDF file in android? I am developing android application. This application allows the user to highlight words in PDF file. Then these words must be extracted, so how can I parse the PDF file to get extracted words from the file without any library? Can any one help me?

A: You have to code it yourself if you don't want to use a libary. There isn't any build-in classes in Android SDK for PDF manipulation.
However you have to use a Libary and have a look at this question:
PDF Library to rendering the PDF files in Android

A: You can parse PDF easily on android easily using the iText library as like I've done it on my project by parsing a pdf file from assets and displaying it in the android listview.
iTextG Link: https://developers.itextpdf.com/itextg-android
assetManager = getAssets();

try{
    InputStream inputStream = assetManager.open("sample.pdf");
    String parsedText = "";
    PdfReader reader = new PdfReader(inputStream);
    int n = reader.getNumberOfPages();

    for (int i = 0; i < n; i++)
        parsedText = parsedText + PdfTextExtractor.getTextFromPage(reader, i + 1).trim() + "\n";

    String[] data = parsedText.split("\n");

    for(String d : data){
        patients.add(d);
    }

    reader.close();

}catch (FileNotFoundException e){
    Toast.makeText(this, "File Not Found", Toast.LENGTH_SHORT).show();
}catch (IOException e){
    Toast.makeText(this, "IO Error reading input stream", Toast.LENGTH_SHORT).show();
}


text:
Q: Proof of Lagrange multipliers theorem I am currently studying Folland's advanced calculus. But it doesn't have a rigorous proof of this theorem, so I try to write one myself.

Let $f$ be a differentiable mapping of $\mathbb{R}^n$ into $\mathbb{R}$ and $\boldsymbol{G}$ a $\mathscr{C}^1$ mapping of $\mathbb{R}^n$ into $\mathbb{R}^k$ ($k < n$). If $f$ attains its extremum on $\boldsymbol{G}^{-1}(\boldsymbol{0})$ at $\boldsymbol{a}$ and $\text{rank}(\boldsymbol{G}'(\boldsymbol{a}))=k$, then $\nabla f(\boldsymbol{a})$ lies in the span of $\{\nabla G_1(\boldsymbol a),\cdots\nabla G_k(\boldsymbol a)\}$.

Proof. Since $\text{rank}(\boldsymbol G'(\boldsymbol a))=k$, it has a k by k invertible submatrix. Without loss of generality, assume the last k columns of $\boldsymbol G'(\boldsymbol a)$ is linearly independent. Then by the implicit function theorem, there exist neighborhoods $N$ and $M$ of $(a_1,\dots,a_{n-k})$ and $(a_{n-k+1},\dots,a_n)$ respectively and a $\mathscr{C}^1$ mapping $\boldsymbol g$ of $N$ into $M$ such that
$$\{(\boldsymbol x, \boldsymbol g(\boldsymbol x):\boldsymbol x\in N\}=\boldsymbol G^{-1}(\boldsymbol0)\cap(N\times M)\text{.}$$
For $j=1,\dots,n-k$, $\boldsymbol H(t)=\boldsymbol G((a_1,\dots,a_{n-k})+te_j,\boldsymbol g((a_1,\dots,a_{n-k})+te_j))=\boldsymbol0$ for all sufficently small $t$, where $e_j$ is the j-th vector of the standard ordered basis for $\mathbb{R}^{n-k}$. Hence
$\boldsymbol H'(0)=\boldsymbol G'(\boldsymbol a)\begin{pmatrix} e_j \\ \boldsymbol g'(a_1,\dots,a_{n-k})e_j\end{pmatrix}=\boldsymbol 0$. It follows that $\nabla G_j(\boldsymbol a)$ lies in the orthogonal complement of $V=\text{span}\{(e_1,g'(a_1,\dots,a_{n-k})e_1),\dots(e_{n-k},g'(a_1,\dots,a_{n-k})e_{n-k})\}$. Clearly $\dim V=n-k$, so $\nabla G_1(\boldsymbol a),\dots,\nabla G_k(\boldsymbol a)$ forms a basis for $V^\perp$.
Next, consider $F(t)=f((a_1,...,a_{n-k}+te_J,\boldsymbol g((a_1,...,a_{n-k}+te_j))$, $j=1,\dots,n-k$, for $t$ in some neighborhood of $0$. By assumption, $F$ attains its extremum at $0$, so that
$$F'(0)=f'(\boldsymbol a)\begin{pmatrix} e_j \\ \boldsymbol g'(a_1,\dots,a_{n-k})e_j\end{pmatrix}=0\text{.}$$
From which we conclude that $f'(\boldsymbol a)\in V^\perp$. Consequently, there are $\lambda_1,\dots,\lambda_k$ such that
$$f'(\boldsymbol a)=\lambda_1\nabla G_1(\boldsymbol a)+\cdots+\lambda_k\nabla G_k(\boldsymbol a)\text{.}$$
Is this proof correct?


text:
Q: Bind  to a List I want the use to enter one or more value to the JSF inputText components and then put them in a List :
private List<String> stringList= new ArrayList<String>();

I want to do something like this :
<c:forEach id="myData" items="#{documentController.listeColonnes}" var="address" varStatus="loop">
       <h:outputLabel value="#{address}" />
       <h:inputText value="#{documentController.stringList[loop.index]}"/>
 </c:forEach>

ListeColonnes has label values (ID,prenom .... )
I want to enter this values(12,sam,....) in a new arrayList ()
Any idea !

A: Ok, I got the same problem and I managed to make it work, after several trials and errors. This is was my case:

*

*I wanted to create a dynamic UI that can be configured with JSON, so a took that data and put it inside a class called property.

*After that, I need to collect the data given by the user to store it in a DB.

This was my approach:
JSF
<h:form id="forma_po" styleClass="form-body" prependId="false">
    <c:forEach items="#{purchaseOrderPrinterBean.properties}" var="property">

    </c:forEach>
</h:form>

As you can see, if the user had previously saved any data at all the I show it with the value attribute on both p:inputTextarea and p:calendar, this purchaseOrderPrinterBean.values[property.name] was of course a java.util.HashMap<String, Object> field, a problem I encounter with this was when the user gave or change the information, the values field did not update at all, hence the
 tags inside the p:inputTextarea and p:calendar.
Bean
In the bean I had this:
public void fieldValue(AjaxBehaviorEvent e) {
    if (e.getSource() instanceof UIInput) {
        UIInput input = (UIInput) e.getSource();
        Object value = input.getValue();
        String id = input.getId();
        if(StringUtils.startsWith(id, "popup_")) {
            id = StringUtils.remove(id, "popup_");
        }
        values.put(id, value);
    }
}

This was the only case I found to make it work, a caution case, and I don't know why, but I had to put the prefix 'popup_' to the calendar, otherwise I got an error for duplicated ids.
Hope it helps, and excuse my bad english.

A: Try this
<ui:repeat value="#{documentController.listeColonnes}" var="address" varStatus="loop">
       <h:outputLabel value="#{address}" />
       <h:inputText value="#{documentController.stringList.get(loop.index)}"/>
    </ui:repeat>


text:
Q: Chrome-cast app crashes after casting to the TV I am modifying CastAndroid-Videos app such that instead of appearing list from JSON request, I put textbox which accepts any url of video to be casted on TV.
So according to that I modified VideoBrowserListFragment.java as follows
public View onCreateView(LayoutInflater inflator,ViewGroup container,Bundle saveInstanceState)
{
View v=inflator.inflate(R.layout.videourl, container,false);

mm=new MediaMetadata(MediaMetadata.MEDIA_TYPE_MOVIE);
mm.putString(MediaMetadata.KEY_SUBTITLE, "Some text");
mm.putString(MediaMetadata.KEY_TITLE, "Some string");
mm.putString(MediaMetadata.KEY_STUDIO, "Something");
mm.addImage(new WebImage(Uri.parse("Some image URL")));
mm.addImage(new WebImage(Uri.parse("Some image URL")));

submit=(Button)v.findViewById(R.id.submit);
url=(EditText)v.findViewById(R.id.texturl);
submit.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        info=new MediaInfo.Builder(url.getText().toString())
            .setStreamType(MediaInfo.STREAM_TYPE_BUFFERED)
            .setContentType("video/mp4")
            .setMetadata(mm)
            .build();

        Toast.makeText(getActivity(), "Info:"+info.getContentId(), Toast.LENGTH_LONG).show();

        Intent intent = new Intent(getActivity(), LocalPlayerActivity.class);
        intent.putExtra("media", Utils.fromMediaInfo(info));
        intent.putExtra("shouldStart", false);
        getActivity().startActivity(intent);
        }
});

return v;

}
But after Casting to TV, app gets crash while video keeps on playing on TV. While testing I am not having my host machine so I can't put log cat.
I am not changing anything throughout whole app. So cam anybody tell me where am I going wrong??

A: The simplest option is to copy these functions to your class: buildMediaInfo and handleNavigation.
On submit do this:
String url = ... //get url from textbox

//
MediaInfo selectedMedia = buildMediaInfo("custom video",
                        "none", "none", url, link_to_some_image, link_to_some_big_image);
handleNavigation(selectedMedia, false);

That is everything you need. In this way, you will acquire URL of the video which must be stored on some server. link_to_some_image is optional, you can provide any image, for example, a chromecast logo.
Handle navigation will start LocalPlayerActivity and that is it.
This works for me.


text:
Q: Amplifier Biasing So I have amplifier circuit that is biased using a sine wave and a DC offset on the NPN and PNP see this question. Wouldn't biasing the circuit at 1v short out the circuit as VBE~07V?
Here is a copy of the schematic:

A: In this circuit, with the sine wave generator at 0 volts, both transistors are on due to the 0.8 volt sources connected to their bases. The output is also sitting at 0 volts due to the symmetry of the circuit.  As the sine wave rises above 0 volts the NPN transistor turns on harder since its base emitter voltage is increasing. Thus the sine wave voltage will appear at the output across R1.  When the sine wave starts to fall below 0 volts, the PNP transistor turns on harder since its base emitter voltage is now decreasing.  Again, this will cause the sine wave voltage to appear at the output.  The 0.8 volt sources, V1 and V2, serve to avoid having the sine wave not appear at the output until its level goes above +0.8 volts or below -0.8 volts. If these sources were not present, the output sine wave would exhibit what is known as cross-over distortion, where the portion of the sine wave near its zero crossings is missing from the output because the transistors do not turn on until their base emitter voltages reach about 0.7 volts (for silicon transistors). In a real circuit, V1 and V2 would be replaced by diodes fed by resistors from the main power supplies, V5 and V7.

A: The forward voltage characteristic of a BJT's base emitter junction has to be taken into account - it is basically a diode and it doesn't draw infinite current as the voltage hits 0.700001V: -

You bias the base with a voltage that causes a certain amount of current to pass through to collector to the emitter and this may require 0.5V or a little higher (say 0.7V). Some power amplifiers may well need more than 0.7V and have a collector current (when no signal is present) of an amp. This is just to try and avoid cross-over distortion.

A: This is the classical issue with what is known as a class A amplifier.  You trade off efficiency for linearity and you also limit power.  This is all because you run power through the limb from rail to rail that does not get put into the load.  The current handling capacity of the transistors are in effect wasted (but that depends upon you view point).  So yes, it does sort of short your rails, but it helps to minimize other effects like cross over distortion.


text:
Q: How to get the current category filter in the catalog collection..? <?php
$_category = $this->getCurrentCategory(); $_categoryCollection = Mage::getResourceModel('catalog/category_collection')
                 ->addCategoryFilter($_category)
                 ->addAttributeToSelect('*')
                 ->addAttributeToSelect('is_brand','yes')
                 ->addAttributeToFilter('level','5')
                 ->addIsActiveFilter();
foreach($_categoryCollection as $cat){?>
<ui>
<?php //display current_Category image
     if($cat->getImageUrl()): ?>
      <img src="<?php echo $cat->getImageUrl(); ?>" />
<?php endif; ?>
     <a href="<?php echo $cat->getUrl(); ?>">
<?php //display current_Category image
     echo $cat->getName(); ?>

<?php
        }
        ?>

I want to display categories which have the value "yes" for the category attribute "is_brand". and i want it to be fetched from the current category. I could not access getCurrentCategory() inside catalog/category_collection..

i need only to fetch the category collection of level 5 only in the current category.
      THE ABOVE CODE FETCHES COLLECTIONS WITH LEVEL 5 FROM ALL CATEGORIES.

A: Please remove  ->addCategoryFilter($_category) which not exclude  current category from Category collection
This addCategoryFilter($_category)  only filter the product collection filter by category.
Use addAttributeToFilter() to filter the category  by path field.Level 5 category
must included current category path According to magento
 $_categoryCollection = Mage::getResourceModel('catalog/category_collection')
                     ->addAttributeToSelect('*')
                     ->addAttributeToSelect('is_brand','yes')
                     ->addAttributeToFilter('level','5')
                     ->addIsActiveFilter()
 ->addAttributeToFilter('path', array('like' => $_category->getPath().'/%'));

You can use addIdFilter(categoryIds)  if you want specific  ids categories

A: Give this a try:
$_category = $this->getCurrentCategory();
$path = $_category->getPath();
$_categoryCollection = Mage::getResourceModel('catalog/category_collection')
             ->addAttributeToFilter('path', array('like' => $path.'/%'))
             ->addAttributeToSelect('*')
             ->addAttributeToFilter('is_brand','1')
             ->addAttributeToFilter('level','5')
             ->addIsActiveFilter();


text:
Q: How to refresh only the section that clicked I'm working on a VisualForce page for a custom object. I have apex form inputfields. It successfully deletes the record - no problem.
But when clicked, it just refreshes the entire VF page.
I have added rerender="Section1" to refresh that section area but did not help me.
Here is the VF page:
<apex:page standardcontroller="Employee__c">
 <apex:form id="frm" >
    <apex:sectionHeader title="Status"></apex:sectionHeader>

     <apex:pageblock title="Status" mode="mainDetail" >

     <apex:pageBlockButtons location="top" >
          <apex:commandButton value="Publish" action="{!Publish}" rendered="{!CanPublish}" />
    </apex:pageBlockButtons>

<apex:pageBlockSection id="Section1" title="Tech" columns="1" >

    <apex:pageBlockTable Title="Creatives" value="{!Employees}" var="item">
        <apex:column headerValue="Action">
           <apex:commandLink action="{!URLFOR($Action.Emp__c.Delete, item.Id, [retURL=URLFOR($Action.Emp__c.View, Id)])}" rendered="{!CanEdit}" value="Delete" rerender="Section1"/>
    </apex:column>

   <apex:column headerValue="Name" >
     <apex:outputLink ....</apex:outputLink>
   </apex:column>
    <apex:column headerValue="Type" value="{!item.CreativeType}" />
    <apex:column headerValue="Creative">
    <apex:outputLink ....</apex:outputLink>
   </apex:column>
 </apex:pageBlockTable>
</apex:pageBlockSection>

</apex:pageblock>

 </apex:form>
</apex:page>

A: Rerender attribute always rerender section if it is a AJX call. here is the definition of render attribute

The ID of one or more components that are redrawn when the result of
  an AJAX update request returns to the client. This value can be a
  single ID, a comma-separated list of IDs, or a merge field expression
  for a list or collection of IDs.

If you will check apex:commandlink documentation it says

A link that executes an action defined by a controller, and then
  either refreshes the current page, or navigates to a different page
  based on the PageReference variable that is returned by the action.

and it render on page in following way
Save

So if you want to refresh only Section 1 use actionfunction

A: Here is what I have end-up doing:
Define the apex:actionFunction
  <apex:actionFunction action="{!deletemyRecord}" reRender="pbs" >
     <apex:param name="selectId" value="" assignTo="{!deleteId }" />
  </apex:actionFunction>

PageBlockSection:
<apex:pageBlockSection title="Areas" columns="1" id="pbs" >
 <apex:pageBlockTable value="{!loadData}" var="item">
 ................

 Delete

</apex:pageBlockTable>
</apex:pageBlockSection>


text:
Q: Improving docker build time for pip based python application We have a python project, and the current docker build takes 350s. Here is the current Dockerfile
FROM python:3.9

RUN apt-get update && \
    apt-get install -y python2.7

WORKDIR /var/app
COPY . .
RUN pip install

ENTRYPOINT ["python3", "/var/app/src/main.py"]

This took 350s on every docker build
There was obvious room for improvement here so, I changed it to this
FROM python:3.9

RUN apt-get update && \
    apt-get install -y python2.7

WORKDIR /var/app
COPY requirements.txt .
RUN pip install -r requirements.txt
COPY . .
RUN pip install

ENTRYPOINT ["python3", "/var/app/src/main.py"]

This brings subsequent build down to 1s
I also came across the following after a bit of searching,
FROM python:3.9

RUN apt-get update && \
    apt-get install -y python2.7

WORKDIR /var/app
COPY requirements.txt .
RUN  --mount=type=cache,target=/root/.cache/pip pip install -r requirements.txt
COPY . .
RUN pip install

ENTRYPOINT ["python3", "/var/app/src/main.py"]

This takes a bit longer around 80s but better than the 1st one

*

*What I don't understand is what are the caveats with #2 (to be safe).

*When should I use #3

I have no experience with pip/docker fyi
With #2, as a side effect of docker caching layers, if any of my dependencies dependency version changes, because of using range operators, then I still won't rebuild anything. Is that what #3 is trying to solve? i.e. it will reuse cache as much as it can but also makes sure to update anything necessary
If not, I have no idea what's going on with #3. Is the /root/.cache/pip a pip specific directory or it can be anything?

A: The difference between the first two is a Docker thing.  Docker maintains a build cache: if the previous step was cached, and either this RUN instruction is one that was run before or this COPY instruction copies identical files, then Docker skips building that layer and uses the output from the previous time you built it.
So in the first form, whenever any file changes, the COPY line invalidates the build cache, and you have to repeat the RUN pip install line.  But in the second form, you only COPY requirements.txt . first.  If that file hasn't changed, then you're still working off the build cache, and you can also skip the RUN pip install line.  This is standard Docker practice; you're not missing out on anything and there aren't really any caveats.

The difference between the last two is a pip thing.  Pip also maintains a cache of things it's downloaded.  Without Docker, if you run pip install -r requirements.txt a second time, pip will find its local cache and avoid re-downloading files.
In Docker, though, every image build starts from the same empty image.  The RUN --mount option mounts a persistent directory to be the pip cache.  This on the one hand gets you a place to store the files that can be reused, and on the other avoids storing the redundant wheel files in the final image.  The mount target directory needs to be the same location as pip is expecting its cache to be.
What you should find is, if you haven't changed requirements.txt, then the build again skips over the RUN pip install step, the same as in your second Dockerfile.  If you have, then it will at least skip downloading many of the packages.  Depending on your network speed, this can lead to subsequent rebuilds running faster.

... if any of my dependencies dependency version changes ...

Most package managers have two different copies of a version list, the user-managed dependency file and a separate lock file that lists exact versions that are to be installed.
In Python the situation is a little confusing because there are several different package managers.  If I wasn't using an alternate tool like Pipfile or Poetry, then the setup I'd suggest is using the standard Setuptools library.  List your application's dependencies in a setup.cfg file
[options]
install_requires =
  some-package >=1.0,<2.0

On your host system, use this to do the installation into a virtual environment, then run pip freeze to generate the requirements.txt file.
python3 -m venv ./venv
. ./venv/bin/activate
pip install -e .
pip freeze > requirements.txt

Now the requirements.txt file contains the exact version of every library you directly and indirectly depend on.  Do not hand-edit this file; do not regenerate it in your Dockerfile; do check it into source control.  With the pair of dependency files, requirements.txt is now functionally the lock file.
Also see the pip documentation on Repeatable Installs.  Both Pipfile and Poetry maintain their own lock files, if you choose to use one of those package managers instead.


text:
Q: azure backup- error during enabling I can't enable Azure backup on some my VMs in Azure. I have already virtual machines migrated from classic to ARM, but disks for a few one are still stored in Classic storage. If I try to enable backup I receive error "Deployment to resource group 'ResourceGroupName' failed." "Write ProtectedItems Failed" I also can't migrate this disk to ARM using standard migration procedure.
On new machines or corrected migrated I can enable Azure backup without any problems.
thanks for any help

A: Easy fix, migrate the storage too.
https://docs.microsoft.com/en-us/azure/virtual-machines/windows/migration-classic-resource-manager-overview#migration-of-storage-accounts
Hope this helps.

A: Yes, I know- storage migration is a solution :) but I get some errors during migration process. I migrated all environment and commit this process but one classic storage account finish with errors. OK, I was hoping that there is some tricky operation. I will retry next days. Thanks


text:
Q: MySQL - Find strings is there a short way to select entries by finding a specific pattern?
I have a column called "keyword" in my table "data" and yes, I find some entries but not all by executing the following query:
SELECT ca.userid_click, ca.keyword
FROM data ca WHERE
ca.date > '2016-05-01'
AND (ca.keyword LIKE '%[AAID]%_%[IDFA]%')
GROUP BY ca.userid_click, ca.keyword;

Sadly I have some missing entries and I have no glue how I can get them.
Common for all wanted entries is a pattern like
47ba96a8-cafa-4ce1-ab23-fa4a5df5a381

or
b839927c-cc05-4235-92e0-86763472700f

So 8 characters-4 characters-4 characters-4 characters-12 characters binded with an "-". The problem is sometimes this substring is in the beginning, sometimes in the middle or the end of my string.
Is there a smart way to extract those entries? I tried several approaches but I guess there is a way to extract all.


text:
Q: Looking for PHP BPMN 2.0 and service bus 'esb' Does anyone know a BPMN 2.0 designer/modeler and process execution engine based on PHP? In the same context, does anyone know an ESB accepting PHP script?

A:
Does anyone know a BPMN 2.0 designer/modeler and process execution
  engine based on PHP?

You could use probably almost every PHP framework like symfony to build some ESB functionality into your application but it generaly seems a bit odd to build an ESB in PHP. I don't think PHP is the right technology to that kind of architecture since PHP was developed to be a front end tool. This brings limitation like the lack of non-blocking execution, timeout problems, complicated handling of asynchronus processes.

In the same context, does anyone know an ESB accepting PHP script?

So my recommendation would be:

*

*Check if you really need an ESB *

*If you do, choose one among the stable systems, e.g. http://www.jboss.org/jbpm or http://www.mulesoft.org/

*Integrate your PHP script as a service using webservices.

* An ESB is not something you can drop in like a jQuery Script so better think twice here.
Related question:
PHP and ESB (with Mule) (ESB: Enterprise Service Bus)

A: you could also use a mix of the camunda BPM tools (which all are open source).
The camunda BPM platform with camunda BPM PHP SDK or your own PHP solution via REST API and camunda BPM javascript renderer would provide the process execution and rendering of diagrams for e.g. monitoring purposes.
The camunda BPM modeler (Eclipse Plugin) deals with the modeling/design aspect.
You can find all these tools here

A: While not a BPMN suite, at least a bit of Workflow is part of ezComponents.
Please be aware, that ezComponents recently failed to get an Apache project after staying some time in incubator...


text:
Q: How do I match elements in rows in two separate data frames, for differing values and counts? I have two data frames, for which I have replicated real data below. The first data frame looks like:
FirstDataFrame <- data.frame("GroupID"   = c(1902, 1905, 1905, 1905, 1906, 1906, 1914, 1914, 1932, 1932, 1964, 1964, 1964),
                         "SubjectID" = c(24626, 13300, 14126, 2619, 914, 872, 13325, 12539, 12597, 13314, 13343, 1723, 13333),
                         "Age"       = c(17, 13, 16, 17, 5, 9, 8, 14, 10, 13, 7, 14, 16))

The second data frame looks like, with the values for each Age being counts:
SecondDataFrame <- data.frame("OtherID" = c(1, 2, 3, 4, 5, 6),
                          "Age5" =c(0, 0, 0, 11, 12, 57),
                          "Age6"= c(0, 0, 0, 12, 8, 52),
                          "Age7" = c(0, 0, 0, 12, 9, 42),
                          "Age8" = c(0, 0, 0, 9, 11, 50),
                          "Age9" = c(0, 0, 0, 12, 7, 46),
                          "Age10" = c(0, 0, 0, 12, 11, 41),
                          "Age11" = c(19, 0, 0, 9, 8, 42),
                          "Age12" = c(14, 0, 0, 13, 12, 39),
                          "Age13" = c(54, 78, 83, 0, 3, 13),
                          "Age14" = c(69, 101, 145, 0, 0, 0),
                          "Age15" = c(59, 114, 128, 0, 0, 0),
                          "Age16" = c(77, 127, 107, 0, 0, 0),
                          "Age17" = c(61, 91, 82, 0, 0, 0))

Each of those AgeX columns in SecondDataFrame correspond to a specific single-year age, as shown in the column name.
My objective is, for each GroupID in FirstDataFrame:

*

*Extract the age values (perhaps into a vector). Note that some ages within GroupID may be the same. For example, I may have two 14-year-olds.

*In SecondDataFrame, locate the ID row that contains the highest frequency of matches to the ages in that GroupID and contains a count of at least 1 (or at least 2, in the case where I have doubled-up ages) in the GroupID. That is, locate the OtherID row (or perhaps vector, I have thought about having one vector for each OtherID) which has the highest frequency of column (vector index?) matches.

*Within the GroupID, allocate the chosen OtherID to each SubjectID that meets that criteria.

*Decrease the count in the associated AgeX column by 1 for each match to that OtherID.

*Repeat within GroupID until all SubjectID have an age match from SecondDataFrame.

*Cycle to the next GroupID.

As you can see in FirstDataFrame, I have GroupID subjects who cannot all be allocated to the same OtherID in the SecondDataFrame. I also have varying numbers of subjects within each GroupID.
To make things even more complicated, there is no cut-off for the OtherID age columns such that if all the OtherID with a non-zero Age11 have either all non-zero counts between the columns Age5 through Age10 or Age12 through Age17.
I have cleaned the data such that each AgeX count in SecondDataFrame contains at minimum the same number of subjects of that age in FirstDataFrame. The minimum and maximum age values in FirstDataFrame and SecondDataFrame have been set so that these match exactly.
How do I ensure the maximum number of matches and decrease the counts appropriately? I've found some questions/answers that relate to obtaining the maximum number of matches. But:

*

*They are doing a simple test of one vector against another single vector, and/or

*They aren't decreasing the counts in the matched vector, but simply testing if an element exists (or not), or how many values in one vector match the values in another vector.

I can use nested for () loops, but I am stuck on how to do the frequency matching and the decrease to the counts. I was thinking I needed to start the match at the youngest age in the GroupID and work with increasing age within GroupID, and that is the point at which I get stuck.
Edit: The finalised FirstDataFrame would look like:
FirstDataFrame <- data.frame("GroupID"   = c(1902, 1905, 1905, 1905, 1906, 1906, 1914, 1914, 1932, 1932, 1964, 1964, 1964),
                         "SubjectID" = c(24626, 13300, 14126, 2619, 914, 872, 13325, 12539, 12597, 13314, 13343, 1723, 13333),
                         "Age"       = c(17, 13, 16, 17, 5, 9, 8, 14, 10, 13, 7, 14, 16),
                         "OtherID"   = c(2, 3, 3, 3, 6, 6, 6, 3, 6, 6, 6, 3, 3)

However, the OtherID will also be chosen probabilistically. For example, the three teenagers in GroupID 1905 also have a probability of being in OtherID 1 or 2.
Correspondingly, the matched age cells will be decreased by 1 for each match in SecondDataFrame. So, for GroupID 1905, OtherID will end up with the counts:
Count13 = 82, Count16 = 127, and Count17 = 81, which represent a decrease of 1 from the original counts, because each child match decreases the matches available by 1.

A: This is a long and tough problem to solve and I'm not sure I have answered everything.
Here's my way of approaching this problem, first by splitting FirstDataFrame according to GroupID and you get a list:
split_df <- split(FirstDataFrame, FirstDataFrame$GroupID)
split_df
#$`1902`
#  GroupID SubjectID Age
#1    1902     24626  17
#
#$`1905`
#  GroupID SubjectID Age
#2    1905     13300  13
#3    1905     14126  16
#4    1905      2619  17
#
#$`1906`
#  GroupID SubjectID Age
#5    1906       914   5
#6    1906       872   9
#
#$`1914`
#  GroupID SubjectID Age
#7    1914     13325   8
#8    1914     12539  14
# ...

Now I'll focus on one case and then we use a for loop to loop through it. I choose 1905 which is second element of the list. First extract the age of that group, then I want to create a vector of frequencies (instead of ages). I don't know of better way, so here's the inelegant solution
i = 2
ages <- split_df[[i]]$Age
ages
#[1] 13 16 17

ind_ages <- ages - 4 # "Indexize" ages: Age 5 become 1, 6 become 2, ..., 17 become 13
ind_ages
#[1]  9 12 13

freq <- tabulate(ind_ages, nbins = 13)
freq
#[1] 0 0 0 0 0 0 0 0 1 0 0 1 1

The frequency vector has length 13, at 9-, 12- and 13-th position are one rest of them zero... This is to match with the column 2 to 14 in SecondDataFrame.
Now you can derive a way to randomly assign an OtherID to these kids. One possibility is to use the multinomial likelihood: Chances of getting 3 balls from bin 9, 12, and 13 given a set of probabilities assigned to the bins.
For each row in SecondDataFrame, we can calculate the proportion of each age (and use them as probabilities):
props <- apply(SecondDataFrame[,2:14], 1, function (x) x/sum(x))
props
#            [,1]      [,2]      [,3]      [,4]       [,5]       [,6]
#Age5  0.00000000 0.0000000 0.0000000 0.1222222 0.14814815 0.14736842
#Age6  0.00000000 0.0000000 0.0000000 0.1333333 0.09876543 0.13684211
#Age7  0.00000000 0.0000000 0.0000000 0.1333333 0.11111111 0.11052632
#Age8  0.00000000 0.0000000 0.0000000 0.1000000 0.13580247 0.13157895
#Age9  0.00000000 0.0000000 0.0000000 0.1333333 0.08641975 0.11842105
#Age10 0.00000000 0.0000000 0.0000000 0.1333333 0.13580247 0.10789474
#Age11 0.05428571 0.0000000 0.0000000 0.1000000 0.09876543 0.11052632
#Age12 0.04000000 0.0000000 0.0000000 0.1444444 0.14814815 0.10263158
#Age13 0.15142857 0.1529412 0.1522936 0.0000000 0.03703704 0.03421053
#Age14 0.19714286 0.1980392 0.2660550 0.0000000 0.00000000 0.00000000
#Age15 0.16857143 0.2235294 0.2348624 0.0000000 0.00000000 0.00000000
#Age16 0.21714286 0.2490196 0.1963303 0.0000000 0.00000000 0.00000000
#Age17 0.17142857 0.1764706 0.1504587 0.0000000 0.00000000 0.00000000

Again, using apply(), we can calculate the likelihood of the three children coming the row (Note in props it becomes column).
likelihood <- apply(props, 2, function (x) dmultinom(freq, size = sum(freq), prob = x))
likelihood
#[1] 0.03382111 0.04032567 0.02699215 0.00000000 0.00000000 0.00000000

prob_OtherID <- likelihood / sum(likelihood)
prob_OtherID
#[1] 0.3344025 0.3987156 0.2668819 0.0000000 0.0000000 0.0000000

Probability of the kids belonging to OtherID 1 is 33.4%, 2 is 39.9% ... This is simply the weighted average of likelihoods. This way of calculation only works if you have small numbers of kids. If you have say 100s of kids in one group, this code break due to numerical issues.
Now use sample() to choose one OtherID for the kids, update the list.
chosenID <- sample(SecondDataFrame$OtherID, size = 1, prob = prob_OtherID)
split_df[[i]]$OtherID <- chosenID

Finally, go to the corresponding row in SecondDataFrame, subtract the age frequencies by the age frequency of this group of kids:
SecondDataFrame[SecondDataFrame$OtherID == chosenID, 2:14] <-
    SecondDataFrame[SecondDataFrame$OtherID == chosenID, 2:14] - freq

Now put them into a for loop and job is done! A few more notes: for loop break at i = 4 in this example because no row in SecondDataFrame simultaneously has Age 8 and 14 kid. Second, this algorithm does not guarantee you to be able to assign them all with an OtherID because as the frequencies get reduced in SecondDataFrame, you're increasingly likely to run into problem like that of i = 4. Perhaps you would be lucky to fill them all up without errors, or perhaps the capacity is much larger than the number of subjects then you'll be fine. Otherwise you'll have to think of other ways to deal with this issue.


text:
Q: Fetching data from core data crashing for iOS version 12 Here is what crash report says:-

Fatal Exception: NSInvalidArgumentException -[_PFFetchPlanHeader
  _genericValueForKey:withIndex:flags:]: unrecognized selector sent to instance 0x282b24730

Crash report for the below crash is:-

Crashed: com.apple.root.user-initiated-qos
                      0  libobjc.A.dylib                0x1edc58d70 objc_msgSend + 16
                      1  CoreData                       0x1f16b653c _PF_Handler_Public_GetProperty + 252
                      2  Foundation                     0x1ef41c3cc -[NSFunctionExpression expressionValueWithObject:context:] + 808
                      3  Foundation                     0x1ef41bfc8 -[NSComparisonPredicate evaluateWithObject:substitutionVariables:] + 228
                      4  CoreData                       0x1f1590e8c -[NSManagedObjectContext executeFetchRequest:error:] + 3476
                      5  Quickride                      0x1044f6d28 specialized static
  NotificationPersistenceHelper.isNotificationAlreadyPresent(uniqueId:)
  (NotificationPersistenceHelper.swift:284)
                      6  Quickride                      0x104465c4c specialized NotificationHandler.saveNotification(clientNotification:)
  (NotificationHandler.swift:58)
                      7  Quickride                      0x1047174c8 AppStartupHandler.sessionChangeOperationCompleted()
  (NotificationStore.swift:26)
                      8  Quickride                      0x104718058 protocol witness for
  SessionChangeCompletionListener.sessionChangeOperationCompleted() in
  conformance AppStartupHandler (AppStartupHandler.swift)
                      9  Quickride                      0x10479f4b0 SessionManagerController.notifyListenerAboutSessionChangeOpCompletion()
  (SessionManagerController.swift:284)
                      10 Quickride                      0x10479e638 SessionManagerController.resumeUserSession(sessionChangeCompletionListener:)
  (SessionManagerController.swift:93)
                      11 Quickride                      0x1047170c8 closure #1 in
  AppStartupHandler.resumeUserSessionAndNavigateToAppropriateInitialView()
  (AppStartupHandler.swift:38)
                      12 Quickride                      0x104371784 thunk for @callee_owned () -> ()
  (RideManagementModuleSessonHandler.swift)
                      13 libdispatch.dylib              0x1ee4a96c8 _dispatch_call_block_and_release + 24
                      14 libdispatch.dylib              0x1ee4aa484 _dispatch_client_callout + 16
                      15 libdispatch.dylib              0x1ee459b5c _dispatch_root_queue_drain + 684
                      16 libdispatch.dylib              0x1ee45a2d0 _dispatch_worker_thread2 + 128
                      17 libsystem_pthread.dylib        0x1ee68c17c _pthread_wqthread + 472
                      18 libsystem_pthread.dylib        0x1ee68ecec start_wqthread + 4

Part of code where crash occurred and this code works fine until iOS version 12  :-
                static func isNotificationAlreadyPresent(uniqueId :Double?) -> Bool{
                        if uniqueId == nil{
                            return false
                        }

                        let managedContext = CoreDataHelper.getNSMangedObjectContext()
                        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: NotificationPersistenceHelper.UserNotification_entity)

                        fetchRequest.predicate = NSPredicate(format: "\(NotificationPersistenceHelper.uniqueID) = %@", argumentArray: [uniqueId!])
                        do{
                            let results = try managedContext.fetch(fetchRequest)

                            return  !results.isEmpty
                        }catch let error as NSError{
                        }
                        return false
                    }

            Crash occurred at below line :-

            let results = try managedContext.fetch(fetchRequest)

Above code to fetch data from core data works fine till iOS version 11 but now for user who is using iOS version 12 this crash happened.
Could you please help me in resolving this crash, am wondering why this is giving trouble for version 12 only is there any other method specific to iOS version 12 to fetch core data or is there any issue with iOS version itself? if there what is the solution for that?
am searching this for past 2 days am not getting why it is crashing only to iOS version 12 Please any one help me to resolve this crash.
Thanks in advance


text:
Q: Is it possible to save an interrupted computation? I've got this really time consuming factoring problem. To decouple things a bit, I decided to start Mathematica using the command line interface (under screen).
$ math

So my code is running, and I know that I can interrupt it with Ctrl-C, but what I want to do is interrupt it, and then write the state of the process to disk, so that I can reboot. On Linux, there is a program called CryoPID which might work. Unfortunately, my computation is running on OS X.
I can detach from the screen session and re-attach to it, but if I reboot the machine I know it'll lose memory and the computation progress so far. My question is: can you save the state of a Mathematica computation that you interrupt (to disk and reloadable after a restart). Thanks.

A: I doubt that there is a practical way to save the complete internal state and resume the computation where it was interrupted.  However, here's what you can do:
When you press Ctrl-C, you get a prompt. If you type i at this prompt, you'll enter a "dialogue" with Mathematica.  You can examine the internal state, look at the values of all the variables, look at Stack[], etc.  Evaluating Return[] will resume the computation. (Warning: Ctrl-D or Quit will still quit.)
If your computation is not too complicated, you may be able to extract enough information so you can resume later.  But the chances that this will work in practice are not great.  For example you can't extract a partial result from Table because it's not stored in a user-accessible variable.
For the future, the best thing you could do would be designing the computation to be interruptible by saving partial results into a variable.  For something that is already running at this moment, unfortunately the chances are slim.


text:
Q: ¿que debo hacer despues para realizar este programa en java poo? Estoy atascado y nose como debo continuar, mi proyecto es el siguiente:
Desarrollar una clase articulo que contenga los siguiente:

*

*Las propiedades: id, descripcion, y existencia.

*Un constructor que inicialice el objeto articulo al crearlo.

*Metodos para dar entrada a artículos (por compra, devoucion, ajustes etc).

*metodo para dar salida a articulos (por venta, por devolucion al
proveedor, ajustes etc).

*metodo publicos que accedan a las propiedades    tanto para obtener
la propiedad o para actualizarla (get y set)

Llevo esto:
public class Articulo {
    private int id;
    private String descripcion;
    private int cantidad;

    public static void main(String[] args) {
        Articulo articulo = new Articulo();
    }
}

A: Hola tu problema solo pide que crees la clase Articulo con un simple constructor y metodos getters y setters , respecto al principio de encapsulamiento. Dejo aqui la clase articulo, y los otros dos metodos que pides pues la verdad no tengo claro que mismo se solicita por lo que lo dejo a tu criterio. Recomendacion no uses el metodo main dentro de una clase al cual vas instanciar un objeto, crea otra clase principal en la cual agregues el metodo main, y ahi si ya podras realizar diferentes instancias de diferentes objetos.
Clase Articulo.
package tester;

public class Articulo {
    private int id;
    private String descripcion;
    private int cantidad;

    // Este es el constructor que instancia un obejto tipo Articulo.
    public Articulo(int id, String descripcion, int cantidad) {
        this.id = id;
        this.descripcion = descripcion;
        this.cantidad = cantidad;
    }

    // Metodos getters y setters
    public int getId() {
        return id;
    }

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

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public int getCantidad() {
        return cantidad;
    }

    public void setCantidad(int cantidad) {
        this.cantidad = cantidad;
    }

    // Y AQUI AGREGAR LOS OTROS METODOS QUE SOLICITAS.

}

Clase principal con un ejemplo de instancia.
package tester;

public class Principal {

    public static void main(String[] args) {
        Articulo articulo1 = new Articulo(1, "Azucar de alta calidad", 5);
        Articulo articulo2 = new Articulo(1, "Arroz", 5);

        //incluso si tuvieras ejemplo un clase tienda con un atributo que sea su nombre pues tambien podrias instanciar
        //y dar un mejor manejo desde aqui.
        // Tienda obTienda = new Tienda(nombreDeLaTienda);
    }

}


text:
Q: Pandas Concatenate dataframes This is driving me nuts! I have several Dataframe that I am trying to concatenate with pandas. The index is the filename. When I use df.to_csv for individual data frames I can see the index column (filename) along with the column of interest. When I concatenate along the filename axis I only get the column of interest and numbers. No filename.
Here is the code I am using as is. It works as I expect up until the "all_filename" line.
for filename in os.listdir(directory):
    if filename.endswith("log.csv"):
        df = pd.read_fwf(filename, skiprows=186, nrows=1, names=["Attribute"])
        df['System_Library_Name'] = [x.split('/')[6] for x in df['Attribute']]
        df2= pd.concat([df for filename in os.listdir(directory)], keys=[filename])
        df2.to_csv(filename+"log_info.csv", index=filename)

        all_filenames = glob.glob(os.path.join(directory,'*log_info.csv'))
        cat_log = pd.concat([pd.read_csv(f) for f in all_filenames ])
        cat_log2= cat_log[['System_Library_Name']]
        cat_log2.to_excel("log.xlsx", index=filename)

I have tried adding keys=filename to the 3rd to last line and giving the index a name with df.index.name=
I have used similar code before and had it work fine, however this is only one column that I am using from a larger original input file if that makes a difference.
Any advice is greatly appreciated!

A: df = pd.concat(
          # this is just reading one value from each file, yes?
         [pd.read_fwf(filename, skiprows=186, nrows=1, names=["Attribute"])
            .set_index(pd.Index([filename]))
            .applymap(lambda x: x.split('/')[6])
            .rename(columns={'Attribute':'System_Library_Name'})
          for filename in glob.glob(os.path.join(directory,'*log.csv'))
         ]
     )
df.to_xlsx("log_info.xlsx")


text:
Q: Left ideals of matrix ring over a field The claim is made here that for $k$ a field

The left ideals of $M_n(k)$ are all of the form  $$\{A \in M_n(k) \mid
 \operatorname{ker}A > S \}, \rlap{ \qquad \text{for some subspace
 $S$.}}$$

I was trying to think through that claim. I understand why all the left ideals of $M_n(k)$ are of the form
$$\{A \in M_n(k) \mid \operatorname{Rowspace}(A) < S \}, \rlap{ \qquad \text{for some subspace $S$.}}$$
In the presence of an inner product, we have that $\operatorname{ker}A^T = \operatorname{Range}(A)^{\bot}$, and therefore we get the characterization we want. But what about if there isn't an inner product?
Does the same hold for $M_n(\Delta)$, where $\Delta$ is a division ring?

A: Using the theory of nondegenerate symmetric bilinear forms, it is possible to show that $\operatorname{ker}A^T = \operatorname{Range}(A)^{\bot}$ without the need for existence of an inner product (when we are discussing matrices over a field). The symbol $\bot$ would then represent an orthogonal complement with respect to the relevant nondegenerate symmetric bilinear form. Here is a copy from some work of mine showing that the row space of a matrix is the right orthogonal complement of the null space with respect to what I would regard as the most natural nondegenerate symmetric bilinear form:

Consider the function $f: \mathscr{F}^n \times \mathscr{F}^n
> \rightarrow \mathscr{F}$, defined by $f(v,w)=v^Tw$. It is easy to see
  that:

*

*$f_{w_0}:\mathscr{F}^n \rightarrow \mathscr{F}$ defined by $f_{w_0}(v)=f(v,w_0)$ for any given $w_0 \in \mathscr{F}^n$ is a
  linear functional and therefore belongs to the dual space of
  $\mathscr{F}^n$.

*Similarly $f_{v_0}:\mathscr{F}^n \rightarrow \mathscr{F}$ defined by $f_{v_0}(w)=f(v_0,w)$ for any given $v_0 \in \mathscr{F}^n$ is a
  linear functional and therefore belongs to the dual space of
  $\mathscr{F}^n$.

  By the properties above, $f$ is a bilinear form, and furthermore it is
  a symmetric bilinear form since $f(v,w)=f(w,v)$ for any $v,w \in
 \mathscr{F}^n$. A symmetric bilinear form $g:\mathcal{V} \times
 \mathcal{V} \rightarrow \mathscr{F}$ is non-degenerate if and only if,
  for every nonzero $v \in \mathcal{V}$ there exists $w \in \mathcal{V}$
  so that $g(v,w) \neq 0$ [p.455]{golan}. Let
  $v=(v_1,v_2,\ldots,v_n)^T \in \mathscr{F}^n$ be nonzero. Suppose $i
 \in \{1,2,\ldots,n\}$ is the least integer so that $v_i$ is nonzero.
  Let $w=(0,\ldots,0,v_i,0,\ldots,0)^T \in \mathscr{F}^n$ (with $v_i$ in
  entry $i$ of $w$). Then $$f(v,w)=v^Tw=v_i^2 \neq 0,$$ since a field
  contains no divisors of zero. This proves that $f$ is non-degenerate
  for any field $\mathscr{F}$.
The right $f$-orthogonal complement [p.458]{golan} of row$(G)$ is
  \begin{eqnarray} \nonumber \text{row}(G)^{\perp_f}&=&\{w \in
 \mathscr{F}^n:f(v,w)=0 \text{ for all } v \in \text{row}(G) \} \\
 \nonumber &=& \{w \in \mathscr{F}^n:Gw=0 \} \\  &=& \text{N}(G).
  \end{eqnarray}

The theory can be studied in detail on page 455-458 of this textbook, which is the source referenced above. As you can see $f(v,w)$ is nondegenerate due to the fact that a field has no divisors of zero.
For a division ring the symmetric property would fail in general, but I don't actually think this is absolutely necessary: You can see in the proof above I mention the right $f$-orthogonal complement, and the last part would still hold in the absence of commutativity.


text:
Q: How to make sure that Bootstrap modal changes the height from down to up only? I want a fixed top for modal when the height is changed. This is the HTML code.

                    <button type="button" id="close-modal-btn" class="close" data-dismiss="modal"></button>

What do you want to do?

                        <button id="save-view-btn" class="btn-modal btn-links btn-active">Signup</button>
                        <button id="copy-link-btn" class="btn-modal btn-links">Login</button>

                        <form>
                            // Some content
                        </form>

        </div

This is CSS for modal
.vertical-alignment-helper {
    display: table;
    height: 100%;
    pointer-events: none;
    width: 100%;
}

.vertical-align-center {
    display: table-cell;
    pointer-events: none;
    vertical-align: middle;
}

The modal will have dynamic body depended on the content. Depended on content, modal's height should change. This CSS does it for me. The modal is centered and the height changes. But what I really need is, the modal should be centered and the height should change only from the bottom. Top position should be fixed.
I tried to change the display:table to display:flex, it gave me fixed position for the modal but modal was not centered.
How to do this ?


text:
Q: the difference between "must have + (past participle)" and "should have + (past participle)" The following is a question from the university entrance examination held in 2013 using the DNC Japan Test.
My brother (  ) have been very popular when he was a high school student.
He still gets lots of New Year's cards from his former classmates.
(1) must, (2) ought to, (3)should, (4) would
The correct answer is (1).
I wonder why (3)should can't be a correct answer.
If must is an answer, should must be another answer,
because both must and should have the meaning of necessity.

A: "Both must and should have the meaning of necessity" - but must have and should have have different meanings.
He must have been very popular = It's extremely likely that he was popular.
He should have been very popular = It seemed likely at the time that he would be popular (with the expected continuation ...but in fact he was not.)


text:
Q: Why is my Unity3D music player script playing my music only for one second? I am making a music player with Unity3D for a game project. I am having an issue with the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MusicManager : MonoBehaviour {

  public AudioSource music1;
  public AudioSource music2;

  private void Start() {
    music1.Play();
  }

  private void Update() {
    if (!music1.isPlaying) {
      music2.Play();
      music1.Pause();
    }

    if (!music2.isPlaying) {
      music1.Play();
      music2.Pause();
    }
  }
}

The problem I am having is that music1 is only played for one second and then there is a static sound. What is the problem here and how can I fix it?


text:
Q: document.evaluate on body node returns element out of body I'm currently using the following line of code to retrieve all the text nodes in the "body" element of a page:
document.evaluate("//text()[normalize-space(.) != '']", document.body, null, XPathResult.ANY_TYPE, null);

However, even though I specify "document.body" as the context node, I get some element contained in the "head" of the page.
How am I supposed to use "document.evaluate" to narrow it down to the body element without having to do it in the XPath query? (I guess it's possible as it seems to be the goal of the second argument)


text:
Q: Code runs correctly only when stepping through it with debugger?
Possible Duplicate:
Random number generator only generating one random number

I was a bit baffled with this few moments ago. I have the following code:
public blockType generateRandomBlock()
{
    Random random = new Random();
    int makeBlockOfType = random.Next(0, 100);

    blockType t = blockType.normal;
    if (makeBlockOfType <= 80 && makeBlockOfType >= 60)
    {
        t = blockType.blue;
    }
    else if (makeBlockOfType > 80 && makeBlockOfType <= 95)
    {
        t = blockType.orange;
    }
    else if (makeBlockOfType > 95 && makeBlockOfType <= 100)
    {
        t = blockType.green;
    }

    return t;
}

Fairly simple, it return an enum value based on a randomly generated number (based of system time). Unfortunately for some odd reason, I have all blocks either one color or the other even though this runs for every single block being put into the game. However, when I step through this with the debugger and then see the results after some run, I see that the blocks are now multi colored based on the chances provided. I am a little bit confused about why this is happening.
For this I am using MonoGame which uses the Mono compiler instead of the Microsoft one. Could this be the issue? I have tried to put this code inline into the constructor from where it is being called but I am getting the same result (I am guessing the compiler inlines the code anyways).
I have tried to restart Visual Studio it separately rather than letting the run do the build; no changes.
Any suggestions and help are greatly appreciated!

A: You should instanciate Random only once (set it as a private field and instanciate in the constructor), see the similar question : Random.Next returns always the same values
See the Random documentation :

The random number generation starts from a seed value. If the same
  seed is used repeatedly, the same series of numbers is generated

In your case, you create a Random instance with the same seed (too close in time) and you take the first value which will be the same for a given seed.

A: You are recreating your random number generator every time you call your method:
public blockType generateRandomBlock()
{
    Random random = new Random();

As the seed of the random number generator is based on the time this will return the same value for consecutive calls.
Move your creation of the generator outside the routine:
Random random = new Random();
public blockType generateRandomBlock()
{

A: When you create multiple instances of Random successively in a very brief period of time, they are likely to end up getting initialized with the same time-dependent seed value.
To work around this, you should initialize your Random as an instance field instead:
private readonly Random random = new Random();

public blockType generateRandomBlock()
{
    int makeBlockOfType = random.Next(0, 100);

    // ...
}


text:
Q: Stacked Wear notification shown on phone too I have 1 summary-notification and serveral stacked notifications.
For some reason the stacked notifications are not only shown on the
Andrid Wear device but also on the phone.
According to the documentation
Stacking Notifications
they should only display on the watch.
NotificationBuilder.setGroup is, of cause, set to the same value and only the summary has .setSummary(true).
Details:
http://marcuswolschon.blogspot.de/2015/05/implementing-k9-mail-wear-support.html
Code:
https://github.com/k9mail/k-9/blob/73ec00b43db81038805999f5642961ae9005d6bc/k9mail/src/main/java/com/fsck/k9/controller/MessagingController.java#L4941

A: Replace NotificationManager with NotificationManagerCompat
Use NotificationManager
private void send() {
    Notification notification1 =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("News1")
                    .setGroup("News")
                    .setContentText("Text")
                    .build();

    Notification notification2 =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("News2")
                    .setGroup("News")
                    .setContentText("Text2")
                    .build();

    NotificationManager notificationManager = (NotificationManager)
            getSystemService(NOTIFICATION_SERVICE);

    notificationManager.notify(1 , notification1);
    notificationManager.notify(2 , notification2);

    Notification Summary = new NotificationCompat.Builder(this)
            .setContentTitle("2 new News")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Text2")
            .setGroup("News")
            .setGroupSummary(true)
            .build();

    notificationManager.notify(-1 , Summary);
}

Use NotificationManagerCompat
private void send() {
    Notification notification1 =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("News1")
                    .setGroup("News")
                    .setContentText("Text")
                    .build();

    Notification notification2 =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("News2")
                    .setGroup("News")
                    .setContentText("Text2")
                    .build();

    NotificationManagerCompat notificationManager =
            NotificationManagerCompat.from(this);

    notificationManager.notify(1 , notification1);
    notificationManager.notify(2 , notification2);

    Notification Summary = new NotificationCompat.Builder(this)
            .setContentTitle("2 new News")
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentText("Text2")
            .setGroup("News")
            .setGroupSummary(true)
            .build();

    notificationManager.notify(-1 , Summary);
}


text:
Q: Password criteria 3 out of 4 I'm trying to write a password validator. The password has the following criteria.

*

*At least 7 characters.

*And should include 3 out of 4 of the following:

*

*A number

*A Upper Case

*A lower Case

*A special character (e.g., ! @ # )

The current regex:
/(^(?=.[^!@#$%^&*()'":;]{6,128}$)(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).*)/

Is there any way to write the regex for meeting 3 out of 4 password requirements?

A: For all 4, you're looking for this:
/^(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z])(?=.*[^A-Za-z0-9\s])(?=.{7,})/

Multiple positive lookaheads for each of the conditions you listed.
If you want 3 out of the 4, you can write the permutations of three of the four, which gets really messy:
/^((?=.*?[A-Z])(?=.*?[a-z])(?=.*[^A-Za-z0-9\s])|(?=.*?[0-9])(?=.*?[a-z])(?=.*[^A-Za-z0-9\s])|(?=.*?[0-9])(?=.*?[A-Z])(?=.*[^A-Za-z0-9\s])|(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z]))(?=.{7,})/

Run an example if you like:

var regex = /^((?=.*?[A-Z])(?=.*?[a-z])(?=.*[^A-Za-z0-9\s])|(?=.*?[0-9])(?=.*?[a-z])(?=.*[^A-Za-z0-9\s])|(?=.*?[0-9])(?=.*?[A-Z])(?=.*[^A-Za-z0-9\s])|(?=.*?[0-9])(?=.*?[A-Z])(?=.*?[a-z]))(.{7,})/
pw = document.getElementById("pw");
pw.oninput = function(e) {
  if (regex.test(e.target.value)) {
    pw.className = "valid";
  } else {
    pw.className = "invalid";
  }
};
html {
  font-family: sans-serif;
}
input {
  border: 1px solid #a0a0a0;
  padding: 5px;
  outline: none;
}

input.invalid {
  border: 1px solid #c0392b;
}

input.valid {
  border: 1px solid #27ae60;
}
<label>Type a password: <input id="pw" type="text"/></label>

If you want my opinion, these are really frustrating for the user. I'd just put a minimum length of 8 characters and leave password security to them.


text:
Q: SQL INSERT INTO random commas appearing One a game I am making I have a saving bug. I have an alert with the PHP message. It gives me an SQL error. The problem is obvious. That last comma before the parentheses shouldn't be there. The question is why is it there? In my code, it isn't.
This is the alert message.

The statement is like this.
> $query2 = "INSERT INTO users VALUES ('$village', $power, $influence, $gold, NULL, $ore, $wood, $food, $honor, $keep, $mine, $sawmill, $farm, $barracks, $tavern, $stables, $temple, $militia, $warriors, $spearmen, $clubmen, $swordsmen, $archers, $vanguards, $legion, $crossbowmen, $knights, $mercs, $mercelites, $bandit1, $bandit2, $bandit3, '$faction', $dwellings, $dwellingscost);";

One of my theories was that the dwellingscost variable had a comma at the end. It is posted from an AJAX request. If you need some of that code to decipher just ask.


text:
Q: Serializing a class that contains other classes I have created a custom imagelist class in VB.NET, and I would like to serialize / deserialize it.
Imports System.Xml.Serialization

<Serializable()>
Public Class clsImageList

    Public Images As New List(Of clsImageItem)

    Public Sub Add(ByVal uGUID As String, ByRef uImage As Image)

        Dim nItem As New clsImageItem(uImage, uGUID)

        Images.Add(nItem)

    End Sub
    Public Function Image(ByVal uIndex As Integer) As Image

        Return Images.Item(uIndex).Image

    End Function

End Class
Public Class clsImageItem

    Public ReadOnly Property [Image] As Image
    Private _sGUID As String

    Public Sub New(uImage As Image, uGUID As String)

        Image = uImage
        _sGUID = uGUID

    End Sub

End Class

Using a regular ImageList, I did it like that:
Public Function ImageListToBytes(ByRef uImageList As ImageList) As Byte()

    Try
        Using ms As New MemoryStream
            Dim bf As New BinaryFormatter()
            bf.Serialize(ms, uImageList.ImageStream)

            Return ms.ToArray
        End Using
    Catch ex As Exception

        Debug.Assert(False)
        Return Nothing
    End Try

End Function

Public Sub BytesToImageList(ByRef uBytes() As Byte, ByRef uImageList As ImageList)

    Using ms As New MemoryStream()

        ms.Write(uBytes, 0, uBytes.Length)
        ms.Seek(0, SeekOrigin.Begin)

        Dim bf As New BinaryFormatter
        uImageList.ImageStream = DirectCast(bf.Deserialize(ms), ImageListStreamer)
    End Using

End Sub

Can somebody tell me how I can serialize / deserialize my clsImageList?

A: The first thing you should do is marking your clsImageItem also Serializable.
Then try serialize and deserialize clsImageList class. so in your serialization and deserialization methods, pass an instance of clsImageList and serialize and deserialize it.
Public Function ImageListToBytes(ByRef c As clsImageList) As Byte()
    Try
        Using ms As New MemoryStream
            Dim bf As New BinaryFormatter()
            bf.Serialize(ms, c)

            Return ms.ToArray
        End Using
    Catch ex As Exception
        Debug.Assert(False)
        Return Nothing
    End Try
End Function

Public Sub BytesToImageList(ByRef uBytes() As Byte, ByRef c As clsImageList)
    Using ms As New MemoryStream()
        ms.Write(uBytes, 0, uBytes.Length)
        ms.Seek(0, SeekOrigin.Begin)

        Dim bf As New BinaryFormatter
        c = DirectCast(bf.Deserialize(ms), clsImageList)
    End Using
End Sub


text:
Q: How to target first child in within an element I want to target the first child of an element which is nested within and element with css

hello

css: tried
.message-send .msg-text> *:first-child {
  border-top-right-radius:.999em;
}

I want to target '.msg-text' as the first child of '.message-send'
i tried
but did not work

A: div div > :first-child

this will affects the direct first-child of parent (second div)
div div :first-child

this will affects each firs-child of children

p{
margin:0;
background:green;
}
span{
display:block;
}
div{
  background:blue;
  padding:10px;
  color:#fff!important;
}
div div > :first-child{
  background:red;
  display:block;
  width:100px;
}

       1

2

3

    22


text:
Q: Insert items with rest into a read only list? So i have this problem. I want my list to be read only for everyone (maybe not administrators). So far i can just set some permissions and work is done. But then i want to be able to upload items using the Rest Services. I know how to upload items it's not a problem. But I want to be able to upload them to a read only list... Is this even possible?
I thought about creating a workflow that would change the item permissions once an item is created and set it to read only. But then it means that you can create items in the list from sharepoint so the list isn't read only. Items once created from rest would, i assume, start the workflow and set the item permission level. But then you would also be able to create items directly from sharepoint (which i don't want).
So far i can't think of a solution.
I've seen people changing list permissions between read only and edit with rest but that's just so risky it's not a viable solution for me.
Do you have any ideas how this could be achieved?
I know that i could do like some crazy look ups but with 20+ columns it means you would have 20+ look ups so threshold would block it and infopath forms would stop working so that wouldn't work neither.


text:
Q: ImportError: No module named Cython.Distutils (But there is) I have Cython 0.20 installed, and can do 'from Cython.Distutils import build_ext' from a python interpreter, so I don't understand
the below error, when I am trying to build an apk with buildozer. My log_level in buildozer.spec is set to 2 already. It appears to be trying to install jnius into a virtualenv(unless i'm mistaken).. I assume this is normal, as I haven't set up any myself. Any suggestions? I've googled around to no avail. My OS is Ubuntu 15.04.
The following is the tail end of the output from the command:
buildozer --verbose android debug deploy run

..
 # Install distribute
    # Run 'curl http://python-distribute.org/distribute_setup.py | venv/bin/python'
    # Cwd /home/yerman/PycharmProjects/genius/.buildozer
      % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                     Dload  Upload   Total   Spent    Left  Speed
      0     0    0     0    0     0      0      0 --:--:--  0:00:16 --:--:--     0
    # Install requirement jnius in virtualenv
    # Run 'pip install --download-cache=/home/yerman/.buildozer/cache --target=/home/yerman/PycharmProjects/genius/.buildozer/applibs jnius'
    # Cwd /home/yerman/PycharmProjects/genius/.buildozer
    DEPRECATION: --download-cache has been deprecated and will be removed in the future. Pip now automatically uses and configures its cache.
    Collecting jnius
      Using cached jnius-1.0.2.tar.gz
        Complete output from command python setup.py egg_info:

        You need Cython to compile Pyjnius.

        Traceback (most recent call last):
          File "<string>", line 20, in <module>
          File "/tmp/pip-build-_tfhLW/jnius/setup.py", line 32, in <module>
            from Cython.Distutils import build_ext
        ImportError: No module named Cython.Distutils

        ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-_tfhLW/jnius
    # Command failed: pip install --download-cache=/home/yerman/.buildozer/cache --target=/home/yerman/PycharmProjects/genius/.buildozer/applibs jnius
    #
    # Buildozer failed to execute the last command
    # The error might be hidden in the log above this error
    # Please read the full log, and search for it before
    # raising an issue with buildozer itself.
    # In case of a bug report, please add a full log with log_level = 2


text:
Q: запуск скриптов на виртуальной машине виндовс посредством jenkins В среде vSphere создано огромное количество виртуальных машин на базе виндовс 10. Среди них есть jenkins сервер. Вход на vsphere только с VPN. Необходимо при билде jenkins-job запускать PowerShell скрипт на определенной виртуальной машине (как я понимаю имя/ip, креды входа виртуальной машины можно использовать как переменные). Пожалуйста, объясните непросвященному каким образом происходит подключение к vsphere, к ОПРЕДЕЛЕННОЙ виртуальной машине и как на ней запустить скрипт? Какие настройки нужно сделать на виртуалке вин10 и непосредственно плагины для jenkins?

A: Важно чтобы виртуалки с Windows имели доступ к Jenkins master (а не наоборот). Нужно обеспечить это условие, а дальше по инстукции.
На Windows инициатором подключения может являться slave. Slave может устанавливаться как служба.


text:
Q: I need to know why? and If I change this line to "println(name+two)" error solved? fun main(args:Array<String>){
    val two=2
    val name:String?
    name="Mensh"
    println(two+name)
}

This is a simple kotlin app and I got the error on println(two+name):
Error:(8, 16) Kotlin: None of the following functions can be called with the arguments supplied:
public final operator fun plus(other: Byte): Int defined in kotlin.Int
public final operator fun plus(other: Double): Double defined in kotlin.Int
public final operator fun plus(other: Float): Float defined in kotlin.Int
public final operator fun plus(other: Int): Int defined in kotlin.Int
public final operator fun plus(other: Long): Long defined in kotlin.Int
public final operator fun plus(other: Short): Int defined in kotlin.Int

A: The reason this doesn't compile in Kotlin is because there is no implicit conversion of a numeric to a String when concatenating, unlike in Java.
For example, this would compile:
fun main(args:Array<String>) {
    val two = 2
    val name = "Mensh"
    println(two.toString() + name)
}

As others have mentioned, string templates would be a more idiomatic way of doing this.

A: The other answers are giving you the solution, but are not explaining your error.
Error:(8, 16) Kotlin: None of the following functions can be called with the arguments supplied:
public final operator fun plus(other: Byte): Int defined in kotlin.Int
public final operator fun plus(other: Double): Double defined in kotlin.Int
public final operator fun plus(other: Float): Float defined in kotlin.Int
public final operator fun plus(other: Int): Int defined in kotlin.Int
public final operator fun plus(other: Long): Long defined in kotlin.Int
public final operator fun plus(other: Short): Int defined in kotlin.Int

Kotlin has operator overloading for + operator.
println(two+name): Here the compiler tries to use the plus operator overloaded function of Int which has a String paramter, but there are no such function. Hence you get the above error. You can see all the plus operator overloaded function in the error above.
println(name+two): But String has a plus operator overloaded function which accepts Any? parameter. So you are not getting any error. This is the plus operator overloaded function of String:
public operator fun plus(other: Any?): String

A: Kotlin has its own style of formatting Strings, try:
println("$two$name")

A: In Kotlin, you can concatenate using string templates:
val c = "$two $name"
print(c)

Other info here.


text:
Q: How can I use the app engine SDK dev_server.py to serve services from different repos? So what I want is this:
~/
  API service/
    App.yaml
    A big ol Python back end for a rest api/
    Dispatch.yaml
       /API -> default
       /* -> frontend static service
  Frontend static site/
     App.yaml
     Index.html
     Bundle.js <- a client side SPA. Talks to other thing via API calls

Note that the front end and backends are completely segregated directories. They do not know about each other at all. I want to run dev_server on my machine, such that my local environment knows about my dispatch.yaml rules, and correctly routes requests accordingly between different ports. But there is no Python app or anything in the front end. It's just an HTML file that loads a script tag. App engine knows how to serve that in prod. I don't see how to do it locally though.
Can it be done? What's the command? Do I run dev_server in both directories? Do I feed both app.yamls to a single command run from above both repos? I just don't get this. The docs are so opaque.


text:
Q: Spring Boot beans overriding I want to override some beans in my integration test.
But I do not want some beans from production configuration were initialized before.
Note: Not only override them and use in tests but stop initialization.
I know that is possible to override beans but they still initialize before running integration test.
Is there any config property for that?
Thanks!
PS. I use Spring Boot 2.5.x


text:
Q: Why does getCurrentListViews().size() equal 2 instead of 3? I am writing an android application with a tabbed interface. I am using a FragmentActivity with a ActionBar.Tab tabs, with each tab displaying a ListFragment.
In my test case, I am using Robotium 3.6 to perform UI interaction, which is needed to test certain aspects of my fragment's. Each fragment has a separate test method, which tests that the ListView for a fragment has the same content at a set index (0), as the ArrayList<String> which the data is from.
The problem is that while the first two fragments pass their respective tests, the final fragment does not, with the failure trace being that:
junit.framework.AssertionFailedError: AbsListView with index 2 is not available!
at com.jayway.android.robotium.solo.Waiter.waitForAndGetView(Waiter.java:362)
at com.jayway.android.robotium.solo.Clicker.clickInList(Clicker.java:405)
at com.jayway.android.robotium.solo.Solo.clickInList(Solo.java:1004)
at com.******.*******.test.ActivityNavigatorTest.testFragmentSongsList(ActivityNavigatorTest.java:62)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.InstrumentationTestCase.runMethod(InstrumentationTestCase.java:214)
at android.test.InstrumentationTestCase.runTest(InstrumentationTestCase.java:199)
at android.test.ActivityInstrumentationTestCase2.runTest(ActivityInstrumentationTestCase2.java:186)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:537)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1551)

Here is the relevant code for the activity being tested:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_navigator);

    PREFERENCES = PreferenceManager.getDefaultSharedPreferences(getBaseContext());

    adapterPager = new AdapterPager(getSupportFragmentManager());

    viewPager = (ViewPager) findViewById(R.id.pager);
    viewPager.setAdapter(adapterPager);
    viewPager.setOnPageChangeListener(new SimpleOnPageChangeListener() {
        @Override
        public void onPageSelected(int position) {
            super.onPageSelected(position);
            getActionBar().setSelectedNavigationItem(position);
        }
    });

    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    actionBar.addTab(actionBar.newTab().setText(R.string.title_fragment_artists).setTag("artists").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText(R.string.title_fragment_albums).setTag("albums").setTabListener(this));
    actionBar.addTab(actionBar.newTab().setText(R.string.title_fragment_songs).setTag("songs").setTabListener(this));
}

The code for each ListFragment is just defining an ArrayList<String>, populating it with dummy content and displaying said content with an ArrayAdapter<String>. Here is the code for the test case:
package com.******.*******.test;

import android.test.ActivityInstrumentationTestCase2;

import com.******.******.ActivityNavigator;
import com.*******.******.FragmentAlbums;
import com.*******.********.FragmentArtists;
import com.*******.******.FragmentSongs;
import com.jayway.android.robotium.solo.Solo;

public class ActivityNavigatorTest extends ActivityInstrumentationTestCase2<ActivityNavigator> {

    private Solo solo;

        public ActivityNavigatorTest() {
        super(ActivityNavigator.class);
    }

    protected void setUp() throws Exception {
        solo = new Solo(getInstrumentation(), getActivity());
    }

    protected void tearDown() throws Exception {
        solo.finishOpenedActivities();
    }

    public void testFragmentArtistsList() {
        solo.assertCurrentActivity("Checking loaded activity is the navigator", ActivityNavigator.class);
        solo.clickOnText("Artists");

        String contentExpected = FragmentArtists.getArtistList().get(0);
        String contentActual = solo.clickInList(0, 0).get(0).getText().toString();

        assertEquals("Testing index 0 has same content in ArrayList and ListView", contentExpected, contentActual);

        int sizeExpected = FragmentArtists.getArtistList().size();
        int sizeActual = solo.getCurrentListViews().get(0).getCount();

        assertEquals("Testing same quantity of data in ArrayList and ListView", sizeExpected, sizeActual);
    }

    public void testFragmentAlbumsList() {
        solo.assertCurrentActivity("Checking loaded activity is the navigator", ActivityNavigator.class);
        solo.clickOnText("Albums");

        String contentExpected = FragmentAlbums.getAlbumList().get(0);
        String contentActual = solo.clickInList(0, 1).get(0).getText().toString();

        assertEquals("Testing index 0 has same content in ArrayList and ListView", contentExpected, contentActual);

        int sizeExpected = FragmentAlbums.getAlbumList().size();
        int sizeActual = solo.getCurrentListViews().get(1).getCount();

        assertEquals("Testing same quantity of data in ArrayList and ListView", sizeExpected, sizeActual);
    }

    public void testFragmentSongsList() {
        solo.assertCurrentActivity("Checking loaded activity is the navigator", ActivityNavigator.class);
        solo.clickOnText("Songs");

        String contentExpected = FragmentSongs.getSongList().get(0);
        String contentActual = solo.clickInList(0, 2).get(0).getText().toString();

        assertEquals("Testing index 0 has same content in ArrayList and ListView", contentExpected, contentActual);

        int sizeExpected = FragmentSongs.getSongList().size();
        int sizeActual = solo.getCurrentListViews().get(2).getCount();

        assertEquals("Testing same quantity of data in ArrayList and ListView", sizeExpected, sizeActual);
    }
}

A: I have a theory but i am not sure it is correct. I believe that your application has each fragemnt displayed one at a time in the view pager right?
Well i believe that possible the first two test cases work by chance more than anything. I believe that only one listview should be being shown at a time and for some reason an extra listview (potentially the one previously seen) is being kept by robotium that means that the count is always two. You can verify this by looking at the hierarchyviewer tool and seeing what listviews are being shown in your application.
The alternative I have for you is to set good ids (or tags/content descriptions) on the different listviews and use these rather than robotiums getCurrentListViews() method which is prone to these sort of issues.


text:
Q: What is the purpose of creating "Mappings" in CloudFormation? See the code below:
Mappings:
    RegionMap:
        us-east-1:
            bucketname: s3bucketname-us-east-1
        us-east-2:
            bucketname: s3bucketname-us-east-2
        us-west-1:
            bucketname: s3bucketname-us-west-1
        us-west-2:
            bucketname: s3bucketname-us-west-2
        ap-south-1:
            bucketname: s3bucketname-ap-south-1
        ap-northeast-2:
            bucketname: s3bucketname-ap-northeast-2
        ap-southeast-1:
            bucketname: s3bucketname-ap-southeast-1
        ap-southeast-2:
            bucketname: s3bucketname-ap-southeast-2
        ap-northeast-1:
            bucketname: s3bucketname-ap-northeast-1
        ca-central-1:
            bucketname: s3bucketname-ca-central-1
        eu-central-1:
            bucketname: s3bucketname-eu-central-1
        eu-west-1:
            bucketname: s3bucketname-eu-west-1
        eu-west-2:
            bucketname: s3bucketname-eu-west-2
        eu-west-3:
            bucketname: s3bucketname-eu-west-3
        eu-north-1:
            bucketname: s3bucketname-eu-north-1
        sa-east-1:
            bucketname: s3bucketname-east-1
        af-south-1:
            bucketname: s3bucketname-south-1
        ap-east-1:
            bucketname: s3bucketname-east-1
        ap-northeast-3:
            bucketname: s3bucketname-ap-northeast-3
        eu-south-1:
            bucketname: s3bucketname-eu-south-1
        me-south-1:
            bucketname: s3bucketname-me-south-1

Resources:
    StateS3Bucket:
        Type: AWS::S3::Bucket
        Properties:
            BucketName: !Sub "cfntf-${AWS::Region}-${AWS::AccountId}"

There is more to this code however I've only included the relevant snippets for the question.
To summarize - why include mappings for bucketname when the bucketname  is set directly, using region and account ID in the 'Resources' section?
There is use of the Fn::FindInMap function which is used here as part of the ExecutorLambdaFunction:
ExecutorLambdaFunction:
        Type: AWS::Lambda::Function
        Properties:
            FunctionName: myfunction
            Handler: index.handler
            Role: !GetAtt ExecutorLambdaServiceRole.Arn
            Environment:
                Variables:
                    BUCKET: !Ref StateS3Bucket
            Code:
                S3Bucket: !If
                  - S3Defined
                  - !Ref S3Bucket
                  - Fn::FindInMap:
                      - RegionMap
                      - !Ref AWS::Region
                      - bucketname
                S3Key: !If
                  - S3Defined
                  - !Ref S3Key
                  - /app.zip
            Runtime: python3.8

A: StateS3Bucket is being built from the region and account ID but that has nothing to do with the Mappings section.
The mappings, in this case, are being used to provide the correct region-specific S3 bucket name for where the packaged source code for ExecutorLambdaFunction exists - that is why Fn::FindInMap is being used in the Lambda declaration.

Sometimes you may want to have dynamic values based on specific keys - the CloudFormation Mappings section is the perfect solution to this problem.
Your packaged Lambda (the source code) is pointing to an S3 location in this case & as S3 buckets are region-specific, you need a way of getting the correct bucket name for the region that the stack is being deployed in.
The code for the ExecutorLambdaFunction must be loaded from the S3 bucket in the relevant region otherwise it won't work.
For example, trying to load the Lambda source code from a bucket in us-east-1 won't work when your Lambda is deployed in eu-west-2 (note: it will work if it is deployed in us-east-2 as while that is in another availability zone, it is still within the same region).
Even if you only intend to have your stack in one region only, it won't harm you to have a Mappings section as it will future proof your CloudFormation template.
If you don't have any region-specific infrastructure (quite rare but e.g. only creating IAM roles which are global & are set at an account-level), then you can not include one.
You'll spend much more time trying to add one in later than if you just spent an extra 3 minutes defining & using Mappings as you write your template - you'll thank yourself if you later decide to deploy your stack in another region.


text:
Q: Why would Z/P cancellation with real part > 0 between the plant and the controller make the system unstable?
Can someone help me verify the claim if there is a zero pole cancellation with real part > 0 between controller Gc and plant Gp, then the system is not stable?
I can't find any literature that confirms or denies this claim.

A: If it were possible to place a zero at EXACTLY the same location as a right half plane pole then the pole would be cancelled. However, exact placement is not achievable practically. The result is a pole and zero very close together on the positive real axis of the s-plane. Consequently, the root locus will have a branch on the positive real axis, going from the pole to the zero, which will give an unstable closed-loop. The zero, essentially, traps the pole in the right half plane.
If, instead, the zero were placed at an appropriate position on the real NEGATIVE axis, the root locus would have the capacity of moving the unstable pole into the left half plane and hence provide a stable closed loop.
Consider the very simple case of an open-loop with a single pole at s=1, i.e. an OLTF:
G(s) = 1/(s-1)
Placing a zero at, say, s=0.9 would give an OLTF:
G(s)=(s-0.9)/(s-1) and a CLTF = (s-0.9)/(2s-1.9), which is unstable.
However, placing a zero at s=-2 would give an OLTF:
G(s)=(s+2)/(s-1) and a CLTF = (s+2)/(2s+1) which has a stable closed-loop pole; ie, the unstable open loop pole at s=1 has been dragged into the left-hand plane by the zero, and now lies at s=-0.5

A: This wouldn't be universally true..
One case where it would be true is if the Plant is actually unstable (due to a pole) & the idea is to cancel it out by including a zero in the controller.  Can you truly cancel out that rogue pole on the right?  no...  you will still have stability concerns
Ideal case (zero exactly on the pole) or practical case (zero just off the pole) still ends up with an unstable system. The only difference is how long it takes for the instability to arise. Never the less a time-dependent stability is still an instability
Consider a plant with a TF:  \$\frac{1}{s^2-1}\$  A second order system. This has poles at +1 and -1
That pole at +1 is a problem,  the right of the origin and thus... unstable.  So why not cancel it out with a zero at +1 from a controller..
Thus a controller would have a TF:   s-1
This produces a closed-loop transfer function of:  \$\frac{s-1}{s^2+s-2}\$
If this was simulated:
s = tf('s');
P=1/(s^2-1);
sys = feedback((s-1)*P,1)
step(sys,100)

This wolfrum alpha link also shows it:
http://m.wolframalpha.com/input/?i=transfer+function+%28s-1%29%2F%28s%5E2%2Bs-2%29&x=0&y=0
If you extend the time of the Unit step response plot you will see its response become undesirable.
--edit--
Take a transfer function \$H = \frac{s-1}{s^2+2s-3}\$
This has a pole at +1 so a 1st thought would be to cancel this pole with a zero at +1 to create:
\$H = \frac{1}{s+3}
Should this system be stable? 1st thought would be yes as it only has one pole. However
The differential equation for this is
\$\ddot{y} + 2\dot{y} - 3y = \dot{u} - u \$
This can further be manipulated to produce:
\$\frac{y_o}{4}(e^{-3t}+e^t)\$
notice that \$e^t\$ term?
http://www.cs.mun.ca/~av/courses/7825-s14/manual_uploads/pole_zero_canc.pdf


text:
Q: recursive sequentially powerset function in python what I expect for [1,2,3] ->
[1]
[1, 2]
[1, 2, 3]
[1, 3]
[2]
[2, 3]
[3]

but my function give this result, I can not fix it ->
def foo(L,first,last,Output):
    if first>=last:
        return
    for i in range(first ,last):
        print(Output+[L[i]])
        foo(L,first+1,last,Output+[L[i]])

foo([1,2,3],0,3,[])

[1]
[1, 2]
[1, 2, 3]
[1, 3]
[1, 3, 3]
[2]
[2, 2]
[2, 2, 3]
[2, 3]
[2, 3, 3]
[3]
[3, 2]
[3, 2, 3]
[3, 3]
[3, 3, 3]

and in some situation I want to stop calculation and continue with others:
let say if 1 and 2 get come together , dont continue anymore
-> for [1,2,3] and (1,2)
what I expect :
[1]
[1, 3]
[2]
[2, 3]
[3]

iterative function is also good for me

A: inductive reasoning
Another way to think about the problem doesn't involve ranges, indexes or incrementing them, leading to many off-by-one errors. Instead we can reason about the problem inductively -

*

*If the input t is empty, yield the empty set

*(inductive) t has at least one element. For all p in the recursive sub-problem powerset(t[1:]), yield p and yield p with the first element, t[0] prepended.

def powerset(t):
  if not t:
    yield ()                       # 1. empty t
  else:
    for p in powerset(t[1:]):      # 2. at least one element
      yield p
      yield (t[0], *p)

By using yield we move the desired effect outside of the powerset function. This allows the caller to decide what happens with each produced set -
for p in powerset("abc"):
  print(p)                   # <- desired effect

()
('a',)
('b',)
('a', 'b')
('c',)
('a', 'c')
('b', 'c')
('a', 'b', 'c')

for p in powerset("abc"):
  print("".join(p))     # <- different effect

a
b
ab
c
ac
bc
abc

changing the order
I just want to process sequentially as I showed in the example.
The particular order you asked for can be achieved by reordering the yields. I also made an adjustment to remove the empty set from the output -

*

*if the input t is empty, stop

*(inductive) t has at least one element

*

*yield the singleton set of the first element, t[0]

*prepend the first element to each result of the sub-problem powerset(t[1:]) and yield

*yield each result of the sub-problem powerset(t[1:])
def powerset(t):
  if not t:
    return                 # 1.
  else:
    yield (t[0],)          # 2.
    yield from map(lambda p: (t[0], *p), powerset(t[1:]))
    yield from powerset(t[1:])

Notice above we compute powerset(t[1:]) twice. This is wasteful and can be avoided using itertools.tee -
from itertools import tee

def powerset(t):
  if not t: return
  yield (t[0],)
  left, right = tee(powerset(t[1:]))          # <- tee left & right
  yield from map(lambda p: (t[0], *p), left)  # <- left
  yield from right                            # <- right

for p in powerset("abc"):
  print(p)

('a',)
('a', 'b')
('a', 'b', 'c')
('a', 'c')
('b',)
('b', 'c')
('c',)

list of all subsets
Is it possible to do it without using yield? I need to keep it in a global list
Python uses iterables throughout its standard library. The prescribed way is to use yield however it's easy to convert to list using list -
result = list(powerset("abc"))
print(result)

[('a',), ('a', 'b'), ('a', 'b', 'c'), ('a', 'c'), ('b',), ('b', 'c'), ('c',)]

without using yield
If you have some compelling reason where powerset must return an array instead of an iterable, the transformation is elementary. Notice the structure of the program is identical -
def powerset(t):
  if not t: return []
  result = list(powerset(t[1:]))
  return [
    (t[0],),
    *map(lambda p: (t[0], *p), result),
    *result
  ]

print(powerset("abc"))

[('a',), ('a', 'b'), ('a', 'b', 'c'), ('a', 'c'), ('b',), ('b', 'c'), ('c',)]