text:
Q: Modal and Epistemic Logic I have been reading about epistemic logic and there is something that I can´t understand very well. Some texts says that an aproach to the epistemic logic is to view it as a modal logic and interpret the necessity operator (◻) as the epistemic operator (K). My question is, If I interchange the operators in a modal logic system to epistemic operators, i.e., ◻ for K and ◊ for B (belief), will that be a system of epistemic logic itself?
Thanks in advance for your help

A: Epistemic logic (as well as doxastic logic) is multimodal, in the sense that there is a modality of each type for every agent.  Let us then extend the box and diamond notation with an index.
If $\Box_i p$ stands for "$i$ knows $p$," (epistemic interpretation) then $\Diamond_i p$ stands for "$p$ is compatible with the sum of $i\,$'s knowledge," or "$i$ considers $p$ possible," rather than "$i$ believes $p$."
If, on the other hand, $\Box_i p$ stands for "$i$ believes $p$," (doxastic interpretation) then $\Diamond_i p$ stands for "$p$ is compatible with the sum of $i\,$'s beliefs."
Giving $\Box$ an epistemic interpretation, while at the same time giving $\Diamond$ a doxastic interpretation, has the drawback that it is no longer the case that $\Box_i p$ if and only if $\neg \Diamond_i \neg p$.

One the one hand, it is useful to relate various modal logics by identifying the "boxes and diamonds" of each logic.  For each "box" one can define a "diamond" via
$$\Diamond p \text{ if and only if } \neg \Box \neg p,$$
though the "diamond" modality may not be as heavily used in some logics.  See, for instance the summary table at the beginning of this article, where no "diamond" is reported for doxastic logic.  (Of course, it can be defined, as in Fitting and Mendelsohn, First-Order Modal Logic, where $\Box_i$ is $\mathcal{B}_i$ and $\Diamond_i$ is $\mathcal{C}_i$.)
On the other hand, when dealing with more than one type of modality, it may be inconvenient not to call them by their proper names.  First, you may have more than two modalities, as the "until" of temporal logic or the "it is common knowledge that" or "every agent in this group knows that" of epistemic logic.  (See Fagin et al., Reasoning about Knowledge.)
Second, when allowing fundamentally different modalities to coexist, as when combining "knows" and "believes", one "box" is not necessarily definable in terms of the other.  In fact, the standard approach to defining the semantics of a logic of knowledge and belief is to have a Kripke structure with two accessibility relations.  (See, for instance, Meyer, Modal Epistemic and Doxastic Logic in Handbook of Philosophical Logic.)
The two accessibility relations are not fully independent.  For instance, it is reasonable to assume $\mathcal{K}_i p \rightarrow \mathcal{B}_i p$.  On the other hand, in most epistemic logics $\mathcal{K_i} \mathcal{K}_j p$ entails $\mathcal{K}_i p$, but in no reasonable doxastic logic does $\mathcal{B_i} \mathcal{B}_j p$ entail $\mathcal{B}_i p$.


text:
Q: Toggle the Boolean value of a nested JavaScript object I want to toggle the Boolean value of this nested input object
var obj = { a: { b: { c: false } } };

in an efficient way so that obj is output as:
{ a: { b: { c: true } } };

I am using:
Object.keys(obj).map(function(k, i) {
    // Check if obj is Boolean else if object nest again till I find the Boolean value and toggle it.
}

A: You could build a new opbject and take either an object with a recursive call or a value and return the toggled value.

const
    toggle = object => Object.fromEntries(Object
        .entries(object)
        .map(([k, v]) => [k, v && typeof v === 'object' ? toggle(v) : !v])
    );

var object = { a: { b: { c: false } } };

console.log(toggle(object));

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to sort file names in alphanumeric order in C I need to sort file names in alphanumeric descending order. I have written the following code In C, but it's sorting in alphabetic only order I guess as file A2 is read before A11. I am using scandir with alphasort
Thanks for the help
   struct dirent **vl_lecture = NULL;
   DIR *vl_repertoire = NULL;
   //I open the directory with opendir
   vl_repertoire = opendir(vg_alias_rep_fichier.arr);
   ...//code
   int n = scandir(vg_alias_rep_fichier.arr,&vl_lecture, NULL, alphasort);
   // I use while to perform some operations with file names ...

A: alphasort sorts strings in descending order. That's why you see A2 come before A11. Supply your own function
#include <string.h>

int
alphasort2 (const struct dirent **a, const struct dirent **b)
{
  return -strcoll ((*a)->d_name, (*b)->d_name);
}

//..
int n = scandir(vg_alias_rep_fichier.arr,&vl_lecture, NULL, alphasort2);

The code is based on the implementation of alphasort.


text:
Q: retrieving data from two mysql tables where the second table depends on the first I have two MySql tables:
 users(id_user, name, age, gender ).

 ways(#id_user,id_way,  start, end, date).

What I want is to retrieve all the ways with their corresponding  users details.
So my result would be like this:
 id_way  | start  | end    | date       | id_user  | name  | age   | gender
---------------------------------------------------------------------------
 2       | place1 | place2 | 12/06/2013 | 145      | john  | 28    | m

A: Have you tried JOIN?
SELECT ways.id_way, ways.start, ways.end, ways.date, users.*
FROM ways JOIN users USING (id_user)


text:
Q: Pipeline of methods taking and returning the same type In a data cleaning application I have a series of methods each of which takes a custom object and returns it after some processing.
I am aware of design patterns which put each of these methods in its own class and chains them together, but I am not interested in splitting up this class. It is a few lines in the middle of one class embedded in a rather large Java monolith. For this same reason I am not going to include a single module from Scala or some other functional language for this small piece of code.
The methods must be implemented in the correct order because the logic of each depends on what has already been done. Thus I have given them new numbered names, and it is the order of this numbering I wish to preserve.
My code at the moment looks like this:
customObject = method1(customObject);
customObject = method2(customObject);
customObject = method3(customObject);
customObject = method4(customObject);
customObject = method5(customObject);
customObject = method6(customObject);

Is there a more fluent way to chain these together, without reversing their order as it appear in the code? In other words, I have dismissed the following as potentially misleading (the real method names would not show they are listed backwards):
customObject = method6(method5(method4(method3(method2(method1(customObject))))));

and
customObject = method6(customObject)
 = method5(customObject)
 = method4(customObject)
 = method3(customObject)
 = method2(customObject)
 = method1(customObject);

(In any case, apart from reversing the order when read, the latter is not valid Java code, as the compiler requires a variable on the left hand side if there is a method call on the right)
It is a small question about a small piece of code. I suspect the answer is 'no' because of the way the processing in each line flows from right-to-left (into the method parameter, and assigned to the variable name on the left). But I can't rid myself of this nagging feeling I might be missing something in the language which will allow a more elegant chaining of these method calls. Perhaps this is something which Java cannot do.

A: You could use a fluent interface pattern. Something like this:
dataCleaner
    .method1(customObject)
    .method2(customObject)
    .method3(customObject)
    .method4(customObject)
    .method5(customObject)
    .method6(customObject)

Where each method on dataCleaner returns this e.g.
public DataCleaner method1(CustomObject customObject) {
    // do some cleaning ...
    // ...
    return this;
}

Notes:

*

*This assumes that each method mutates customObject in such a way that it is ready to be the input into the next method. Based on how you showed your current code, I think this assumption is valid. If this is not valid then you could make DataCleaner stateful and share state between the discrete methods via a class member(s), something like this perhaps:
CustomObject clean = new DataCleaner(customObject)
    .method1()
    .method2()
    .method3()
    .method3()
    .method5()
    .method6()
    .get();

*It could be argued that the above approach is just method chaining rather than a formal fluent interface but it's possible that your actual implementation could return something or could have some methods which take additional context etc all of which would bring it closer to the canonical form of a fluent interface. And leaving aside the semantics of how to describe this pattern, it does at least allow you to tidy up your code and to express the dependencies between this chain of methods in a way which can be easily understood.


text:
Q: How to get the SELinux Type Enforcement (.te) file which contains all rules regarding certain type? I would like to change permissions of certain directories(with user_home_t type) to further disallow guest_t to perform some actions on them.
I thought to do so by creating new type (protected_t) and then not allowing guest_t the actions I don't want to be performed while leaving permissions regarding protected_t and other types the same as regarding user_home_t and other types.
The problem is that I don't know where to find policy that describes actions allowed between other types and user_home_t so that I can change it for protected_t. Generating the entirely new policy for protected_t and allowing what was denied in SELinux permissive mode didn't work well. MCS and MLS also can't be used.
Is there a way to get Type Enforcement file where all allow rules regarding user_home_t are written? I am using Linux Fedora 36.


text:
Q: Holomorphic function with a.e. vanishing radial boundary limits Hello everybody.
I'm looking for an "easy" example of a (non-zero) holomorphic function $f$ with almost everywhere vanishing radial boundary limits: $\lim\limits_{r \rightarrow 1-} f(re^{i\phi})=0$.
Does anyone know such an example.
Best
CJ

A: I am not sure if this would qualify as 'easy' but the first example of such a function was constructed by Lusin. It can be found in N. Lusin, J. Priwaloff, Sur l'unicité et la multiplicité des fonctions analytiques,  Ann. Sci. École Norm. Sup. (3), 1925, p. 143-191 (see p. 185).

A: According to a footnote in the famous Hardy-Ramanujan paper "Asymptotic formulae in combinatory analysis", the function $f(q)=\prod_{n=1}^{\infty}\frac{1}{1-q^n}$ vanishes like $f(re^{i\theta})=o((1-r)^{1/4-\varepsilon})$ for almost all $\theta$. No proof is given, though I can't imagine Hardy would have made a statement like this without a proof in his pocket.
Edit: This isn't actually hard to guess at.  By Euler's pengatonal number theorem, we have $f(q)^{-1}=\sum_{n\in \mathbf{Z}}(-1)^{n}q^{n(3n-1)/2}$, so Plancherel gives
$\int_{0}^{2\pi}|f(re^{i\theta})|^{-2}d\theta=2\pi\sum_{n\in \mathbf{Z}}r^{n(3n-1)} \sim 2 \pi^{3/2}3^{-1/2}(1-r)^{-1/2}.$

A: To complement Andrey Rekalo's response, Lusin's construction was generalized by Bagemihl and Seidel (Math. Zeitschrift 61 (1954), online here). See their Corollary 4 whose proof takes about 2 pages, much less than the original one by Lusin-Priwaloff. Of course the proof relies on Mergelyan's famous approximation theorem for which see Section 20.5 in Rudin: Real and Complex Analysis.
EDIT: Lvriemsurf asked in a comment if we can replace "almost every angle" by "every angle" in the construction. The answer is "no", as follows from the Lusin-Priwaloff theorems.


text:
Q: Leetcode problem 9. Palindrome Number (Python3). Why is my code failing? Here is the code:
class Solution:
    def isPalindrome(self, x: int) -> bool:
        if str(x) == reversed(str(x)):
            return True
        else:
            return False

The testcase where x = 121 fails - it return False as output. But it seems to me that 121 must be equal to 121 reversed.
What is wrong?

A: As mentioned in the comments, a working solution would be:
class Solution:
    def isPalindrome(self, x: int) -> bool:
        return str(x) == str(x)[::-1]

A: This real issue is that reversed() returns an iterator.
print(reversed(str(5)))
<reversed at 0x22c166a78e0>

So, you are comparing a string with an iterator thats why you are getting False.
str(5)==reversed(str(5))
#False

This is the correct syntax:
str(5)==''.join(reversed(str(5)))
#True

Link to document : reversed()


text:
Q: Word "file" in bash script meaning I have a line in bash script.
for i in `ls /sbin`; do file /sbin/$i | grep ASCII; done

Could somebody let me know the reason of use the word "file" in the script?

A: file is a tool/command, that determine file type.
for example:
file /path/someFile

do a man file to read the manual.

A: In for i in 'ls /sbin'; do file /spin/$i | grew ASCII ;done, the
file /spin/$i | grew ASCII bit is the command that is executed on each item in the for loop.
Check out http://explainshell.com/ to get a breakdown of any linux command. Here is Your Command explained.


text:
Q: Import an OpenSSL ECDSA PEM private key and sign it To generate a private and public key with OpenSSL I have run
openssl ecparam -genkey -name secp256k1 -out private-key.pem
openssl ec -in private-key.pem -out public-key.pem -pubout

I upload the public key to the remote server. Then import the private-key.pem to a .Net Framework (it has to be .Net Framework) C# service to use it to sign an API payload:
public string LoadFromCng(byte[] request, string privateKeyFile)
{
    CngKey cng = CngKey.Open(privateKeyFile);

    // Sign the request body with the private key.
    ECDsaCng dsa = new ECDsaCng(cng);
    byte[] signedRequest = dsa.SignData(request, HashAlgorithmName.SHA256);
    return Convert.ToBase64String(signedRequest);
}

With privateKeyFile = private-key.pem the above code gives Keyset does not exist
If I use mkcert and run  mkcert -ecdsa -pkcs12 private-key.pem it generates a PKCS#12 key called private-key.pem.p12 and then:
public string LoadFromX509(byte[] request, string privateKeyFile)
{
    var cert = new X509Certificate2(privateKeyFile, "changeit");
    var key = cert.GetECDsaPrivateKey();
    byte[] signedRequest = key.SignData(request, HashAlgorithmName.SHA256);
    return Convert.ToBase64String(signedRequest);
}

With privateKeyFile = private-key.pem.p12 the above code appears to sign the request, but the API response is The remote server returned an error: (400) Bad Request which means the API provider can't decode the payload from the public key.
I get the same 400 error when going through the cheat sheet here and creating an X509 pfx certificate.
openssl req -new -x509 -key private-key.pem -out cert.pem -days 360
openssl pkcs12 -export -inkey private-key.pem -in cert.pem -out cert.pfx

The method above appears to sign the payload but the provider responds with a 400.
The suggestions here and here and here and here and others have not worked.
I can't use Net Core or NET 5 so this doesn't work either. The ImportPkcs8PrivateKey method is not available in Net Framework.
If I try and use Bouncy Castle per here I get Unable to cast object of type 'Org.BouncyCastle.Crypto.Parameters.ECPrivateKeyParameters' to type 'Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters'

A: The first OpenSSL statement creates an EC parameter file private-key.pem, which contains, among others, a PEM encoded private EC key in SEC1 format.
With .NET Framework the easiest way is to use BouncyCastle for key import. BouncyCastle also supports the ASN.1/DER format and the IEEE P1363 (r|s) format for EC signatures.
The following code imports a PEM encoded private EC key in SEC1 format and signs a message.
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.OpenSsl;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.Encoders;
...
string pkcs8 =  @"-----BEGIN EC PRIVATE KEY-----
                MHQCAQEEIMmN/YG6BtIqm9eAcYtKdcbJosNKbB76vGMTSltPLNiioAcGBSuBBAAK
                oUQDQgAESGnGxuBPdrwv1TkJEorsaNk74+ZFh2jzww2SpLTqQqkvOf5IP6fuODS/
                hzztSBpsBpX9LUZh8TYHX0HRMagkaA==
                -----END EC PRIVATE KEY-----";

TextReader privateKeyTextReader = new StringReader(pkcs8);
AsymmetricCipherKeyPair privateKeyParams = (AsymmetricCipherKeyPair)new PemReader(privateKeyTextReader).ReadObject();

byte[] message = Encoding.UTF8.GetBytes("The quick brown fox jumps over the lazy dog");
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA"); // ASN.1/DER format
//ISigner signer = SignerUtilities.GetSigner("SHA-256withPLAIN-ECDSA"); // r|s format
signer.Init(true, privateKeyParams.Private);
signer.BlockUpdate(message, 0, message.Length);
byte[] signature = signer.GenerateSignature();
Console.WriteLine(Hex.ToHexString(signature)); // 3046022100967c2e890d933c75468dceaf61152add41f143568dcb967583e1b307a0b495e30221008f6837c0d9cc01fc7bfe54ed5b6267fd3e64c2d3ff771e72762f24c20071c454


text:
Q: Update ObservableCollection without Clearing it? I was trying to bind data to datagrid using observablecollection and was wondering how i can update the collection without clearing it.
The new data is provided to me every 500ms-1s.
What is currently have is i clear the Observable collection everytime and re-add the items using new data.
Although this works fine and cant see any flickering on the UI but i was wondering if there is a proper way to update the collection.
    private ObservableCollection<AC> m_Label = new ObservableCollection<AC>();
    public ObservableCollection<AC> Label
    {
        get => m_Label;
        private set => Set(ref m_Label, value);
    }

    ...
    ...
    ...
    Label = ThreadInvoker.Instance.RunByUiThread(() => {
                Label.Clear();
                return Label; });

    {
        //parse and convert data that is provided every 500 milisecond
        ...
        ...

        Label = ThreadInvoker.Instance.RunByUiThread(() => {
                Label.Add(new AC(pass parameters obtained from the new data);
                return Label; });
        }
    }

XAML
  <StackPanel Grid.Column="2">
            <Label Content="Customer"/>
            <DataGrid ItemsSource="{Binding Path=Label}"  Name="dgCustomer" AutoGenerateColumns="False"  IsReadOnly="True">
                <DataGrid.Columns>
                    <DataGridTextColumn Width="Auto" Header="ID" Binding="{Binding AlcoveId}"/>
                    <DataGridTextColumn Width="Auto" Header="Description" Binding="{Binding StateDescription}"/>
                    <DataGridTextColumn Width="Auto" Header="OrderID" Binding="{Binding OrderID}"/>
                </DataGrid.Columns>
            </DataGrid>
   </StackPanel>

A: Since the collection isn't going to change, you might be better just updating the individual classes; for example:
class MyData : INotifyPropertyChanged
{
    public decimal StockPrice {get;set;} // ToDo: Call notify property changed
}

. . .

ObservableCollection<MyData> Data;

. . .

foreach (var d in Data)
{
    d.StockPrice = Rnd.Next(...);
}


text:
Q: plt.show and plt.savefig give different result This is my code, and i get different result from plt.savefig and plt.show
I have trid to use the bbox_inches='tight', but that makes the picture size become not exactly 700*400.
x=np.linspace(1*13,20*13,20)
ys=[[9.429781134779862, 5.29464711177, 3.607607723166614, 2.899937651340496, 2.191804841696895, 1.9843671555485882, 1.7248100121771586, 1.3670895074513212, 1.3698780260605596, 1.2462146230823874, 1.1289892836337199, 1.032841253332204, 0.9543441746831577, 0.7484693801176594, 0.8376893177858197, 0.7849478402160176, 0.7434280956345902, 0.7000987139186625, 0.665212069607791, 0.6300403225806451], [126.98106331402796, 53.50512044002611, 30.074826167504753, 24.227858160427186, 16.471886607532593, 14.13705307473836, 11.449887848348526, 8.72965989245059, 8.840716805318575, 7.263008047412916, 6.293385023002322, 5.634501177610746, 4.6241919224615495, 3.9431399223201433, 3.937845053672828, 3.578854694920532, 3.3610282057487026, 2.947140095251568, 2.629807287721956, 2.5260498894853174]]
plt.figure(figsize=(7,4))
plt.plot(x, ys[0], marker='o',markersize=10,  label='original method')
plt.plot(x, ys[1], marker='s',markersize=10,   label='our method')

plt.xlabel('Number of trajectories(×1000)',fontsize=20)
plt.ylabel("QPS",fontsize=20)
plt.yscale('log')
plt.xticks(fontsize=15)
plt.yticks(fontsize=15)
plt.legend(fontsize=20)
plt.savefig("../res/dense.png",dpi=plt.gcf().dpi)
plt.show()

This is the two pictures I got from savefig() and show()

A: You can use:
plt.show() before
plt.savefig("../res/dense.png",dpi=plt.gcf().dpi)
It's just a matter of convention. When we call plt.savefig the reference of all the variable point till plt.savefig after that any statement it corresponds to new plot.
You can accept the answer. If it helps.


text:
Q: Apache Pluto portlet set path to .java file I'm new to portlets and I have a problem with the HelloWorld application. The app displays all the static content (from the index.jsp) but the code inside HelloWorldPortlet.java is not displayed at all.
I'm talking about
response.getWriter().print("Hello World Portlet!");

I also put some console log's (System.out.println) inside the lifecycle methods just to check it out, but nothing is displayed in the console :(
public class HelloWorldPortlet extends GenericPortlet{
    public void doView( RenderRequest request, RenderResponse response )
            throws PortletException, IOException {
System.out.println("doView()");
            response.getWriter().print("Hello World Portlet!");
        }
}

My guess is that some setting regarding the .java file/class is wrong inside one the numerous XML config files...
Edit: I'm using the Maven build tool which I only vaguely understand.
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.journaldev</groupId>
    <artifactId>HelloWorldPortlet</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>HelloWorldPortlet Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>org.apache.portals</groupId>
            <artifactId>portlet-api_2.0_spec</artifactId>
            <version>1.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.portals.pluto</groupId>
                <artifactId>maven-pluto-plugin</artifactId>
                <version>2.1.0-M3</version>
                <executions>
                    <execution>
                        <phase>generate-resources</phase>
                        <goals>
                            <goal>assemble</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <configuration>
                    <webXml>${project.build.directory}/pluto-resources/web.xml</webXml>
                </configuration>
            </plugin>
        </plugins>
        <finalName>HelloWorldPortlet</finalName>
    </build>
</project>

A: This should help...
protected void doView(RenderRequest request, RenderResponse response)
        throws PortletException, IOException, UnavailableException
    {
        response.setContentType(request.getResponseContentType());
        PortletRequestDispatcher dispatcher = getPortletContext().getRequestDispatcher((new StringBuilder("/WEB-INF/jsp/TestPortlet")).append(VIEW).toString());
        dispatcher.include(request, response);
    }

    public void processAction(ActionRequest request, ActionResponse response)
        throws PortletException, PortletSecurityException, IOException
    {
        String name = request.getParameter("firstname");
        if(name != null && !name.equals(""))
            response.setRenderParameter("helloname", name);
    }

    public static String VIEW = "/view.jsp";
    public static final String PORTLET = "TestPortlet";

And in the jsp you can use...
String requestParameter = request.getParameter("helloname");


text:
Q: How can i add a activity indicator below the UITableView? In my application i want to add activity indicator under UItableview where tableview will scroll but i do not know how can i add activity indicator over there.
To elaborate,when i will finish the scrolling of tableview then for more data i have to set a refresh option by an activity indicator.
i have tried it at the top of the tableview and it worked but i dont know how can i add it below the tableview. here is some sample code..
      - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
if (isLoading) return;
isDragging = YES;

refreshHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
refreshHeaderView.backgroundColor = [UIColor clearColor];

refreshLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT, 320, REFRESH_HEADER_HEIGHT)];
refreshLabel.backgroundColor = [UIColor clearColor];
refreshLabel.font = [UIFont boldSystemFontOfSize:12.0];
refreshLabel.textAlignment = UITextAlignmentCenter;

refreshArrow = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"refresharrow.png"]];
refreshArrow.frame = CGRectMake((scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT - 27) / 2,
                                (scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT - 44) / 2,
                                27, 44);

refreshSpinner = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
refreshSpinner.frame = CGRectMake((scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT - 20) / 2, (scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT - 20) / 2, 20, 20);
refreshSpinner.hidesWhenStopped = YES;

[refreshHeaderView addSubview:refreshLabel];
[refreshHeaderView addSubview:refreshArrow];
[refreshHeaderView addSubview:refreshSpinner];
[tableview addSubview:refreshHeaderView];

}

 - (void)scrollViewDidScroll:(UIScrollView *)scrollView {
if (isLoading) {
    // Update the content inset, good for section headers
    if (scrollView.contentOffset.y > 0){
        NSLog(@"scrollView.contentOffset.y 1= %d",scrollView.contentOffset.y );
        tableview.contentInset = UIEdgeInsetsZero;
    }
    else if (scrollView.contentOffset.y >= -REFRESH_HEADER_HEIGHT){
        NSLog(@"scrollView.contentOffset.y 2= %d",scrollView.contentOffset.y );
        tableview.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
    }
} else if (isDragging && scrollView.contentOffset.y > scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT) {
    // Update the arrow direction and label
    [UIView beginAnimations:nil context:NULL];
    if (scrollView.contentOffset.y > scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT) {
        // User is scrolling above the header
        NSLog(@"scrollView.contentOffset.y 3= %d",scrollView.contentOffset.y );
        refreshLabel.text = self.textRelease;
        [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI, 0, 0, 1);
    } else { // User is scrolling somewhere within the header
        refreshLabel.text = self.textPull;
        [refreshArrow layer].transform = CATransform3DMakeRotation(M_PI * 2, 0, 0, 1);
    }
    [UIView commitAnimations];
}
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
if (isLoading) return;
isDragging = NO;
if (scrollView.contentOffset.y >= scrollView.contentOffset.y + REFRESH_HEADER_HEIGHT) {
    // Released above the header
    [self startLoading];
}
}

so please someone give me some example code about how can i do that.
actually i am new in iphone application development.So please help me.
Thanks in Advance.

A: This is how I've done it:
UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
[spinner startAnimating];
spinner.frame = CGRectMake(0, 0, 320, 44);
self.tableView.tableFooterView = spinner;

Then you just set tableFooterView to nil to remove it.
Note:
44, btw, is the default height of a UITableViewCell when using UITableViewStylePlain.
It's 45 for UITableViewStyleGrouped.

A: Swift Update :-
let pagingSpinner = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
pagingSpinner.startAnimating()
pagingSpinner.color = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
pagingSpinner.hidesWhenStopped = true
tableView.tableFooterView = pagingSpinner

A: The best way to add activity indicator is at footer of tableview.
    - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
UIView *headerView = [[[UIView alloc] init]autorelease];

    [headerView setBackgroundColor:[UIColor clearColor]];

UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self
           action:@selector(aMethod:)
 forControlEvents:UIControlEventTouchDown];
[button setTitle:@"Load More" forState:UIControlStateNormal];
button.frame = CGRectMake(10.0, 210.0, 160.0, 40.0);

    [headerView addSubview:button];

    [headerLabel release];

    return headerView;

}

Add a button to the footerView and set action to button (as you needed). This how app store tableview works. On clicking button fetch some more data add to table array scroll the table without animation.

A: One more way to add activity indicator. Check if your data displayed is not equals to the total count of data. Then you add one extra cell and Add "View More" button. When i click on the view more the hide that button and add activity indicator in that cell. And when process is done then reload the table view.
Thanks.


text:
Q: show alert then when click the alert, redirect to the specific controller with pass the parameter too I'm working with codeigniter and this is my current code:
function pesan()
{
    $rute_id = $this->input->post('rute_id');
    $namapemesan = $this->input->post('fullname');

    if ($namapemesan == "" || $namapemesan == null)
    {
        ?>
            <script type="text/javascript">
                var id = "<?php $rute_id ?>";
                alert("Error!");
                window.location.href="prepare_pesan/id";
            </script>
        <?php
    }
}

and this is my prepare_pesan function
public function prepare_pesan($id)
{

}

When namapemesan == null, I can't see rute_id in my url. I think I misapplied the rute_id in my javascript. Any solution?

A: Try this
window.location.href="prepare_pesan/"+ id;

public function prepare_pesan($id = null)
{

}

And in this line you lack of echo
var id = "<?php echo $rute_id ?>";


text:
Q: sed, regex replace with vars I'm trying to use sed (4.2.2-4+b1 debian 8 (jessie)) to replace text in multiple files.
To go from this:
$var1 = array(foo=>"bar",bar=>"foo");
$var2 = array( foo=>"bar", bar=>"foo" );
$var1 = array(
    foo=>"bar",
    bar=>"foo"
);

To get this:
$var1 = array( "foo" => "bar","bar" => "foo");
$var2 = array( "foo" => "bar", "bar" => "foo" );
$var1 = array(
    "foo" => "bar",
    "bar" => "foo"
);

The normal regex would be:
/(\(|\(\s|,|,\s.+?)([a-z|A-Z].+?)=>/$1"$2" => /g

Using sed like this doesn't seem to be working though
sed -i "s#\((\|(\s\|,\|,\s.+?\)\([a-zA-z].+?\)=>#\1\"\2\" => #g" *.php

Or:
sed -i "s#\((\|(\s\|,\|,\s.+?\)\([a-z\|A-z].+?\)=>#\1\"\2\" => #g" *.php

Anyone know what I'm doing wrong?

A: sed -r 's/([^"])([[:alpha:]_][[:alnum:]_]*)[[:blank:]]*=>/\1"\2" => /g'

find a non-quote character, followed by the hash key, followed by optional whitespace followed by =>, and insert quotes around the key.


text:
Q: A macro to set a particular transition between powerpoint slides before go to the next slide I'm working on a Slideshow where all the slides have set the "Push from Left" transition. I'm going to insert in every slide a button to go back to the previous one, and just when the button is pressed I'd like to switch the transition to "Push from Right", go to the previous slide, then set the transition to "Push from Left" again.
I wrote this, but it does not work:
Sub previousslide()
With ActivePresentation.SlideShowWindow.View
    .Slide.SlideShowTransition.EntryEffect = ppEffectPushRight
    .GotoSlide (ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1)
    .Slide.SlideShowTransition.EntryEffect = ppEffectPushLeft
End Sub

Thanks

A: You are missing an 'End With' to complete the With-End With block. Also, I would skip referencing ActivePresentation object because it will work only if there is an active presentation. If you run the code above while running a .PPSX/.PPSM file then the code will fail. The code below removes the reference.
Sub PreviousSlide()
With SlideShowWindows(1).View
    .Slide.SlideShowTransition.EntryEffect = ppEffectPushRight
    .GotoSlide (SlideShowWindows(1).View.Slide.SlideIndex - 1)
    .Slide.SlideShowTransition.EntryEffect = ppEffectPushLeft
End With
End Sub

A: Here's another way to reference a slide:
Presentations.Item(#).Slides(#).SlideShowTransition.EntryEffect
This works whether or not a slideshow's running, the octothorps should be replaced by your intended 1-based index number
Also I've experienced that the code API applies different transition styles than the GUI

A: I am working on the same thing. If you're on slide x and going to the previous slide, what you need to do is set the slide transition of slide x-1 to 'Push from Right'. If you're going to the next slide, you need to set the transition of slide x+1 to 'Push from Left'.
Sub previousSlide()
' Define previous slide index
Dim previousSlide As Integer
previousSlide = ActivePresentation.SlideShowWindow.View.Slide.SlideIndex - 1
' Change slide transition of previous slide
ActivePresentation.Slides.Range(previousSlide).SlideShowTransition.EntryEffect = ppEffectPushRight
' Previous slide
ActivePresentation.SlideShowWindow.View.GotoSlide (previousSlide)
End Sub

Strangely, I've noticed if slides start with NO animation, setting the animation using this code doesn't work. The animation must be pre-set manually to the Slide animation, then this code works. Strange...


text:
Q: How to set a default page within hotspot MikroTik to be open automatically after wifi connect I'm trying to set a Default HTML Page to be opened after wifi connects automatically.
Kinda like the Login page. I've tried writing a few javascript lines to make the redirect work but after redict, there is no content within my HTML.
Is it possible to set an HTML page instead of the login page to be opened directly after wifi connect with MikroTik?

A: When using the Mikrotik hotspot functionality the login page is displayed which is stored on the Mikrotik router. This page is called login.html and can be modified to your needs.
If you want to use an external site to display to your users you can modify login.html with http meta refresh to redirect to an external url. You may want to add this URL to the walled garden so it can be accessed.
When the page is displayed, the user is not logged in. A HTTP POST must be done with a username and password to login the user and access other sites. You can do this by adding a form to the external site or the login.html page to login the user with one click. Without the login any request will be redirected to the login.html page and/or your external site.

A: MikroTik calls this the Hotspot Gateway. You can begin the setup with /ip hotspot setup or from IP > Hotspot from Winbox. Check the wiki page for several more in-depth examples.


text:
Q: iPhone - Edit storyboard elements in separate window I am trying to edit a UIView inside a UIScrollView. I have set the UIView's hight to 700, but I can't scroll around to place objects. I want to open the UIView in a separate window to edit its content. Or, is there another way I should be approaching this? The first answer in this question contains an example of what I am trying to do, although in storyboard. What am I doing wrong, or is it possible? Thanks!

A: I would create a separate XIB file for the UIView you are going to be creating, then create a new class as the file owner of this XIB. You would then want to connect the UIView inside your UIScrollView to this.
The steps involved are illustrated in this past question:
Add subview from a xib or another scene with storyboard

A: I found that using this link was the best solution. I was able to get Devin's solution to partly work, but it involved a lot of hacking with my code. While the above link disables auto-layout, I am ok with that for my small application.


text:
Q: How do I scrape ::before element in a website using selenium python I am trying to scrape phone number from this website using selenium. I found the class to be "tel ttel" but when I try to scrape the website by find_element_by_xpath. I get an empty string.
My code:
wd = webdriver.Chrome(chrome_path)
url = 'https://www.justdial.com/Bangalore/Spardha-Mithra-IAS-KAS-Coaching-Centre-Opposite-Maruthi-Medicals-Vijayanagar/080PXX80-XX80-140120184741-R6P8_BZDET?xid=QmFuZ2Fsb3JlIEJhbmsgRXhhbSBUdXRvcmlhbHM='
wd.get(url)
phone = wd.find_element_by_xpath('//a[@class="tel ttel"]').text
print(phone)

Output:

' '

The phone number is located over here:

The Inspect element for the phone number is:

A: You don't need selenium. The instructions to apply the content which gives the pseudo before elements their values is carried in the css style instructions:

Here, the 2/3 letter strings after the .icon- e.g. acb map to the span elements which house your before content. The values after \9d0 are + 1 of the actual value shown. You can create a dictionary from these pairs of values (with the adjustment) to decode the number at each before from the span class value.
Example of how 2/3 letter strings map to content:

My method is perhaps a little verbose as I am not that familiar with Python but the logic should be clear.
import requests
import re
from bs4 import BeautifulSoup
url = 'https://www.justdial.com/Bangalore/Spardha-Mithra-IAS-KAS-Coaching-Centre-Opposite-Maruthi-Medicals-Vijayanagar/080PXX80-XX80-140120184741-R6P8_BZDET?xid=QmFuZ2Fsb3JlIEJhbmsgRXhhbSBUdXRvcmlhbHM='
res  = requests.get(url, headers  = {'User-Agent': 'Mozilla/5.0'})
soup = BeautifulSoup(res.content, 'lxml')

cipherKey = str(soup.select('style[type="text/css"]')[1])
keys = re.findall('-(\w+):before', cipherKey, flags=0)
values = [int(item)-1 for item in re.findall('9d0(\d+)', cipherKey, flags=0)]
cipherDict = dict(zip(keys,values))
cipherDict[list(cipherDict.keys())[list(cipherDict.values()).index(10)]] = '+'
decodeElements = [item['class'][1].replace('icon-','') for item in soup.select('.telCntct span[class*="icon"]')]

telephoneNumber = ''.join([str(cipherDict.get(i)) for i in decodeElements])
print(telephoneNumber)

A: You can also get the :before content from the computed style:
chars = driver.execute_script("return [...document.querySelectorAll('.telCntct a.tel span')].map(span => window.getComputedStyle(span,':before').content)")

But in this case you're left with weird unicode content that you then have to map to numbers.


text:
Q: Is scope=request good fit for high-load spring application? Is it common practice when singleton beans was injected to request-scoped beans, which injected to singleton-scoped beans?
For example, something like this:
@Scope(value="request", proxyMode=ScopedProxyMode.INTERFACES)
public class CurrentUser {
    @Resource
    private UserRepository userRepository;
    ...
}

public class ApplicationController {

    @Autowired
    private CurrentUser currentUser;
    ...
}

Is any overhead expenses for memory management possible? This implementation is tread-safe?
Thanks!

A: Essentially what is going to happen is that there will be an instance of CurrentUser for every active http request. The instances are managed behind a proxy created by Spring and the instance itself is maintained as a http request attribute and the lifecycle is tied to this request.
I would say that this is going to be costly in terms of the effort to instantiate and autowire each CurrentUser request instance. It should not be costly memory wise as the instances are short lived and scoped to request. On whether the instance is thread safe, yes it is.
One bug though, the proxyMode has to be ScopedProxyMode.TARGET_CLASS as your CurrentUser class does not implement any interfaces.


text:
Q: Spring Form Submit to Delete a Collection Item I have a page that has a form backing object that contains a collections property that I loop through on the page. I want to give the user the option of deleting an item of the collection by clicking on a remove button.  However I don't know which remove button was pressed in the controller since each item in the collection has a remove button.  Basically I need to know which remove button was pressed so I know what question id should be deleted.  What is the best way to go about this?  Please see my page below:
<%@ include file="/WEB-INF/jsp/taglibs.jsp" %>

<sf:form method="POST" modelAttribute="surveyInfo" >

                    Schedule Number ${surveyInfo.surveyNumSch}
                    <input type="submit" class="small-short inner2" value="Save" alt="Save" title="Save"    />
                    <input type="button" class="small-short inner2" value="Print" alt="Print" title="Print" />
                    <input type="button" class="small-short inner2" value="Remove" alt="Remove" title="Remove"  />
                    <sf:input type="hidden" path="id" id="id" cssClass="inputbox-survey" maxlength="100" size="100" />
                    <sf:input type="hidden" path="surveyTitle" id="surveyTitle" cssClass="inputbox-survey" maxlength="100" size="100" />
                    <sf:input type="hidden" path="surveyName" id="surveyName" cssClass="inputbox-survey" maxlength="100" size="100" />

            <c:forEach items="${surveyInfo.allSurveyQuestions}" var="surveyQuestion" varStatus="status">

                            Question ${status.count}  <input type="submit" class="small-short inner2" value="Remove${status.count}" alt="Remove" title="Remove" />
                            <sf:input type="hidden" path="allSurveyQuestions[${status.index}].questionId" id="questionId${status.count}" cssClass="inputbox-survey" maxlength="100" size="100" />
                            <sf:input type="hidden" path="allSurveyQuestions[${status.index}].id" id="id${status.count}" cssClass="inputbox-survey" maxlength="100" size="100" />

                        Text:
                        <sf:input path="allSurveyQuestions[${status.index}].questionText" id="questionText${status.count}" cssClass="inputbox-survey" maxlength="100" size="100" />

            </c:forEach>

</sf:form>

A: Well I solved my issue, what I did was created a property called isDeleted in my domain object which is also my form backing object and created a bound checkbox for each record on the page.  If the user clicks on the checkbox or checkboxes and clicks saves, the controller checks the value of the checkbox and populates 2 different collections one for toBeSaved and another for toBeDeleted.  Unchecked records gets saved and checked records get deleted from the database.
I saw lots of options on the web to do this via the jquery route, but I am still learning jquery and preferred to do it server side.


text:
Q: How to copy the values of the first and last column of a pivot table? I currently have code to copy the values from the pivot table and paste them onto a sheet:
the summary code is:
Sub Pivotcopy()

    Dim pt As PivotTable
    Set pt = ActiveSheet.PivotTables("pivottable2")
    .
    .
    .
    pt.TableRange2.Copy
    Sheets("newsheet").Range("A20").PasteSpecial xlPasteValues

However, this copies all the values. What I want is to copy only the first and last columns of the pivot table, i.e. the row labels column and the grand total column. After that I want to paste it in the "newsheet" sheet.

A: Try this. You'd broken the back of it, just need to reference the two columns appropriately.
Sub Pivotcopy()

Dim pt As PivotTable
Set pt = ActiveSheet.PivotTables("pivottable2")

With pt.TableRange2
    Union(.Columns(1), .Columns(.Columns.Count)).Copy
End With

With Sheets("newsheet").Range("A20")
   .PasteSpecial xlPasteValues
   .Resize(3).EntireRow.Delete shift:=xlUp
End With

End Sub


text:
Q: Problems setting up Roboguice 2.0 in eclipse OK so i've looked into this a couple of times, and I simply cannot get my project up and running with RoboGuice 2.0
Eclipse just simply doesn't recognize the annotations, eg.
@InjectView(R.id.link_email) TextView linkEmail;

I get ( in 'Problems' pane) :
'InjectView cannot be resolved to a type MyActivity.java'
'The attribute value is undefined for the annotation type InjectView'
I've followed the instructions at :
http://code.google.com/p/roboguice/wiki/InstallationNonMaven
I've got these jars in my libs folder and added to the build path :
RoboGuice 2.0,
Guice 3.0-no_aop,
jsr305
I'm sure I'm missing something simple here, anyone any ideas? Thanks in advance.

A: OK so I was being extremely daft and the answer was pretty obvious.
I've not used the custom annotations before but unlike standard ones like '@Override' you have to import the class for Eclipse to recognise the code eg.
import roboguice.inject.InjectView;

Eclipse will autocomplete this for you in the normal manner when writing the code if you hit control and space.
Hope this helps someone else too!


text:
Q: How do I add a blog_id prefix to article controller? I have a Shopify rails app and in my Articles controller I'm not sure how to add a "prefix_option" like it's asking for in the exception catcher. I'm a beginner rails developer so it's very possible I'm missing something obvious. This is all I have in the controller at the moment:
class ArticleController < ApplicationController

around_filter :shopify_session

  def show
     @article = ShopifyAPI::Article.find(params[:id])
  end

end

Thanks for any help.

A: Articles are nested under Blogs, so you need to specify the id of the blog under which you're looking.
This should work: ShopifyAPI::Article.find(params[:id], :params => {:blog_id => blog_id})
N.B: The Shopify API's ruby wrapper is based on ActiveResource, so a lot of questions can be answered by looking at AR's docs.
Specs for the find method are here: http://api.rubyonrails.org/classes/ActiveResource/Base.html#method-c-find


text:
Q: A more attractive way of handling hash url changes? On my current site that I'm developing, I am just appending #whatever to my url, so www.example.com/product#doughdough or www.example.com/product#sweet
Don't get me wrong, it works fine and functions great when using the back button, but I'm curious to see if there are any other "creative" ways of presenting it? Maybe something like www.example.com/products/#/doughdough or www.example.com/#/products/doughdough? Do the added slashes change anything?

A: The hash technique has many problems, so many that Twitter has stopped using it, switch to using the history API which lets you have real URIs to fall back to a (search engine friendly) server side solution with.

A: If you don't mind HTML5 only support you can check pushState method.
Good tutorial for using HTML5 History API (Pushstate?)
https://developer.mozilla.org/en-US/docs/DOM/Manipulating_the_browser_history


text:
Q: how to Upload Image from fragment to firebase using activity Result? (Kotlin) Trying to upload an image to firebase from fragment. I also start the activity by using this command: activity!!.startActivityForResult......
But still the same error.
Libraries I used to crop image and compress the image:
implementation 'com.theartofdev.edmodo:android-image-cropper:2.7.+'
implementation 'id.zelory:compressor:2.1.0'

changeProfile is a button
val GALLERY_ID:Int = 1
val changeProfile = view.findViewById<Button>(R.id.changeProfileImage)
    changeProfile.setOnClickListener{
        var galleryIntent = Intent().apply {
            type = "image/*"
            action = Intent.ACTION_GET_CONTENT
        }
       startActivityForResult(Intent.createChooser(galleryIntent,
                "SELECT_IMAGE"), GALLERY_ID)
    }

Heres my activity result where I first check the error in the activity result. The I upload the croped image to firebase storage as a profile image.
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)

    if (requestCode == GALLERY_ID
            && resultCode == Activity.RESULT_OK) {

        var image: Uri = data!!.data
        var userId = mCurrentUser!!.uid

        CropImage.activity(image)
                .setAspectRatio(1, 1)
                .start(context as Activity,this)

        if (requestCode == CropImage.CROP_IMAGE_ACTIVITY_REQUEST_CODE) {
            val result = CropImage.getActivityResult(data)

            if (resultCode == Activity.RESULT_OK) {
                val resultUri = result.uri
                var thumbFile = File(resultUri.path)
                var thumbBitmap = Compressor(activity)
                        .setMaxWidth(200)
                        .setMaxHeight(200)
                        .setQuality(65)
                        .compressToBitmap(thumbFile)

                //We upload images to firebase
                var byteArray = ByteArrayOutputStream()
                thumbBitmap.compress(Bitmap.CompressFormat.JPEG,  100,
                        byteArray)
                var thumbByteArray: ByteArray
                thumbByteArray = byteArray.toByteArray()

                var filePath = mStorageRef!!.child("chat_profile_images")
                        .child(userId + ".jpg")

                //Create another directory for thumbimages ( smaller, compressed images)
                var thumbFilePath = mStorageRef!!.child("chat_profile_images")
                        .child("thumbs")
                        .child(userId + ".jpg")

                filePath.putFile(resultUri)
                        .addOnCompleteListener{
                            task: Task<UploadTask.TaskSnapshot> ->
                            if (task.isSuccessful) {

                                //Let's get the pic url
                                var donwloadUrl = task.result.downloadUrl.toString()

                                //Upload Task
                                var uploadTask: UploadTask = thumbFilePath
                                        .putBytes(thumbByteArray)

                                uploadTask.addOnCompleteListener{
                                    task: Task<UploadTask.TaskSnapshot> ->
                                    var thumbUrl = task.result.downloadUrl.toString()

                                    if (task.isSuccessful) {

                                        var updateObj = HashMap<String, Any>()
                                        updateObj.put("image", donwloadUrl)
                                        updateObj.put("thumb_image", thumbUrl)

                                        //We save the profile image
                                        mDatabase!!.updateChildren(updateObj)
                                                .addOnCompleteListener {
                                                    task: Task<Void> ->
                                                    if (task.isSuccessful) {
                                                        Toast.makeText(activity, "Profile Image Saved!",
                                                                Toast.LENGTH_LONG)
                                                                .show()

                                                    }else {
                                                    }
                                                }

                                    }else {
                                    }
                                }
                            }
                        }
            }
            else if (resultCode == CropImage.CROP_IMAGE_ACTIVITY_RESULT_ERROR_CODE) {
                val error = result.error
                Log.e("Error", error.toString())
            }
        }

    }
    else {
        Toast.makeText(activity,"Activity Result Error", Toast.LENGTH_LONG).show()
    }
}


text:
Q: Application of Strong Markov Property
Theorem SMP (Strong Markov Property)
Let $X$ be a time homogenous Markov process with $T=\mathbb R_+$ or
  $\mathbb Z_+$ and let $\tau$ be a stopping time taking countably many
  values. Then $$P[\theta _{\tau}X\in  A\mid \mathscr
F_{\tau}]\overset{\text {a.s on }\left\{ \tau <\infty \right\}
}{=}P_{X_\tau}(X\in A)$$

Assume from now on $T=\mathbb{Z}_+$ and that $X$ is canonical. Define the first hitting time of state $y$ as $\tau=\inf \left\{  n\geq 0:X_n=y \right\} $. Now define recursively $$\tau_y ^{k+1}=\tau_y^k+\tau_y\circ \theta_{\tau^k_y},\;\;\;k\geq 0$$ starting from $\tau^0_y=0$.
Why does the SMP imply the following equality?$$P_x \left\{ \tau^k_y<\infty,\;\tau_y\circ\theta_{\tau^k_y} \right\}=P_x \left\{ \tau^k_y<\infty  \right\} P_y \left\{ \tau_y<\infty \right\}$$

A: The missing step has nothing in particular to do with Markov processes - it uses the decomposition $P(A\cap B)=P(B\mid A)P(A)$. Thus $$\begin{align} P_x \left\{ \tau^k_y<\infty,\;\tau_y\circ\theta_{\tau^k_y} \right\} & =P_x \left\{ \tau_y\circ\theta_{\tau^k_y} \mid \tau _y^k<\infty  \right\} P_x \left\{ \tau^k_y<\infty  \right\}\\ & =P_x \left\{ \tau^k_y<\infty  \right\} P_y \left\{ \tau_y<\infty \right\} \end{align}$$ where the strong Markov property is used in the final transition.


text:
Q: Can ReduceLrOnPlateau scheduler in pytorch use test set metric for decreasing learning rate? Hi I am currently learning the use of scheduler in deep learning in pytroch. I came across the following code :
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision.datasets as dsets

# Set seed
torch.manual_seed(0)

# Where to add a new import
from torch.optim.lr_scheduler import ReduceLROnPlateau

'''
STEP 1: LOADING DATASET
'''

train_dataset = dsets.MNIST(root='./data',
                            train=True,
                            transform=transforms.ToTensor(),
                            download=True)

test_dataset = dsets.MNIST(root='./data',
                           train=False,
                           transform=transforms.ToTensor())

'''
STEP 2: MAKING DATASET ITERABLE
'''

batch_size = 100
n_iters = 6000
num_epochs = n_iters / (len(train_dataset) / batch_size)
num_epochs = int(num_epochs)

train_loader = torch.utils.data.DataLoader(dataset=train_dataset,
                                           batch_size=batch_size,
                                           shuffle=True)

test_loader = torch.utils.data.DataLoader(dataset=test_dataset,
                                          batch_size=batch_size,
                                          shuffle=False)

'''
STEP 3: CREATE MODEL CLASS
'''
class FeedforwardNeuralNetModel(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim):
        super(FeedforwardNeuralNetModel, self).__init__()
        # Linear function
        self.fc1 = nn.Linear(input_dim, hidden_dim)
        # Non-linearity
        self.relu = nn.ReLU()
        # Linear function (readout)
        self.fc2 = nn.Linear(hidden_dim, output_dim)

    def forward(self, x):
        # Linear function
        out = self.fc1(x)
        # Non-linearity
        out = self.relu(out)
        # Linear function (readout)
        out = self.fc2(out)
        return out
'''
STEP 4: INSTANTIATE MODEL CLASS
'''
input_dim = 28*28
hidden_dim = 100
output_dim = 10

model = FeedforwardNeuralNetModel(input_dim, hidden_dim, output_dim)

'''
STEP 5: INSTANTIATE LOSS CLASS
'''
criterion = nn.CrossEntropyLoss()

'''
STEP 6: INSTANTIATE OPTIMIZER CLASS
'''
learning_rate = 0.1

optimizer = torch.optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, nesterov=True)

'''
STEP 7: INSTANTIATE STEP LEARNING SCHEDULER CLASS
'''
# lr = lr * factor
# mode='max': look for the maximum validation accuracy to track
# patience: number of epochs - 1 where loss plateaus before decreasing LR
        # patience = 0, after 1 bad epoch, reduce LR
# factor = decaying factor
scheduler = ReduceLROnPlateau(optimizer, mode='max', factor=0.1, patience=0, verbose=True)

'''
STEP 7: TRAIN THE MODEL
'''
iter = 0
for epoch in range(num_epochs):
    for i, (images, labels) in enumerate(train_loader):
        # Load images as Variable
        images = images.view(-1, 28*28).requires_grad_()

        # Clear gradients w.r.t. parameters
        optimizer.zero_grad()

        # Forward pass to get output/logits
        outputs = model(images)

        # Calculate Loss: softmax --> cross entropy loss
        loss = criterion(outputs, labels)

        # Getting gradients w.r.t. parameters
        loss.backward()

        # Updating parameters
        optimizer.step()

        iter += 1

        if iter % 500 == 0:
            # Calculate Accuracy
            correct = 0
            total = 0
            # Iterate through test dataset
            for images, labels in test_loader:
                # Load images to a Torch Variable
                images = images.view(-1, 28*28)

                # Forward pass only to get logits/output
                outputs = model(images)

                # Get predictions from the maximum value
                _, predicted = torch.max(outputs.data, 1)

                # Total number of labels
                total += labels.size(0)

                # Total correct predictions
                # Without .item(), it is a uint8 tensor which will not work when you pass this number to the scheduler
                correct += (predicted == labels).sum().item()

            accuracy = 100 * correct / total

            # Print Loss
            # print('Iteration: {}. Loss: {}. Accuracy: {}'.format(iter, loss.data[0], accuracy))

    # Decay Learning Rate, pass validation accuracy for tracking at every epoch
    print('Epoch {} completed'.format(epoch))
    print('Loss: {}. Accuracy: {}'.format(loss.item(), accuracy))
    print('-'*20)
    scheduler.step(accuracy)

I am using the above strategy. The only thing that I am not able to understand is that how are they using test data to step up the accuracy and decreasing learning rate on the basis of that via scheduler? It is the last line of the code. Can we during training show the test accuracy to the scheduler and ask that it to reduce the learning rate? I found the similar thing on github resnet main.py
too. Can someone please clarify ?

A: I think there might be some confusion regarding the term test here.
Difference between test and validation data
What the code actually refers to by test is the validation set not the actual test set. The difference is that the validation set is used during training to see how well the model generalizes. Normally people just cut off a part of the training data and use that for validation. To me it seems like your code is using the same data for training and validation but that's just my assumption because I don't know what ./data looks like.
To work in a strictly scientific way, your model should never see actual test data during training, only training and validation. This way we can assess the models actual ability to generalize on unseen data after training.
Reducing learning rate based on validation accuracy
The reason why you use validation data (called test data in your case) to reduce the learning rate is probably because if you did this using the actual training data and training accuracy the model is more likely to overfit. Why? When you are on a plateau of the training accuracy it does not necessarily imply that it's a plateau of the validation accuracy and the other way round. Meaning you could be stepping in a promising direction regarding the validation accuracy (and thus in a direction of parameters that generalize well) and suddenly you reduce or increase the learning rate because there was a plateau (or non) in the training accuracy.


text:
Q: Close Dynamsoft Web Twain Popup I am trying to implement Dynamsoft Web Twain in my Angular project. But there is no close button in the installation popup. How to add close button in the popup?
My Angular version is 13.3
Dynamsoft Webtwain version: 17.2.4
Screenshot of popup

A: There are three ways to add the close button in dynamsoft.webtwain.install.js:

*

*Change the value of closeButton to true in _this.DWT.ShowMessage(ObjString.join(''), { width: promptDlgWidth, headerStyle: 1, closeButton: true });. By default, it is false.

*Add a button element based on current code.
For example, add
ObjString.push('

Close

');

below
ObjString.push(' onclick="Dynamsoft.DCP_DWT_onclickInstallButton()">

Download

');

Then add the button click function
Dynamsoft.onClose = function() {
  document.getElementsByClassName('dynamsoft-dialog')
[0].style.display = 'none';
}

above
Dynamsoft.DCP_DWT_onclickInstallButton = function ()

Now the popup window looks as follows:

You can click the close button to close the dialog. Due to z-index, the HTML elements under the popup dialog are not selectable. A tricky way is to modify z-index after hiding the popup dialog:
let divs = document.getElementsByTagName('div');
  for (let i = 0; i < divs.length; i++) {
    divs[i].style.zIndex = -1;
  }

*Do not call _this.DWT.ShowMessage(ObjString.join(''), { width: promptDlgWidth, headerStyle: 1, closeButton: true });. Instead, use jQuery to create a custom dialog. For example:
<!doctype html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.13.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">

This is the default dialog which is useful for displaying
information. The dialog window can be moved, resized and closed with
the 'x' icon.


text:
Q: How to properly set up jfxtras iCalendarAgenda in intellij I am trying to use the calendar plug in by jfxtras. I originally tried setting the project up as a maven project or gradle project and importing the jfxtras-all, and setting the snapshot to latest. Unfortunately it seems that iCalendarfx and iCalendarAgenda are not included in this. So I tried just downloading the zip on github. But after setting a file up that had them all in the jfxtras package it gave me a Java.lang.runtime exception. I think maybe it would be best to make a jar of these libraries but I don't really know. Any suggestions as to how to include these libraries would be helpful thanks.

A: I finally got it working. I included every library in maven separately. For some reason labs has to have a snapshot of 8.0-r4 instead of 8.0-r5. And then I downloaded the zip from github and just included the Java files of iCalendaragenda and iCalendar fx.


text:
Q: How would I go about setting an images default location to a CGRect, and only allow the image to be dropped inside another CGRect I've been working at this for two days and have not had much luck. I have a little, tile image that I'm able to drag and drop anywhere on the screen with a touche's coordinates. My first question is: how can I set the tile images coordinates so that it starts off inside of the green CGRect instead of the top corner screen? In other words, I want to make the green CGRect the image's default location with affecting the users toch coordinates. My next question is how can I code it to where the only other location on the screen that I can drag and drop the image to, is inside the red CGRect? And if more then half of the image is inside the red CGRect, how can I make it snap to the inside of the Red CGRect if someone lets go of it. If more then half of the image is OUTSIDE of the CGRect, I want to animate it back to it's default location. If your going to answer please explain your answer in detail because I'm new to objective-c. Here's a screen shoot of my GUI.

Here is my code so far:
DADViewController.h
#import <UIKit/UIKit.h>
#import "DADView.h"
@interface DADViewController : UIViewController
@property(nonatomic, weak)IBOutlet DADView *dadView;
@end

DADViewController.m
#import "DADViewController.h"
@implementation DADViewController
@synthesize dadView = _dadView;
-(void)setDadView:(DADView *)dadView
{
    _dadView = dadView;
    [self.dadView setNeedsDisplay];
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    UITouch *touch = [[event allTouches] anyObject];
    CGPoint location = [touch locationInView:touch.view];
    location.x -= 40;
    location.y -= 40;
    self.dadView.thePoint = location;
    [self.dadView setNeedsDisplay];

}
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
    [self touchesBegan:touches withEvent:event];
}

DADView.h
@interface DADView : UIView
@property(nonatomic) CGPoint thePoint;
@end

DADView.m
#import "DADView.h"
@implementation DADView
@synthesize thePoint = _thePoint;

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
    }
    return self;
}
- (void)drawRect:(CGRect)rect
{
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGContextSetLineWidth(ctx, 2.0);
    CGContextSetStrokeColorWithColor(ctx, [UIColor redColor].CGColor);
    CGRect rectangle = CGRectMake(120, 70, 70, 70);
    CGContextAddRect(ctx, rectangle);
    CGContextStrokePath(ctx);

    CGContextSetLineWidth(ctx, 2.0);
    CGContextSetStrokeColorWithColor(ctx, [UIColor greenColor].CGColor);
    CGRect rectangle2 = CGRectMake(120, 290, 70, 70);
    CGContextAddRect(ctx, rectangle2);
    CGContextStrokePath(ctx);

    UIImage* pngWord = [UIImage imageNamed:@"wordbutton_01.png"];
    [pngWord drawAtPoint:self.thePoint];
}
@end

A: To set the view at the beginning:
CGRect viewFrame = view.frame;
viewFrame.origin = startingRect.origin;
view.frame = viewFrame;

view is your image, and startingRect is the rect where you want your image to start, and this code in the awakFromNib or in or when you set the image
To check if the image is inside of a frame when being dragged:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
    CGFloat middleX = CGRectGetMidX(imageView.frame);
    CGFloat middleY = CGRectGetMidY(imageView.frame);
    if(middleX > rectangle2.origin.x && middleX < CGRectGetMaxX(rectangle2) && middleY > rectangle.origin.y && middleY < CGRectGetMaxY(ractangle2)) {
   // if the imageView is inside of the box
   }
else imageView.frame = defaultFrame;

imageView is the image that is being moved and rectangle 2 is the frame that you want the imageView in, while default frame is where the image's frame should be set to if it doesn't end in the box


text:
Q: Converting a string containing both char's and int's into an integer in C Say I have the string (represented as a char pointer) given from a strSHA2 hash of a file:
"f731d405b522b69d79f2495f0963e48d534027cc1852dd99fa84ef1f5f3387ee"

How could I effectively turn it into an integer? Is there any way to cast it? atoi() terminates as soon as it reaches a char.
Would iterating through and converting char's using arithmetic such as letter - 'a' be the best way?
I intend to use it as an index for a hash table, thus need an integer.
Length of the integer would be the standard 32bit for C

A: You probaly want to transform the hexadecimal number made of the first 8 chars of the SHA2 string into an unsigned integer (32 bit) which sounds like a pretty good hash function to me as it is pretty unlikely that two different sha2 hashes start with the same 8 bytes:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

unsigned int GetHashValueFromSHA2String(const char *sha2string)
{
  char first[9];
  memcpy(first, sha2string, 8);  // copy first 8 chars of sha2 string
  first[8] = 0;                  // null terminate
  return strtoul(first, NULL, 16);
}

int main()
{
  unsigned int hashvalue = GetHashValueFromSHA2String("f731d405b522b69d79f2495f0963e48d534027cc1852dd99fa84ef1f5f3387ee");
  printf("Hashvalue = %08x", hashvalue);
}

Or even simpler:
unsigned int GetHashValueFromSHA2String(const char *sha2string)
{
  unsigned int value;
  sscanf(sha2string, "%8x", &value);
  return value;
}

A: In order to convert a hexadecimal string to a 32-bit unsigned integer data type, you can use the function strtoul.
However, a 32-bit unsigned integer data type is only able to represent numbers up to 232-1, which is insufficient in your example of a 256-bit number.
Therefore, it would only be possible to convert this number into eight 32-bit integers.
However, as pointed out in one of the other answers, it does not make sense to use a 256-bit index into a hash table. Since you can probably assume that all of the bits of a SHA-2 hash are sufficiently uniformly distributed for your use-case, it should be sufficient to simply take the first 10 or 16 bits of the SHA-2 hash and use them as an index into your hash table. That way, your hash table would have a length between 8 KiB or 512 KiB, assuming 8 bytes per hash table entry.

A:
Say I have the string (represented as a char pointer) given from a strSHA2 hash of a file:

That is then a hexadecimal representation of a 256 bit integer.
Your computer doesn't have a 256 bit integer type, so you can't cast that, possibly.
Instead, you'll want to use a different function from your hashing library that doesn't give you a printable string, but just 32 bytes of raw hash data. You can then use, say, the upper 2 bytes as hash table indices.
Using a 32 byte (256 bit) hash table index makes no sense – no computer in this world has enough memory for a table with 2²⁵⁶ entries.
Honestly, however, if you want a hash table, use an existing hash table instead of building your own.


text:
Q: Printing out results in case of object relational table (Oracle) This is how I print out results in the standard relational table using JAVA. However I am using a object-relational table.
 public static void results_view ()
    throws SQLException
    { String sql =
      "SELECT * from House";
    try { Connection conn = DriverManager.getConnection
("jdbc:default:connection:");
      PreparedStatement pstmt = conn.prepareStatement(sql);
      ResultSet rset = pstmt.executeQuery();
      printResults(rset);
      rset.close();
      pstmt.close();
      }
    catch (SQLException e) {System.err.println(e.getMessage());
    }
  }

 static void printResults (ResultSet rset)
   throws SQLException { String buffer = "";
    try { ResultSetMetaData meta = rset.getMetaData();
      int cols = meta.getColumnCount(), rows = 0;
      for (int i = 1; i <= cols; i++)
       {
        int size = meta.getPrecision(i);
        String label = meta.getColumnLabel(i);
        if (label.length() > size) size = label.length();
        while (label.length() < size) label += " ";
        buffer = buffer + label + "  "; }
        buffer = buffer + "\n";
        while (rset.next()) {
      rows++;
      for (int i = 1; i <= cols; i++) {
          int size = meta.getPrecision(i);
          String label = meta.getColumnLabel(i);
          String value = rset.getString(i);
          if (label.length() > size) size = label.length();
          while (value.length() < size) value += " ";
          buffer = buffer + value + "  ";  }
          buffer = buffer + "\n";   }
          if (rows == 0) buffer = "No data found!\n";
         System.out.println(buffer); }
    catch (SQLException e) {System.err.println(e.getMessage());}  }

How do I print out the results in case of object relational table?
My case bellow:
CREATE OR REPLACE TYPE Boat AS OBJECT(
Name varchar2(30),
Ident number,
);

CREATE OR REPLACE TYPE Type_boats AS TABLE OF Boat;

CREATE TABLE HOUSE(
Name varchar2(40),
MB Type_boats)
NESTED TABLE MB store as P_Boat;

INSERT INTO House VALUES ('Name',Type_boats(Boat('Boat1', 1)));

I also have the package written with the procedure to call, which looks like this..
CRATE OR REPLACE package House_boats
PROCEDURE add(everything works here)
PROCEDURE results_view;
END House_boats;

CREATE OR REPLACE Package.body House_boats AS
PROCEDURE add(everything works here) AS LANGUAGE JAVA
Name House_boats.add(...)

PROCEDURE results_view AS LANGUAGE JAVA
Name House_boats.resuts_view();
END House_boats;

So yeah, basicly I just don't know how to print them out in case of objects.
I call it out using:
CALL House_boats.results_view();  <<< nothing works here.

A: System.out.println() writes to standard out.  I don't what you were imagining would happen, but in an Oracle database standard out and error write to the trace files.
If you want to re-direct your Java output to a screen you need to use DBMS_JAVA.SET_OUTPUT.  Find out more.


text:
Q: Как узнать размер ТОЛЬКО файлов в папке linux? Я перепробовал множество команд, но не получается вывести только файлы (не папки). Нужно отсортировать файлы <100 байт, <1 Кб, <10 Кб и тд. Использовал команду -du -sh *, но она показывает файлы И папки.
Благодарю за ответы! (:

A: Воспользуйтесь утилитой find. Она довольно универсальна. У неё есть оператор -size как раз для выяснения размера файлов. Например,

*

*find каталог -type f -size -100c рекурсивно выводит имена всех регулярных файлов размером строго меньше 100 байт,

*find каталог -type f -size -1k также выводит файлы, чей размер меньше 1 КиБ.

Минус перед цифрами означает «меньше».

У этой программы есть ещё довольно любопытный оператор -printf, позволяющий выводить разнообразную информацию о файле. Как пример,

*

*find каталог -type f -printf '%p %s\n' | column -t выведет на терминал размеры файлов в байтах.

Подробнее со списком параметров можно ознакомиться в руководстве find(1).


text:
Q: Cloud Endpoints calculated an Entity property at query time How can I have a property in an Entity be calculated at query time?
For example if I had a Post Entity and I did getPost(Long postId), I would like the myPost.likes property to be calculated at that moment by getting a count of how many Like Entities there are with the specific Post key.
OR
If this is not possible, I was considering storing a Int likes property for each Post Entity that I simply increment by one every time a new Like is inserted.

A: Both would work. For the latter i would use sharding counters if you expect many lps (likes per second). I would  use the first approach though since then a like can have meta like, when it was created, by whom, etc.
There's no real at query time calculation for that. You would have to write the query to sum up the likes yourself. In Objectify you could use the @OnLoad annotation to query it for each post, after a query. I strongly recommend that you don't do that though since that would be a query for each returned Post of a query. You really should do that manually to avoid redundant queries for likes when you don't even need them.


text:
Q: createMaterialTopTabNavigator not rendring properly in one screen in react native I am implementing createMaterialTopTabNavigator in one screen but nothing is rendering in my app. i am returning MainNavigator which is app container of this screen. am i making mistake to use to app containers or not ?  if it is mistake then please guide me how to work with proper flow in react navigation like    in app using drawer navigator ,bottom navigator and top navigator at same time.
App Flow :
MainScreenNavigation > MainJobScreen >
MainScreenNavigation code:
import React from "react";
import {createStackNavigator, createAppContainer} from "react-navigation";
import {Signin} from "../screens/Signin";
import {Splash} from '../screens/Splash';
import {HomeScreen} from '../screens/Home/HomeScreen'
import {Profile} from '../screens/Profile/Profile'
import {Notifications} from '../screens/Notifications/Notifications'
import {MainJobScreen} from '../screens/JobFeed/MainJobScreen'

export const MainScreenNavigation = createAppContainer(createStackNavigator({
    Home: {
        screen: Splash
    },
    Signin: {
        screen: Signin
    },
    HomeScreen: {
        screen: HomeScreen
    },
    Profile: {
        screen: Profile
    },
    Notifications: {
        screen: Notifications
    },
    JobFeed: {
        screen: MainJobScreen
    }

}));
;

MainJobScreen code: acutaly where i am using createMaterialTopNavigator
import React from 'react'
import {createMaterialTopTabNavigator,createAppContainer,createStackNavigator } from 'react-navigation'

import { AllTab } from './AllTab'
import { ActiveTab} from './ActiveTab'
import { CompletedTab } from './CompletedTab'
import { JobScreen} from './JobScreen'

const TabNavigator = createMaterialTopTabNavigator({
    TabOne: AllTab,
    TabTwo: ActiveTab,
    TabThree: CompletedTab,
},
{
    initialRouteName: 'TabOne',
    tabBarOptions: {
        style: {
            backgroundColor: 'red'
        }
    },
    tabBarPosition: 'top',
    swipeEnabled: true,
    animationEnabled: true,

})

TabNavigator.navigationOptions={
    headerTitle: 'JobFeed'
}
const MainNavigator= createAppContainer(createStackNavigator({
    Tabs: TabNavigator,
    MainScreen: JobScreen,
},{
    initialRouteName: 'MainScreen'
}))

export class MainJobScreen extends React.Component{

    static navigationOptions = {
        headerTitle: 'JobFeed'
    }
    render(){
        return(
            <MainNavigator />
        )
    }
}

Help will be highly appreciated
Thanks  in advance

A: Mixing the Nav Stacks is your solution here brother.

You have to put the tab navigator inside of your main navigator!

and when the  navigation stack hits the TabScreen it will show up the first default screen of the tab navigator you have created.
//....your imports
export const MainScreenNavigation = createAppContainer(createStackNavigator({
    Home: {
        screen: Splash
    },
    Signin: {
        screen: Signin
    },
    HomeScreen: {
        screen: HomeScreen
    },
    Profile: {
        screen: Profile
    },
    Notifications: {
        screen: Notifications
    },
    JobFeed: {
        screen: MainJobScreen
    },
    JobFeed: {
        screen: MainJobScreen
    },
    TabScreen: {
        screen: TabNavigator  //------> add this in your main navigator
    }

}));
;

now the stack should go like this!
a file exporting your main navigatior which should be used in your App.js
and in that navigation stack your Tabnavigation stack should be added like you add any other screen or so as shown in code
NOTE ! you should be separately exporting the TabScreen Navigator from a file! and if you are using the navigator in your code file MainScreen then that main Screen should be in the Tab navigation stack's first screens!


text:
Q: Registration of Azure Resource Provider hangs indefinitely I'm just starting to look into Azure and AKS. In order to do this, I have to enable a bunch of resource providers. I did this using the Azure CLI, like so:
az provider register -n Microsoft.Network
az provider register -n Microsoft.Storage
az provider register -n Microsoft.Compute
az provider register -n Microsoft.ContainerService

But, for some reason, one of those providers, specifically Microsoft.Compute, is indefinitely in a Registering state. I can check it via CLI, like so:
$ az provider show -n Microsoft.Compute |jq .registrationState
"Registering"

Or via the portal, which yields the same result:

I left it in this state overnight and it's still in the same state. I tried unregistering, which left it hanging in the Unregistering state. Then tried to register again and it has been like that for about 10 minutes. The other 3 providers registered almost instantaneously.

A: This appears to be an issue that pops up on occasion. As far as I can tell there's no self-service way to fix this when it happens, and your only recourse is to file a support request via the Azure Portal here: https://portal.azure.com/#blade/Microsoft_Azure_Support/HelpAndSupportBlade/overview


text:
Q: How to inherit a certain position (CSS) After ~2 hours of researching I couldn't find a solution for my problem, I am trying to inherit the center of the background since the "blurred-box" gets bigger depending on the computer resolution.
It looks like this(laptop resolution):

And I would like to make it show the center of the background image instead of the corner.

* {
  margin: 0;
  padding: 0;
}

html {
  width: 100vw;
  height: 100vh;
}

body {
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  background-position: top;
  background-image: url(https://images.unsplash.com/photo-1477346611705-65d1883cee1e?dpr=0.800000011920929&auto=format&fit=crop&w=1199&h=800&q=80&cs=tinysrgb&crop=);
  width: 100%;
  height: 100%;
  font-family: Arial, Helvetica;
  letter-spacing: 0.02em;
  font-weight: 400;
  -webkit-font-smoothing: antialiased;
}

.blurred-box {
  position: fixed;
  width: 550px;
  height: 670px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background: inherit;
  border-radius: 2px;
  overflow: hidden;
}

.blurred-box:after {
  content: '';
  width: 1000px;
  height: 1000px;
  background: inherit;
  position: absolute;
  bottom: 0;
  box-shadow: inset 0 0 0 200px rgba(255, 255, 255, 0.05);
  filter: blur(10px);
}

.user-login-box {
  position: relative;
  margin-top: 50px;
  text-align: center;
  z-index: 1;
}

.user-login-box>* {
  display: inline-block;
}

text here

If someone posts a solution I would like to have a link for documentation with those informations(if that is okay), thanks.

A: You are almost good, remove the use of translate() which is creating the issue and center your element using margin:auto instead:

body {
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-size: cover;
  background-position: top;
  background-image: url(https://images.unsplash.com/photo-1477346611705-65d1883cee1e?dpr=0.800000011920929&auto=format&fit=crop&w=1199&h=800&q=80&cs=tinysrgb&crop=);
  margin:0;
  height: 100vh;
  font-family: Arial, Helvetica;
  letter-spacing: 0.02em;
  font-weight: 400;
  -webkit-font-smoothing: antialiased;
}

.blurred-box {
  position: fixed;
  width: 550px;
  height: 670px;
  top: 0;
  left: 0;
  bottom:0;
  right:0;
  margin:auto;
  background: inherit;
  border-radius: 2px;
  overflow: hidden;
}

.blurred-box:after {
  content: '';
  width: 1000px;
  height: 1000px;
  background: inherit;
  position: absolute;
  bottom: 0;
  box-shadow: inset 0 0 0 200px rgba(255, 255, 255, 0.05);
  filter: blur(10px);
}

.user-login-box {
  position: relative;
  margin-top: 50px;
  text-align: center;
  z-index: 1;
}

.user-login-box>* {
  display: inline-block;
}

text here


text:
Q: Cannot run ANY shell scripts even when root when trying to run a teamspeak server and a minecraft server on a newly rented VPS I ran into some big troubles. Whenever I try to run a shell script even when root it does not work.
One script: spigot.sh
#!/bin/sh
BINDIR=$(dirname "$(readlink -fn "$0")")
cd "$BINDIR"
java -Xms5G -Xmx7G -XX:MaxPermSize=128M -jar spigot.jar

Error after trying to use this as root
root@vps23946:/home/user/minecraft# ./spigot.sh
-bash: ./spigot.sh: Permission denied

Error after trying to use this as user
user@vps23946:~/minecraft$ ./spigot.sh
-bash: ./spigot.sh: Permission denied

Results from ls -l
root@vps23946:/home/user/minecraft# ls -l
total 22616
drwxr-xr-x 16 user root     4096 Jun  6 22:39 backups
-rw-r--r--  1 user root        2 Jun  7 13:54 banned-ips.json
-rw-r--r--  1 user root      110 May 25 17:32 banned-ips.txt.converted
-rw-r--r--  1 user root      229 Jun  7 13:54 banned-players.json
-rw-r--r--  1 user root      267 May 25 17:32 banned-players.txt.converted
-rw-r--r--  1 user root     1474 Jun  7 13:54 bukkit.yml
-rw-r--r--  1 user root      610 Jun  7 13:54 commands.yml
drwxr-xr-x  2 user root     4096 Jun  6 19:56 crash-reports
drwxr-xr-x  2 user root     4096 Jun  7 13:54 C:\Users\Rory Finnegan\Desktop\Prep     server\backups
drwxr-xr-x  6 user root     4096 Jun  7 14:25 flat
-rw-r--r--  1 user root     2576 Apr  3 16:04 help.yml
drwxr-xr-x  2 user root     4096 Jun  7 13:54 logs
-rw-r--r--  1 user root      415 Jun  7 13:54 ops.json
-rw-r--r--  1 user root      191 May 28 19:02 ops.txt.converted
-rw-r--r--  1 user root        0 Apr  3 16:05 permissions.yml
drwxr-xr-x 27 user root     4096 Jun  6 22:39 plugins
-rw-r--r--  1 user root      768 Jun  7 13:54 server.properties
-rw-r--r--  1 user root 23053543 May 30 15:48 spigot.jar
-rw-r--r--  1 user root      122 Jun  7 13:36 spigot.sh
-rw-r--r--  1 user root     2749 Jun  7 13:54 spigot.yml
-rw-r--r--  1 user root     2404 Jun  7 14:07 usercache.json
-rw-r--r--  1 user root     1588 Apr  3 16:04 wepif.yml
-rw-r--r--  1 user root      783 Jun  6 16:21 whitelist.json
-rw-r--r--  1 user root      250 May  3 19:31 white-list.txt.converted
drwxr-xr-x  7 user root     4096 Jun  7 14:25 world
drwxr-xr-x  6 user root     4096 Jun  7 14:25 world_nether
drwxr-xr-x  6 user root     4096 Jun  7 14:25 world_the_end

Second Script: ts3server_minimal_runscript.sh
    #!/bin/sh
export LD_LIBRARY_PATH=".:$LD_LIBRARY_PATH"

D1=$(readlink -f "$0")
D2=$(dirname "${D1}")
cd "${D2}"

if [ -e ts3server_linux_x86 ]; then
    if [ -z "`uname | grep Linux`" -o ! -z "`uname -m | grep 64`" ]; then
            echo "Do you have the right TS3 Server package for your system? You have:        `    uname` `uname -m`, not Linux i386."
    fi
    ./ts3server_linux_x86 $@
elif [ -e ts3server_linux_amd64 ]; then
    if [ -z "`uname | grep Linux`" -o -z "`uname -m | grep 64`" ]; then
            echo "Do you have the right TS3 Server package for your system? You have: `  uname` `uname -m`, not Linux x86_64."
    fi
    ./ts3server_linux_amd64 $@
elif [ -e ts3server_freebsd_x86 ]; then
    if [ ! -z "`uname | grep Linux`" -o ! -z "`uname -m | grep 64`" ]; then
@

With these I get the same errors.
I am running Ubuntu Server 14.04

A: Scripts and programs must be executable to be invoked by name. Either use chmod to add the executable permission to the file (chmod a+x ./spigot.sh) or invoke an executable interpreter and pass in the script, e.g. /bin/sh ./spigot.sh

A: Try
 chmod +x spigot.sh

and that will enable the script to be executed


text:
Q: MDX adding two values of a dimension in a new column I am new to MDX and using the Calculations from OLAP Pivot table Extensions, I want to add two Values of one Dimension into a new field. For Example, I have the 'Net Sales' Dimension with different values such as, Store, Street, Distribution and I want to create a total column only for Street+Store. Is there anyway to do it?
Thanks,
FP

A: Assuming Store and Street are members of a hierarchy called Hier, which is part of dimension Dim, then the expression for the sum of Street + Store would be
Sum( { [Dim].[Hier].[Street], [Dim].[Hier].[Store] }, [Measures].[Net Sales] )

Alternatively, you could use
([Dim].[Hier].[Street], [Measures].[Net Sales]) +
([Dim].[Hier].[Store], [Measures].[Net Sales])


text:
Q: Why are App Engine instances shutting down with a "start" message? I am getting a lot of these errors in my App Engine Standard Environment Python 3 application. The application seems to initialize and to work fine: I can't see any sort of failure during initialization.
How can I figure out the cause? Could it be ordinary instance scale-down  despite what this log says?
 Start program failed: termination triggered by nginx exit

 [INFO] Shutting down: Master
 Worker exiting (pid: 20)

 [INFO] Worker exiting (pid: 23)
 Handling signal: term

 Quitting on terminated signal

I see a number of these shut-down errors in a row, suggesting that multiple instances are shutting down. So, the last step from 1 to 0 instances is not the relevant one.
The app.yaml is as follows:
runtime: python39
service: iris3

env_variables:
  TOKENPS: 54

A: I tested a Hello World example and found that this is the ordinary log during  instance scaledown.
The log should be considered a bug. It clearly says that start -- i.e., initialization -- is failing, where in fact nothing  is failing and this involves shutdown rather than startup.

A: Check if you return a status of 204 it can shut down your instance,
It's a kind of bug in gunicorn, you can see here

A: This is an expected behavior, the instances began to shut down in response to some events, like exceeding the number of idle instances and they are no longer processing requests.
That log messages correspond to SIGTERM signals sended by the GAE environment to the app container. The full log messages represents the steps taken to terminate all processes and the instance


text:
Q: Error with tensorflow map_fn. Unable to specify output signature I am trying to use tensorflow's tf.map_fn to map a ragged tensor but I am getting an error that I can't fix.
Here is some minimal code that demonstrates the error:
import tensorflow as tf

X = tf.ragged.constant([[0,1,2], [0,1]])
def outer_product(x):
  return x[...,None]*x[None,...]
tf.map_fn(outer_product, X)

My desired output is:
tf.ragged.constant([
 [[0, 0, 0],
  [0, 1, 2],
  [0, 2, 4]],
 [[0, 0],
  [0, 1]]
])

The error I am getting is:

"InvalidArgumentError: All flat_values must have compatible shapes.
Shape at index 0: [3].  Shape at index 1: [2].  If you are using
tf.map_fn, then you may need to specify an explicit
fn_output_signature with appropriate ragged_rank, and/or convert
output tensors to RaggedTensors. [Op:RaggedTensorFromVariant]"

I realize I need to specify fn_output_signature but despite experimentation, I cannot figure out what it should be.
EDIT: I cleaned up AloneTogether's excellent answer a little bit and created a function that maps ragged tensors. His answer uses the tf.ragged.stack function to convert the tensors to ragged tensors which tf.map_fn needs for some reason
def ragged_map_fn(func, t):
  def new_func(t):
    return tf.ragged.stack(func(t),0)
  signature = tf.type_spec_from_value(new_func(t[0]))
  ans = tf.map_fn(new_func, t, fn_output_signature=signature)
  ans = tf.squeeze(ans, 1)
  return ans

A: Ragged tensors are sometimes really tricky. Here is one option you can try out:
import tensorflow as tf

X = tf.ragged.constant([
                        [0,1,2],
                        [0,1]
                       ])
def outer_product(x):
  t = x[...,None] * x[None,...]
  return tf.ragged.stack(t)

y = tf.map_fn(outer_product, X, fn_output_signature=tf.RaggedTensorSpec(shape=[1, None, None],
                                                                    dtype=tf.type_spec_from_value(X).dtype,
                                                                    ragged_rank=2,
                                                                    row_splits_dtype=tf.type_spec_from_value(X).row_splits_dtype))
tf.print(y)
#y = tf.concat([y[0, :], y[1, :]], axis=0) # Remove additional dimension from Ragged Tensor
y = y.merge_dims(0, 1)
tf.print(y)

[
 [
  [
   [0, 0, 0],
   [0, 1, 2],
   [0, 2, 4]
  ]
 ],
 [
  [
   [0, 0],
   [0, 1]
  ]
 ]
]

And after removing the additional dimension with y.merge_dims(0, 1) or tf.concat:
[
 [
  [0, 0, 0],
  [0, 1, 2],
  [0, 2, 4]
 ],
 [
  [0, 0],
  [0, 1]
 ]
]


text:
Q: setup and write demo test the robolectric in Android Studio Do anyone know how to integrate robolectric into android studio?
How to write sample test?
How to launch it?
I am working with android studio not to long, and I am too bad with gradle.
Searching the net didn't give me a result - I even could not launch official demo - https://github.com/robolectric/robolectric-samples . My android studio do not saw the test class.
Please give me simpliest step by step gide, thanks

A: Since robolectric runs in a JVM (i.e. not on a device or emulator), it is just a library and adding the test runner is all that's needed.
Make sure that the android SDK is later in the classpath than robolectric or junit - otherwise you'll get the stubbed methods from the android SDK.
@RunWith(RobolectricTestRunner.class)
public class MyActivityTest {

@Test
public void shouldHaveApplicationName() throws Exception {
    String appName = new MyActivity().getResources().getString(R.string.app_name);
    assertThat(appName, equalTo("MyActivity"));
}

}
See http://robolectric.org/quick-start/


text:
Q: issue with getting data from url Here is the code I wrote
NSString *str = [NSString stringWithFormat:@"https://graph.facebook.com/me?access_token=CAADbwxRRgq8BANULcGGn3d4NPZB4LlP3tCL9YjYH3Nd0fD2XvgjG0qTECEmOsFhNhcu4NCdgYzQK3lYaATiedLRP4ZAIRgf8FBtDBYd22z5BrMabHlex12nZAbm8UfJTrPVRw5rjN8abi9"];

NSURL* url = [NSURL URLWithString:[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSError* error = nil;
NSData* data = [NSData dataWithContentsOfURL:url options:NSDataReadingUncached error:&error];
if (error) {
     NSLog(@"%@", [error localizedDescription]);
} else {
     NSLog(@"Data has loaded successfully.");
}

I got the error

Error Domain=NSCocoaErrorDomain Code=256 "The operation couldn't be
  completed. (Cocoa error 256.)" UserInfo=0x218446a0

{NSURL=https://graph.facebook.com/me?access_token=CAADbwxRRgq8BANULcGGn3d4NPZB4LlP3tCL9YjYH3Nd0fD2XvgjG0qTECEmOsFhNhcu4NCdgYzQK3lYaATiedLRP4ZAIRgf8FBtDBYd22z5BrMabHlex12nZAbm8UfJTrPVRw5rjN8abi9ZBoVD1DYVZCo8hcZC0n2CnMyk3ryeCQntRpdZCc2e}

A: Try:
NSString *str = [NSString stringWithFormat:@"https://graph.facebook.com/me?access_token=CAADbwxRRgq8BANULcGGn3d4NPZB4LlP3tCL9YjYH3Nd0fD2XvgjG0qTECEmOsFhNhcu4NCdgYzQK3lYaATiedLRP4ZAIRgf8FBtDBYd22z5BrMabHlex12nZAbm8UfJTrPVRw5rjN8abi9"];

NSURL* url = [NSURL URLWithString:[str stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:30] returningResponse:nil error:&error];

if (error) {
    NSLog(@"%@", [error localizedDescription]);
} else {
    NSLog(@"Data has loaded successfully.");
}

Albeit, I have no idea why your other request fails. Error code 256 isn't very descriptive.

A: Here is a nice explanation of why NSCocoaErrorDomain occurs.
NSData dataWithContentsOfURL: not returning data for URL that shows in browser
Read it and see if any of the suggestions in that answer might be useful to you.


text:
Q: Change Density Using AVD Manager I have created 3 Device Descriptions that mimic the latest models of Samsung mobile devices (S2, S3 & S4). Although I enter the diagonal screen length and pixels (w x h), I am unable to see a change in density across the 3 AVDs when I start them using the AVD Manager (screen caps below). Did I miss something or does the tool support density changes? Also, this is poorly documented.

A: After a quit and re-enter, things worked fine but the density value never updated, always reads 320 - probably based on my laptops screen. Also DON'T use option 'Scale display to real size". Let the emulator do the rendering and move app to device for native testing.


text:
Q: Finding the area of this ellipse written in complex polar form. I was reading the Chapter $4$ of Hubbard's Teichmüller Theory where he begins to introduce quasiconformal mappings. Here he writes a linear tranformation $T: \mathbb{C} \rightarrow \mathbb{C}$ as $T(u)=au+b\bar{u}$ and then notes that the determinant is
$$\det{T}= |a|^{2}-|b|^{2}$$
He justifies this by saying that if we let $u=re^{i\theta}$, $a:=|a|e^{i\alpha}$, $b:=|b|e^{i\beta}$, then expanding $|T(u)|=|au+b\bar{u}|=1$, we get an ellipse with minor axis of semi-length $\frac{1}{|a|+|b|}$ and major axis $\frac{1}{||a|-|b||}$
and then noting that the ratio of the unit circle to the area of this ellipse is $|a|^{2}-|b|^{2}$.
Anyways the actual equation for the ellipse is as follows:
$$\bigg|(|a|+|b|)\cos\big(\theta+\frac{\alpha-\beta}{2}\big)+i(|a|-|b|)\sin\big(\theta+\frac{\alpha-\beta}{2}\big) \bigg|=\frac{1}{r}$$

I was wondering why the $r$ doesn't come up in the area or the semi-length of the major and minor axis? (Sorry, if this is a dumb question)

A: The $r$ comes in as the semimajor/semiminor axes' lengths when you expand $|T(re^{i\theta})|=1$, i.e., the minimum $r_\min$ is the semiminor axis length and $r_\max$ is the semimajor axis length.

A: The author is determining all $u$ that satisfy the equation $|T(u)|=1$.  When converted to polar coordinates, the solution is the set of all $(r,\theta)$ that satisfy:
$$
\bigg|(|a|+|b|)\cos\big(\theta+\frac{\alpha-\beta}{2}\big)+i(|a|-|b|)\sin\big(\theta+\frac{\alpha-\beta}{2}\big) \bigg|=\frac{1}{r}.\tag1
$$
So the equation (1) is a condition that $r$ and $\theta$ have to satisfy.
To see that (1) represents an ellipse, here is the argument in more detail: Squaring both sides of (1) and multiplying by $r^2$, (1) is equivalent to
$$
(|a|+|b|)^2\left(r\cos\big(\theta+\frac{\alpha-\beta}{2}\big)\right)^2+(|a|-|b|)^2\left(r\sin\big(\theta+\frac{\alpha-\beta}{2}\big)\right)^2=1.\tag2
$$
We can convert (2) from polar coordinates back to orthogonal axes $(u,v)$ using the transformation $u:=r\cos\big(\theta+\frac{\alpha-\beta}{2}\big)$ and $v:=r\sin\big(\theta+\frac{\alpha-\beta}{2}\big)$, yielding
$$
(|a|+|b|)^2u^2+(\big||a|-|b|\big|)^2v^2=1\tag3
$$
(note the $(u,v)$ plane is rotated from the original $(x,y)$ plane). But equation (3) is the equation of an ellipse, whose semi-major and semi-minor axis lengths you can read off.
In summary, you're misinterpreting the generic polar-coordinates variable $r$ as a property of the ellipse. Rather, $r$ is a variable in a particular coordinate system. The variable $r$ doesn't come up in the major and minor axes of the ellipse any more than $x$ or $y$ come up in the radius of the circle defined by $x^2+y^2=c^2$.


text:
Q: Is it a good practise to store special characters in database as html escape equivalent character eg. & as & I am not using standard parser to read input xml.
Input xml is having &,<,> special characters and I want to store them after converting them to html escape charcters as & , > in database.
This is required because I want to display the same ie. in format & in my output xml for other client.

A: No. What if you have a later requirement for JSON output, or something else that isn't HTML or XML? Now you need to undo the HTML escaping first and then perform whatever escaping is appropriate for the new medium.
Databases should store data. Leave presentation concerns to applications, services or reporting tools which know what format is required for each use case (and may even have to make decisions on a per-request basis, such as a REST service using content negotiation)

I am not using standard parser to read input xml.

That's also a really bad plan. People who ignore standard tools and write their own frequently make mistakes. If you're writing your own, have you actually read the full spec for XML? Do you properly understand namespaces (A frequent source of errors in my experience)?