text:
Q: $1/r^2$ force and "photon decay" Background: My question is about the interpretation of the $1/r^2$ force in terms of the fundamental processes of the underlying QFT. We know that if the photon had mass $m$, then we may have a "massive" version of QED that is still renormalizable but has no gauge freedom (the photon mass term kills the gauge symmetry explicitly).
Assuming such a theory, we would observe a modification of the Coulomb law between two charges, namely the Yukawa potential $~e^{-mr}/r$ instead of the usual $~1/r$.
Massless photon case: Now, the $1/r$ potential gives rise to a force that goes as $~1/r^2$. This force decreases as the area of the sphere of radius $r$, indicating that the force $~1/r^2$ is a purely geometrical fact of 3 spatial dimensions: intuitively, we emit $N$ photons from a point and the force decreases with the surface density of the photons on the sphere of radius $r$, see this answer. This works if $N$ is constant, i.e. there should be no diagrams that look like a "photon decay".
Massive photon case: Let's come back to the massive case. It looks like $N$ should decrease with $r$, in such a way as to reproduce the Yukawa potential. However, massive and massless QED look like having the same vertex diagrams (but different propagators).
Question: If the difference between the two theories is only in the photon's propagator, does it mean that the intuitive interpretation linking $1/r^2$ and the conservation of $N$ is misleading, or even wrong?
Is it possible to make the above intuitive argument more precise by considering the different behaviour of the photon number operators in the massless and massive cases?
Note: see this answer for the standard derivation of the $1/r$ electric potential. This question is about the interpretation in terms of photon exchange, not about this well-known calculation.

A: *

*In a nutshell, to recover the static Yukawa potential between 2 points in 3 spatial dimensions, one should consider the 2-point correlation function/Greens function$^1$
$$G(\vec{r})
~=~\frac{e^{-mr}}{4\pi r}, \qquad (-\vec{\nabla}^2+m^2)G(\vec{r})~=~\delta^3(\vec{r}),\tag{1}
$$
in the static picture, cf. e.g. Wikipedia & this Phys.SE post.

*Example: For a scalar field in 3+0D, the partition function is
$$\begin{align} e^{-\beta F[J]}~=~~& Z[J]\cr
~=~~&\int \! {\cal D}\phi~\exp\left\{\beta \int\! d^3r  \left(-\frac{1}{2}\phi(-\vec{\nabla}^2+m^2)\phi +J\phi\right)\right\} \cr
~\stackrel{\begin{array}{c}\text{Gauss.}\cr\text{int.}\end{array}}{\sim}&
\exp\left\{\frac{\beta}{2}\int\! d^3r\int\! d^3r^{\prime}J(\vec{r})G(\vec{r}-\vec{r}^{\prime})J(\vec{r}^{\prime}) \right\}.
\end{align} \tag{2}$$
Given 2 Dirac delta function point-sources
$$ J(\vec{r})~=~q_1\delta^3(\vec{r}\!-\!\vec{r}_1) +q_2\delta^3(\vec{r}\!-\!\vec{r}_2),\tag{3}$$
the free energy (excluding self-interactions) is the Yukawa potential energy
$$ F[J]~\stackrel{(2)+(3)}{=}~-q_1q_2G(\vec{r}_1\!-\!\vec{r}_2).\tag{4}$$

*For what it's worth, in the "exchange particle decay picture" (that OP asks about) the mass $m$ can be interpreted as an attenuation coefficient of virtual exchange particles. In terms of Feynman diagrams, the mass-term in the action (2) can be seen as a 2-vertex. The only connected Feynman diagrams are necklaces where the mass 2-vertices play the role of pearls.
--
$^1$ Here we work in units where $\hbar=1=c$.

A: I find the "intuitive number" argument to be very misleading. One argument against it is... what is $N$? In fact the state of the electrostatic field around a point particle is a coherent state, which is a superposition of states with different numbers of particles. So it's not really possible to say that there are a definite number of photons "spreading out" from a central source. Additionally, as you point out, I don't see a good reason why the intuitive argument would fail for massive photons. Third, in the particle model, for finite $N$, you would expect the law to break down for large enough distance from the source -- you would expect to have "shot noise" in the force as the "rate" of photons arriving in a given spherical area decreased because the photons will have become spread very thin over a large spherical area; this has never been observed. Finally, the photons that appear in this kind of "static" force are actually virtual particles, not real particles, which is to say that they aren't really "propagating particles" but more like a colorful set of words to describe mathematical terms in a perturbative expansion, which don't need to obey things like continuity equations that hold on shell (e.g., when the classical equations of motion are satisfied).
The straightforward explanation for the $1/r^2$ vs Yukawa suppression, is simply that these force laws follow from the Green's functions (aka propagators) for the massless and massive Poisson equations, respectively.
If you want to look for a deeper explanation as to why massive and massless particles behave differently, in my view, the $1/r^2$ law is really a consequence of Gauss's Law
\begin{equation}
\nabla \cdot \vec{E} = \frac{\rho}{\epsilon_0} \implies E \sim \frac{1}{r^2}\ \ {\rm (point\ charge)}
\end{equation}
and in fact Gauss's law is deeply tied to the masslessness of the photon. In the Hamiltonian formulation of electrodynamics, Gauss's law is a first class constraint associated with the $U(1)$ gauge invariance of the photon. For the massive case, because the gauge invariance is broken, this first class constraint becomes two second class constraints, and Gauss's law no longer holds in its original form. In turn, this means that there is nothing that forces the field to fall off as $1/r^2$, and allows for the Yukawa solution to exist.
You may wonder about scalar fields, which do not have gauge invariance, but still have a difference between a $1/r^2$ behavior exhibited by massless scalar fields, and a Yukawa suppression for massive scalar fields. In fact there is also a symmetry explanation here. A massless scalar field has a shift symmetry under $\phi \rightarrow \phi + c$, which guarantees that the equations of motion can be written in the form of a total divergence. This total divergence plays the role of Gauss's law. A massive scalar breaks the shift symmetry and correspondingly has a different behavior.

A thought struck me while walking. I think this question comes from a similar place as the aether theory of the late 1800s -- an attempt to explain features of (what we now call) relativistic field theory with mechanical models. In your case you want to explain the inverse square law with particles spreading out in space, in the aether case people wanted to explain the medium in which electromagnetic waves are supposedly traveling. I think the modern response to both the "intuitive particle" argument and the aether idea are the same: we have found that mechanical models are both unnecessary and often misleading in describing relativistic field theories. What really matters are the equations satisfied by the fields. While these equations can be used to describe mechanical systems (for example Gauss's law can be used to describe some systems in fluid mechanics), the laws themselves are more general than the specific systems they can be applied to, and there is no need for there to be a mechanical model underlying these equations when they are applied in field theory. The structure matters more than the bricks out of which it is built.

A: The electrostatic potential in QED is represented by virtual photons, which in this case have [no] zero frequency and do not propagate. These photons do not transport energy. They're just Fourier components of the potential. A model of photon decay or density does it herefore not apply.

A: I think your question can really only be answered by observations. If the observed potential appears to be different from $1/r$ though, this would mean that you would not be looking at a pure interaction between two particles but that some 'screening' of the potential due to other effects occurs.


text:
Q: Android DataOutputStream.write(byte[], int, int)' on a null object reference I want to upload images and audio files from sd card to server. When run no app crash but image and audio is uploaded proper way. When i go to server and check the image and audio and showing file not found.Means when i click on audio symbol try to play on server it shows file not found.
here is my Image and Audio file upLoad method
uploadFile(uploadFilePath+""+imagePath , imagePath);

public int uploadFile(String uploadFileName ,String upLoadImageAudioName )
    {
        String fileName = uploadFileName;
        String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
        String upLoadFilePath = baseDir+"/classnkk_images/";
        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File sourceFile = new File(uploadFileName);

        if (!sourceFile.isFile())
        {
            Log.e("uploadFile", "Source File not exist :" +upLoadFilePath + "" + upLoadImageAudioName);
            return 0;
        }
        else
        {
            try
            {
                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(sourceFile);
                URL url = new URL("http://xxxx/xxxx/MobileService.svc/UploadFileStream/");

                // Open a HTTP  connection to  the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

                if(fileName.endsWith(".png"))
                {
                    dos = new DataOutputStream(conn.getOutputStream());
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"file_name\";filename=\"" + fileName + "\"" + lineEnd);
                    dos.writeBytes(lineEnd);
                    // Code for sending the image....
                    dos.writeBytes(lineEnd);
                }

                // create a buffer of  maximum size
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                if(fileName.endsWith(".mp3"))
                {
                    dos.writeBytes(twoHyphens + boundary + lineEnd);
                    dos.writeBytes("Content-Disposition: form-data; name=\"file_name_audio\";filename=\""+ fileName + "\"" + lineEnd);
                    dos.writeBytes(lineEnd);
                    // Code for sending the MP3
                    dos.writeBytes(lineEnd);
                    dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                }
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();
                Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
                if(serverResponseCode == 200)
                {runOnUiThread(new Runnable() {
                        public void run() {}
                    });
                }
                //close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex)
            {
                ex.printStackTrace();
                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e)
            {
                e.printStackTrace();
            }
            return serverResponseCode;

        } // End else block
    }

Here is Log information
09-23 05:25:45.178  23676-24640/com.example.tazeen.classnkk W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void java.io.DataOutputStream.write(byte[], int, int)' on a null object reference
09-23 05:25:45.178  23676-24640/com.example.tazeen.classnkk W/System.err﹕ at com.example.tazeen.classnkk.AddPost.uploadFile(AddPost.java:798)
09-23 05:25:45.178  23676-24640/com.example.tazeen.classnkk W/System.err﹕ at com.example.tazeen.classnkk.AddPost$7$1$1.run(AddPost.java:419)

Thanks in advanced .

A: Near the top of your code you have
    DataOutputStream dos = null;

Later on
if(fileName.endsWith(".png"))
{
   dos = new DataOutputStream(conn.getOutputStream());
   ...
}

Thus you are initializing your DataOutputStream when the filename ends with .png
but still later
if(fileName.endsWith(".mp3"))
{
    dos.writeBytes(twoHyphens + boundary + lineEnd);
}

If the filename ended with .png dos would have been initialized, but then the filename cannot end with .mp3 thus when you get here dos is null, hence the error.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you make a WPF application from an Empty Project? When coding WinForms applications, I always start with an empty project, then add an Application Class, Forms, etc...  In doing so, I can build up the application from scratch, keeping it clean, without all the "fluff" of the Standard WinForms projects, which add Forms, etc... for you.
I want to do the same with WPF.  I've created my application class, made a Window class and I can run the application just fine, but there is no XAML associated with the window because I'm just declaring it as a derived class from Window.
My question is, can WPF -Windows be added to a project like WinForms -Forms such that the XAML is also added and the designer can be used to layout the controls etc...?  Or do I have to use the canned "WPF Project" and go from there?
Apparently it's not possible to create an Empty Project and add XAML backed Windows.  If anyone knows why, I would appreciate an explanation. (You can, however, create programmatically generated windows, or if you want your own startup object in a default WPF Project, simple delete the App.xaml and add your own class with a static Main().)
class OrderEntry : System.Windows.Application
    {
        [STAThread]
        static void Main(string[] commandLine)
        {
            OrderEntry app = new OrderEntry();
            app.MainWindow = new WindowMain();
            app.MainWindow.Show();
            app.Run();
        }
    }

public partial class WindowMain : System.Windows.Window
{

}

Works fine, but WindowMain has no XAML associated with it.

A: To answer your question, yes - XAML based windows can be added to the project as and when you want.
The trick is to ensure your project type is correct, because this governs the list of template items that you will see when you go Add->New...
If you find the right project in your Solution Explorer, right click and select Unload Project, then right click it again and select to Edit, you will then get the proj file in XML format. In it you will see a line similar to the following:
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

Those GUIDs dictate what project or file templates you will see in the add list. You can find more details in the previous SO question Visual Studio project type guids and the blog post linked in one of the answers INFO: List of known project type Guids

A: This is what I have tried, it worked for me

*

*Create an empty project from Visual Studio 2013 Templates

*Add reference for below dll's which are present at Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\

*Modify the .csproj file located at project root folder through a text editor. Add below entry for <ProjectTypeGuids> in <PropertyGroup> node.

{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}

Read more about Project Type Guids here

*Change the <OutputType>WinExe</OutputType>
<PropertyGroup>
<ProjectGuid>{C60226AB-DDB6-49C2-8B0D-F59E6B590236}</ProjectGuid>
<OutputType>WinExe</OutputType>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>

*Add a App.Xaml file to your application and replace its content like this

Note here WpfApplication1 is the default namespace and we haven't created MainWindow.xaml yet

*Modify the code behind and inherit it from Application

*Modify the .csproj to add <ApplicationDefinition> under <ItemGroup>
eg:
  <ItemGroup>
     <ApplicationDefinition Include="App.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </ApplicationDefinition>
    <Page Include="MainWindow.xaml">
      <Generator>MSBuild:Compile</Generator>
      <SubType>Designer</SubType>
    </Page>
    <Compile Include="App.xaml.cs">
      <DependentUpon>App.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
    <Compile Include="MainWindow.xaml.cs">
      <DependentUpon>MainWindow.xaml</DependentUpon>
      <SubType>Code</SubType>
    </Compile>
  </ItemGroup>

Note MainWindow is a file which I have added later.
Now we can create XAML backed windows

A: As HighCore said in comments that using given WPF FCL/Template are best I also agree with that . But if you still wants your own xaml Then do this

1) Add Xml file to your View Project and keep its extension .xaml say WindowMain.xaml
2) Remove the below line from it

<?xml version="1.0" encoding="utf-8" ?>

3)Copy and Paste

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

</Window>

4) add x:class attribute to Window element like and set another attribute like Title height width etc

 <Window x:Class="Namespace.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MyWindow" Height="350" Width="525">

</Window>

5) Close the project and edit project file like

<Page Include="MainWindow.xaml">
  <Generator>MSBuild:Compile</Generator>
  <SubType>Designer</SubType>
</Page>

<Compile Include="MyWindow.xaml.cs">
  <DependentUpon>MyWindow.xaml</DependentUpon>
  <SubType>Code</SubType>

 //or MainWindow.cs
      MainWindow.xaml
      Code

6) Save and close
7)Open your project you will find your .cs file under .xaml file as we mentioned it in DependentUpon
8) Add Constructor to your partial class and call InitializeComponent() method

public MainWindow()
    {
        InitializeComponent();
    }

This worked for me . But this is all we doing what Wpf exactly provide by itself by using their WPF Window . And I have assumed that your App class builded and worked correctly but I doubt it you calling window Show before App Run. I hope this will help.


text:
Q: i am getting this error Invalid parameter value for approval_prompt: 'auto'' is not valid this is the error i am getting
400. That's an error.

Error: invalid_request

Invalid parameter value for approval_prompt: 'auto'' is not valid

Request Details
response_type=code
access_type=offline
client_id=xyz-
xyx.apps.googleusercontent.com
redirect_uri=http://localhost/xyz/init/googleCallBack.php
state=scope=https://www.googleapis.com/auth/plus.me
approval_prompt=auto'

here is the config for google login
$gClient= new Google_Client();
$gClient->setAuthConfig('init/client_secret.json');

$gClient->setApprovalPrompt('consent');
$gClient->setApplicationName('abc');
$gClient->setAccessType('offline');
$gClient>setRedirectUri('http://localhost/xyz/init/googleCallBack.php';
$gClient->setScopes(Google_Service_Plus::PLUS_ME);

i tried setting up approval_prompt or prompt both but it isn't working if i leave these two unset still i get invalid parameter 'prompt=auto'

A: It is a mistake in official web. You need set:
$gClient = new Google_Client();
$gClient->setPrompt('consent');

Via merged pull-request in documentation https://github.com/googleapis/google-api-php-client/pull/1796


text:
Q: Compare field to see if it changed from yesterday until today I need to see records where the COMP_DATE changed or as added from yesterday and only show records that changed. I need to see if someone changed the value.
I've tried LAST_VALUE and LAG but I can't seem to get the comparison right.
Example Data:
Date          JOB    COMP_DATE
SYSDATE -1   1       09-01-2017

SYSDATE      1       09-27-2018

SELECT

   JOB, COMP_DATE,

   LAST_VALUE(COMP_DATE) OVER (ORDER BY JOB ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS Last_Value

    FROM  JOB_TABLE

   *** I know this section is not valid ***

    Where LAST_VALUE <> Current COMP_DATE

A: You can try to use a subquery.
select * from (
    SELECT
        JOB,
        COMP_DATE,
        LAG(COMP_DATE) OVER (ORDER BY JOB) AS Last_Value
    FROM JOB_TABLE
) t1
where  LAST_VALUE <> COMP_DATE

A: First part will get changed records, the part after the union all will get new records.. assuming I'm interpreting your table structure correctly. Although you might have to put "'s around the "date" field name.
 select * from job_table j1
  join job_table j2 on j2.job_id=j1.job_id and j2.date = j1.date - 1
 where
 j1.comp_date != j2.comp_date
 and j1.com_date=sysdate;
 union all
 select * from job_table j1 where not exists (select * from job_table j2
    where j1.date != j2.date and j1.job_id=j2.job_id)

A: The result using flashback query (note, the "as of timestamp" needs to be "yesterday" in your example-- might get away with using sysdate -1, but I cannot get on oracle right now to test.
This will tell you that it was changed between yesterday and now, but with no greater precision than that.
 select j1.comp_date, j2.comp_date, j1.job_id
   from job_table j1
   left outer join job_table j2
     as of timestamp('2018-09-28 00:00:00','yyyy-mm-dd hh:mi:ss')
     on j1.job_id=j2.job_id
   where j2.comp_date is null or j2.comp_date != j1.comp_date


text:
Q: Should I inject ServiceStack's ICacheManager? I'm looking to implement a caching tier in our application and accidentally came across ServiceStack's ICacheManager.
ICacheManager.Resolve looks as though it's exactly what I'm after (try and get, if it's not in the cache then call the function to get and store it). All documentation I can find however is about using ICacheClient.
How I can wire up ICacheManager using AutoFac? I assume I need to wire up a client e.g.:
_builder.Register(c => new MemoryCacheClient())
        .As<ICacheClient>();

But then I'm not sure what ICacheManager should resolve to.
Is this a good idea or am I abusing ServiceStack?
I've added a custom cache manager for the time being but it feels wrong for some reason:
public class CacheManager : ICacheManager
{
    public CacheManager(ICacheClient cacheClient)
    {
        CacheClient = cacheClient;
    }

    public void Clear(IEnumerable<string> cacheKeys)
    {
        Clear(cacheKeys.ToArray());
    }

    public void Clear(params string[] cacheKeys)
    {
        CacheClient.ClearCaches(cacheKeys.ToArray());
    }

    public ICacheClient CacheClient { get; private set; }

    public T Resolve<T>(string cacheKey, Func<T> createCacheFn) where T : class
    {
        return Resolve(cacheKey, new TimeSpan(0, 15, 0), createCacheFn);
    }

    public T Resolve<T>(string cacheKey, TimeSpan expireIn, Func<T> createCacheFn) where T : class
    {
        var cacheResult = CacheClient.Get<T>(cacheKey);
        if (cacheResult != null)
            return cacheResult;

        var item = createCacheFn();
        CacheClient.Set(cacheKey, item, expireIn);
        return item;
    }
}


text:
Q: Podman v4.2.1 on Windows 10 via WSLv2 using Fedora Remix for WSL unable to install Flask dependencies in a Container I am attempting to build a Python Flask application using Podman via the podman play kube command, however, that command fails, but when building the container itself, the build works. I don't understand why. I am running on Windows 10 WSLv2 with Fedora Remix for WSL. When I run this same set of commands on my personal machine running Fedora 36 Silverblue, I have zero issues, this seems to be a WSLv2 thing when running with GlobalProtect VPN or something, but the manual building part seems to debunk the VPN issue.
➜  k8s-owasp-crs-examples git:(main)
> podman version
Client:       Podman Engine
Version:      4.2.1
API Version:  4.2.1
Go Version:   go1.18.5
Built:        Wed Sep  7 14:58:19 2022
OS/Arch:      linux/amd64

➜  k8s-owasp-crs-examples git:(main)
> uname -a
Linux LAP-5CD91424PB 5.10.102.1-microsoft-standard-WSL2 #1 SMP Wed Mar 2 00:30:59 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux

➜  k8s-owasp-crs-examples git:(main)
> cat /etc/os-release
NAME="Fedora Remix for WSL"
VERSION="36"
ID=fedoraremixforwsl
ID_LIKE=fedora
VERSION_ID=36
PLATFORM_ID="platform:f36"
PRETTY_NAME="Fedora Remix for WSL"
ANSI_COLOR="0;34"
CPE_NAME="cpe:/o:fedoraproject:fedora:36"
HOME_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL"
SUPPORT_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL"
BUG_REPORT_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL/issues"
PRIVACY_POLICY_URL="https://github.com/WhitewaterFoundry/Fedora-Remix-for-WSL/blob/master/PRIVACY.md"
FEDORA_REMIX_VERSION=36.0.5

➜  k8s-owasp-crs-examples git:(main)
> tree .
.
├── k8s-owasp-crs-setup.yaml
├── philflaskapp
│   ├── Containerfile
│   └── phil_flask_app.py
├── README.md
├── tags
└── Taskfile.yaml

1 directory, 6 files

Here, I perform the build manually, and it works.
➜  k8s-owasp-crs-examples git:(main)
> podman build -t philflaskapp -f philflaskapp/Containerfile ./philflaskapp
STEP 1/6: FROM docker.io/library/python:3.10-alpine
STEP 2/6: RUN python -m pip install --upgrade pip
Requirement already satisfied: pip in /usr/local/lib/python3.10/site-packages (22.2.2)
Collecting pip
  Downloading pip-22.3-py3-none-any.whl (2.1 MB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 2.1/2.1 MB 3.7 MB/s eta 0:00:00
Installing collected packages: pip
  Attempting uninstall: pip
    Found existing installation: pip 22.2.2
    Uninstalling pip-22.2.2:
      Successfully uninstalled pip-22.2.2
Successfully installed pip-22.3
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
--> e205c3fff63
STEP 3/6: RUN python -m pip install flask
Collecting flask
  Downloading Flask-2.2.2-py3-none-any.whl (101 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 101.5/101.5 kB 83.4 kB/s eta 0:00:00
Collecting Jinja2>=3.0
  Downloading Jinja2-3.1.2-py3-none-any.whl (133 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 133.1/133.1 kB 1.5 MB/s eta 0:00:00
Collecting Werkzeug>=2.2.2
  Downloading Werkzeug-2.2.2-py3-none-any.whl (232 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 232.7/232.7 kB 5.7 MB/s eta 0:00:00
Collecting click>=8.0
  Downloading click-8.1.3-py3-none-any.whl (96 kB)
     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 96.6/96.6 kB 6.8 MB/s eta 0:00:00
Collecting itsdangerous>=2.0
  Downloading itsdangerous-2.1.2-py3-none-any.whl (15 kB)
Collecting MarkupSafe>=2.0
  Downloading MarkupSafe-2.1.1-cp310-cp310-musllinux_1_1_x86_64.whl (29 kB)
Installing collected packages: MarkupSafe, itsdangerous, click, Werkzeug, Jinja2, flask
Successfully installed Jinja2-3.1.2 MarkupSafe-2.1.1 Werkzeug-2.2.2 click-8.1.3 flask-2.2.2 itsdangerous-2.1.2
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
--> 6239080ad3d
STEP 4/6: WORKDIR /app
--> 63086ff8158
STEP 5/6: COPY ./phil_flask_app.py /app/phil_flask_app.py
--> 4556872dbce
STEP 6/6: ENTRYPOINT ["flask", "--app", "phil_flask_app", "run", "--host=0.0.0.0"]
COMMIT philflaskapp
--> 8da4ebdfce6
Successfully tagged localhost/philflaskapp:latest
8da4ebdfce65cef0aa8fccc6b43152f3e94f4a61087c74964ea30290e05e0fc3

Here, I perform the podman play kube command, and it seems to have issues getting the flask dependencies.
➜  k8s-owasp-crs-examples git:(main)
> task podman-play
task: [podman-play] podman play kube --build --replace k8s-owasp-crs-setup.yaml
STEP 1/6: FROM docker.io/library/python:3.10-alpine
STEP 2/6: RUN python -m pip install --upgrade pip
Requirement already satisfied: pip in /usr/local/lib/python3.10/site-packages (22.2.2)
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7fc25f5bfaf0>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/pip/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7fc25f5bfa00>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/pip/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7fc25f5bcdf0>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/pip/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7fc25f2cf580>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/pip/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7fc25f2cf610>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/pip/
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: https://pip.pypa.io/warnings/venv
WARNING: There was an error checking the latest version of pip.
STEP 3/6: RUN python -m pip install flask
WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7efefdb0c730>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/flask/
WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7efefdb0ca60>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/flask/
WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7efefdb0ceb0>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/flask/
WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7efefdb0d060>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/flask/
WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7efefdb0d210>: Failed to establish a new connection: [Errno -2] Name does not resolve')': /simple/flask/
ERROR: Could not find a version that satisfies the requirement flask (from versions: none)
ERROR: No matching distribution found for flask
WARNING: There was an error checking the latest version of pip.
subprocess exited with status 1
subprocess exited with status 1
Error: k8s-owasp-crs-setup.yaml: error encountered while bringing up pod owasp-crs-demo-pod-0: error building at STEP "RUN python -m pip install flask": exit status 1
task: Failed to run task "podman-play": exit status 125

I don't understand why it is having issues or doesn't seem to work when ran with podman play kube but when ran manually, works. THEN, why it works on my personal machine, but not on my work laptop.
Code repository:

*

*https://github.com/FilBot3/k8s-owasp-crs-examples


text:
Q: Is there a better way to summerize a table information instead of using iloc and append method with nested loops in pandas? I have a table of grant application numbers and their corresponding disciplines given by cell value 1.
import pandas as pd
import numpy as np
data={'Application number':[0,1,2,3,4,5,6,7,8,9],
      'Physics':[0,0,1,0,0,0,0,1,1,0],
     'Chemistry':[1,0,0,0,0,0,0,0,0,1],
     'Biology':[0,1,0,1,0,0,1,0,0,0],
     'Mathematics':[0,0,0,0,1,1,0,0,0,0]}

#creation of dataframe
df=pd.DataFrame(data)

#column counting all disciplines per grant
df['All_Discipline_count']=df.loc[:,'Physics' : 'Mathematics'].sum(axis=1)

df.head(10)

I would like to summarize discipline list and discipline count per grant application. I do that using iloc and multiple nested loops.
# Creation of resulting dataframe
dfA = pd.DataFrame(columns = ['Application number', 'Discipline_list', 'All_Discipline_count'])

# Pay attention to how iloc a cell selects. 'Application number' is zeroth column.
i=0 #starts from oth row
j=1 #starts from 1st column
Aanvraag_nummer=0
k=df.columns.get_loc("All_Discipline_count") #column number where the All_Discipline_count is
l=len(df.index)#number of rows
for i in range (0,l):
    Discipline_count=0 #introducing zero discipline count
    Discipline_list=" " #introducing empty discipline list
    for j in range (1,k): #counting columns of disciplines
        if (df.iloc[i,j]==1) & (Discipline_count<df.iloc[i,k]): #if the given cell has 1 as value
            Discipline_list=Discipline_list+ df.columns[j] #adds a column name to discipline list
            Discipline_count+=1 #counts the number of disciplines with 1 as value
            if Discipline_count==df.iloc[i,k]:#if all disciplines are counted
                Aanvraag_nummer=df.iloc[i,0]
                new_row = {'Application number':Aanvraag_nummer, 'Discipline_list':Discipline_list, 'All_Discipline_count':df.iloc[i,k]}
                dfA = dfA.append(new_row, ignore_index=True)
dfA.head(10)

The script works for 10 to 100 applications and 20 disciplines as columns. It also works when there are multiple disciplines are given per grant application.
However, I notice that I get warning while running the code.
/tmp/ipykernel_26718/1290491379.py:19: FutureWarning: The frame.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.

The code is also slow..Any better method to get the same results?

A: you can make Discipline_list following code:
df.loc[:,'Physics' : 'Mathematics'].apply(lambda x: '/'.join(x[x > 0].index), axis=1)

output:
0      Chemistry
1        Biology
2        Physics
3        Biology
4    Mathematics
5    Mathematics
6        Biology
7        Physics
8        Physics
9      Chemistry
dtype: object

If there is over 1 discipline list, it is expressed like 'Biology/Phsics'

make result to Discipline_list column
df['Discipline_list'] = df.loc[:,'Physics' : 'Mathematics'].apply(lambda x: '/'.join(x[x > 0].index), axis=1)

A: You just need to use pandas.idxmax in this case.
Be aware: This only works if there is only 1 application per row. If there are multiple it will only choose the first it finds.
df['Application Count'] = df.iloc[:,1:].idxmax(axis=1) # iloc because we only want to apply idxmax on the applications (without application number)
#or
df['Application Count'] = df.set_index('Application number').idxmax(axis=1)

In case you have multiple subjects per row here is another solution (I changed Input for that a bit, in row 0 and 8 there are 2 subjects, in row 4 we have 4 subjects.
data={'Application number':[0,1,2,3,4,5,6,7,8,9],
      'Physics':[1,0,1,0,1,0,0,1,1,0],
     'Chemistry':[1,0,0,0,1,0,0,0,0,1],
     'Biology':[0,1,0,1,1,0,1,0,0,0],
     'Mathematics':[0,0,0,0,1,1,0,0,1,0]}

df=pd.DataFrame(data)
print(df)

   Application number  Physics  Chemistry  Biology  Mathematics
0                   0        1          1        0            0
1                   1        0          0        1            0
2                   2        1          0        0            0
3                   3        0          0        1            0
4                   4        1          1        1            1
5                   5        0          0        0            1
6                   6        0          0        1            0
7                   7        1          0        0            0
8                   8        1          0        0            1
9                   9        0          1        0            0

df = df.set_index('Application number')

out = (
    df[df==1]
    .stack()
    .reset_index()
    .drop(0, axis=1)
    .rename(columns={'level_1': 'Discipline_list'})
    .groupby('Application number', as_index=False)
    .agg(Discipline_list=('Discipline_list', lambda x: ', '.join(x)), All_Discipline_count=('Discipline_list', 'count'))
)

print(out)

   Application number                           Discipline_list  All_Discipline_count
0                   0                        Physics, Chemistry                     2
1                   1                                   Biology                     1
2                   2                                   Physics                     1
3                   3                                   Biology                     1
4                   4  Physics, Chemistry, Biology, Mathematics                     4
5                   5                               Mathematics                     1
6                   6                                   Biology                     1
7                   7                                   Physics                     1
8                   8                      Physics, Mathematics                     2
9                   9                                 Chemistry                     1


text:
Q: Does go-get run builds forked from current shell process with different environment variables? I have a simple Makefile like this:
unexport GOPATH

help :
                @echo "libedkafka"
                @echo "libedkafka-clean"

opt/librdkafka:
                (mkdir -p ./opt && cd ./opt && git clone https://github.com/edenhill/librdkafka.git --depth=1)

opt/librdkafka/config.cache: opt/librdkafka
                (cd ./opt/librdkafka && ./configure --prefix build)

opt/librdkafka/build/lib/pkgconfig/rdkafka.pc: opt/librdkafka/config.cache
                (cd ./opt/librdkafka && make && make install)
                make -t opt/librdkafka/build/lib/pkgconfig/rdkafka.pc

opt/librdkafka-goget-done: opt/librdkafka/build/lib/pkgconfig/rdkafka.pc
                ( export PKG_CONFIG_PATH="$$PKG_CONFIG_PATH:opt/librdkafka/build/lib/pkgconfig"; \
                go env; \
                echo $$PKG_CONFIG_PATH; \
                pkg-config --cflags  -- rdkafka-static; \
                echo "So it should work "; \
                go get -u -tags static gopkg.in/confluentinc/confluent-kafka-go.v1/kafka && \
                touch opt/librdkafka-goget-done; )

librdkafka: opt/librdkafka-goget-done

librdkafka-clean:
                rm -rf ./opt/librdkafka
                rm -rf ./opt/librdkafka-goget-done

When I run it, it fails with error that it can't find related configs for pkg-config while when I print it in the target, it shows the value to me!
$ make librdkafka
( export PKG_CONFIG_PATH="$PKG_CONFIG_PATH:opt/librdkafka/build/lib/pkgconfig"; \
                go env; \
                echo $PKG_CONFIG_PATH; \
                pkg-config --cflags  -- rdkafka-static; \
                echo "So it should work "; \
                go get -u -tags static gopkg.in/confluentinc/confluent-kafka-go.v1/kafka && \
                touch opt/librdkafka-goget-done; )
GOARCH="amd64"
GOBIN=""
GOCACHE="/Users/me/Library/Caches/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/me/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/Cellar/go/1.12.5/libexec"
GOTMPDIR=""
GOTOOLDIR="/usr/local/Cellar/go/1.12.5/libexec/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/me/Workspace/TBNew/test/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-g -O2"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/s_/tygqt0_56pzg6jk2xycqr7_w0000gq/T/go-build935984301=/tmp/go-build -gno-record-gcc-switches -fno-common"
:opt/librdkafka/build/lib/pkgconfig
-I/Users/me/Workspace/TBNew/test/opt/librdkafka/build/include
So it should work
# pkg-config --cflags  -- rdkafka-static
Package rdkafka-static was not found in the pkg-config search path.
Perhaps you should add the directory containing `rdkafka-static.pc'
to the PKG_CONFIG_PATH environment variable
No package 'rdkafka-static' found
pkg-config: exit status 1
make: *** [opt/librdkafka-goget-done] Error 2

So my questions is that does go-get use different enviroment while it's building?
I'm using mac-os (Darwin Kernel Version 18.5.0) as my operating system.

A: I found the problem! I mean I fixed it: the value in PKG_CONFIG_PATH contained relative path to my config file. when I changed it to absolute path script worked.
# Assuming PRJ_DIR is defined before!
export PKG_CONFIG_PATH="$$PKG_CONFIG_PATH:$${PRJ_DIR}opt/librdkafka/build/lib/pkgconfig";

Not sure, but I think that go-get, before using the values in environment, evalutes them and in case of detecting inappropriate values, drop them siliently!


text:
Q: Web Bluetooth API get list of all available device nearby I am looking for an API call that could be used to retrieve all the Bluetooth devices near me. These samples Web Bluetooth talk about getting different characteristics from a single Bluetooth device, however I couldn't find any example which retrieves all the Bluetooth devices(like available bluetooth devices list on windows native Bluetooth app). Is it even supported?

A: (Well, this question sent me down a rabbit hole...)
It's a couple years later and we're starting to signs of life from api.Bluetooth.getDevices. I eventually got an experimental demo working in Chrome.
You'll probably need to enable Chrome's "Web Bluetooth experiment".  (Firefox has an equivalent but I didn't try it.)

*

*Go to chrome://flags/ then search for bluetooth and enable the API.

*Click the buttons on the demo page: Web Bluetooth / Get Devices Sample

Demo code from the same page:
function onGetBluetoothDevicesButtonClick() {
  log('Getting existing permitted Bluetooth devices...');
  navigator.bluetooth.getDevices()
  .then(devices => {
    log('> Got ' + devices.length + ' Bluetooth devices.');
    for (const device of devices) {
      log('  > ' + device.name + ' (' + device.id + ')');
    }
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

function onRequestBluetoothDeviceButtonClick() {
  log('Requesting any Bluetooth device...');
  navigator.bluetooth.requestDevice({
 // filters: [...] <- Prefer filters to save energy & show relevant devices.
    acceptAllDevices: true
  })
  .then(device => {
    log('> Requested ' + device.name + ' (' + device.id + ')');
  })
  .catch(error => {
    log('Argh! ' + error);
  });
}

Good luck!

A: I personally haven't experimented with Web Bluetooth API a lot, but I think you're looking for Device Discovery and Request Bluetooth Devices:

This version of the Web Bluetooth API specification allows websites,
  running in the Central role, to connect to remote GATT Servers over a
  BLE connection. It supports communication among devices that implement
  Bluetooth 4.0 or later.
When a website requests access to nearby devices using
  navigator.bluetooth.requestDevice, Google Chrome will prompt user with
  a device chooser where they can pick one device or simply cancel the
  request.
The navigator.bluetooth.requestDevice function takes a mandatory
  Object that defines filters. These filters are used to return only
  devices that match some advertised Bluetooth GATT services and/or the
  device name.

Also, here's the list of GATT
Services.

A: A Web Bluetooth Scanning specification draft exists, but implementation isn't started anywhere as of 2018.


text:
Q: Internal Server Error 500, out of memory error running Yii So I'm running Yii, which has an application that manages some scientific data.
I'm running Apache on CentOS.
PHP Version 5.2.10
Apache/2.2.3 (CentOS)
Here's my error log (obfuscated personal identifying information).
[Wed Apr 18 15:27:42 2012] [error] [client 000.000.000.000] PHP Notice:  Use of undefined constant \x94512M\x93 - assumed '\x94512M\x93' in /var/www/MySite/www/admin/index.php on line 12, referer: http://MySite.com/admin/index.php?r=factsheet/admin
[Wed Apr 18 15:27:44 2012] [error] [client 000.000.000.000] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 57 bytes) in /var/www/MySite/www/yii/framework/db/ar/CActiveRecord.php on line 1856, referer: http://MySite.com/admin/index.php?r=factsheet/admin

If I remove the renderPartial() out of my view, I can get the page to load, so it appears it's somehow tied into that.
CActiveRecord.php:
protected function instantiate($attributes)
{
    $class=get_class($this);
    $model=new $class(null);
    return $model;
}

My Model:
Extends an abstract class which extends GxActiveRecord.

View:
<?php

$this->breadcrumbs = array(
    $model->label(2) => array('index'),
    Yii::t('app', 'Create'),
);
$this->menu = array(
    array('label'=>Yii::t('app', 'List') . ' ' . $model->label(2), 'url' => array('index')),
    array('label'=>Yii::t('app', 'Manage') . ' ' . $model->label(2), 'url' => array('admin')),
);
?>

<?php echo Yii::t('app', 'Create') . ' ' . GxHtml::encode($model->label()); ?>

<?php
$this->renderPartial('_form', array(
        'model' => $model,
        'buttons' => 'create'));
?>

Line 12 of index.php
ini_set("memory_limit","512M");

Any ideas?

A: The message
[Wed Apr 18 15:27:42 2012] [error] [client 000.000.000.000] PHP Notice:  Use of undefined constant \x94512M\x93 - assumed '\x94512M\x93' in /var/www/MySite/www/admin/index.php on line 12, referer: http://MySite.com/admin/index.php?r=factsheet/admin

indicates, that you missed the $-sign before a variable.
Please provide line 12 of index.php. I don't believe the problem is located in the source provided above.
The message
[Wed Apr 18 15:27:44 2012] [error] [client 000.000.000.000] PHP Fatal error:  Allowed memory size of 134217728 bytes exhausted (tried to allocate 57 bytes) in /var/www/MySite/www/yii/framework/db/ar/CActiveRecord.php on line 1856, referer: http://MySite.com/admin/index.php?r=factsheet/admin

frequently indicates a certain looping PHP-operation or complex queries.
You could enhance the amount of PHP memory, but this most likely won't solved the actual problem.


text:
Q: I am trying to display a list view in designer mode but I cannot see any list displayed I am trying to run a project involving creating lists. I have just started and I already got the issue that if I drag and drop the listView from the palette in the designer mode, there is no list displayed in the app.
I only had one error, that the list is not constrained. Well, I have constrained it and still no list. Even if I start to code the elements of the list in the strings code, the code is running, but still nothing to be seen on the screen in the emulator (which is a nexus 5). Can anyone help me please?
This is the code in main activity where I call all the items of the list.
{
ListView myListView;
String [] items;

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

    Resources res = getResources();
    myListView = (ListView) findViewById(R.id.myListView);
    items = res.getStringArray(R.array.items);

    myListView.setAdapter(new ArrayAdapter<String>(this, R.layout.my_listview_detail, items));

}

}
}


text:
Q: How to get code behind variable value into repeater I have a variable in my code behind file in asp.net say string myVariable = "SomeValue";
I use this declaration in the code-behind:
  Public myVariable As String = "SomeValue"

I want to bind this string inside the in Repeater.
 <td id="Td5" class="Text" style="text-align:right; width:70px;" >
        <%#DataBinder.Eval(Container, "'<%=myVariable%>'", "{0:N2}")%>
 </td>

The Repeater is binded using a datatable. I  use vb.net
thanks for yours comments.

A: Set your value within session and then bind sessionh  with <%=Session("yourfiledName")%>


text:
Q: Pbl xcode C++ typedef struct toto toto I am working on a C++ project on macOS X 10.6.2 with xcode.
I tried to compile my code on windows and do not have any problem, I guess Linux is working but I don't have one with me right now.
My problem is xcode do not accept this kind of instruction :
struct direction {
double x;
double y;
double z;
double t; };

typedef struct direction direction;

Here is my error :

/Users/sbarbier/dev/xcode/Infographie/TP9-RayTracing/RayTracing-Direction.h:22:0     /Users/sbarbier/dev/xcode/Infographie/TP9-RayTracing/RayTracing-Direction.h:22: error: changes meaning of 'direction' from 'typedef struct direction direction'

I am using GCC4.2 and haven't change anything. This code works on every platform, can any one help me ?

A: This isn't C. In C, to use a struct you had to use the keyword struct:
struct some_struct{ int i; };
struct some_struct myStruct;

This was alleviated like this, commonly:
typedef struct { int i; } some_struct;
some_struct myStruct;

In C++ this is not required. direction already has a type, then you're trying to make a new type of the same name, and that's bad. Take out your entire typedef, it isn't needed.

A: In C++, struct and class are used only when declaring or defining the struct or class.  You might want the typedef in C, but in C++ it doesn't make any sense.


text:
Q: Problem in cursor movement when the text is entered in textbox? Textbox textwrap property is set to wrap.
My scenario is enter the text in textbox from SIP. When cursor reaches almost at the end of line may be 3 or 4 char left for line change just enter space so that it should came to next line. But after pressing space 4 or 5 time or more the cursor will not come to next line moreover it will not shown . It will come to next line when i enter some char.
I think it should came to next line because user may want to enter some space. is this can be fixed.

A: The other property you need to set on the TextBox is AcceptsReturn to true.


text:
Q: AttributeError: module 'PIL.ImageFile' has no attribute 'PyEncoder' AttributeError                            Traceback (most recent call last)
<ipython-input-15-3844ec9c99de> in <module>
     30
     31 # Traceability
---> 32 tracability(final_video_driver)
     33 final_video_driver = "marked.mp4"
     34 get_ipython().system('ffmpeg -i $final_video_driver -i $audio_driver final_generated.mp4 -y &> /dev/null')

9 frames
/usr/local/lib/python3.7/dist-packages/PIL/BlpImagePlugin.py in <module>
    427
    428
--> 429 class BLPEncoder(ImageFile.PyEncoder):
    430     _pushes_fd = True
    431

AttributeError: module 'PIL.ImageFile' has no attribute 'PyEncoder'

Has anyone found another solution?


text:
Q: Am I using MurmurHash2 correctly? So i'm writing a hashing program for one of my classes and he's letting us find a hashing function online. However when I use the following hashing function I get huge numbers. My question is, do I have to mod the answer I get from this function with the size of my table or am I doing something wrong?
  uint32_t MurmurHash2(const void * key, int len, uint32_t seed)
{
    // 'm' and 'r' are mixing constants generated offline.
    // They're not really 'magic', they just happen to work well.

    const uint32_t m = 0x5bd1e995;
    const int r = 24;

    // Initialize the hash to a 'random' value

    uint32_t h = seed ^ len;

    // Mix 4 bytes at a time into the hash

    const unsigned char * data = (const unsigned char *)key;

    while (len >= 4)
    {
        uint32_t k = *(uint32_t*)data;

        k *= m;
        k ^= k >> r;
        k *= m;

        h *= m;
        h ^= k;

        data += 4;
        len -= 4;
    }

    // Handle the last few bytes of the input array

    switch (len)
    {
    case 3: h ^= data[2] << 16;
    case 2: h ^= data[1] << 8;
    case 1: h ^= data[0];
        h *= m;
    };

    // Do a few final mixes of the hash to ensure the last few
    // bytes are well-incorporated.

    h ^= h >> 13;
    h *= m;
    h ^= h >> 15;

    return h;
}


text:
Q: How to get the length of a mp3 link in python? I need get a mp3 lenght(from a url) to transform the lenght in seconds for a delay, someone know how to do it?

A: Here is an example of retrieving the resource (mp3 file), and printing the track length via mutagen library:
from urllib import urlretrieve

from mutagen.mp3 import MP3

url = 'http://example.com/foo.mp3'
filename, headers = urlretrieve(url)

audio = MP3(filename)
print audio.info.length

A: You don't need to retrieve he resource, you can just check the headers as here:
How do you send a HEAD HTTP request in Python 2? You want to call the HEAD method which gets you the file size without downloading the file:


text:
Q: env-cmd Error: Failed to find .env file at path can anyone help me with .env-cmd issue?
env-cmd Error: Failed to find .env file at path: .env.development at getEnvFile C:\Users\Jake\project\fcmanager-frontend\node_modules\env-cmd\dist\get-env-vars.js
package.json file:
  "scripts": {
    "start": "env-cmd -f .env.development react-scripts start",
    "build": "env-cmd -f .env.development react-scripts build",
    "start-prod": "env-cmd -f .env.production react-scripts start",
    "build-prod": "env-cmd -f .env.production react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

A: Try this.
    "scripts": {
    "start": "env-cmd -f ./.env.development react-scripts start",
    "build": "env-cmd -f ./.env.development react-scripts build",
    "start-prod": "env-cmd -f ./.env.production react-scripts start",
    "build-prod": "env-cmd -f ./.env.production react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },

A: After the certain version for env-cmd, they ask you to add -e be
   "start-dev": "env-cmd -e dev react-scripts start",
    "build-dev": "env-cmd -e dev react-scripts build",
    "start-local": "env-cmd -e local react-scripts start",
    "build-local": "env-cmd -e local react-scripts build",
    "start-prod": "env-cmd -e prod react-scripts start",
    "build-prod": "env-cmd -e prod react-scripts build",

A: There can be an additional problem cause. If you're using .env-cmdrc make sure that you haven't missed any commas and your file structure corresponds to the JSON structure

A: I try with this ->
env-cmd -f [path of dev.env] nodemon src/index.js and it works.

*

*"start-dev": "env-cmd -e ./dev react-scripts start",

*"build-dev": "env-cmd -e ./dev react-scripts build"

A: You just need to add an empty file called .env.local beside package.json file.
The file need to be in the outer layer.


text:
Q: Shannon entropy with regards to independent random variables I had a question regarding a question on Shannon entropy I came across. It has to do with representing entropy in the form of their probability distributions, but let me elaborate. Here's the specific problem I'm referring to:
$\space$
Consider three independent random variables $u$, $v$, and $w$ with entropies $H_u$, $H_v$, $H_w$. Let,
$$X \equiv (U,\ V)$$
$$Y \equiv (V,\ W)$$
What is $H(X, Y)$, $H(X | Y)$, and $I(X; Y)$?
$\space$
Here's what I've come up with so far:
Since the random variables $u$, $v$, and $w$ are independent,
$$P(X) = P(U)P(V)$$
$$P(Y) = P(V)P(W)$$
And since
$$P(X, Y) = P(X|Y)P(Y)$$
$$P(X|Y) = \frac{P(Y|X)P(U)}{P(W)}$$
But I'm not sure how to progress further from here... The solution my instructor provided for this particular problem in the textbook I'm using (Information Theory, Inference, and Learning Algorithms) is that:
$$P(X|Y) = \left\{
\begin{array}{c}
P(U)\ (x_2 = y_1) \\
0\ (else)
\end{array}
\right.$$
$$P(X, Y) = \left\{\begin{array}{c} P(U)P(V)P(W)\ (x_2 = y_1) \\ 0\ (else) \end{array}\right.$$
And with this result the solution is fairly easy to derive.
$\space$
What I'm wondering is, where did the $x_2 = y_1$ come from, and how were the results for those probability distributions come to be? The approach I was taking was causing me to go in circles without any real results.
Thank you.

A: Since $X = (U, V)$ and $Y = (V, W)$ share the variable $V$ in any observation of both $X =x$ and $Y=y$ there is only one fixed value for $V=v$ so that that $x_2 = v = y_1$.
Thus, any outcome where $x_2 \neq y_1$ is impossible and gets zero probability.


text:
Q: Structuremap: Scan Folder, instantiate Class by name (For.Use(string)) I'm trying to use Structuremap, which gives me a hard time since the documentation on the structure-map-site is pretty old (most the time I work with the provided code, I get an obsolete-msg in VS...)
Anyway, I'm trying to provide something like this:
private static ITest GetInstance()
{
    return (new Container(x => x.For<ITest>().Use<Test2>())).GetInstance<ITest>();
}

This piece of code works fine, BUT now I'm trying to achieve the same thing without the Class "Test2" in this project.
My goal is:
I want to have a folder with all kind of .dlls, which provides ITest-Methods (like Test1, Test2, Test3, aso).
Structuremap should register those dlls (x.Scan(s => s.AddAllTypesOf)) and with a simple string I want to tell my application to use "Test2".
Here is my idea in code-form (not working):
public static class TestHandler
{
    static TestHandler()
    {
        Tests = new Container();
        Tests.Configure(x => x.Scan(scanner =>
                                        {
                                            scanner.AssembliesFromPath(@"TestCases");
                                            scanner.AddAllTypesOf<ITest>();
                                            scanner.LookForRegistries();
                                        }));
    }
    public static Container Tests { get; set; }

    public static ITest GetHandler(string handlerName)
    {
        return Tests.Configure(x => x.For<ITest>().Use(handlerName)))
.GetInstance<ITest>(handlerName);
    }
}

So how can I create an object, which I can pass then .Use?
And what variable would I have to pass anyway?
If I have to guess, I would say one of those:

*

*Full qualified Assembly Name

*Just the name of the class (which would be in this case Test2)

*AssemblyName.ClassName

I tried the WhatDoIhave()-Method, which gives me:

ITest (smTests.ITest) TestExample1.FirstName, TestExample1,
  Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Configured Instance of
  TestExample1.FirstName, TestExample1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
  Scoped as: Transient

From that I'm quite positive that I have to use TestExample1.FirstName.
But how can I create an Instance in the first place?
Thanks!

A: This should provide you with functionality for registering and getting all types by name:
public static class TestHandler
{
    static TestHandler()
    {
        Tests = new Container();
        Tests.Configure(x => x.Scan(scanner =>
            {
                scanner.AssembliesFromPath(@"TestCases");
                scanner.AddAllTypesOf<ITest>().NameBy(i => i.Name);
            }));
    }

    public static IContainer Tests { get; set; }

    public static ITest GetHandler(string handlerName)
    {
        return Tests.GetNamedInstance<ITest>(handlerName);
    }
}


text:
Q: php Login Verification - How to retrieve and send back a value from a database to method I am new to PHP and am looking for guidance on how to send data from a database back up to a function for User Login verification purposes, essentially all I need to do is be able to send a user's salt value to the authentication function.
authentication function code:
$userSalt= $this->saltFinder($user["username"]);

This line here sends the username entered into the login form to the function meant to retrieve the user's salt value from the database.
I can retrieve the correct salt value through sql/sqlite3 statements and some array manipulation (pop/shift/implode) or by selecting the appropriate array index.
saltFinder function code:
private function saltFinder($user)
{
    $select = "SELECT usersalt FROM users
    WHERE username = :username";

    $stmt = $this->db->prepare($select);
    $stmt->bindValue(':username', $user, SQLITE3_TEXT);

    $res = $stmt->execute();
    $row = $res->fetchArray();

    $saltValue = $row[0];
}

This here will select the correct salt value I require but I am totally stumped on how to send it back up to the appropriate function so that it can continue through its process to complete user login verification.
I have tried using return() and if statements but cannot get it working, any guidance on how to solve my issue or direction to information that could help would be appreciated.
Edit:
Forgot to mention that both the authentication and saltFinder functions are within the same class, so as far as I can tell it shouldn't be an object scope issue.
I have attempted a completely different way of retrieving the user's salt value as shown here:
private function saltFinder($user)
{
    $arr = array('username'=>$user);
    $sql = "SELECT salt FROM users WHERE username = :username";
    $this->all($sql,$arr);
}

which leads to
protected function all($sql, $arr = null)
{
    $stmt = $this->db->prepare($sql);
    foreach ($arr as $key => $value) {
        $stmt->bindValue(":$key", $value, SQLITE3_TEXT);
    }
    $results = $stmt->execute();
    $this->outputNestedObject($results);
}

and ends at
protected function outputNestedObject($result)
{
    $data = array();
    while ($res = $result->fetchArray(1)) {
        array_push($data, $res);
    }
    echo "{\"data\":" . json_encode($data) . "}";
    exit();
}

These two protected functions are primarily used for other aspects of my site and I had a thought that maybe I could use them to help with my goal of user authentication and I have ended up with a JSON object displaying the following:

{"data":[{"salt":"users salt value"}]}

This here displays the correct salt value for the user as if it was pulled right from the database but again have no idea on how to send this data back to the authentication function.


text:
Q: Endomomorphisms of Chain Complexes of vector spaces and determinants Let $C_{\ast} : \cdots \to A_{2} \to A_{1} \to A_{0} \to 0$ be a chain complex of finite dimensional vector spaces over a field $K$.
And let $f_{\ast} : C_{\ast} \to C_{\ast}$ and $g_{\ast} : C_{\ast} \to C_{\ast}$ be two chain endomorphisms of $C_{\ast}$ satisfying $\det (f_{n}) \neq 0$ and $\det (g_{n}) \neq 0$ for any $n$.
Assume that the homology group $H_{n}(C_{\ast})$ is zero for all but finitely many $n$.
Then, the induced homomorphism $H_{n}(f_{\ast}) : H_{n}(C_{\ast}) \to H_{n}(C_{\ast})$ is zero for all but finitely many $n$, and so  the alternating product $\prod_{n}\det (H_{n}(f_{\ast}))^{(-1)^{n}}$ is well-defined (of course, the same holds for $g_{\ast}$).
Moreover, assume that $\det (f_{n}) = \det (g_{n})$ for any $n$.
My question is:

QUESTION
Under the above conditions, does the next equation hold up to sign?
$\prod_{n} \det (H_{n}(f_{\ast}))^{(-1)^{n}} = \prod_{n} \det (H_{n}(g_{\ast}))^{(-1)^{n}}$.

Note that if the chain complex $C_{\ast}$ is bounded above, the statement can be proved as follows:
$\prod_{n} \det (H_{n}(f_{\ast}))^{(-1)^{n}} = \prod_{n} \det (f_{n})^{(-1)^{n}} = \prod_{n} \det (g_{n})^{(-1)^{n}} = \prod_{n} \det (H_{n}(g_{\ast}))^{(-1)^{n}}$
Here, the first and the last equation can be shown by using induction on the length of $C_{\ast}$, snake lemma and the multiplicativity of $\det$ for short exact sequences. The middle equation is the result of the assumption.
The problem is that, in general, $\prod_{n} \det (f_{n})^{(-1)^{n}}$ and $\prod_{n} \det (g_{n})^{(-1)^{n}}$ are not well-defined.
By Sawin's answer
There is a counterexample if one does not admit the difference of sign.
Please give me any advice.

A: This is false. Let $C_*$ be the complex where each $C_i$ is two-dimensional and all the maps have rank one, so that there is homology only in degree $0$. Let $f$ be the identity, and let $g$ be multiplication by $-1$. Then since they are acting on two-dimensional vector spaces, their determinants are the same everywhere. But the homology group is one-dimensional, so the determinants of their action on homology are $+1$ and $-1$ respectively, which are different.


text:
Q: Как удалить дубликаты в цикле Python (спарсеные данные BeautifulSoup) def main():
    url = 'http://sample.ru'
    all_links = get_all_links(get_html(url))
    for i in all_links:
        print(i)

На выходе получаются дубликаты, так как одинаковые ссылки на странице (ссылка другая)
Хочу узнать как удалять такие

A: Если нужно сохранить исходный порядок, то можно воспользоваться OrderedDict:
In [197]: lst = ['cc','dd','aa','bb','aa','cc','bb','dd','aa']

In [198]: from collections import OrderedDict

In [199]: new = list(OrderedDict.fromkeys(lst))

In [200]: print(new)
['cc', 'dd', 'aa', 'bb']

или вот так:
In [201]: seen = set()
     ...: new = [x for x in lst if x not in seen and not seen.add(x)]

In [202]: new
Out[202]: ['cc', 'dd', 'aa', 'bb']


text: Q: Tokenstream create() I am currently creating a custom token filter factory for an elasticsearch plugin. I am new to the es plugin development. I was going through some of the existing code of token filter factory on github but was not able to understand the tokenstream create() function's working. I know what it does, but I am curious to know how it works under the hood and all the other dependencies of the file containing this function.


text:
Q: log4net dynamic filename issue I'm using log4net and trying to get a filename format that looks like this:
AriaClient_2016_11_11_08_38_54-[7988].log

I have set up the configuration like this:
<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString">
    <conversionPattern value="AriaClient_%date{yyyy_MM_dd_HH_mm_ss}-[%processid].log" />
  </file>
  <preserveLogFileNameExtension value="true" />
  <staticLogFileName value="false" />
  <param name="AppendToFile" value="true" />
  <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
  <!--+InterProcessLock-->
  <layout type="log4net.Layout.PatternLayout">
    <param name="ConversionPattern" value="%date (#%property{pid}) [%thread] %-5level %logger - %message%newline" />
  </layout>
</appender>

When generated, the filename comes out like this:
AriaClient_2016_11_11_08_38_54-[7988].2016-11-11.log

I don't understand where the second date is coming from before the .log extension. Does anyone have an idea?

A: After 10 seconds to posted this post, I found that all I had to do was set staticLogFileName to true.


text:
Q: How to pass DSN to cfcomponent datasource property What is the best practice for passing application-scoped DSN value to a component?  Is it as follows?
component datasource="#application.dsn#"

I have always thought that it's not a good practice to use application-scoped variables inside components.  Would it be better like this?
component{
    function init( dsn, arg1, arg2 ){
          this.datasource = arguments.dsn;
   }
}

A: Best practice is to keep components completely isolated from knowing anything about the outside world (including any variables external to a component, such as the application scope). You should pass in via arguments any data a component needs to fulfill it's intended purpose. So, based on that premise, your second code sample is the preferred approach.

A: @cfvonner has replied in detail and is the correct answer, I believe. ColdFusion most of times allow you to do things as you want, use DSN as session, application, request, hardcoded too. But this flexibility should not an excuse for writing poor code. And as the question itself strive for "Good Practice" and your 2nd block of code does it rightly except the point @Adam Cameron raised. In short OOPs--->ENCAPSULATION--->Passing through parameter


text:
Q: Create a startup script from Powershell on windows I'm working on an installation script of certain software I am developing. Installation of the software on a remote server requires a certain startup script to run on each boot.
I'm writing a powershell script so I'm looking for a way to create a start up script from powershell
I have the batchfile ready to execute I just need to run it on each boot of the remote server
I couldn't find any resources on Google therefore I am asking here if anyone could achieve such a result

A: This is one of the way you can create a startup script using powershell. This will create a startup script. Everytime you restart your machine, the script will execute
$TaskAction1 = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-ExecutionPolicy Bypass -File C:\scripts\Config.ps1"
$TaskTrigger = New-ScheduledTaskTrigger -AtStartup
$TaskPrincipal = New-ScheduledTaskPrincipal -UserID "NT AUTHORITY\SYSTEM" -LogonType ServiceAccount -RunLevel Highest
Register-ScheduledTask -Action $TaskAction1 -Trigger $TaskTrigger -Principal $TaskPrincipal -TaskName "Config" -Description "Config Script"

A: You can start a command procedure from PowerShell with the following code. Replace the path and file with your own information.
C:Pathfile.bat

Once you've called your batch file, you can customize it to the task at hand. For example…
If you want to capture the output of the .bat file, you can use:
$out = C:Pathfile.bat

If you want to start a process with your .bat file, you can use the PowerShell start-process cmdlet:
start-process C:Pathfile.bat

And, if you if you want to control cmd.exe, you can use this:
start-process "cmd.exe" "/c C:Pathfile.bat"

The start-process cmdlet is a standard PowerShell cmdlet, so anyone can use it. JAMS users leverage it regularly and combine it with JAMS specific cmdlets in our PowerShell snap-in to add intelligent automation to batch files.
Place it in this path:
C:\Users\<user_name>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\startup.cmd

A: To run your script on each boot of the remote server, do following settings on remote server.

*

*open task scheduler (Win+R and enter command
    "%windir%\system32\taskschd.msc /s"

*Action --> Create Task

*Select required options in 'General' tab

*Click on 'Triggers'-->New --> Begin the task: select 'At Startup'
from dropdown list.

*Click on 'Actions' --> New --> Action: 'Start a Program' -->
    Settings: path to your script.

To configure point number 5 you can take help on google.


text:
Q: Summing results in for loop with pandas I am trying to write a code to read an excel file, in which I have a list of number of machines 'No' and its price and size respectively, and I am trying to sum it to obtain the total price and total size needed. This is what I have tried, but it gives me a NaN output.
ttp = 0
tts = 0
for abcde in ws_all:
    price = fn.loc[fn['WS Name'] == abcde]['Tool Price']
    size = fn.loc[fn['WS Name'] == abcde]['Size']
    nooo = fn.loc[fn['WS Name'] == abcde]['No']
    mprice = price * nooo
    msize = size * nooo
    ttp += mprice
    print(ttp)

May i know how to troubleshoot this issue? Thank you all!

A: If your dataframe fn looks like:
# df = pd.DataFrame({'WS Name': np.random.choice(['abcde', 'fghij', 'klmno', # 'pqrst'], 20),
#                    'Tool Price': np.random.randint(10, 20, 20),
#                    'Size': np.random.randint(1, 10, 20),
#                    'No': np.random.randint(1, 10, 20)})

>>> df
   WS Name  Tool Price  Size  No
0    klmno          18     4   1
1    klmno          16     7   4
2    pqrst          15     9   8
3    pqrst          17     1   3
4    klmno          10     5   9
5    pqrst          13     9   8
6    abcde          16     8   2
7    klmno          11     5   1
8    abcde          18     1   7
9    klmno          12     7   2
10   fghij          18     7   4
11   abcde          14     1   3
12   klmno          10     6   4
13   fghij          10     6   9
14   abcde          19     9   4
15   abcde          12     8   4
16   abcde          15     3   7
17   fghij          10     6   8
18   klmno          18     8   8
19   pqrst          19     3   1

You cans use the split-apply-combine pattern:
ttp = df.groupby('WS Name').apply(lambda x: sum(x['Tool Price'] * x['No']))
tts = df.groupby('WS Name').apply(lambda x: sum(x['Size'] * x['No']))

Build your combined dataframe
>>> pd.DataFrame({"Total Price": ttp, "Total Size": tts})

         Total Price  Total Size
WS Name
abcde            429         115
fghij            242         130
klmno            391         184
pqrst            294         150


text:
Q: Python variables not defined after if __name__ == '__main__' I'm trying to divvy up the task of looking up historical stock price data for a list of symbols by using Pool from the multiprocessing library.
This works great until I try to use the data I get back.  I have my hist_price function defined and it outputs to a list-of-dicts pcl.  I can print(pcl) and it has been flawless, but if I try to print(pcl) after the if __name__=='__main__': block, it blows up saying pcl is undefined.  I've tried declaring global pcl in a couple places but it doesn't make a difference.
from multiprocessing import Pool

syms = ['List', 'of', 'symbols']

def hist_price(sym):
    #... lots of code looking up data, calculations, building dicts...
    stlh = {"Sym": sym, "10D Max": pcmax, "10D Min": pcmin} #simplified
    return stlh

#global pcl
if __name__ == '__main__':
    pool = Pool(4)
    #global pcl
    pcl = pool.map(hist_price, syms)
    print(pcl) #this works
    pool.close()
    pool.join()

print(pcl) #says pcl is undefined

#...rest of my code, dependent on pcl...

I've also tried removing the if __name__=='__main__': block but it gives me a RunTimeError telling me specifically to put it back.  Is there some other way to call variables to use outside of the if block?

A: I think there are two parts to your issue. The first is "what's wrong with pcl in the current code?", and the second is "why do I need the if __name__ == "__main__" guard block at all?".
Lets address them in order. The problem with the pcl variable is that it is only defined in the if block, so if the module gets loaded without being run as a script (which is what sets __name__ == "__main__"), it will not be defined when the later code runs.
To fix this, you can change how your code is structured. The simplest fix would be to guard the other bits of the code that use pcl within an if __name__ == "__main__" block too (e.g. indent them all under the current block, perhaps). An alternative fix would be to put the code that uses pcl into functions (which can be declared outside the guard block), then call the functions from within an if __name__ == "__main__" block. That would look something like this:
def do_stuff_with_pcl(pcl):
    print(pcl)

if __name__ == "__main__":
    # multiprocessing code, etc
    pcl = ...
    do_stuff_with_pcl(pcl)

As for why the issue came up in the first place, the ultimate cause is using the multiprocessing module on Windows. You can read about the issue in the documentation.
When multiprocessing creates a new process for its Pool, it needs to initialize that process with a copy of the current module's state. Because Windows doesn't have fork (which copies the parent process's memory into a child process automatically), Python needs to set everything up from scratch. In each child process, it loads the module from its file, and if you the module's top-level code tries to create a new Pool, you'd have a recursive situation where each of the child process would start spawning a whole new set of child processes of its own.
The multiprocessing code has some guards against that, I think (so you won't fork bomb yourself out of simple carelessness), but you still need to do some of the work yourself too, by using if __name__ == "__main__" to guard any code that shouldn't be run in the child processes.


text:
Q: Why can I not test for ParameterBindingValidationException in Pester? Given a function that has validation for a parameter:
function Test-Validation {
    [CmdletBinding()]
    param (
        [Parameter()]
        [ValidateScript({
            # Add some validation that can throw.
            if (-not (Test-Path -Path $_ -PathType Container)) {
                throw "OutDir must be a folder path, not a file."
            }
            return $true
        })]
        [System.String]
        $Folder
    )
    Process {
        $Folder + " is a folder!"
    }
}

We should be able to check the error type and set that as the ExpectedType in a Pester Test.
Test-Validation -Folder C:\Temp\file.txt
Test-Validation : Cannot validate argument on parameter 'Folder'. OutDir must be a folder path, not a file.
At line:1 char:17
+ Test-Validation C:\Temp\file.txt
+                 ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Test-Validation], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Test-Validation

$Error[0].Exception.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
False    True     ParameterBindingValidationException      System.Management.Automation.ParameterBindingException

However, when testing in Pester, the test fails because it cannot find the type.
$ShouldParams = @{
    Throw           = $true
    ExpectedMessage = "Cannot validate argument on parameter 'OutDir'. OutDir must be a folder path, not a file."
    ExceptionType   = ([System.Management.Automation.ParameterBindingValidationException])
}
{ Test-Validation -Folder C:\Temp\file.txt } | Should @ShouldParams

# Result
RuntimeException: Unable to find type [System.Management.Automation.ParameterBindingValidationException].

How can I fix this test so that I know I am not just catching any exception type?

A: To generalize your own answer a bit:

*

*Since working with the types of objects starting from a given instance isn't that common in PowerShell, the fact that an instance's type may be non-public isn't usually obvious, as long as the type derives from (is a subclass of) the expected public type.

*

*While you can obtain an object's non-public type via .GetType(), you cannot refer to it via a type literal (e.g. [System.Management.Automation.ParameterBindingException]), such as for use in Pester tests or parameter declarations.

*You can call .GetType().IsPublic on any given instance to check whether its type is public, and .GetType().BaseType to get that type's base type - though you may have to call the latter multiple types until you reach a type for which .IsPublic is $true - see the convenience function at the bottom.
In the case at hand .GetType().BaseType.FullName is sufficient to reach the public base type:
# Provoke a non-public [System.Management.Automation.ParameterBindingValidationException]
# exception.
try { & { param([ValidateScript({ $false })] $foo)} bar } catch { $err = $_ }

# Output the full name of the exception type underlying the
# statement-terminating error that the failed validation reported:
$err.Exception.GetType().FullName

# It is only its *base* type that is public and therefore usable as a type
# literal ([...]), such as in a Pester test.
$err.Exception.GetType().BaseType.FullName

The above yields:
System.Management.Automation.ParameterBindingValidationException  # non-public
System.Management.Automation.ParameterBindingException            # public base type

Below is convenience function Get-PublicType, which, given any instance, reports the most derived type in the inheritance chain of the instance's type that is public (which may be the instance's type itself:
Sample call:
PS> Get-PublicType $err.Exception

PublicType                                             NonPublicDerivedType                                               Instance
----------                                             --------------------                                               --------
System.Management.Automation.ParameterBindingException {System.Management.Automation.ParameterBindingValidationException} System.Management.Automation.ParameterBindingValidationException: Cannot validate argument on par…

Get-PublicType source code:
function Get-PublicType {

  [CmdletBinding()]
  param(
    [Parameter(Mandatory, ValueFromPipeline)]
    $Instance
  )

  process {

    $type = $Instance.GetType()
    $nonPublicTypes = @()

    while (-not $type.IsPublic) {
      $nonPublicTypes += $type
      $type = $type.BaseType
    }

    # $type.FullName
    [pscustomobject] @{
      PublicType = $type
      NonPublicDerivedType = $nonPublicTypes
      Instance = $Instance
    }

  }

}

A: The reason why you cannot capture this type is because it is not a public class within [System.Management.Automation]. Instead you can set the -ExceptionType to the class it derives from [System.Management.Automation.ParameterBindingException] and your test will now pass with validation for the exception type thrown.
$ShouldParams = @{
    Throw           = $true
    ExpectedMessage = "Cannot validate argument on parameter 'OutDir'. OutDir must be a folder path, not a file."
    ExceptionType   = ([System.Management.Automation.ParameterBindingException])
}
{ Test-Validation -Folder C:\Temp\file.txt } | Should @ShouldParams


text:
Q: DateTime change date value and set specific value of time in VB.Net I have value of this for example
Dim start_time As String = 12/30/1899 8:30:00 PM

Then i want to change it into
Dim final_start_time As String = 0000-00-00 20:30:00 ' i want to come up with this value

or another example is
   Dim start_time As String =  12/30/1899 10:30:00 AM

to
Dim final_start_time As String = 0000-00-00 10:30:00

A: Try this link:
http://msdn.microsoft.com/en-us/library/zdtaw1bw(v=vs.110).aspx
And this:
http://msdn.microsoft.com/en-us/library/vstudio/az4se3k1(v=vs.100).aspx
You use the .tostring method, and specify a format.

A: Based on your revised Question, here is some code. Revise it as necessary. I used es-ES as culture.. actually have no clue what culture that is... but on the dateformat MSDN page, that seems to generate the format you want...
Dim myOriginalDateTime As DateTime = Now
Dim mynewDateString As String = ""
Dim myFinalDateString As String = ""
Dim culture As New System.Globalization.CultureInfo("es-ES")

mynewDateString = myOriginalDateTime.ToString("G", culture)

Dim arrDateParts() As String = Split(mynewDateString, " ")

myFinalDateString = "0000-00-00 " & arrDateParts(1)

MsgBox(myFinalDateString)


text:
Q: I can't print a map with QGIS 2.8.1 and Mac OS X I'm using Mac OS X 10.7.5 and QGis 2.8.1.
I want to print a map with Print Composer. But the Buttons "Print" or "Export as PDF" don't work for me. If I use these buttons, the window for choosing a directory or printer appears but only for 1 sec. Afterwards nothing happens. What am I doing wrong?
If I want to save a QGIS Project the window for choosing a directory appears and I can choose the path. The issue is only by using Print Composer.


text:
Q: itertools product blocks, when using generators as parameters I need to construct the cartesian product of output generated by two or more generator functions on the fly.
I would like for itertools.product not to block, but instead to give mr the first product elements before the generator input functions raised StopIteration.
Is there a function that provides sth like that?
I wrote a simple program to demonstrate my problem:
#!/usr/bin/python
import time
import itertools

def g_delay(l, delay):
    for i in range(l):
        yield i
        time.sleep(delay)

def g(l):
    for i in range(l):
        yield i

if __name__ == "__main__":
    start_time = time.time()
    p = itertools.product(g_delay(2,1), g_delay(3,1))
    elapsed_time = time.time() - start_time
    print '%f' % elapsed_time
    for i in p:
        print i

    print

    start_time = time.time()
    p = itertools.product(g(2), g(3))
    elapsed_time = time.time() - start_time
    print '%f' % elapsed_time
    for i in p:
        print i

And the output:
5.004710
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)

0.000017
(0, 0)
(0, 1)
(0, 2)
(1, 0)
(1, 1)
(1, 2)

What I would like to have as a result is, that the first delay of 5.004710 seconds is similar to the latter one (0.000017) and the blocking occurs on accessing the product elements (in the for loop).

A: Here is a version of product (for just two iterators), that tries to be as lazy as possible.
def product(i1, i2):
    for a in i1:
        j2, i2 = itertools.tee(i2)
        for b in j2:
            yield (a, b)


text:
Q: Excel 2013 scatter plot Hi I'm creating a sieve analysis graph. The graph is in logarithmic scale but I want the labels in the horizontal axis to be exactly as per the sieve sizes (horizontal data values)
Can I make the horizontal axis labels reflect the sieve sizes?
Can I make the horizontal major gridlines match the plots?

A: You can use an XY Scatter chart for your main data series.
Add a helper data series with all Y values set to the minimum value of the log scale and the X values at the desired sieve sizes. Then use data labels (X Value) for that series and place them underneath the data points. Hide the X axis labels and format the helper series data markers to be invisible. Or you can use the + sign as the data marker, so it looks like a tick mark.
For major gridlines you can use error bars on the helper series. Set them to a custom value that is the same as the Max value of the Y axis.
In the screenshot I have applied this technique and used red for the error bar color and the data marker symbol. The only thing left to do is to remove the out of the box grid lines and use gray for the error bars and data marker.


text:
Q: How to capture page regions in TWebBrowser? I am trying to make a program which would make screenshots of various areas on the site that is loaded inside TWebBrowser component.
So far i have found only solutions to 'how to make screenshot of the whole page', but i just could not make it work to capture specific region, it just stretches the page in whatever direction.
http://www.delphifaq.com/faq/f408.shtml
I have been using the code presented in the site above.
Is there a way to modify the code so it would do what i need? I tried but i failed.
I would appreciate if anybody could at least give me a direction to how to solve this.
Thanks

A: I recommend to use the IHTMLElementRender interface of the HTML Elemwnt instead. You can easily find the element under the cursor and render this to a bitmap.
In my TWebBrowser descant I implemented it like this:
function TWebBrowserIBMA.ElementAsBitmap(pElement : IHTMLElement2) : TBitmap;
var
  pRender       : IHTMLElementRender;
  oBmpPart      : TBitmap;
  nClientWidth  : Integer;
  nClientHeight : Integer;
  nX            : Integer;
  nLastX        : Integer;
  bDoneX        : Boolean;
  nY            : Integer;
  nLastY        : Integer;
  bDoneY        : Boolean;
begin
  Result := TBitmap.Create;

  try
    Result.Height := pElement.scrollHeight;
    Result.Width  := pElement.scrollWidth;
  except
    exit;
  end;

  LockWindowUpdate(Handle);

  if (pElement.QueryInterface(IID_IHTMLElementRender, pRender) = S_OK) then begin
    try
      oBmpPart        := TBitmap.Create;
      oBmpPart.Width  := pElement.scrollWidth;
      oBmpPart.Height := pElement.scrollHeight;
      nClientWidth    := pElement.clientWidth;
      nClientHeight   := pElement.clientHeight;

      try
        nX      := pElement.scrollWidth;
        nLastX  := -1;
        bDoneX  := false;

        while not bDoneX do begin
          pElement.scrollLeft := nX;
          nX := pElement.scrollLeft;
          if nLastX = -1 then begin
            nLastX := nX + nClientWidth;
          end;
          nY     := pElement.scrollHeight;
          nLastY := (-1);
          bDoneY := false;

          while not bDoneY do begin
            pElement.scrollTop := nY;
            nY := pElement.scrollTop;

            if nLastY = -1 then begin
              nLastY := nY + nClientHeight;
            end;

            if (pRender.DrawToDC(oBmpPart.Canvas.Handle) = S_OK) then begin
              BitBlt(Result.Canvas.Handle, nX, nY, nLastX-nX, nLastY-nY, oBmpPart.Canvas.Handle, 2, 2,SRCCOPY);
            end;

            bDoneY  := (nY = 0);
            nLastY  := nY;
            Dec(nY, nClientHeight-4);
          end;

          bDoneX  := (nX = 0);
          nLastX  := nX;
          Dec(nX, (nClientWidth-4));
        end;
      finally
        FreeAndNil(oBmpPart);
      end;
    finally
      pRender := nil;
    end;
  end;

  LockWindowUpdate(0);
end;

A: You can use sourceBitmap.Canvas.CopyRect

A: Have you tried setting sourceDrawRect to a rectangle with negative top and left, and a right and bottom past the width and height of the bitmap you let the viewobject draw onto, so that the region you want falls onto this bitmap?


text:
Q: number of AppBarButton in PrimaryCommands Is there any limit on number of AppBarButtons that can be added in PrimaryCommands in BottomBar. I am trying to add 5th button in bottom bar but its now showing up on device. Any workaround to do this?

A: In Windows Phone 8.1 (also in 8.0) you can have up to 4 items in Application Bar (primary commands, note that you can add more options to SecondaryCommands which will show up once ellipsis is clicked). If you need more, then I you will have to create your own control that will mimic the behavior of application bar.
For more about application bar in 8.1 see MSDN and guidelines.


text:
Q: Edit Yoast SEO breadcrumbs output I want to customise the output of Yoast SEO breadcrumbs, I have this so far which works great:
add_filter( 'wpseo_breadcrumb_single_link', 'ss_breadcrumb_single_link', 10, 2 );
function ss_breadcrumb_single_link( $link_output, $link ) {
    $element = 'li';
    $element = esc_attr( apply_filters( 'wpseo_breadcrumb_single_link_wrapper', $element ) );
    $link_output = '<' . $element . ' typeof="v:Breadcrumb">';
    if ( isset( $link['url'] ) && ( $i < ( count( $links ) - 1 ) || $paged ) ) {
        $link_output .= '' . esc_html( $link['text'] ) . '';
    } else {
        if ( isset( $opt['breadcrumbs-boldlast'] ) && $opt['breadcrumbs-boldlast'] ) {
            $link_output .= '' . esc_html( $link['text'] ) . '';
        } else {
            $link_output .= '
' . esc_html( $link['text'] ) . '
';
        }
    }
    $link_output .= '</' . $element . '>';
    return $link_output;
}

add_filter( 'wpseo_breadcrumb_output_wrapper', 'ss_breadcrumb_output_wrapper', 10, 1 );
function ss_breadcrumb_output_wrapper( $wrapper ) {
    $wrapper = 'ol';
    return $wrapper;
}

Next step is to change this line:
return apply_filters( 'wpseo_breadcrumb_output', '<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>' );

I want to add an aria element of aria-labelledby="breadcrumblabel" to that output. So I setup this function:
add_filter( 'wpseo_breadcrumb_output', 'ss_breadcrumb_output' );
function ss_breadcrumb_output() {
    return apply_filters( 'ss_breadcrumb_output', '<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>' );
}

Problem I am having is $wrapper $id $class and $output all return null. I think I know why they are null although as a PHP beginner I can't explain it.
If someone could point me in thr right direction so I can go figure this out, i'd appreciate it.
Thanks.

A: http://wpquestions.com/question/showChrono/id/8603
I used the first function using str_replace
add_filter( 'wpseo_breadcrumb_output', 'custom_wpseo_breadcrumb_output' );
function custom_wpseo_breadcrumb_output( $output ){
    if( is_page() ){
        $from = '...';   // EDIT this to your needs
        $to     = '';
        $output = str_replace( $from, $to, $output );
    }
    return $output;
}

A: They are all null. You haven't set any of those variables. Here is your function.
function ss_breadcrumb_output() {
    return apply_filters( 'ss_breadcrumb_output', '<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>' );
}

All of the variables in that function are isolated to that function. Variables set outside that function don't work. Since you haven't set any variables (in the function), and they aren't passed into the function, they are empty.  It is a matter of scope. There are ways around that, like globalization, but that isn't critical to this question so I'll leave you to your own devices.
But to your problem... Look at the filter where it is applied in the plugin.
return apply_filters( 'wpseo_breadcrumb_output', '<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>' );

I think this may be where you are going wrong. This--'<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>'-- is all one parameter. That . is string concatenation operator, meaning all of that is merged together into a string. When that is passed to the filter, there are no variables anymore. They are passed to the filter as a simple string.
Your function could catch and manipulate that string if you added parameter like:
function ss_breadcrumb_output($output) {
    var_dump($output); // you should see the string referred to above
    return apply_filters( 'ss_breadcrumb_output', '<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>' );
}

I am confused about this part: return apply_filters( 'ss_breadcrumb_output', '<' . $wrapper . $id . $class . ' xmlns:v="http://rdf.data-vocabulary.org/#">' . $output . '</' . $wrapper . '>' );
If you are trying to pass the breadcrumb output to another filter (of your creation, I assume) you'd want:
function ss_breadcrumb_output($output) {
    return apply_filters( 'ss_breadcrumb_output', $output );
}

But why? Anything you could do with that you could do with the wpseo_breadcrumb_output filter.
I think you just want:
function ss_breadcrumb_output($output) {
    $output = preg_replace('/([^>]+)>(.*)/','$1 aria-labelledby="breadcrumblabel" >$2',$output);
    return $output;
}

I should also not that regex on markup is pretty dicey. It is easy to get it wrong. Use with caution.


text:
Q: How to create a jar without manifest file and main class? I have around 40 to 50 class files, and none have a main method or a manifest file. Now I have to create a JAR file from these files. How do I do this?

A: $ jar cf myjarfile.jar *.class

will create a jar file with a manifest containing info about the jar file, but without specifying a main class. A main class is not mandatory (e.g. if you're simply creating a library and not an application jar)
Or (perhaps more what you want), the M flag
$ jar cMf myjarfile.jar *.class

will create the jar file without the manifest.

A: Try this (Linux).
zip -r jar.zip classPathDirHere (just create zip)
mv jar.zip jar.jar (just rename)


text:
Q: How to convert .npy(numpy) file to .png file where .npy array shape (30,256,256)? I want to convert .npy file to .png file
from scipy.misc import toimage, imsave
img_array = np.load('MRNet-v1.0/train/sagittal/0003.npy')
print(img_array.shape)
name = "img"+str(i)+".png"
imsave(name,img_array)

shape : (30,256,256)
But getting error like
ValueError: 'arr' does not have a suitable array shape for any mode.

A: First of all, these scipy image tools are deprecated and will be removed in the future (beginning at scipy version 1.2.0). Instead, install imageio and then run:
import imageio
for i in range(30):
    imsave("./slice_{0}.png".format(i), img_array[i,...])


text:
Q: Doing concrete multiplication of two positive rational Dedekind cuts using definition(s) According to what I have learned about rational Dedekind cut,
the multiplication of two positive rational cuts $u$, $v$ is defined as the following:

In Rudin's Principles of Mathematical Analysis:   $uv\triangleq\{q\in\mathbb{Q}|\text{there exist }{r}\in{u}\text{ and }s\in{v}\text{ such that }r>0\text{ and }s>0\text{ and }q<rs\}$.

and,

In Pugh's Real Mathematical Analysis:   $uv\triangleq\{q\in\mathbb{Q}|q<0\text{ or there exist }r\in{u}\text{ and }s\in{v}\text{ such that }r>0\text{ and }s>0\text{ and }q=rs\}$.

Now consider:
$a\triangleq\{q\in\mathbb{Q}|q<0\text{ or }q^2<2\}$ is a rational cut representing the real number $\sqrt{2}$,
$b\triangleq\{q\in\mathbb{Q}|q<2\}$ is a rational cut representing the real number $2$,

Question:  How to prove that $aa=b$ using the above fancy definition(s) for the multiplication of two positive rational cuts?

A: If $q \in aa$ and $q>0$ (WLOG, if $q<0$, $q <2$ and we're done), we know there are $r,s\in a$ with $r,s>0$ and $q < rs$ (Rudin style). By definition of $a$ we know that r^2 < 2 and $s^2 < 2$ so $q^2 < r^2s^2 < 4$. This implies $q< 2$ (as $q \ge 2$ would imply $q^2 \ge 4$ etc., by standard ordered field properties of $\Bbb Q$).
So $aa \subseteq b$ (With $q=rs$ the argument is almost identical).
Now try to do the other inclusion yourself.