text:
Q: edittext setvisibility giving null exception I am trying to set my edittext to hide when i open the dialog box but when i check the checkbox it should get visible... this dialop is in my options selected menu
unfortunately i am getting this exception

07-31 15:23:31.129: E/AndroidRuntime(4143): FATAL EXCEPTION: main
  07-31 15:23:31.129: E/AndroidRuntime(4143): java.lang.NullPointerException
  07-31 15:23:31.129: E/AndroidRuntime(4143):     at com.EVS.homeautomation.MainActivity.onOptionsItemSelected(MainActivity.java:1153)

here is the code
 final Dialog dialog = new Dialog(MainActivity.this);
            dialog.setContentView(R.layout.testing);
            dialog.setTitle("Configurations");

            final EditText up_num=((EditText)findViewById(R.id.unum));
            up_num.setVisibility(View.VISIBLE);
           CheckBox cb= ((CheckBox) findViewById(R.id.checkBox1));
            cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
            {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    if ( isChecked )
                    {
                        up_num.setVisibility(View.VISIBLE);
                        // perform logic
                    }
                    else
                    {
                        up_num.setVisibility(View.GONE);
                    }

                }
            });

A: You are invalidating EditText that is into the Dialog.So you have to initialize this EditText using this way:
EditText up_num=((EditText) dialog.findViewById(R.id.unum));

Thanks

A: First you have to inflate the view then you can call setContentView()
So you can try :
final Dialog dialog = new Dialog(MainActivity.this);

LayoutInflater inflater1 = this.getLayoutInflater();

        final View customview = inflater1.inflate(
                R.layout.testing, null);
dialog.setContentView(customview);

            dialog.setTitle("Configurations");

            final EditText up_num=((EditText)findViewById(R.id.unum));
            up_num.setVisibility(View.VISIBLE);
           CheckBox cb= ((CheckBox) findViewById(R.id.checkBox1));
            cb.setOnCheckedChangeListener(new OnCheckedChangeListener()
            {
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
                {
                    if ( isChecked )
                    {
                        up_num.setVisibility(View.VISIBLE);
                        // perform logic
                    }
                    else
                    {
                        up_num.setVisibility(View.GONE);
                    }

                }
            });

i hope this will help you :)


text:
Q: Duplicate bindings with TestInstallIn for instrumented test I'm using Hilt to inject some dependencies like so:
@Module
@InstallIn(SingletonComponent::class)
object SomethingModule {

    @Provides
    fun provideSomething(@ApplicationContext context: Context): Something {
        //return RealSomething
    }
}

I want to replace this binding in my tests and following this guide I added this fake module to the same folder as my instrumented test:
@Module
@TestInstallIn(
    components = [SingletonComponent::class],
    replaces = [SomethingModule::class]
)
object FakeSomethingModuleModule {

    @Provides
    fun provideSomethingModule(): Something {
        return FakeSomething()
    }
}

When I try to run my instrumented test the build fails with a duplicate binding error:
error: [Dagger/DuplicateBindings] com.example.Something is bound multiple times:
  public abstract static class SingletonC implements HiltWrapper_ActivityRetainedComponentManager_ActivityRetainedComponentBuilderEntryPoint,

Commenting out the Fake Module fixes the issue. Anyone see what I'm missing here?
EDIT: Just tried with @UninstallModules and ran into the same build error:
@UninstallModules(SomethingModule::class)
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class MyInstrumentedTest {

    @Module
    @InstallIn(SingletonComponent::class)
    object FakeSomethingModule {

        @Provides
        fun provideSomthing(): Something = FakeSomething()
    }

A: I tried lots of different things in order to finally get to a solution:

*

*Make sure the fake implementations have @Inject constructor()

*In the test @Module use @Binds and an abstract class instead of @Provides

*You don't need a component that combines all your modules, this code is not necessary:
@Module(
    includes = [ <modules> ]

*It wasn't apparent in this sample but in my actual code the module I was trying to test was included as a binding to another class using @Module(includes = SomethingBinding). I created a module just for the object I wanted to mock in my instrumented tests

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to retrieve access token from ClaimsTransformationContext I am using Identity Server 4 to secure an mvc app and all peripheral APIs. During principal creation I'm using the claims transformation middleware, in which I'd like to make a call to a secured API for additional information.
The claims transformation middleware is wired up in the Configure method like so:
 app.UseClaimsTransformation(o => new ClaimsTransformer().TransformAsync(o));

And the ClaimsTransformer class looks like:
   public async Task<ClaimsPrincipal> TransformAsync(ClaimsTransformationContext    context)
   {
       // meat and potatoes goes here...
       return context.Principal;
   }

I've tried getting the access token from the ClaimsTransformationContext with the following code within TransformAsync, however this seems to result in an infinite loop back to the TransformAsync method on the ClaimsTransformer class.
 var accessToken = context.Context.Authentication.GetTokenAsync("access_token");

Is it possible to retrieve the access token during the .net core claims transformation?
Or is this specific API call something htat shouldn't be done on behalf of the user and better handled one step up and suited for a more server to server approach (client credentials grant)?


text:
Q: ActionScript: Using 'in' on protected/private variables? Is there any way to mimic the in operator, but testing for the existence of protected or private fields?
For example, this:
<mx:Script><![CDATA[
    public var pub:Boolean = true;
    protected var prot:Boolean = true;
    private var priv:Boolean = true;
]]></mx:Script>

<mx:creationComplete><![CDATA[
    for each (var prop in ["pub", "prot", "priv", "bad"])
        trace(prop + ":", prop in this);
]]></mx:creationComplete>

Will trace:

pub: true
prot: false
priv: false
bad: false

When I want to see:

pub: true
prot: true
priv: true
bad: false

A: you can just try to access it and catch resulting errors. :)
in is unaware of any namespaces currently opened (including private and protected in your case), and will only look within the public namespace.
in for objects actually just calls Object::hasOwnProperty. Unfortunately, you effectively cannot override this method to alter its behaviour. the only class that can influence it is flash.utils::Proxy, which actually uses flash_proxy::hasProperty to to determine the return value of hasOwnproperty.
So no, other than trying, there's no other way sadly.

A: How about:
  <mx:creationComplete>
    for each (var prop:String in ["pub", "prot", "priv", "bad"])
    {
      try
      {
        t.text += prop + ":" + this[prop] + "\n";
      }
      catch (e:Error)
      {
        t.text += prop + ": false" + "\n";
      }
    }
  </mx:creationComplete>


text:
Q: Why can I use 1.5px as size? I knew that 1px is the smallest unit that a computer can represent. But when I put 1.5px in css, it worked. Moreover, this 1.5px was bigger than 1px and smaller than 2px.
So, does that mean that px is not the smallest unit that can be expressed on a monitor?
Is it okay to use units smaller than 1px?

A: "I know that 1px is the smallest unit that a computer can represent" - what does this mean?
I think there may be some confusion between different types of pixel. There are device pixels, the 'blobs' that make up a physical screen. And there are CSS pixels.
In the 'old days' often a CSS pixel and a screen pixel would match so, yes, one CSS pixel was the minimum that could be represented on the physical device.
But nowadays often several device pixels are used to represent one CSS pixel.
This means that fractions of a CSS pixel may be able to be represented with more accuracy than in the past.
Hence a CSS value such as 1.5px may get represented accurately on a device which is using say 2 physical pixels (in each direction) to represent one CSS pixel.
A warning though- different devices use different numbers of physical pixels per CSS pixel, and browsers can interpret things differently and odd little fractions of CSS pixels can get 'left behind' when the system is trying to decide how to split things.

A: Although you can use fractional pixels (since the very first version of CSS, as stated in this question), your browser will round it to the closest integer.
To answer your question of why it can be done, I see one major use case: calc().
Let's say you have the following CSS code:
:root {
  --small-unit: 1px;
  --large-unit: 1.5px;
}

#something {
  width: calc(100 * var(--small-unit));
  height: calc(100 * var(--large-unit));
}

In that case, although --small-unit and --large-unit are visually the same when applied directly on screen, they are not the same when multiplied by 100. #something will be 100px wide and 150px high.


text:
Q: Preg match patterns for PHP and JS could you help me with preg_match patterns for php and js, I want users to be abel to enter only number `
from 0.5 то 8.
The step between number is 0.5 i.e.
 0.5 , 1 , 1.5 , 2, 2.5 and so one up to 8

so users can't input numbers like:
2.3 2.7  and so on

A: JavaScript
var string = '7.5';
var pattern = new RegExp('^([1-8]|([0-7]\.5))$');

pattern.test(string);

A: Php:
<?php
$string = '7.5';
var_dump(preg_match('~^([1-8]|([0-7]\.5))$~', $string));

Online demo


text:
Q: Adding Version number as well as Document ID Value to a Sharepoint Online Word document I've read many articles on this now but it seems the the {version} tag it's no longer possible to add the {version} tag as an option in a content type information management policy in the  label format field in sharepoint online. In addition, it looks like the label field is no longer shown as an option in Word Quick Parts any more (unlike the document id value). Anyone know how I can do this please?

A: Per my test, I can create a {Version} label in Information Management Policy settings in SharePoint Online library.

And I can also insert the label in Word after open document from SharePoint Online library.


text:
Q: How to prove a tempered distribution is in $L^p(\mathbb{R}^n)$ Given $g \in L^p(\mathbb{R}^n)$, how can I to prove that the tempered distribution  $$f=\mathcal{F}^{-1}[(z-4\pi^2|x|^2)^{-1}\mathcal{F}g]$$ is in $L^{p}(\mathbb{R}^n)$ where $z \in \{u \in \mathbb{C}-\mathbb{R}_{+};Re(u) \geq 0\}, x \in \mathbb{R}^n$ and $\mathcal{F}$ and $\mathcal{F}^{-1}$ denotes the Fourier Transforms and Inverse Fouries Tranformes respectively?
This problems appears in a proof line of theorem 2.3.3, pg 40, from book "The Theory of Fractional Powers of Operators", by C. Martínez Carracedo and M. Sanz Alix.

A: Try to write $k \mapsto (z- 4 \pi^2 |k|^2)^{-1}$ as the Fourier transform of a function $h\in L^1$ (try a multiple of $x \mapsto e^{-\alpha |x|}$, with $\alpha$ a square root of $-z$ - notice the condition on $z$ is what ensures you can pick a square root with strictly positive real part which is needed to get it to be in $L^1$), then recall $$\mathcal F h  \cdot \mathcal F g = \mathcal F (h * g),$$so you are looking at $h * g$ which is in $L^p$ by Young's inequality.


text:
Q: AUTO_INCREMENT in composite key I have table as below
personalInfo
CREATE TABLE personalInfo(userid BIGINT AUTO_INCREMENT PRIMARY KEY)

patentInfo
CREATE TABLE patentInfo
(
 userid BIGINT,
 patentId BIGINT AUTO_INCREMENT,
 FOREIGN KEY (userid) REFERENCES personalInfo(userid),
 PRIMARY KEY (userid,patentId)
)

While creating table patentInfo, I am getting error as
Incorrect table definition; there can be only one auto column and it must be defined as a key.

What I want to do is add patent for Users. So I was trying to use patentId as AUTO_INCREMENT and keep compiste primary key as combination of patentId & userid.
Any idea how can I get this done?
Update 1:
My AIM is, I don't want to insert patentId in mysql query. mysql itself will create next number.

A: Since patentId is AUTO_INCREMENT, then the it should be the primary key.

A: I'll use a Person instead user -- suppose you have a clinic...

*

*Patient is a Person

*Doctor is a Person

*Doctor may become (is a) a Patient too.

*

*Keep all common personal information in Person

*Only patient-specific columns in Patient

*Only doctor specific in Doctor

*The subtype is inclusive, so discriminator has {B= both}

*Note how primary key propagates into sub-type tables.

To summarize, for your specific example, both tables should have UserID as the primary key. In the second table it is also a foreign key too.

A: you cannot have to auto-increment values in one table. so You have to manally insert the userid in patentinfo table at code level by using last_insert_id() or something similar to that instead of doing this at db-level

A: It seems you can have a composite primary key with one auto_increment column provided the auto_increment column is the first clause to the primary key.
The following works on my machine
CREATE TABLE patentInfo
(
  userid BIGINT,
  patentId BIGINT AUTO_INCREMENT,
  PRIMARY KEY (patentId, userid)
)

Where as
PRIMARY KEY (userid, patentId)

gives the error you are seeing.
Tested on MariaDB 10.0 YMMV


text:
Q: Why is the SSRS Barcode breaks up with a space in between? I have a SSRS report which I've initially created with SQL Server 2014 Report Builder (12.0.6024.0) using Code128 according to this post. It has been working great until we wanted to upgrade our SQL Server to 2016 and then I made the same report using SQL Server 2016 Report Builder (15.0.19611.0).
Now the issue is the new version does not support that custom code which I got from above mentioned post. After installing many Code128 fonts found one of them that works but it did not like all other fonts and barcodes won't show up.
So it would look like following figure

As the counter attack I installed that previously mentioned working one Code128 font which is IDAutomationC128L and turns out it works really until I realize this one glitch. As you can see in the bottom picture I compared the working version(2014) with the new version (2016) the glitch is there is a space in the middle of the barcode, sometimes it's in the Item Number field and sometimes it's under Raw Material Item Number field.
Here's the SQL Server 2014 version(Code128) for the same parameter

Here's the SQL Server 2016 version(IDAutomationC128L) for the same parameter

Does anybody know how to fix that issue? I have tried couple of other things too just to make sure, such as attaching the newest .NET version's(4.8.4390.0) System.Drawing.dll just becuase I thought SQL Server 2016 might not support .NET version 2.0(which I'm using for SQL Server 2014)
Appreciate all your support!


text:
Q: Relationship between minima of scalar potential and mass of particles in the theory? Consider the free scalar field theory
$$
\mathcal{L}=\partial _\mu \phi \partial ^\mu \phi^* - V(|\phi|)
$$
where $V(|\phi|)=-m^2|\phi|^2$.
There are several answers on this site about why the quadratic term in the Lagrangian corresponds to the mass (see here and here for instance). But most of these explanations assume there are no higher-order terms in the scalar potential. What happens if we have a more complicated scalar potential such as $V(|\phi|)=-a^2|\phi|^2+b^2|\phi|^4$?  Is the mass still just $a$ or would it be some combination of $a$ and $b$? The difference here is that now the potential has minima at $V(|\phi|)\neq 0$.
Do the locations of the minima of the potential have any affect on what we consider the mass of the particle in the theory? i.e. in an interacting theory would a field configuration be considered more or less massive than the free theory?

A: As far as I understand the mass $m_P$ of an asymptotic (i.e. observable) particle,e.g. corresponding to some scalar field $\phi$, is the location of the pole of the full two-point function, i.e.
$$
\int d^4x~e^{ip(x-y)}\langle \Omega | T \phi(x) \phi(y) |\Omega \rangle = \frac{i Z}{p^2 - m_P^2 + i0} + \text{terms regular at }p^2 = m_P^2.
$$
Note that $m_P$ is not the bare mass $m$ appearing in the Lagrangian, in fact the bare mass is formally divergent. $m_P$ receives perturbative corrections, so it does indeed depend on the interaction terms.
The bare mass is the mass of the free theory, where all the interactions terms, i.e. all non-quadratic terms, are zero, but it is by no means a physical quantity, just a parameter.
I should also mention that the minima business that you mention is related to the Spontaneously broken symmetry Lagrangians. In such cases in order to do perturbation theory, one has to expand the fields around the minimum which changes the terms in the Lagrangian. It is important to understand that the actual observable particle corresponds to excitations around the vacuum, i.e. it corresponds to the field after you did the expansion. As said above, the mass of this particle is then the location of the pole of its full 2-pt function.

A: So the simplest explanation of why the quadratic term is the mass term is because it generates the correct mass term in the equations of motion,
\begin{equation}
\mathcal{L} = \partial_\mu \phi \partial^\mu \phi^* - m^2 |\phi|^2 \quad \longrightarrow (\square + m^2 ) \phi = 0.
\end{equation}
Under normal circumstances, the quadratic part is not included in the potential, simply because it is the mass term. This is true as long as $a^2 < 0$ in
\begin{equation}
\mathcal{L} = \partial_\mu \phi \partial^\mu \phi^* - V(|\phi|), \quad V(|\phi|) = -a^2 |\phi|^2 + b^2 |\phi|^4.
\end{equation}
In this case you have a minimum at $\phi = 0$ and thus no spontaneous symmetry breaking (SSB). If $a^2 >0$, then you are right and the vacuum state is no longer at $\phi =0$ hence we have SSB. However then $a^2$ is no longer the mass-term because $\phi$ is no longer a physical field since physical fields require a vanishing vacuum expectation value (VEV). The physical fields are obtained by expanding around the VEV. A quick calculation shows you that you'll get one massless scalar (the Goldstone boson) and one boson with mass $\sqrt{2} a$.


text:
Q: How to reset msconfig My friend told me that when he changed his msconfig cores from 1 to 2 his laptop performance increased. So I changed it from 1 to 2 the clickled apply without restarting my pc. Then I regretted it and switched back to one core without restarting. Now I'm standing here with my BIOS open because qhen I start up my pc it doesn't matter if I pick start windows normally it always redirects me to launch startup repair which does nothing. I have an Optiplex 760.

A: *

*Press Windows key + X key. And select Run.

*Type msconfig in the Run box and hit Enter.

*On the Services tab of the System Configuration dialog box, tap or click to select the Hide all Microsoft services check box, and
then tap or click Enable all.

*On the Startup tab of the System Configuration dialog box, tap or click Open Task Manager.

*On the Startup tab in Task Manager, for each startup item, select the item and then click Enable.

*Close Task Manager.

*On the Startup tab of the System Configuration dialog box, tap or click OK, and then restart the computer.


text:
Q: Delete photo from custom photo album ios I am working in IOS app which load photos from custom album. Now I need to delete photo from custom album. Is there any ways to delete photos.
Thanks in advance
Varadharaj

A: Sorry, You cannot delete any photo saved in the User Album. Apple didn't provided APIs to do that.


text:
Q: Complex-valued spacetime curvature I've just been reading about tachyons and tachyonic fields, and although they probably don't exist/are wildly unstable, I'm curious: What does imaginary mass do to spacetime curvature? Does 'complex valued curvature' even have a single plausible meaning the way real-valued curvature does?

A: The notion of complex curvature does exist: see Y. Martinez-Maure, Real and complex hedgehogs, their symplectic area,curvature and evolutes. For instance, a complex circle with (complex) radius R has a (complex) radius of curvature equal to R (see page 17).
The author says the paper is to appear in the Journal of Symplectic Geometry.


text:
Q: How to show that $\sqrt{p\over p+1}$ is irrational? I want to prove that $\sqrt{p\over p+1}$ is irrational where $p$ is any prime number.
I have been thinking about this problem for several hours without any progress.
To show that $\sqrt{p\over p+1}$ is irrational, I assume that it is rational. So there are integers $m$ and $n$ (which have no common divisors) such that $\sqrt{p\over p+1}=\frac{m}{n}$. By squaring and rearranging, I get $pn^2=(p+1)m^2$ but I am not sure how to proceed from here. I can say that $(p+1)m^2$ is divisible by $p$ and then I do not know what to do!

A: Suppose
$$\sqrt\frac p{p+1}=\frac mn\;,\;\;m,n\in\Bbb Z\;,\;\;\frac mn\;\;\text{ is a reduced fraction} \implies pn^2=m^2(p+1)\implies p\,\mid\,m$$
since clearly $\;p\;$ divides the left side and $\;p+1\;$ cannot be divisible by $\;p\;$, but then
$$\;m=pk\implies m^2=p^2k^2\implies pn^2=m^2(p+1)=p^2k^2(p+1)\implies n^2=pk^2(p+1)$$
and thus also $\;p\,\mid n\;$ , contradiction.

A: Here's an alternative proof.
Consider the polynomial $(p+1)X^2-p$. By Eisenstein's criterium this polynomial is irreducible over $\mathbb{Q}$. Clearly $\sqrt{\frac{p}{p+1}}$ is a root of this polynomial. It follows that the extension degree $[\mathbb{Q}(\sqrt{\frac{p}{p+1}}):\mathbb{Q}]=2$. In particular this implies that $\sqrt{\frac{p}{p+1}}\notin \mathbb{Q}$.
Once you understand Eisenstein's criterium and field extensions you'll probably like this method. But it is of course overkill compared to the standard method.


text:
Q: Accessing the same object instance from multiple Threads I'm developing application in JavaFX and I have the following structure with the object "config" which is created in the class Controller and then I'm accessing the config from the two classes which extend the original Controller class and also from other Thread.
public class Controller {

    protected Config config = new Config();

    private void setupConfig() {
        var machineStatus = new MachineStatus();
        machineStatus.setRemainingTime(25);
        machineStatus.setMessage("Running");
        config.setMachineStatus(machineStatus);
    }
}

public class MainController extends Controller {
    Thread taskThread = new Thread(new Runnable() {
                @Override
                public void run() {
                    while(true) {
                        var newStatus = getNewStatus();          // Returns new status containing different RemainingTime and Message value every time
                        config.setMachineStatus(newStatus);
                        Thread.sleep(10000);
                    }
                }
    });
    taskThread.start();
}

public class StatusController extends Controller {
    System.out.println(config.getMachineStatus().getRemainingTime()) // Always prints 25
    System.out.println(config.getMachineStatus().getMessage())      // Always prints "Running"
}

public class Config {
    private MachineStatus machineStatus;

    public MachineStatus getMachineStatus() {
        return machineStatus;
    }

    public void setMachineStatus(MachineStatus value) {
        machineStatus = value;
    }
}

public class MachineStatus {
    private int remainingTime;
    private String message;

    public int getRemainingTime() {
        return remainingTime;
    }

    public void setRemainingTime(int value) {
        remainingTime = value;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String value) {
        message = value;
    }
}

I would like to achieve that when I call getRemainingTime() or get Message() in the StatusController, I will always get the latest status which was written in the config variable. But instead, I'm still getting the initial values which were stored when the variable was initialized.
The second Thread runs every 10 seconds and always updated the config variable with the new machine status. Even if I let the second Thread running for several minutes, in StatusController, I'm always getting the initial values.
Could someone help me how to achieve this?

A: Ah, got it.
Looks like you think that StatusController and MainController access to the same instance of Config. But it doesn't work like that.
StatusController extends Controller
MainController extends Controller

Each controller have the own Config object instance. It means that MainController change config of MainController. But StatusController have the own Config.
You need to have access to the Config of MainController and print their status.
The second issue. Config is not thread safe. You may not see changes of threads due to CPU cache and etc. You could use any synchronization concept for solving it.
rzwitserloot - Already answered...


text:
Q: Validating django models on runserver command I want to create some custom validation on models when I do python manage.py runserver command.
Can I do this somehow?

A: Well, the problem in fact is that you want to run some custom code when your server starts up.
Two possibilities:

*

*Use wsgi.py as suggested by this post. This seems to be the more elegant solution.

*Put all your code inside some __init__.py file. Be warn that this code will be executed any time you import that package (for example, when you run a django command)


text:
Q: Hilbert tree: Does anyone know where to find a code implementation of this? I'm looking for the code or even a visual demo on how this tree works.
I have read this paper on Hilbert R-Trees and tried to implement the algorithms stated
I get lost when I have to adjust the tree with the sets, as well as not sure on most other things.
It doesn't matter what language if there is an implementation as it will be used to build a C# implementation and I will be using it for reference.
Its for moving points with boundaries, that needs to have very fast insert and update calls.

A: Try these links for a R-Tree demo
http://gis.umb.no/gis/applets/rtree2/jdk1.1/
http://gist.cs.berkeley.edu/libgist-2.0/amdb_demo.html
http://donar.umiacs.umd.edu/quadtree/points/rtrees.html
cheers

A: If you are looking for an Hilbert tree, this might help:
https://code.google.com/p/uzaygezen/
If you need a spatial index with fast delete/insert capabilities, have a look at the PH-tree. It partly based on quadtrees but faster and more space efficient.
Btw, the Hilbert curve is a space filling curve. The PH-Tree also uses a space filling curve internally, however it does not use the Hilbert curve but the z-curve (Morton order) which is much easier to calculate.


text:
Q: Is RVO (Return Value Optimization) applicable for all objects? Is RVO (Return Value Optimization) guaranteed or applicable for all objects and situations in C++ compilers (specially GCC)?
If answer is "no", what are the conditions of this optimization for a class/object? How can I force or encourage the compiler to do a RVO on a specific returned value?

A: Return Value Optimization can always be applied, what cannot be universally applied is Named Return Value Optimization. Basically, for the optimization to take place, the compiler must know what object is going to be returned at the place where the object is constructed.
In the case of RVO (where a temporary is returned) that condition is trivially met: the object is constructed in the return statement, and well, it is returned.
In the case of NRVO, you would have to analyze the code to understand whether the compiler can know or not that information. If the analysis of the function is simple, chances are that the compiler will optimize it (single return statement that does not contain a conditional, for example; multiple return statements of the same object; multiple return statements like T f() { if (condition) { T r; return r; } else { T r2; return r2; } } where the compiler knows that r or r2 will be returned...)
Note that you can only assume the optimization in simple cases, specifically, the example in wikipedia could actually be optimized by a smart enough compiler:
std::string f( bool x ) {
   std::string a("a"), b("b");
   if ( x ) return a;
   else return b;
}

Can be rewritten by the compiler into:
std::string f( bool x ) {
   if ( x ) {
      std::string a("a"), b("b");
      return a;
   } else {
      std::string a("a"), b("b");
      return b;
   }
}

And the compiler can know at this time that in the first branch a is to be constructed in place of the returned object, and in the second branch the same applies to b. But I would not count on that. If the code is complex, assume that the compiler will not be able to produce the optimization.
EDIT: There is one case that I have not mentioned explicitly, the compiler is not allowed (in most cases even if it was allowed, it could not possibly do it) to optimize away the copy from an argument to the function to the return statement:
T f( T value ) { return value; } // Cannot be optimized away --but can be converted into
                                 // a move operation if available.

A:
Is RVO (Return Value Optimization) guaranteed for all objects in gcc compilers?

No optimisation is ever guaranteed (though RVO is fairly dependable, there do exist some cases that throw it off).

If answer is "no", what is the conditions of this optimization for a class/object?

An implementation detail that's quite deliberately abstracted from you.
Neither know nor care about this, please.

A: To Jesper: if the object to be constructed is big, avoiding the copy might be necessary (or at the very least highly desirable).
If RVO happens, the copy is avoided and you need not write any more lines of code.
If it doesn't, you'll have to do it manually, writing extra scaffolding yourself. And this will probably involve designating a buffer in advance, forcing you to write a constructor for this empty (probably invalid, you can see how this is not clean) object and a method to 'construct' this invalid object.
So 'It can reduce my lines of code if it's guaranteed. Isn't it?' does not mean that Masoud is a moron. Unfortunately for him however, RVO is not guaranteed. You have to test if it happens and if it doesn't, write the scaffolding and pollute your design. It can't be herped.

A: Move semantics (new feature of C++11) is a solution to your problem, which allows you to use Type(Type &&r); (the move constructor) explicitly, instead of Type(const Type &r) (the copy constructor).
For example:
class String {
  public:
    char *buffer;

    String(const char *s) {
      int n = strlen(s) + 1;
      buffer = new char[n];
      memcpy(buffer, s, n);
    }

    ~String() { delete [] buffer; }

    String(const String &r) {
      // traditional copy ...
    }

    String(String &&r) {
      buffer = r.buffer; // O(1), No copying, saves time.
      r.buffer = 0;
    }
};

String hello(bool world) {
  if (world) {
    return String("Hello, world.");
  } else {
    return String("Hello.");
  }
}

int main() {
  String foo = hello();
  std::cout <<foo.buffer <<std::endl;
}

And this will not trigger the copy constructor.

A: I don't have a yes or no answer, but you say that you can write fewer lines of code if the optimization you're looking for is guaranteed.
If you write the code you need to write, the program will always work, and if the optimization is there, it will work faster. If there is indeed a case where the optimization "fills in the blank" in the logic rather than the mechanics of the code and makes it work, or outright changes the logic, that seems like a bug that I'd want fixed rather than an implementation detail I'd want to rely on or exploit.


text:
Q: How does write cache work with a filesystem spanning disks with different speeds? On a modern Linux system with multiple disks and a software RAID spanning both slow (HDD) and fast (SSD) drives, how are writes to the filesystem cached?
For md-raid RAID1 the array can be configured with disks as --write-mostly and --write-behind which suggests that reads are performed from the faster disk, and that writes to the slower disk can lag behind. But how is that cached at kernel level? Does the kernel cache the disk writes before or after the md-raid layer? At the end of a write() call is the data guaranteed to be written to one of the not---write-behind disks?
For a btrfs RAID1 how would the same situation play out? There's no --write-behind functionality, so are dirty pages counted at a device level or filesystem level? At what point would a write() return?
How do the vm.dirty_*ratio tunables affect these setups?

A: The --write-mostly, --write-behind is handled by the md driver internally. md keeps metadata, like the write-intent bitmap (which is mandatory for the write-behind feature) that basically logs which data has been written yet vs. which data is still missing. This is necessary in case there is a power loss event, when the data hasn't reached the write-mostly devices yet. In that case the affected data area will be re-synced (in your case read from SSD, write to HDD).

But how is that cached at kernel level?

For the write-behind case, the md driver basically duplicates the write request internally. The master write request goes to the primary drive(s) and tells the upper layers "OK I've done this already"; the copied write request then stays around for the write-mostly-behind side of the RAID and may take longer to complete, hopefully without anyone noticing.
Then the raid layer takes a lot of steps to make sure no data will be read from the write-mostly device while there are still pending write-behind requests in the queue. Why would data be read from a write-mostly device? Well, the SSD might have failed so it's all there's left. It's complicated, and write-behind introduces some corner cases.
Which is probably also why it's only supported for RAID-1 level, not any of the others. Although it might make sense in theory to have SSDs essentially as RAID-0 and two parity HDDs in write-behind mode, there's no support for a write-behind RAID-6 like that. It's RAID-1 only and rarely used even there.
The other cache settings remain unaffected by this, basically the overall caching mechanism does not care in the least about how the md driver has implemented things internally. The cache does its thing and md does its thing. So a filesystem cache works the same for a filesystem on top of md vs. a filesystem on top of a bare drive. (The reality is a tad more complicated than that but you can think of it this way.)

A:
For md-raid RAID1 the array can be configured with disks as --write-mostly and --write-behind which suggests that reads are performed from the faster disk, and that writes to the slower disk can lag behind. But how is that cached at kernel level? Does the kernel cache the disk writes before or after the md-raid layer?

After, since this feature is specific to md-raid.
You should think about this md-raid feature as buffering, not caching.  It is bounded by the following mdadm option:

--write-behind=
Specify that write-behind mode should be enabled (valid for RAID1 only). If an argument is specified, it will set the maximum number of outstanding writes allowed. The default value is 256.

I can only think that it is also limited by the normal kernel and hardware buffering (i.e. if that is smaller).  The normal kernel buffering is bounded by nr_requests and max_hw_sectors_kb.  See /sys/class/block/$write_behind_device/queue/.  By hardware buffering, I mean the write cache on the drive.

At the end of a write() call is the data guaranteed to be written to one of the not---write-behind disks?

Of course, assuming you mean the write() was on a file opened with O_SYNC / O_DSYNC, or you actually meant write()+fsync().  If not, no guarantees apply at all.


text:
Q: Can below scenario cause: Too many SOQL queries 101 exception? for (Lead ObLeads : ListOfLead){
    if(condition){
        1 SOQL query;
        1 DML statement;
     }
}

Here ListOfLead has 500 records and condition will be true only for 1 Lead record. So in this scenario can this code generate Too many SOQL queries 101 exception? How?

A: The problem with your approach is that you are not centering your thinking around collections. You're still working with single records. So you're not really working with the platform in the way it was designed when you code this way.
While you are correct that if your assumption holds, you will only execute these operations once, your assumption could be plain wrong, or be invalidated down the road. I recommend you instead adopt filters so that you can build your approach around collections. This way, even if you know for certain sure that there should only be one record to act on, you still don't risk operations in a loop that shouldn't be there.
List<Lead> leadsToActOn = new List<Lead>();
for (Lead record : allRecords)
{
    if (condition)
    {
        leadsToActOn.add(record);
    }
}
// SOQL
// DML

If you adopt this approach, you can really improve your Separation Of Concerns, because almost every action you take has these two components: Filter and Action. You may notice that Workflow Rules and Process Builder break logic down in a similar manner, so it shouldn't be a huge adjustment.
One extra benefit is that there is a great library already out there to do this sort of filtering for you called Selector.

A: No it will not encounter the 'Too many SOQL queries 101 exception' exception provided you don't have 99 others SOQLs running in the same transaction from other places and this includes the trigger if there is any which will get fired due to the DML. :)
However as the best practice you should fire your SOQL queries either before or after the for loop and hold the result in a List or set and re-use wherever required.

A: I assume this is relate to your other post
As Santanu said, no, it won't trigger that exception by itself.
The thing is that when you are doing this operation take note that also you are updating a Lead and therefore triggering Lead triggers before update / after update. They are in the same execution context than your code and therefore you should also take count of all the SOQL operations that are generated in any subsequent codes you call from there.
And same applies otherwise, if this was triggered by a DML operation you should take into account that all other queries&DML operations done in the same execution context will remain till the end of it. So maybe isn't just this piece of code that exceeds it but the whole context.

A: The key part in your code is the "if condition".  If that condition satisfies for "more than 100 leads" in the list ListofLead, then it would cause the error. Because you mentioned that your if condition satisfies for only 1 lead, you are safe for now.
However, I suggest, as a best practice, do NOT include a SOQL/DML statement inside a for loop.


text:
Q: How to pause script execution in Developers console I'm trying to create a rotating banner (JavaScript & CSS). For debugging and making changes on the CSS etc in the developers' console, I want to pause the JavaScript execution while I make changes and then run it or so on.
So, is there a way to pause the script execution in the browser?

A: You can write a pause code yourself.
Pause javascript excution using debugger. In the chrome console, run:
window.addEventListener('keydown', function(event) {
  if (event.defaultPrevented) {
    return; // Should do nothing if the default action has been cancelled
  }
  let handled = false;
  if (event.keyCode == 121) {
    handled = true;
    debugger;  // 121 is the keyCode of F10
  }
  if (handled) {
    // Suppress "double action" if event handled
    event.preventDefault();
  }
});

Highlight element with inspector
Hit F10

A: You are looking for "breakpoints".
Which browser are you using?
Chrome supports breakpoints right away in its developer tools:
F12 (or Ctrl-Shift-I), "Script" tab, select script from dropdown, click the line number.
Update:
On PC: F12 or Ctrl+Shift+I / On Mac: Cmd+Alt+I
select "Sources" tab, select script from the file pane on the left, click the line number.
In Firefox use the Firebug extension:
On PC and Mac: F12,
"Script" tab, activate & reload if needed, select script from dropdown, click line number.
When your Javascript pauses at a breakpoint, both browsers offer you the usual debugging tools to single step through the code, inspect & change variable values, watch expressions,...

A: As katspaugh mentions in their comment:

F8

This only works for me from the Sources tab of the Developer Tools window in Chrome 59.0.3071.115 (on Mac OS X).


text:
Q: How to communicate with CEF via Sockets How can I communicate with CEF via Indy Sockets through Remote debugging protocol?
As described here: https://developers.google.com/chrome-developer-tools/docs/debugger-protocol

A: The API currently requires using the WebSocket protocol which is not supported in Indy. The API documentation page contains this note:

Note that we are currently working on exposing an HTTP-based protocol
  that does not require client WebSocket implementation.

There are WebSocket client libraries available for Delphi both free and commercial (some use Indy as their internal TCP library).
You will also need a JSON library, available in newer Delphi versions and also as free open source (for example SuperObject and lkJSON).

A: I made a Proof of Concept for DWS (pascal to javascript compilation, as used in Smart Mobile Studio) some time ago:
https://code.google.com/p/asmprofiler/source/browse/#svn%2Ftrunk%2F-Other-%2FRemoteDebuggerDWS
You can use my Indy 10 websocket (and socket.io!) components from here:
https://github.com/andremussche/DelphiWebsockets


text:
Q: Differential equation with a function defined such that $f(x+1)=f(x)$ I just tried to do the following question, but I can't help but think I've done it completely wrong. The question states:

The function $f$ satisfies $f(x+1)=f(x)$ and $f(x)>0$ for all $x$.

*

*Give an example of such a function

*The function $F$ satisfies: $$\frac{\text{d}F}{\text{d}x}=f(x)$$ and $F(0)=0$. Show that $F(n)=nF(1)$, for any positive integer $n$.

*Let $y$ be the solution to the differential equation: $$\frac{\text{d}y}{\text{d}x}+f(x)y=0 $$ that satisfies $y(0)=1$. Show that $y(n)\rightarrow 0$ as $n \rightarrow \infty$, where $n=1,2,3,4,\dots$

Now I think I'm completely missing the point the question is getting at. Since for the first part I said let $f(x)=c$ for some $c>0$. Then for the second part I continued assuming $f(x)=c$ which gives answers that seem correct but after some thought it's clear that there are other functions such that e.g. $f(x+1)=f(x)$, $f(x)=\sin(2\pi x)+k$ ($x\in \mathbb{Z}$ and $k$ to make $f(x)>0$) since $\sin(2\pi x)+k=\sin(2\pi x+2\pi)+k$. But I'm not sure how to continue with the question only using the the general case of $f$.

A: Hint for (2):
$$\begin{align}
F(n+1)-F(n) &= \int_n^{n+1} f(x) dx \\[1em]
&\quad\left\downarrow f(x+n)=f(x) \text{ for } n\in\mathbb N\right.\\[1em]
&=\int_0^{1} f(x) dx \\
&=F(1)-F(0) \\
&=F(1)
\end{align}$$
The property $f(x+n)=f(x)$ follows from $f(x+1)=f(x)$ (you can prove it via induction).

A: I am assuming that $f$ satisfies some measureability/integrability condition so
that the various integrals are defined and a suitable Lipschitz condition is
satisfied so the differential equation (3.) has a unique solution passing
through a given initial conditon.

*

*Example $f(x) = 1$.

*Suppose $F$ solves 2. on $[0,1]$. Let $\phi(x) = F(x+1)-F(1)$, then
$\phi'(x) = F'(x+1) = f(x+1) = f(x)$, and $\phi(0) = F(1)$, hence $\phi$
satisfies the same differential equation with the same initial condition
and so $\phi(x) = F(x) = F(x+1)-F(1)$. This gives
$F(x+1) = F(x)+F(1)$ from which the desired result follows.

*Let $y$ be a solution of $y' = -f(x) y$ with $y(0) = 1$.
Note that $x \mapsto 0$ solves the one dimensional system, and $y(0) =1$,
hence $y(x) >0$ for all $x \ge 0$ (since the trajectories cannot cross).
Hence $y'(x) < 0$ for all $x \ge 0$, and so $y$ is strictly decreasing, and
hence $y(1) \in (0,1)$.
Let $\upsilon(x) = {1 \over y(1)}y(x+1)$ and note that
$\upsilon'(x) = {1 \over y(1)}y'(x+1) = f(x+1) {1 \over y(1)}y(x+1) = f(x) \upsilon(x)$, and $\upsilon(0) = 1$, hence
$\upsilon(x) = y(x) = {1 \over y(1)}y(x+1)$. It follows that
$y(n) = y(1)^n$, and since $y(1) \in (0,1)$, we see that $y(x) \to 0$
(since $y$ is decreasing).


text:
Q: Connecting to multiple Rails DBs, SQLite3 and SQLServer 2008 I'm trying to connect to a SQL server called Demand using this gem:
https://github.com/rails-sqlserver/I'm
I'm following recipe #3 from the book 'Rails Recipes' http://pragprog.com/book/rr2/rails-recipes
Here's my database.yml file:
demand:
  adapter: sqlserver
  host: 172.21.148.01
  port: 1433
  database: Demand
  username: DEapp
  password: @pp1user
  timeout: 5000

From rails console, when I test the connection with Demand.connection i get the following:
(I know the addy and pw are good as i'm connected via toad currently, also created the model 'Demand' so rails would have an object)
> TinyTds::Error: Login failed for user 'DEapp'. from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/tiny_tds-0.5.1/lib/tiny_tds/client.rb:68:in
> `connect' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/tiny_tds-0.5.1/lib/tiny_tds/client.rb:68:in
> `initialize' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.1.6/lib/active_record/connection_adapters/sqlserver_adapter.rb:400:in
> `new' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.1.6/lib/active_record/connection_adapters/sqlserver_adapter.rb:400:in
> `connect' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.1.6/lib/active_record/connection_adapters/sqlserver_adapter.rb:198:in
> `initialize' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.1.6/lib/active_record/connection_adapters/sqlserver_adapter.rb:35:in `new' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-sqlserver-adapter-3.1.6/lib/active_record/connection_adapters/sqlserver_adapter.rb:35:in `sqlserver_connection' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:304:in
> `new_connection' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:323:in
> `checkout_new_connection' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:265:in
> `block (2 levels) in checkout' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:261:in
> `loop' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:261:in
> `block in checkout' from
> /Users/drewgilliam/.rvm/rubies/ruby-1.9.2-p290/lib/ruby/1.9.1/monitor.rb:201:in
> `mon_synchronize' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:260:in
> `checkout' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:162:in
> `connection' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_pool.rb:409:in
> `retrieve_connection' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:115:in
> `retrieve_connection' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/activerecord-3.1.3/lib/active_record/connection_adapters/abstract/connection_specification.rb:89:in `connection' from (irb):11 from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/commands/console.rb:45:in
> `start' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/commands/console.rb:8:in
> `start' from
> /Users/drewgilliam/.rvm/gems/ruby-1.9.2-p290/gems/railties-3.1.3/lib/rails/commands.rb:40:in
> `' from script/rails:6:in `require'

Any help? Here's the Pragmatic Programmer forum if you care to answer there as well: http://forums.pragprog.com/forums/189/topics/10476

A: I found out that because the external DB user password started with the @ symbol, rails wasn't happy about it because it thought it was and instance variable.
I changed the PW to something not starting wth @ and it connected just fine.
    Drews-MacBook-Air:DE_App drewgilliam$ rails console
Loading development environment (Rails 3.1.3)
1.9.2p290 :001 > Externaldb.connection
  EXECUTE (36.7ms)  USE [DemandEstimator]
 => #<ActiveRecord::ConnectionAdapters::SQLServerAdapter version: 3.1.6, year: 2008, product_level: "SP1", product_version: "10.50.2500.0", edition: "Enterprise Edition (64-bit)", connection_options: {:adapter=>"sqlserver", :host=>"172.21.148.01", :port=>1433, :database=>"DemandEstimator", :username=>"DEapp", :password=>"demand_app_user", :timeout=>5000, :mode=>:dblib}>
1.9.2p290 :002 >


text:
Q: [[:space:]] is not matching newline in sed I am trying to replace all words "BBB" ins a file to "XXX" But for some reason I cant seem to make [[:space:]] match the newline:
[root@REDHAT]# cat file
AAA
BBB
 BBB
CCC

[root@REDHAT]# sed 's/[[:space:]]BBB/XXX/g' file
AAA
BBB
XXX
CCC

Note how only the second BBB was replaced; [[:space:]] didn't match the newline preceding the first occurrence.

A: As Sundeep points out:

*

*sed reads its input line by line by default.

*Each line read doesn't include the trailing newline,

*

*so the only thing [[:space:]] can possibly match is a space or a tab char.

Perhaps the following command does what you want (works with BSD Sed and GNU Sed):
$ sed -E 's/(^|[[:blank:]])BBB/XXX/' file
AAA
XXX
XXX
CCC

*

*(^|[[:blank:]]) matches either the beginning of a line (^) or a single tab or space character ([[:blank:]]).

*I've omitted the g option, under the assumption that there's at most one BBB per line.


text:
Q: Surjective morphism between projective varieties of different dimensions If you have two projective varieties $X$ and $Y$ such that $\dim(X) < \dim(Y)$, is it necessarily true that we can't have surjective morphism $f : X \to Y$? I am familiar with first chapter of Hartshorne.

A: In the context of Hartshorne chapter I, the dimension of a variety $X$ over $k$ is the transcendence degree of its function field $k(X)$ over $k$. A dominant (in particular, a surjective) map of varieties $X\to Y$ induces a pullback map on function fields $k(Y)\to k(X)$. But given any sequence of maps of fields $k\to F\to E$, we have $\operatorname{trdeg} E/k = \operatorname{trdeg} E/F + \operatorname{trdeg} F/k$, and therefore $\operatorname{trdeg} E/k \geq \operatorname{trdeg} F/k$. So for any dominant morphism of varieties $X\to Y$ over $k$, we see that $\dim X\geq\dim Y$.


text:
Q: Limit zoom to button only in leaflet and phonegap Is it possible to make it so you can only zoom in and out by using the zoom buttons as opposed to been able to pinch the screen? Perhaps only sensing one touch at a time or something similar?

A: The solution is right there in the Leaflet documentation: simply set the map option touchZoom to false when instantiating the map.


text:
Q: SQL - Generate counts for "mismatched" records I am now trying to use Metabase v0.29 to develop a question. Suppose I have three tables and would like to produce an output table shown below.
Table 1 - Job/Student ID (job_student_ids)
Job ID   Student ID
J101     S101
J101     S102
J102     S101

Table 2 - Job Items (job_items)
Job ID   Job Item
J101     Apple
J101     Orange
J102     Apple
J102     Banana

Table 3 - Student Items (student_items)
Student ID   Student Item
S101         Apple
S101         Orange
S102         Pear
S102         Orange
S103         Apple
S103         Orange

Output Table - Item Matches
Job Item   Student Item Match
Apple      3
Orange     2
Banana     1

Example explanation - how to work out Apple?
Notice both J101 and J102 request Apple (shown in Table 2), and J101 has applicants S101 and S102 (shown in Table 1) while J102 only has applicant S101.
J101: One match from applicant S101 who has an Apple, another match from applicant S102 who also has an Apple (shown in Table 3). Therefore 2 Apple matches.
J102: One match from applicant S101 who has an Apple.
Hence, in total 3 matches for Apple.
Please note: Due to the actual size of Table 1-3 on our database, it is impossible to append/union all of them together to make that count.
Is there any efficient way to achieve this goal? Thanks in advance - this is my first time to post a question here so please let me know if you'd like any clarifications.


text:
Q: How big should a Flex SWF be? I've a fairly small Flex4 project targeting Flash 10, developed in FlashDevelop. I know Flex SWFs carry extra overheads to a plain AS3 project, but 240Kb for release build seems still a lot - is it? Or is this a realistic minimum?
In case it's relevant, FlashDevelop builds my project with the following (anonymized):
mxmlc -load-config+=obj\********.xml -incremental=true -benchmark=false -optimize=true -static-link-runtime-shared-libraries=true -o obj\*****************

Doesn't Flash player include Flex runtimes or something sensible like that?

A: The player does not include the Flex framework.  It shouldn't. The Flex framework is independent of the player and if it was included the player would have to include every version of the framework to use the one each swf was built against.  To solve this the framework is different (as is the Flash framework).
The resolution to large swfs is to use Framework Runtime Shared Libraries.  This way the player will load a shared library swf once for the specific framework version you used and this shared library will be used across all swfs that were compiled against the same framework version.
You can find more information here:
http://livedocs.adobe.com/flex/3/html/help.html?content=rsl_09.html
In practice, it's somewhat like having the framework in the player, but it's just not pre-loaded.  The frameworks get loaded as needed.

A: 240KB is not a lot. Yet.
However, in my opinion, Flex does make files quite large when you start developing bigger applications, which is the reason I do plain ActionScript projects.
Flash Player does not come with preloaded framework data in. Therefore, 1) do what sam said with Runtime libraries. 2) load almost all files after the main flash has loaded, thus giving the user meaningful info, while the rest loads (you could load homepage, display it, and only then start loading the other sections). You could use something nice called BulkLoader.
hth


text:
Q: Dropzone append dynamic attributes to #dz-remove I am trying to implement a removedfile on dropzone. I am using rails, to implement this I have to add an id = 1 attribute to my dz-remove class.
This is my current code:
    var dropzone = new Dropzone ("#my-dropzone", {
        maxFiles: 50,
        maxFilesize: 30,
        paramName: "album[images][]",
        addRemoveLinks: true,
        uploadMultiple: true,
        autoProcessQueue: false,
        parallelUploads: 10,
        processing: function(){
                dropzone.options.autoProcessQueue = true;},
        init: function(){
              var thisDropZone = this;
              $.getJSON('image_list', function(data) {
                $.each(data, function(index, val) {
                      var mockFile = { name: val.name, size: val.size };
                      thisDropZone.emit("addedfile", mockFile);
                      thisDropZone.emit("thumbnail", mockFile, val.path);
                      thisDropZone.emit("complete", mockFile);
                    });
                });
              }

I have tried this code:
    success: function(file, response){
                $(file.previewTemplate).find('.dz-remove').attr('id', response.fileID);
                $(file.previewElement).addClass("dz-success");
            }

fileID is gotten from my picture controller:
if @picture.save
  render json: { message: "success", fileID: @picture.id }, :status => 200
else

It works but, when I refresh the browser the attribute id = 1 is gone. I also want to separate my upload and edit pages.
I also tried to get the id value from json file with this code:
init: function(){
    var thisDropZone = this;
    $.getJSON('image_list', function(data) {
       $.each(data, function(index, val) {
           var mockFile = { name: val.name, size: val.size };
           thisDropZone.emit("addedfile", mockFile);
           thisDropZone.emit("thumbnail", mockFile, val.path);
           thisDropZone.emit("complete", mockFile);

           $(".dz-remove").attr("id", val.id);
        });
    });
}

Again this works and adds a permanent id = 1 attribute to my html. But the appended val.id is constant. Example if I have 3 images:
Remove
Remove
Remove

my desired output is:
Remove
Remove
Remove

I also tried $(".dz-remove").each but the value is still constant instead of dynamic. I am also confused because when I do console.log($(".dz-remove").attr("id", val.id)) The console values are appended correctly (id=1, id=2, id=3). On html all I get are id=1.

A: change $(".dz-remove").attr("id", val.id); to
$(".dz-remove").eq(index).attr("id", val.id);
$(".dz-remove") return array of elements, u want add id to current, use eq(index of element)


text:
Q: Constructing all graphs with $n$ vertices and $n-1$ edges I would like to get information on what is known about the generation of all graphs with given number of edges and vertices. Specifically, $n$ vertex and $n-1$ edges.

A: You can use the graph isomorphism software nauty and Traces. Specifically, this software package comes with a tool called geng that will generate all distinct unlabelled graphs of a given size and order. For example, to generate all graphs with seventeen vertices and sixteen edges, you would run
geng 17 16

This command returns $11,932,174$ graphs.


text:
Q: Simple css example that breaks margin-bottom for
* and I don't know why Code: http://jsfiddle.net/74y7h/
When I float:left the item-content div, suddenly margin-bottom no longer works on each of the items in the list.  Remove the float:right line and re-run the code and you'll see the margins reappear between the list items.
Why is this happening?  I don't need a full lesson, but a simple one or two sentence explanation would be appreciated, not just the fix.  Thanks!

A: See how to clear the last <li> tag within a <ul>

A: Apply overflow:hidden to the containing element (.item).  Give it a shot.  It works.  Applying the overflow (hidden or auto) triggers a new "block formatting context" for the containing div that doesn't run all over the floated elements.  I can't say I understand completely why it works, but it does (and it's different from hasLayout issues).


text:
Q: Why was Hermes allowed to say "Star Trek" when it is a banned phrase? How come in the episode "Brannigan, Begin Again," Hermes says, "Star Trek," after the professor fails to compare their government to the United Nations to Fry? In a later episode of Futurama it is shown that you are not allowed to say the phrase "Star Trek."

A: Well, lots of things are illegal/banned, but people still do them anyways, especially in private. Hermes is prone to doing a few other illegal things as well. The episode where his son Dwight finds his 'cigar' comes to mind. "That's not a cigar! ... and it's not mine!"

A: The episode was written before the Star Trek episode.  That is all I can provide.  (I've noticed this as well)

A: This is what I found
"Hermes mentions the Star Trek program. However, Star Trek has been banned (4ACV11), so he shouldn't have done it. But this continuity error appears in many other episodes.
Hermes has shown numerous times that he does not care about breaking the law and, since Planet Express is privately owned, the Police wouldn't know to interfere unless someone at the company told them to."
Source:Under Goofs

A: It is one of the alternate universes that allows him to say it.  This would also explain the 3 original crew backgrounds. Death by space wasps, space bees, and lost in space. We know that 3 universes exist.  The original, shot Hitler, and shot Eleanor Roosevelt. This is assumed to keep a timeline.


text:
Q: Kivy: bind method inside the .kv file I would like to delete this line from my .py file:
self.layout.bind(minimum_height=self.layout.setter('height'))

and replace it by the same instruction but in the .kv file. Is there any way to bind self.layout.setter('height') to minimum_height ?

A: How about?
height: self.minimum_height

I am guessing you use that in a ScrollView. If true this should work.
See for example this post https://stackoverflow.com/a/45313388/6646710 which uses exactly that.

A: To adapt layout height to child widgets's height you can simply do:
height: self.minimum_height

Example:

*

*Only python code:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.scrollview import ScrollView

class RootWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)
        self.orientation = "vertical"
        self.sv = ScrollView()
        self.btn = Button(text="Addd button", size_hint_y=0.1,
                                      on_press = self.add_button)
        self.layout = GridLayout(cols = 1, size_hint_y= None,
                                            row_default_height= 100)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        self.add_widget(self.sv)
        self.add_widget(self.btn)
        self.sv.add_widget(self.layout)

    def add_button(self, instance):
        self.layout.add_widget(Button())

class TestApp(App):
    def build(self):
        return RootWidget()

if __name__ == '__main__':
    TestApp().run()

*Using Kivy Languaje:
main.py:
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.button import Button
from kivy.uix.boxlayout import BoxLayout

class RootWidget(BoxLayout):
    def __init__(self, **kwargs):
        super(RootWidget, self).__init__(**kwargs)

    def add_button(self):
        self.layout.add_widget(Button())

class TestApp(App):
    def build(self):
        return RootWidget()

if __name__ == '__main__':
    TestApp().run()

test.kv:
<RootWidget>:
    orientation: "vertical"
    layout: glayout
    ScrollView:
        GridLayout
            id: glayout
            cols:1
            row_default_height: 100
            size_hint_y: None
            height: self.minimum_height  # <<<<<<<<<<<<<<<<

    Button:
        text: "Add button"
        on_press: root.add_button()
        size_hint_y: 0.1

A: You can do height: self.minimum_height in the .kv file. Just keep in mind that sometimes you will also have to set size_hint_y: None to see the desired effect.


text:
Q: @staticmethod return value In Python 3.6, I was trying to define a property in an AbstractBaseClass; my first try was something like this (later I discovered I can omit @staticmethod):
class AnAbstractClass(ABC):
    @property
    @staticmethod
    @abstractmethod
    def my_property():
        pass

However PyCharm shows me a warning on the property decorator:

As far as I understand, the @staticmethod decorator does not return a callable but something different.
(I suspect this is also causing mypy to raise an error on the return value type in my code, however I cannot reproduce the issue in a smaller code sample).
What's going on here?

A: To understand why you are getting the warning you are getting, you need to understand a bit about both decorators and descriptors.
Decorators
A decorator is a callable that replaces the thing it is decorating, and assigns it to the same name in the namespace. Normally, decorators are used for functions and classes to add some functionality, like type checking or threading or something, but really they can return anything at all.
Since the output of a decorator does not have to be of the same type as the input, or perform any of the same processing, the order of decorators very much matters. Decorators are applied in order from the one closest to the function, to the one at the top of the list. In your case, abstractmethod, then staticmethod, then property.
Descriptors
Descriptors define a fairly complex protocol that allows for customization of objects using the binding behavior they provide. For your purposes, you need to know that functions are descriptors, and that placing them into a class object uses this. When you invoke any descriptor that is defined in a class on the instance of that class, the descriptor protocol binds the descriptor to the instance using the descriptor's __get__ method. The descriptor itself doesn't even have to be a callable, and neither is the return value of __get__, even though in most cases it is expected to be. For a function, __get__ returns a closure that automatically passes self as the first positional argument.
For example, given a class A with a method def b(self, arg):, and an instance of that class called a, doing a.b(arg) turns into A.b.__get__(a, A)(arg). So while b is defined to have two positional arguments, it only needs one to be passed in explicitly when called on an instance. However, when you call b through the class, e.g., A.b(a, arg), it is just a normal function, and you need to pass in all the parameters manually, including self.
Putting it all together
abstractmethod, property and staticmethod are all decorators that return callable descriptor objects. However, the __get__ method of their decriptors works a bit differently than the __get__ of a normal function object.
abstractmethod creates a fairly normal class method, but it interacts with the metaclass ABCMeta, so that you get all kinds of useful errors when you try to instantiate a class with abstract methods. It does not modify the input parameters expected by the result in any way. In fact, the documentation hints at the fact that all the side-effects may be related to the metaclass, and that the original input is just passed through. The only thing to really keep in mind here is

When abstractmethod() is applied in combination with other method descriptors, it should be applied as the innermost decorator, as shown in the following usage examples: ...

Your code seems to be following that injunction. In fact abstractmethod has nothing to do with your warning, but it seemed like a good idea to mention it here anyway.
staticmethod returns a callable that bypasses normal binding behavior to create a method that does not care what class or instance it is invoked from. In particular, a method bound using staticmethod.__get__ will pass its arguments through to your function, instead of prepending self first (i.e., __get__ basically just returns your original function). You can imagine that this would be a problem for something that expects to receive a self parameter, like the setter of a property.
Unlike abstractmethod and staticmethod, property creates a data descriptor. This means that it returns an object that has both a __get__ binding and a __set__ binding (and also a __del__ binding). A property's __get__ method works pretty much just like a normal function's __get__ method, but applied specifically to the getter function. property cares very much what instance it is invoked from because of course you want different instances to have different values of the attribute the property wraps.
So what you have in your code is staticmethod followed by property. The first decorator returns a function that does not prepend self to its argument list when bound, while the second expects one that does. There is nothing stopping you from invoking the decorators, but the IDE warning is telling you that you are not going to succeed in calling the resulting object. If you try to access my_property on a concrete implementation of AnyAbstractClass, you will probably get a TypeError telling you that my_property does not accept any positional parameters, but one was given, because property.__get__ will prepend self to the argument list of the static method, which does not accept any arguments.
Keep in mind that applying staticmethod to the result of property won't help you much either. A property instance is not callable at all. It operates entirely through its __get__, __set__ and __del__ methods, while staticmethod assumes that you pass in a callable.
Solution
As you have correctly discovered, staticmethod and property don't mix well. A property, by its very nature, should always be aware of the instance it operates on. The correct way to go about doing this is to add a self parameter and allow normal method binding to take place.
Both property and staticmethod play well with abstractmethod (as long as abstractmethod is applied first), because it makes effectively no change to your original function. In fact, the docs of abstractmethod mention specifically that the getter, setter or deleter of a property abstract makes the whole property abstract.
TL;DR
staticmethod returns a descriptor that is callable, but whose __get__ method returns an unbound version of itself. property creates an uncallable descriptor whose __get__ method calls the getter of the property. Using the resulting property will attempt to pass self to a static method which doesn't accept it.


text:
Q: What order should I watch various X-Files Universe TV series in? This question is following similar question about Stargate:
In what order should I watch the various Stargate TV Series?
After looking at pages about Millennium and The Lone Gunmen on X-Files wikia, I noticed references to certain episodes of X-Files series themselves; is there any established order of watching the series, or should I just watch the spin-off series at any point before watching episodes of the original series that are said to conclude spin-offs?

A: X-Files 1
X-Files 2
X-Files 3
X-Files 4/Millennium 1
X-Files 5/Millennium 2
X-Files Movie (AKA "Fight the Future")
X-Files 6/Millennium 3
X-Files 7
X-Files 8
The Lone Gunmen
X-Files 9
X-Files: I Want to Believe
X-Files 10

A: You don't really need to watch either Millennium or The Lone Gunmen to understand the events in the main X-Files series.  Millennium isn't really a proper spin-off; it was just created by many of the same people.  The only place where it intersects with the X-Files is in the season seven episode of the X-Files called "Millennium".  This episode wraps up the entire Millennium story, so you can watch all of that series and all of the X-Files up to season seven in any order before watching that episode.
The Lone Gunmen is a proper spin-off, since the characters Langley, Frohike, and Byers appeared in the X-Files for years before they got their own show.  They appeared in all nine seasons of the X-Files, but they didn't get their own show until the eighth season.  To watch their appearances in order, watch the first eight seasons of the X-Files up to episode 11 (The Gift, original air date February 4, 2001), which was their last appearance before they got their own show.  Then watch the first six episodes of The Lone Gunmen (which premiered March 4 through March 30, 2001), switch back to the X-Files for a few episodes up through episode 15, watch episode seven of TLG, episode 16 of the X-Files, then finish up TLG before you get to the season eight finale of the X-Files.

A: A good site for the X-Files "mythos" episodes (the overarching story line) is Wikipedia.  Keep in mind, many of the standalone episodes not related to the overarching story line were also stand out episodes.  As for the Lone Gunmen spin-off series; most of the 13 episodes were just re-hashed episodes of the X-Files from the Lone Gunmen's point of view.


text:
Q: Trying to start a new activity when the screen is touched I'm trying to start a new activity when the screen is touched.The background is a resized bitmap. But the touch is not detected. Here's my code:
public class DispCover extends Activity implements OnTouchListener{
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    bg = new DispCoverG(this);
    setContentView(bg);
   }

@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();

}
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    bg.pause();
}
@Override
protected void onResume() {
    // TODO Auto-generated method stub
    super.onResume();
    bg.resume();
}

float dtp(float dp,Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float px = dp * (metrics.densityDpi/160f);
    return px;
}

@Override
public boolean onTouch(View v, MotionEvent e) {
    int action = e.getAction();
    int xd = (int) e.getX();
    int yd = (int) e.getY();

    int x = (int) dtp(xd,this);
    int y = (int) dtp(yd,this);

    switch(action){
    case MotionEvent.ACTION_DOWN:
    startActivity(new Intent(//));
    break;
    }
    return true;
}

public class DispCoverG extends SurfaceView implements Runnable{

    public DispCoverG(Context context) {
        //code
    }

    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth)
    {
        //code
    }

    public void pause(){
        //code
    }

    public void resume(){
        //code
    }

    @Override
    public void run() {
        //code

        }
    }
}

};
Thanks in advance.

A: write the below code under setContentView(bg);
bg.setOnTouchListener(this);

OR
bg.setOnTouchListener(new OnTouchListener() {
    public boolean onTouch(View v, MotionEvent event) {
        // TODO Auto-generated method stub
        int action = event.getAction();
        switch(action){
            case MotionEvent.ACTION_DOWN:
            startActivity(new Intent(YourActivity.this,NewActivity.class));
            break;
        }
        return true;
    }
});

implement OnTouchListener in Activity.

A: Another approach would be to catch the MotionEvents directly in your view:
public class DispCoverG extends SurfaceView implements Runnable{
....
    @Override
    public boolean onTouchEvent(MotionEvent event){
       // to dispatch click / long click event,
       // you must pass the event to it's default callback View.onTouchEvent
       boolean defaultResult = super.onTouchEvent(event);

       ...
       switch (event.getAction()){
          case MotionEvent.ACTION_DOWN:
               Intent intent = new Intent(DispCover.this, XActivity.class);
               startActivity(intent);
               break;
             }
       return defaultResult;
       //return true; //this should work if you need just ACTION_DOWN
    }
}


text:
Q: Most efficient method of returning coefficients for a fit in Python for use in another languages? So, I have the following data I've plotted in Python.

The data is input for a forcing term in a system of differential equations I am working with. Thus, I need to fit a continuous function to this data so I will not have to deal with stability issues that could come with discontinuities of a step-wise function. Unfortunately, it's a pretty large data set.
I am trying to end up with a fitted function that is possible and not too tedious to translate into Stan, the language that I am coding the differential equations in, so was preferring something in piece-wise polynomial form with a maximum of just a few pieces that I can manually code.
I started off with polyfit from numpy, which was not very good. Using UnivariateSpline from scipy gave me a decent fit, but it did not give me something that looked tractable for translation into Stan. Hence, I was looking for suggestions into other fits I could try that would return functions that are more easily translatable into other languages? Looking at the shape of my data, is there a periodic spline fit that could be useful?

A: The UnivariateSpline object has get_knots and get_coeffs methods. They give you the knots and coefficients of the fit in the b-spline basis.
An alternative, equivalent, way is to use splrep for fitting (and splev for evaluations).
To convert to a piecewise polynomial representation, use PPoly.from_spline (check the docs for the latter for the exact format)
If what you want is a Fourier space representation, you can use leastsq or least_squares. It'd be essential to provide sensible starting values for NLSQ fit parameters. At least I'd start from e.g. max-to-max distance estimate for the period and max-to-min estimate for the amplitude.
As always with non-linear fitting, YMMV, however.

A: From the direction field, it seems that a fit involving the sum of or composition of multiple sinusoidal functions might be it.
Ex: sin(cos(2x)), sin(x)+2cos(x), etc.
I would use Wolfram Alpha, Mathematica, or Matlab to create direction fields.


text:
Q: Why is triggerJob disabled in Quartz's JMX? I have successfully configured our app to export Quartz's MBeans into JMX and can view everything in JConsole.  I can run the majority of the scheduler operations.
The one I really want to run is 'triggerJob', but that is showing up in JConsole as greyed-out/disabled so I can't run it.
I've scanned the commits that added the JMX code to Quartz but can't see any differences between triggerJob and the other operations that are enabled.
Anyone have a clue what's going on?
EDIT - explanation found
A different StackOverflow issue describes what's going on: Why are some methods on the JConsole disabled
triggerJob (and two other operations) take non-primitive parameters, these complex parameters cannot be provided in JConsole.
I am not clear if the MBean provider might provide a custom editor for JConsole (or simlar), but at least I have my answer.

A: Thank you for your explanation. I have successfully triggered a job remotely through JMX using the following Groovy code:
def callParams = new Object[3]
callParams[0] = 'com.test.project.TestJob'
callParams[1] = 'DEFAULT_JOB_GROUP'
callParams[2] = new HashMap()

def callSignature = new String[3]
callSignature[0] = 'java.lang.String'
callSignature[1] = 'java.lang.String'
callSignature[2] = 'java.util.Map'

// server is an instance of MBeanServerConnection
server.invoke('triggerJob', callParams, callSignature)


text:
Q: Can we remove any prime number with this strange process? This is a prime-removal algorithm I made, which may appear to be quite complex so I will start with an example. @Max has since added this sequence to OEIS, number A332198.
The process goes as follows:

*

*Start with the first prime number, $$S(1)=2.$$

*From $2$, add the next prime number $3$ to get $$S(2)=2+3=5.$$ There are no non-trivial factors, so we move on.

*From $2+3$, add the next prime number $5$ to get $$S(3)=2+3+5=10.$$ Since $10=2\times5$ and these two numbers appear in the sum, we remove $2$ and $5$.
 We are left with $3$.

*From $3$, add the next prime number $5$ to get $$S(4)=3+5=8.$$ Now $8=2\times2\times2$, but $2$ does not appear in the sum, so we move on.

*From $3+5$, add the next prime number $7$ to get $$S(5)=3+5+7=15.$$ Since $15=3\times5$ and these two numbers appear in the sum, we remove $3$ and $5$.
 We are left with $7$.

*(and so on)
So essentially, we keep on adding consecutive prime numbers until we reach a sum whose prime factorisation contains some of those primes. We remove those primes and start the process once again. Great, except...
There is one more rule that needs to be added. If we continue doing this, we soon find ourselves in a rather strange scenario.

*

*(and so on) a continuation:

*From $37+47+59+\cdots+241+251+257$, add the next prime number $263$ to get $$S(57)=37+47+59+\cdots+251+257+263=5918.$$ Now $5918=2\times11\times269$, but neither of the three primes appear in the sum, so we move on.

*From $37+47+59+\cdots+251+257+263$, add the next prime number $269$ to get $$S(58)=37+47+59+\cdots+251+257+263+269=6187.$$ Since $6187=23\times269$ and $269$ appears in the sum, we remove $269$.
 We are left with $37+47+59+\cdots+251+257+263$.
This is a cycle! The sequence of $263$ and $269$ will continue forever, if we don't add another rule to this process. Therefore, I call $269$ a cyclic prime, and I propose this new rule.

*

*From $37+47+59+\cdots+251+257+263$, add the next non-cyclic prime number $271$ to get $$S(59)=37+47+59+\cdots+251+257+263+271=6189.$$ Now $6189=2\times2063$ and these two numbers do not appear in the sum, so we move on.

I do not know whether there are any dicyclic primes; that is, primes that are still cyclic after more than one iteration.

Questions

*

*Will every prime number in the sum eventually be removed? If not, which prime numbers will remain in the sum forever?

It appears to be true. From this Python program by @EuxhenH, we see that all primes up to $16903$ are eliminated at some point before overflow. The table linked shows how long it takes ($N$ iterations) for the smallest prime $P$ in the sum to be removed. It appears that $P$ increases as $N$ increases despite significant fluctuation.

*Follow-up: What is the asymptotic growth of $N(P)$? For instance, does it admit a $\log$ or $\log\log$ increase?

*Are there infinitely many cyclic prime numbers?
As of writing, the only known cyclic prime numbers are $269$ and $94793$.

Using @Max's PARI/GP program, I plotted $S(n)$ for $n\le575$

which should grow like $Cx^a\log^bx$.
Note that this sequence, by definition, is bounded above by $$\sum_{i\le n}p_i\sim\frac12n^2\log n.$$ Indeed, when $a=2$ and $b=1$, Mathematica gives an optimal value of $C\approx0.4716$. However, the residual plot suggests there is perhaps a better asymptotic.

A: I have no proof so far but also written a program that checked that the only cyclic primes among the first $10^5$ steps are $p = 269$ in $S(58) = 6187$, and $p = 94 793$ in $S(9141) = 377 844 898$, where I call $S(n)$ the value of the sum at step $n$ (after adding the "next larger prime", not considering the removal of terms as a step, with $S(1) = 2$ which can be seen as result of adding $2$ to the empty sum $S(0)$).
FWIW, I get \begin{align}S(1000) &= 3\,362\,713\\S(2000) &= 14\,797\,503\\S(5000) &= 105\,157\,142\\S(10\,000) &= 456\,622\,646\\S(20\,000) &= 1\,979\,852\,987\\S(50\,000) &= 13\,618\,461\,808\\S(10^5) &= 58\,316\,786\,321.\end{align}
The smallest prime in the sum at these points is \begin{align}p(1000) &= 457\\p(2000) &= 509\\p(5000) &= 1451\\p(10\,000) &= 2281\\p(20\,000) &= 4129\\p(50\,000) &= 10\,631\\p(77\,000) &= p(10^5) = 16\,903.\end{align}
To be precise, my program considers a prime cyclic if it would give twice the same result, $\widehat S(n+1) = S(n)$, if it were used, which is then however avoided by using the next larger prime. I agree that this may not be the conceptually most satisfying definition...
On the other hand, $p_{k+1}\mid\sum p_i$ isn't complete either (as mentioned in a comment), because depending on the smaller primes removed at that step or the next one, this does not necessarily give a loop. [However, if I'm not wrong, it's excluded that the next smaller prime is a factor of the sum at the same time as the largest prime $p_{k+1}$, because the sum is at most $\sim p_{k+1}^2/2 < p_{k}\cdot p_{k+1}$.]
The experimental results seem to confirm that eventually all primes will be removed. I agree with the heuristic argument that, if there's no particular modular restriction on the sum, then any prime factor will eventually occur (even infinitely often), and thus be removed from the sum. Given the "sequential" way of adding one prime after the other to the sum, there appears indeed no reason that from some point on, a particular prime factor should never occur again. This would yield the required result, but again, it's not a proof.
PS: I proposed the sequence $S(n)$ as oeis.org/A332198, where my program can be found.


text:
Q: findContours in opencv Java   if (DETECT_RED_OBJECTS_ONLY)
  {
    Imgproc.cvtColor(inputFrame, gray,
    Imgproc.COLOR_BGR2RGB);
  }
  else
  {
     Imgproc.cvtColor(inputFrame, gray, Imgproc.COLOR_BGR2GRAY);
  }
     Imgproc.cvtColor(inputFrame, dst, Imgproc.COLOR_BGR2RGB);

     // down-scale and upscale the image to filter out the noise
     Imgproc.pyrDown(gray, downscaled, new Size(gray.cols() / 2, gray.rows()  2));
     Imgproc.pyrUp(downscaled, upscaled, gray.size());

     if (DETECT_RED_OBJECTS_ONLY) {
         // convert the image from RGBA to HSV
         Imgproc.cvtColor(upscaled, hsv, Imgproc.COLOR_RGB2HSV);
         // threshold the image for the lower and upper HSV red range
         Core.inRange(hsv, HSV_LOW_RED1, HSV_LOW_RED2, lowerRedRange);
         Core.inRange(hsv, HSV_HIGH_RED1, HSV_HIGH_RED2, upperRedRange);
         // put the two thresholded images together

         Core.addWeighted(lowerRedRange, 1.0, upperRedRange, 1.0, 0.0, bw);
         // apply canny to get edges only
         System.out.println(bw);
         Imgproc.Canny(bw, bw, 0, 255);
     } else {
         // Use Canny instead of threshold to catch squares with gradient shading
         Imgproc.Canny(upscaled, bw, 0, 255);
     }

    // dilate canny output to remove potential
     // holes between edge segments
     Imgproc.dilate(bw, bw, new Mat(), new Point(-1, 1), 1);

     // find contours and store them all as a list
     List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
     contourImage = bw.clone();
     Imgproc.findContours(
             contourImage,
             contours,
             hierarchyOutputVector,
             Imgproc.RETR_EXTERNAL,
             Imgproc.CHAIN_APPROX_SIMPLE
     );

     System.out.println("contours" + contours);

     // loop over all found contours
     for (MatOfPoint cnt : contours) {
         MatOfPoint2f curve = new MatOfPoint2f(cnt.toArray());

         // approximates a polygonal curve with the specified precision
         Imgproc.approxPolyDP(
                 curve,
                 approxCurve,
                 0.02 * Imgproc.arcLength(curve, true),
                 true
         );

         int numberVertices = (int) approxCurve.total();

When I use triangle as an input image , this one works and detect triangle[counters become 1 and numberVertices becomes 3]. But when i input a rectangle image , contours become 2 and numberVertices becomes 2. It must be 4 . Isn't it. Can anyone help me to find the bug.

A: If you are using this in latest visual studio, I suggest you to use :
JavaList List<MatOfPoint> contours = new JavaList<MatOfPoint>();

this might change the behavior of your contours. Please let me know if this fixed your bug. Otherwise  lets try with something else


text:
Q: here are more undefined behaviour in c++, sorry for this que[s]tion, but again UB There is very simple UB example:
int i = 1;
i = i++; // classic example of UB.

I recently saw, how to use Pascal style inc operation. Eric Niebler github
// this structure little difference than original.
struct inc_t
{
  template< typename T>
  T operator()(T& t ) const { return t++; }
};

constexpr inc_t inc{};

//usage
int i = 1;
inc(i);
//or
int j = inc(i);

So, combine :
int i = 1;
i = inc(i); // Is there still UB ?

Thanks.

A: No.
i = i++ is UB because it's not specified when i is incremented; it could be at any point after the value computation of i++ (i.e., lvalue-to-rvalue conversion of i) and before the end of the full-expression. Therefore this write is unsequenced with respect to the assignment statement. Two unsequenced writes to the same int is undefined behaviour.
But in i = inc(i) the incrementation of i occurs before the function returns, because the full-expression in which t++ occurs lies inside the function. In turn, the function has to return before the value computation of the right-hand side, and the assignment is sequenced after the value computation of both sides. Therefore the incrementation of i is sequenced before the assignment, and there is no UB.
Relevant quotes from the C++11 standard:
§1.9/14

Every value computation and side effect associated with a full-expression is sequenced before every value
   computation and side effect associated with the next full-expression to be evaluated.

§5.17/1

In all cases, the assignment is sequenced after the value
  computation of the right and left operands, and before the value computation of the assignment expression.


text:
Q: Group a list of originals into list of lists by key based on dictionary of its copies I have a List<Route> targetroutes
and I have a dictionary of the same routes (their copies)
IDictionary<int,IList<Route>>  finalsetofCombinations

I need to group targetroutes into List<List<Route>>Routes
The same way their copies are grouped in the dictionary
A do not need copies in the List<List<Route>>Routes
I need grouped originals

A: If performance is not an issue, perhaps something like this would do:
var listOfLists = dictionary
    .Select(pair => pair.Value
        .Select(copy => list
            .First(original => original == copy)) // insert proper equality check
        .ToList())
    .ToList();


text:
Q: How can we put ViewBag data in $scope object? I am newbie in Angular and sending ViewBag data from ActionResult into the View. where in the view i want to access the ViewBag and put the content in the $scope object like
$scope.productList = ViewBag.productList;

but not having any idea about how to do this. Please suggest any reference.
Update:
I tried to get the ViewBag object in Window scope and then window scope to $scope object. but it does not work out.
        <script>
            window.Category = [];
            @foreach (var listItem in (IEnumerable<SelectListItem>)ViewBag.Categories)
            {
                window.Category.Add(listItem.Text);
            }

        </script>

A: try using <script type="text/javascript">
that allowed you to mix razor and javascript
see hare and hare


text:
Q: multi git account management with ssh key I have multiple Git accounts one is my personal use and one is for company use. Both accounts source need to be activated from my laptop.
1st, I generated two ssh keys:
% ssh-keygen -t ed25519 -C "my@gmail.com" -f ~/.ssh/my
% ssh-keygen -t ed25519 -C "work@company.com" -f ~/.ssh/work

2nd, use ssh-agent
% eval "$(ssh-agent -s)"

% ssh-add --apple-use-keychain ~/.ssh/my
% ssh-add --apple-use-keychain ~/.ssh/work

3rd, Edit the SSH config
touch ~/.ssh/config and edit contents like below:
Host *
  UseKeychain yes
  AddKeysToAgent yes
  IdentityFile ~/.ssh/my
  IdentityFile ~/.ssh/work

# account of myself, my@gmail.com
Host my
  HostName github.com
  User my
  IdentityFile ~/.ssh/my

# account of work, work@company.com
Host work
  HostName github.com
  User work
  IdentityFile ~/.ssh/work

4th, Adding new SSH key to my GitHub account
as the reference: https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
5th, Ensure the ssh-agent is running and loaded these two keys
% ps -e | grep ssh-agent

% ssh-add -l

256 SHA256:RnbFaLfrSIX4Al134lkjaleiur1SMIz7+OFwx5I9RHVMewwo9eq my@gmail.com (ED25519)

Now my question is :
After I reboot the macOS, there is only one ssh key, I must activate another ssh key for work manually by the command below:
% ssh-add ~/.ssh/work

% ssh-add -l

256 SHA256:RnbFaLfrSIX4Al134lkjaleiur1SMIz7+OFwx5I9RHVMewwo9eq my@gmail.com (ED25519)
256 SHA256:QEWRrqpeowiufkndliuroqijr15u30491u3ojhjkrefaosdyflk work@company.com (ED25519)

and I cannot switch to the work ssh key when I working on the work repo (like ~/workcode), but I can found the % git remove -v response right, but got the wrong information when I run % git push as below:
ERROR: Permission to work/Test.git denied to my.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Please tutor me how to switch to my or work ssh key when I working for myself or working for company.
Thank you.

A: The ssh account to use should be git in both cases: User git.
As suggested in the "testing" sction of the docs: test your ssh configuration by running : ssh my / ssh work (or ssh git@my / ssh git@work to explicitly pass the user account to connect with).
AFAIK, you don't need to explicitly load the keys in ssh-agent at startup, the first ssh connection will do that.

[edit] as suggested by @torek in the comments :
to avoid having ssh trying on its own other keys, you can also add  IdentitiesOnly yes to both config blocks.

A: you can firstly revise the ~/.ssh/config as below:
Host *
  UseKeychain yes
  AddKeysToAgent yes

# account of my@gmail.com
Host mysec
  HostName github.com
  User git
  IdentityFile ~/.ssh/mysec

# account of work@company.com
Host work
  HostName github.com
  User git
  IdentityFile ~/.ssh/work

and check the current ssh loaded by run % ssh-add -l
if you want to push code by private account or work account, you can run
% ssh-add -D
This will Deletes all identities from the agent. Then you can load the ssh key you want by:
% ssh-add ~/.ssh/my or % ssh-add ~/.ssh/work
there is only one ssh key effect even if you load the two ssh key, so please only load one ssh key for you push.


text:
Q: Hive MQ connect request URL i wanted to know. when we connect to a hiveMQ broker via URL( tcp:\localhost:1883), and then client. connect(MqttConnectOptions), which have username and password. can this whole URL be accessed like tcp:\localhost:1883=username+password? something like this please, i need to know. i want to use it to servlet filter. client->filter->hiveMQ broker like this. can it be possible?

A: HiveMQ is a MQTT Broker and not a Servlet Container, so Servlet Filters are not possible. If you want to intercept the MQTT message, you can use the HiveMQ plugin system. The documentation is available here: http://www.hivemq.com/docs/plugins/latest/
It's not possible to add the username password to the connection URL, you should use the standard MQTT mechanisms for authentication and authorization. You can read more about that here: http://www.hivemq.com/blog/mqtt-security-fundamentals-authentication-username-password


text:
Q: Rearrange equation involving matrix multiplication and Hadamard product I have the following equation:
$Y = [ C \bullet R ] \times X \times[C^T \bullet R^T ]$
In my textbook, this conveniently rearranges to:
$Y = [ C \times X \times C^T ] \bullet [R \bullet R^T ]$
where $\times$ denotes matrix multiplication, $\bullet$ is Hadamard (pointwise multiplication), and $R^T$ is the transposition of $R$.
How do they manage to rearrange this?
I've played around with it, and it seems that they're using the following identity:
$[ A \bullet B ] \times C = A \bullet [B \times C]$
I've tried proving it true, without success.  For example, if
$D = [ A \bullet B ] \times C$ and $E = A \bullet [B \times C]$,
then
$D_{00} = \sum_{k=0}^m A_{0k} B_{0k}C_{k0}$
$E_{00} = A_{00} \sum_{k=0}^m B_{0k}C_{k0}$
As $D_{00} \neq E_{00}$, the identity is false.
Where have I gone wrong?
EDIT
I'm working with $4 \times 4$ matrices here.
EDIT 2
Here are the matrices I'm dealing with:
$
C =
\begin{pmatrix}
1 &  1  &  1 &  1\\\\
2 &  1  & -1 & -2\\\\
1 & -1  & -1 &  1\\\\
1 & -2  &  2 & -1\\\\
\end{pmatrix}
$
$
R =
\begin{pmatrix}
\frac{1}{2}         & \frac{1}{2}         & \frac{1}{2}         & \frac{1}{2}\\\\
\frac{1}{\sqrt{10}} & \frac{1}{\sqrt{10}} & \frac{1}{\sqrt{10}} & \frac{1}{\sqrt{10}}\\\\
\frac{1}{2} & \frac{1}{2} & \frac{1}{2} & \frac{1}{2}\\\\
\frac{1}{\sqrt{10}} & \frac{1}{\sqrt{10}} & \frac{1}{\sqrt{10}} & \frac{1}{\sqrt{10}}\\\\
\end{pmatrix}
$
$X$ is an arbitrary matrix with integer-only values.

A: With these matrices the identity is true.
In order to prove it, notice that $R=DE$, where $D=\operatorname{diag}(\frac12,\frac1{\sqrt{10}},\frac12,\frac1{\sqrt{10}})$ and $E$ is the matrix of all ones. You can juggle around the diagonal factor $D$ (your proof shows that the "triple product identity" holds if $A$ is diagonal) and in particular you can reabsorb it into $C$, which is particularly convenient since now $Q=DC$ is orthogonal (that's where all those $\sqrt{10}$ come from, I guess).
So after moving the diagonal factors the two terms become
$$
Y_1=(Q \bullet E)\times X\times (Q^T\bullet E^T)
$$
$$
Y_2=(Q \times X \times Q^T) \bullet (E\bullet E^T)
$$
Here all the remaining Hadamard products have $E$ as one factor and thus are trivial.
Anyway, it definitely looks like someone is overcomplicating things in that book; they could have removed those $R$s and those Hadamard products completely: you can replace every $R\bullet M$ with $D\times M$ and every $M\bullet R^T$ with $M\times D$.

A: What is true, though, is that the diagonal entries of $(A \circ B)C^{T}$ and $(A \circ C)B^{T}$ coincide. (See Lemma 5.1.4 on p. 305 of Topics in Matrix Analysis by Horn and Johnson).