Q: Spring MVC not loading static resources from webapp Issue
Unable to get Spring to add a resource handler for static resources.
Background Information
I have a Spring MVC webapp running in a standalone Jetty instance. My webapp structure is
webapp root/
    resources/
        css/
        images/
        js/
    WEB-INF/
        layouts/
            tiles.xml
            page.jsp
        lib/
        views/
            home/
                home.jsp
                tiles.xml
        web.xml

I've extended the WebMvcConfigurerAdaptor to add a resource mapping such that urls like company.com/myservlet/resources/css/main.css will get resolved to the webapp root/resources/css folder.
@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }
}

My little controller is this:
@Controller
public class SpringAppController {

    public SpringAppController() {
    }

    @RequestMapping(value = "/home", method = RequestMethod.GET)
    public ModelAndView handleRequestHome(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        return new ModelAndView("home");
    }
}

My web.xml is simply this:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <!-- Java-based Spring container definition -->
    <context-param>
        <param-name>contextClass</param-name>
        <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value>
    </context-param>

    <!-- Location of Java @Configuration classes that configure the components that makeup this application -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>com.company</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- Processes application requests -->
    <servlet>
        <servlet-name>admin</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value></param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>admin</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- Ensure UTF-8 encoded pages so that certain characters are displayed and submitted correctly -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- Enables support for DELETE and PUT request methods with web browser clients -->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

My JavaConfig for the webapp to instantiate some mvc resolvers is this:
@Configuration
public class MainConfig {

    @Bean
    public ViewResolver viewResolver() {
        UrlBasedViewResolver viewResolver = new UrlBasedViewResolver();
        viewResolver.setViewClass(TilesView.class);
        return viewResolver;
    }

    @Bean
    public TilesConfigurer tilesConfigurer() {
        TilesConfigurer configurer = new TilesConfigurer();
        configurer.setDefinitions(new String[] {
            "/WEB-INF/layouts/tiles.xml",
            "/WEB-INF/views/**/tiles.xml"
        });
        configurer.setCheckRefresh(true);
        return configurer;
    }

    @Bean
    public org.springframework.context.MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/messages");
        return messageSource;
    }

}

When I hit the url company.com/myservlet/home the tiles stuff works and the home.jsp page is displayed but the css and images are not loaded. The servlet logs this warning:
[DEBUG] [DispatcherServlet] [DispatcherServlet with name 'admin' processing GET request for [/api/v1/tlb/resources/page.css]]
[DEBUG] [RequestMappingHandlerMapping] [Looking up handler method for path /resources/form.css]
[DEBUG] [RequestMappingHandlerMapping] [Did not find handler method for [/resources/form.css]]
[WARN ] [PageNotFound] [No mapping found for HTTP request with URI [/api/v1/tlb/resources/form.css] in DispatcherServlet with name 'admin']

I've tried debugging the servlet and the WebMvcConfig.addResourceHandlers() method is never called and hence why the static resources cannot be found. What am I missing to get this working?
As a note if I add the following to my web.xml the css resource will be loaded but I would like to know why the WebMvcConfig.addResourceHandlers() method is not called so I don't need this servlet mapping.
<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

A: Well, I've fixed the issue but not exactly sure why/how yet. The project had imported a jar that contained a class that extended WebMvcConfigurationSupport like the following:
@Configuration
public class EnableUriMatrixVariableSupport extends WebMvcConfigurationSupport {

    @Override
    @Bean
    public RequestMappingHandlerMapping requestMappingHandlerMapping() {
        RequestMappingHandlerMapping hm = super.requestMappingHandlerMapping();
        hm.setRemoveSemicolonContent(false);
        return hm;
    }
}

Additionally I also has @EnableMvc annotation which imports DelegatingWebMvcConfiguration. I think this ends up creating two instances of a WebMvcConfigurationSupport and this causes havoc in the spring container. Unfortunately I upgraded to spring 4.x in the process of fixing this issue so I'm not sure yet if this helped in some way.


Q: Create new database on the fly in Laravel 4 I want dynamically create new database, database user and password with privileges, create some tables in new database on the fly in Laravel 4 for every new user. This is for a multi tenant website.
Whats the best solution?
thanks.

A: This is not your first database connection it's easy, but you'll have to execute raw statements because database creation is no available as connection methods:
DB::statement(DB::raw('CREATE DATABASE <name>'));

To do that you can use a secondary connection:
<?php
return array(

    'default' => 'mysql',

    'connections' => array(

        'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'host1',
            'database'  => 'database1',
            'username'  => 'user1',
            'password'  => 'pass1'
        ),

        'store' => array(
            'driver'    => 'mysql',
            'host'      => 'host2',
            'database'  => 'database2',
            'username'  => 'user2',
            'password'  => 'pass2'
        ),
    ),
);

Then you can, during application bootstrap, change the database of the secondary connection:
DB::connection('store')->setDatabaseName($store);

or
Config::set('database.connections.store', $store);

And use the secondary connection in your queries:
$user = User::on('store')->find(1);

or
DB::connection('store')->select(...);


Q: How to show in Action bar, only if it can fit with text? I am having the following buttons, with some ic_menu icons: Register, Clear.
I want them, in whatever device(smartphone or tablet), to be shown if they can fit, including their text.
If i use on both them: withText|ifRoom, on smartphone they appear both, without their text on portrait, and landscape with text.
On tablet they appear both with text.
I want them, on smartphone, NOT to appear if they cant fix with their text too.
Are any other combinations ?
Also what is collapseActionView for?


Q: What's the behavior of limits of greatest integer functions when the numbers are negative? I'm trying to prove that $\lim_{x\to 2}$$[[x]]+[[-x]]$ exists, and to do that I have to prove that right-and left-hand limits are the same, so I have done this:
$$\text{Left-Hand}$$
$$\lim_{x\to 2^-}[[x]]+[[-x]]$$
$$\lim_{x\to 2^-}[[x]]+\lim_{x\to 2^-}[[-x]]$$
$$\lim_{x\to 2^-}[[2]]=1 \lim_{x\to 2^-}[[-2]]=-3$$
$$1+-3=-2$$
$$\text{Right-Hand}$$
$$\lim_{x\to 2^+}[[x]]+[[-x]]$$
$$\lim_{x\to 2^+}[[x]]+\lim_{x\to 2^+}[[-x]]$$
$$\lim_{x\to 2^+}[[2]]=2 \lim_{x\to 2^+}[[-2]]=-2$$
$$2+-2=0$$
The right-and left-hand limits are supposed to be the same for $\lim_{x\to 2}$$[[x]]+[[-x]]$ to be true, and the problem I am doing says that this is supposed to be true. What am I doing wrong?

A: Your working doesn't really make sense. Mann's comment is roughly right but you should write down a rigorous version. For example you wanted to prove:
  $\lim_{x \to 2^-} [x] = 1$ and $\lim_{x \to 2^-} [-x] = -2$.
To do so note that:
  ( $[x] = 1$ and $[-x] = -2$ ) for any $x \in (1,2)$
Similarly to get the other two limits:
  ( $[x] = 2$ and $[-x] = -3$ ) for any $x \in (2,3)$
In general you should split cases according to the discontinuities of the expression, and since you want the limit at $x = 2$ the only discontinuity that matters is the one at $x = 2$. All the other discontinuities are made irrelevant by choosing a sufficiently small neighbourhood of $2$.


Q: What is meant by indexing in MongoDB? To be true, After typing the Question title only, i had a look about DB indexing in Wiki.
Now i know something about Indexing in general. But, still i have some questions on MongoDB indexing.
What is indexing in MongoDB? What it will exactly do, If i index a collection?
What i can do with indexing in MongoDB?
Will i able to use it for searching specific data?
Can anyone explain it with the below set of documents in a Collection in some MongoDB?
{ "_id":"das23j..", "x": "1", "y":[ {"RAM":"2 GB"}, {"Processor":"Intel i7"}, {"Graphics Card": "NVIDIA.."}]}

Thanks!!!

A: An index speeds up searching, at the expense of storage space. Think of the index as an additional copy of an attribute's (or column's) data, but in order. If you have an ordered collection you can perform something like a binary search, which is much faster than a sequential search (which you'd need if the data wasn't ordered). Once you find the data you need using the index, you can refer to the corresponding record.
The tradeoff is that you need the additional space to store the "ordered" copy of that column's data, and there's a slight speed tradeoff because new records have to be inserted in the correct order, a requisite for the quick search algorithms to work.
For details on mongodb indexing see http://www.mongodb.org/display/DOCS/Indexes.


Q: Unable to display username from another table I currently am able to view a list of contacts with no issues and would like to be able to view the mentors / tutors for the clients.
The username is stored in another table to the contact information and the mentor ID is stored in the contacts table.
I have followed a tutorial on how to do this but can't get it to work.
I have tried to join the accounts and contacts table together and has stopped the everything from showing. My old code showed everything fine apart from the mentor. (Old code also below)
Error reporting says Warning: Undefined array key "id"
Code;
$stmt = $pdo->prepare('SELECT c.id
     , c.name
     , c.last_name
     , c.mobile_number
     , c.status
     , a.username as mentorname
FROM contacts c
     LEFT JOIN
     accounts a ON c.mentor = a.id
WHERE c.id = ?;');
$stmt->execute([$_GET['c.id']]);
$fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

}

Display code
                <?php if($fullContactInfo == null){
                    echo "
No Record Found!
";
                }else{ foreach($fullContactInfo as $info){ ?>

                    <?php echo $info['name']; ?> <?php echo $info['last_name']; ?>
                    <?php echo $info['mobile_number']; ?>
                    <?php echo $info['status']; ?>
                    <?= $info['mentorname']; ?>

Table examples
Contacts
ID: 1
Name: Joe Blogs
Mobile: 1889454
Status: Current
Mentor: 25

Accounts
ID: 25
Username: jbloggs

Old Code
$stmt = $pdo->prepare('SELECT id,name,last_name,mobile_number,status,dob,mentor,image FROM contacts');
$stmt->execute([$_GET['id']]);
$fullContactInfo = $stmt->fetchAll(PDO::FETCH_ASSOC);

if($fullContactInfo == true){
    $stmt = $pdo->prepare('SELECT username FROM accounts WHERE id = ?');
    $stmt->execute([ $fullContactInfo['mentor'] ]);
    $fullContactInfo1 = $stmt->fetch(PDO::FETCH_ASSOC);

A: You can just replace $_GET['c.id'] with $_GET['id'].


Q: Compute the Smith Normal Form for some characteristic matrix
Let $k$ be a field. I'm trying to compute the Smith Normal Form for the characteristic matrix of $A=(a_{ij}) \in M_{n\times n} (k)$ where $a_{ij}=1$ for all $i$ and $j$.

I haven't figured it out yet but when I use Maplesoft to compute $SmithForm(A)$ for finite integer values of $n$, it returns the $n\times n$ matrix with $1$ in position $1,1$ and zero everywhere else. Does anyone know why it's doing this?  expected it to at least return a matrix in which each diagonal entry is nonzero.
Thanks

A: For the SNF of $XI-A$ I suggest you to switch between the first and the last columns, then subtract the first row from all the others, and so on. You will easily get the SNF: $\operatorname{diag}(1,X,\dots,X,X(X-n))$.


Q: Capacitors in series for higher voltage applications From the second circuit below, the red area is a startup network. The App Note states:

My question is, if I have three capacitors in series because my application reaches 1100V, then the bus voltage is divided by three. Now I don't have a middle point, but two middle points. Is it okay if I connect my startup transistor in the second point, like this?


Q: How can I get my WCF Service constructor called? I'm currently trying to get my head around WCF services for an ASP.NET dev environment, and I believe that I'm doing well save for one thing that has me stumped.
Basically, I've got a WCF service set up (let's take the default, with an added constructor):
public class MyService : IMyService
{
    public MyService() { /* blah */ }
    public DoWork() { /* blah */ }
}

The IMyService interface defines the DoWork() method as an [OperationContract], as it should.
So I've got this service referenced in another project (let's say a [Unit] Test Project), via Add Service Reference on the VS2010 UI. This creates a reference to a MyServiceClient which exposes my WCF service methods, as it should.
However, when I do this in my test project:
ServiceReference.IMyService service;
service = new ServiceReference.MyServiceClient();

... the MyService() constructor does not get called, basically because I'm instantiating a MyServiceClient, not a MyService per se.
How do I go about getting that constructor called? I'm planning to use that for initialization purposes (perhaps grabbing a layer in a tiered implementation, for example?).

A: That constructor will be called on the server when you make your request from the client.
Creating a "reference" to a web service (and then using the client classes) is very different to referencing a regular .DLL.  All of your service code will run on the server-side, but not until the service is invoked...

A: The only way for the server-side constructor to be called for each request is to set the InstanceContextMode to PerCall (in the ServiceBehavior attribute).


Q: report module for sugarcrm 6.2 Which Report module is suitable for making reports in sugarcrm 6.2 . I had installed the zucker Report Module on the local site it works properly but when i used to install them on my server it does not installed
Anyone please help
Thanks

A: KReporter certainly the best Reporting tool in the Marketing for SugarCRM, regardless of edition - be it PRO, ENT, CORP or CE.
The new free Google Charts are really cool

A: I suggest KINAMU Reporter, http://www.sugarforge.org/projects/kinamureporter


Q: Can I create a device context that is just a portion of another device context? I have subclassed a graphics control that takes a device context handle, HDC, as an input and uses that for drawing. My new control is just the original control centered on top of a larger image. I would like to be able to call the original control's Draw() method for code re-use, but I'm unsure how to proceed.
Here's the idea:
void CCheckBox::DrawCtrl( HDC hdc, HDC hdcTmp, LPSIZE pCtlSize, BYTE alpha ) {
    // original method draws a checkbox
}

void CBorderedCheckBox::DrawCtrl( HDC hdc, HDC hdcTmp, LPSIZE pCtlSize, BYTE alpha ) {
    // Draw my image here
    // Create new hdc2 and hdcTemp2 which are just some portion of hdc and hdcTemp
    //   For example, hdc2 may just be a rectangle inside of hdc that is 20 pixels
    //   indented on all sides.
    // Call CCheckBox::DrawCtrl() with hdc2 and hdcTemp2
}

A: I think you may be confused of what a device context is. A device context is a place in memory that you can draw to, be it the screen buffer or a bitmap or something else. Since I imagine you only want to draw on the screen, you only need one DC. To accomplish what you want, I would recommend passing a rectangle to the function that tells it where to draw. Optionally, and with poorer performance, you could create a new Bitmap for the smaller area, and give the function the Bitmap's DC to draw on. Now that I think about it, that might have been what you meant in the first place :P Good luck!

A: While not foolproof, you can fake a DC as a subsection of a DC by using a combination of SetViewportOrgEx and SelectObject with a region clipped to the sub area in question.
The problem with this approach is if drawing code already uses these APIs it needs to rewritten to be aware that it needs to combine its masking and offsetting with the existing offsets and clipping regions.


Q: VBA code to read word document footer I have a folder of completed word document forms and I have an excel file that reads all the answers on the forms into different worksheets in spreadsheet. The worksheet that the data is exported to depends on the filename of the word document.
This currently works fine.
However, I now need it to be able to take into account the version number of the form which is stored in the footer of the word document but I don't know how to reference it.
I'm quite a noob when it comes to VBA so havent tried much.
The VBA that I have tried can be found below but unsurprisingly doesnt work.
Sub ReadWordDoc(filenme As String)

Dim Val As String
Dim WrdDoc As Document
Dim FormFieldCounter As Integer

Dim version As String

Set wordapp = CreateObject("word.Application")
wordapp.Documents.Open filenme
wordapp.ScreenUpdating = False

Set WrdDoc = wordapp.Documents(filenme)
wordapp.Visible = True

version = WrdDoc.Sections(1).Footers(wdHeaderFooterFirstPage).Range.Text

FormFieldCounter = 1

If InStr(version, "5.00") Then

    RowCounter = RowCounter + 1

    Sheets("Version 5").Cells(RowCounter, FormFieldCounter) = filenme

    Do While FormFieldCounter <= 125
    WrdDoc.FormFields(FormFieldCounter).Select
    Val = WrdDoc.FormFields(FormFieldCounter).result
    Sheets("Version 5").Cells(RowCounter, FormFieldCounter + 1) = Val

    FormFieldCounter = FormFieldCounter + 1

    Loop

    wordapp.Documents(filenme).Close SaveChanges:=wdDoNotSaveChanges
    wordapp.Quit

Else

    'Do something else

End If

End Sub

A: After having a bit of a play and a Google, I found this page which helped me fix my issue
https://msdn.microsoft.com/en-us/library/office/aa221970(v=office.11).aspx
I changed my code as below:
version = WrdDoc.Sections(1).Footers(wdHeaderFooterPrimary).Range.Text

Although I'm not sure why the previous version didnt work as there is a footer on the first page.


Q: Stopping thread Immediately I want to stop a running thread immediately. Here is my code:
Class A :
public class A() {
    public void methodA() {
        For (int n=0;n<100;n++) {
        //Do something recursive
        }
        //Another for-loop here

        //A resursive method here

        //Another for-loop here

        finishingMethod();
    }
}

Class B:
public class B() {
    public void runEverything() {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                    A a = new A();
                    a.methodA();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        };
       Thread thread = new Thread(runnable);
       thread.start();
    }

My problem is that i need to be able to stop the thread in Class B even before the thread is finished. I've tried interrupt() method, but that doesn't stop my thread. I've also heard about using shared variable as a signal to stop my thread, but I think with long recursive and for-loop in my process, shared-variable will not be effective.
Any idea ?
Thanks in advance.

A: I think you should persevere with using Thread.interrupt().  But what you need to do to make it work is to change the methodA code to do something like this:
public void methodA() throws InterruptedException {
    for (int n=0; n < 100; n++) {
        if (Thread.interrupted) {
             throw new InterruptedException();
        }
        //Do something recursive
    }
    // and so on.
}

This is equivalent declaring and using your own "kill switch" variable, except that:

*

*many synchronization APIs, and some I/O APIs pay attention to the interrupted state, and

*a well-behaved 3rd-party library will pay attention to the interrupted state.

Now it is true that a lot of code out there mishandles InterruptedException; e.g. by squashing it.  (The correct way to deal with an InterruptedException is to either to allow it to propagate, or call Thread.interrupt() to set the flag again.)  However, the flip side is that that same code would not be aware of your kill switch.  So you've got a problem either way.

A: Thread.interrupt will not stop your thread (unless it is in the sleep, in which case the InterruptedException will be thrown). Interrupting basically sends a message to the thread indicating it has been interrupted but it doesn't cause a thread to stop immediately.
When you have long looping operations, using a flag to check if the thread has been cancelled is a standard approach. Your methodA can be modified to add that flag, so something like:
// this is a new instance variable in `A`
private volatile boolean cancelled = false;

// this is part of your methodA
for (int n=0;n<100;n++) {
  if ( cancelled ) {
    return; // or handle this however you want
  }
}

// each of your other loops should work the same way

Then a cancel method can be added to set that flag
public void cancel() {
  cancelled = true;
}

Then if someone calls runEverything on B, B can then just call cancel on A (you will have to extract the A variable so B  has a reference to it even after runEverything is called.

A: You can check the status of the run flag as part of the looping or recursion. If there's a kill signal (i.e. run flag is set false), just return (after whatever cleanup you need to do).

A: There are some other possible approaches:
1) Don't stop it - signal it to stop with the Interrupted flag, set its priority to lowest possible and 'orphan' the thread and any data objects it is working on.  If you need the operation that is performed by this thread again, make another one.
2) Null out, corrupt, rename, close or otherwise destroy the data it is working on to force the thread to segfault/AV or except in some other way.  The thread can catch the throw and check the Interrupted flag.
No guarantees, sold as seen...

A: From main thread letsvsay someTask() is called and t1.interrput is being called..
t1.interrupt();

    }

    private static Runnable someTask(){
        return ()->{

            while(running){
                try {
                    if(Thread.interrupted()){
                        throw new InterruptedException(  );
                    }
               // System.out.println(i + " the current thread is "+Thread.currentThread().getName());

                  //  Thread.sleep( 2000 );
                } catch (Exception e) {

                    System.out.println(" the thread is interrputed "+Thread.currentThread().getName());
                    e.printStackTrace();
                    break;
                }
            }

o/P:
java.lang.InterruptedException
    at com.barcap.test.Threading.interrupt.ThreadT2Interrupt.lambda$someTask$0(ThreadT2Interrupt.java:32)
    at java.lang.Thread.run(Thread.java:748)
 the thread is interrputed Thread-0

Only t1.interuuption will not be enough .this need check the status of Thread.interrupted()  in child thread.


Q: Definition of equalizer for $\textbf{Sh}(X)$ Let $\textbf{Sh}(X)$ denote the category of all (set - valued) sheaves on a topological space $X$.

My question is: Given sheaves $F,G \in \textbf{Sh}(X)$ and morphisms $\varphi : F \to G$ and $\psi : F\to G$, is there a definition in the literature for the equalizer of $\varphi$ and $\psi$? I looked in Mac Lane's book and searched on the stacks project but couldn't find anything. Can we define it as the sheaf $E$ such that for any $W \subseteq X$ open,

$$E(W) \to F(W) \begin{array}{c} \longrightarrow \\ \longrightarrow \end{array} G(W) $$
is an equalizer?

A: The sheafification functor $a : PSh(X) \to Sh(X)$ is left exact (meaning it preserves fintie limits). Its right adjoint is the inclusion $i: Sh(X) \to PSh(X)$ of the category of sheaves into the category of sheaves
Being a right adjoint, $i$ preserves all limits. This means that if $E$ is the equalizer of two arrows $f$ and $g$ in $Sh(X)$, then $i(E)$ is the equalizer of $i(f)$ and $i(g)$ in $PSh(X)$.
In $PSh(X)$, limits and colimits are computed pointwise; that is, if $X$ is the (co)limit of $X_j$, then $X(U)$ is the (co)limit of $X_j(U)$
So these facts together tell us how to compute equalizers, or any limit of sheaves.
Colimits are a little harder; $a$, being a left adjoint, preserves all colimits. So we can compute colimits by taking colimits pointwise, then sheafifying:
$$ \text{colim } X_j \cong \text{colim } ai(X_j) \cong a\left( \text{colim } i(X_j) \right) $$


Q: Right Triangle Trig I need to find the measure of each angle indicated and round to the nearest tenth.
I am given two sides 12 and 13 and one angle C which is 90 degrees. How do I figure this out?

A: Since you have a triangle with an angle of $90^\circ$, you have a right triangle.
That means you'll want to use the Pythagorean Theorem. (HINT!)
The side opposite the right angle is the longest side: the hypotenuse with length $c$. In your case, we have $c = 13$. The other two sides of the right triangle that meet at the right angle are its legs: say they are of length $a, b$: In your triangle, $a$ is the side opposite angle $A$, and $a$ is unknown; $b$ is the side opposite angle $B$ and $b = 12$. Then we know that $$a^2 + b^2 = c^2\tag{Pythagorean Theorem}$$
Solving for $a$ will give you the length of the side opposite side $A$. To find the measures of the unknown angles, you can use the trigonometric relations given by "TOA SOH CAH" (ask me if you need to, what this means) to determine the two unknown angles.
TOA: $\text{tangent} = \dfrac{\text{opposite}}{\text{adjacent}}$ $\quad \tan A = \dfrac{a}{12}$
SOH: $\text{sine} = \dfrac{\text{opposite}}{\text{hypotenuse}}$ $\quad \sin B = \dfrac{12}{13}$
CAH: $\text{cosine} = \dfrac{\text{adjacent}}{\text{hypotenuse}}\;\;$ E.g.,$\quad \cos B = \dfrac{a}{13}$
You will need only to know one angle, using, say, $B =\sin^{-1}\left(\dfrac{12}{13}\right)$ to find its measure. Then you can solve for $A$ since the sum of the angles of any triangle is standard Euclidean Geometry is $180^\circ$: $$A + B + C = A + B + 90 = 180$$

A: First use Pythagoreas' theorem to find the side of the last side. By the SOH CAH TOA rule, $\sin \theta=\frac{opposite}{hypotenuse}\implies \sin^{-1}(\theta)=\square $degrees. And then since there are 180 degrees in a triangle, $180-90-\text{(the angle you found)}$= the other angle measure for the last angle. Also if you didn't want to find the last angle that way, you could have just used SOH CAH TOA again, just like you are going to do for the second step of this problem.

A: You can use laws of sine (http://www.transtutors.com/math-homework-help/laws-of-triangle/)
12/ Sin B = 13 / Sin 90
Sin B = 12 / 13
From here you can calculate Angle B and then using A + B + C = 180
Calculate Angle A


Q: Auto-configuring postfix using dpkg-set-selections On Ubuntu 12.04, I'm trying to use dpkg-set-selections to automagically configure postfix on deployed machines with the following:
debconf-set-selections <<EOF
postfix postfix/main_mailer_type select Satellite system
postfix postfix/root_address string admin@mydomain.org
postfix postfix/mailname string mydomain.org
postfix postfix/relayhost string gw.mydomain.internal
postfix postfix/destinations string $(hostname -f), localhost
EOF
DEBIAN_FRONTEND=noninteractive apt-get install postfix mailutils

Unfortunately, the configurator insists on adding mydomain.org to the postfix/destinations (aka mydestinations) config parameter:
postfix postfix/destinations    string  mydomain.org, myserver.mydomain.internal, localhost

How can I configure this properly? I want any unqualified mail to go out as user@mydomain.org and be relayed through the smarthost.

A: I think the problem is in the install scripts, postfix.preinst has some interesting code about it, and some comments:

Add a 'mydomain' entry in main.cf for upgrade?  Postfix version
  2.3.3-2 and later require changes in main.cf.  Specifically, mydomain must be specified, since hostname(1) is not  a fully qualified domain
  name (FQDN).  .  Failure to fix this will result in a broken mailer.
  Decline this option  to abort the upgrade, giving you the opportunity
  to add this configuration  yourself. Accept this option to
  automatically set mydomain based on the  FQDN of the machine.*


Q: unexpectedly found nil while unwrapping an Optional value on return I am calling Url which will give me Json in get() function.
I am calling get() function from another class and try to return result of Json in Array format. but it shows Found null error on return statement . when I tried to print values of Json it writing correctly.
This is my code in swift.
 func get() -> NSArray
        {
            let postEndpoint: String =  "Link_For_JSON_Data"
            let session = NSURLSession.sharedSession()
            let url = NSURL(string: postEndpoint)!
            var jsonArray : NSArray?
            var jsonArray1 : NSArray?

            session.dataTaskWithURL(url, completionHandler: { ( data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
                // Make sure we get an OK response
                guard let realResponse = response as? NSHTTPURLResponse where
                    realResponse.statusCode == 200 else
                {
                        print("Not a 200 response")
                        return
                }

                // Read the JSON
                do
                {
                    if let contentString = NSString(data:data!, encoding: NSUTF8StringEncoding)
                    {
                        // Print what we got from the call
                        jsonArray = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers) as? NSArray
                        print("jsonArray here", jsonArray)
                        // Update the label

                        dispatch_async(dispatch_get_main_queue())
                            { () -> Void in
                            self.getDataFormREST(jsonArray!)
                            }

                    }
                }

                catch
                {
                    print("bad things happened")
                }

            }).resume()

       return jsonArray!
        }

     func getDataFormREST(resultArray: NSArray) //-> NSArray
        {
            //        let resultDictionary = resultArray[(searchDetails)!-1] as! NSDictionary
            testArray = resultArray
            print("TESTArray ON ",testArray)
    }

A: You can't write a function that does an async call and then returns the results as the function result. That's not how async code works. Your function queues up the async dataTaskWithURL request, and then returns before it has even had a chance to send the request, much less receive the results.
You have to rewrite your get() function to be a void function (no result returned) but take a completion block. Then, in your data task's completion handler you get the data from the jsonArray and call the get() function's completion block, passing it the jsonArray.
See this project I posted on Github that illustrates what I'm talking about:
SwiftCompletionHandlers on Github


Q: Attempting to load the view of a view controller while it is deallocating. CoreSpotlight I integrate CoreSpotlight in my app. I want that user will find need information in spotlight search and after user will open this information in spotlight information opens in DetailViewController. I made it, spotlight works nice, but when application is opening I see this error Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (UIAlertController: 0x1245a0560)  although I don't use UIAlertController. I made in AppDelegate func which call function of UITableViewController which must to open object by index. But it is not appear. Still there is an error in showData()              performSegueWithIdentifier("show", sender: nil)reason: 'Receiver () has no segue with identifier 'show''. Although I add segue ( with show name) and it works when I usually select cell. Please help me.
    AppDelegate
  func application(application: UIApplication, continueUserActivity userActivity: NSUserActivity, restorationHandler: ([AnyObject]?) -> Void) -> Bool {
        if userActivity.activityType == CSSearchableItemActionType {
            if let identifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String {
                print(identifier)
                checkWord = identifier // checkWord is String

                let tableC = TableViewController()
                tableC.showData()

                return true
            }
        }
        return false
    }

  func showData() {
    let matchString = appDel.checkWord
    if mainArray.contains(matchString) {
        let ind = mainArray.indexOf(matchString)!

        let indexPathMain = NSIndexPath(forItem: ind, inSection: 0)
        print(indexPathMain)
        self.tableView.selectRowAtIndexPath(indexPathMain, animated: true, scrollPosition: UITableViewScrollPosition.None)

        performSegueWithIdentifier("show", sender: nil)
        print("Show data")
    }
}

A: If you don't implement willContinueUserActivityWithType or if it returns false, it means that iOS should handle activity. And in this case it can show UIAlertController. So to get rid this warning return true for your activity in this delegate call:
func application(application: UIApplication,
   willContinueUserActivityWithType userActivityType: String) -> Bool {
      return true
}


Q: Getting protractor promise, variables and results synchronized Okay, I have this piece of code I'm trying, and failing, at writing. What I want to do is to make sure an index that is passed to a function is within the bounds of available elements on a page. And, if it is, pass back an element reference.
Suppose I have the following:

First row

Second

Third

So, I've got this function:
function getRow(index) {
   // get count of rows.
   var count = $$('li').count();

   // Ensure a parameter has been passed.
   if (!index) {
      throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
   }
   // Ensure the parameter is within bounds
   if (index < 0 || index >= count) {
      throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
   }

   return $$('li').get(index);
}

The above will fail because count is not really count, but a promise.
So, I've tried modifying it in various ways.  The one I thought would be successful is as follows:
// get count of rows.
var count;
$$('li').count().then(function(c) { count = c; });

or
// get count of rows.
var count = $$('li').count().then(function(c) { return c; });

I've gotten frustrated and tried to throw the whole if block within the thenable function, but it won't "see" index.
(Every time I think I've figured this out, I don't. Thank you for any and all assistance!)
UPDATE:
Following the suggestion below I tried modifying my code to:
function getRow(index) {
  //get count of rows.
  var count = $$('li').count().then(function(c) {
    return function() {
      return c;
    }
  });

  protractor.promise.all(count).then(function(count) {
    // Ensure a parameter has been passed.
    if (!index) {
      throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
    }
    // Ensure the parameter is within bounds
    if (index < 0 || index >= count) {
      throw Error("The parameter, " + index + ", is not within the bounds of 0 through " + count-1);
    }
  });

  return $$('li').get(index);
}

But it failed because, within the protractor.promise.all().then() block, index is undefined.  Also, in the error message, I don't even get a value for count.
> getRow(0);
A parameter must be supplied for function getRow. Valid values are 0 through

A: I think you must use the javascript closures in order to achive it.
Try it:
var count = element(by.css('li')).count().then(function(c){
    return function(){
        return c
    }
});

var value = count();

Your value should be in the "value" variable.
PS: I don't have a protractor environment to test this code now

A: Here's how I solved it.
function getRow(index) {
    var count = $$('li').count();

    var test = function(index, count) {
        // Ensure a parameter has been passed.
        if (index == undefined) {
            throw Error("A parameter must be supplied for function getRow. Valid values are 0 through " + count-1);
        }
        // Ensure the parameter is within bounds
       if (index < 0 || index >= count) {
           throw Error("The parameter, " + index + ", is not within the  bounds of 0 through " + count-1);
        }
    });

    count.then(function(count) {
        test(index, count);
    }

    return $$('li').get(index);
}

I'm not sure why this works and my previous attempt didn't.  Well, other than I abstracted the function and allowed myself to pass in the index in a clean manner.


Q: Java, Possible to modify method declaration of super class in abstract class hierarchy? I have an abstract class UserdataUpdater which extends Updater
Updater has a method declaration
 public abstract void processRow (Cluster cluster, IAppendOnlyData row);

Is there anyway to modify this method declaration inside UserdataUpdater to make it more specific, like
 public abstract void processRow (Cluster cluster, IUserData row);

IUserData extends IAppendOnlyData, because I want classes that extends UserdataUpdater to only take IUserData

A: No, you can't. This would break the contract of the superclass, which says: this method accepts a IAppendOnlyData as second argument.
Remember that an instance of a subclass is also an instance of its superclass. So anyone could refer to the subclass instance as its superclass, and call the base method, passing a IAppendOnlyData, without knowing that the instance is actually a subclass instance.
Read more about the Liskov substitution principle.
The only way to do that is to make the superclass generic:
public class Updater<T extends IAppendOnlyData> {
    ...
    public abstract void processRow(Cluster cluster, T row);

}

public class UserdataUpdater extends Updater<IUserData> {
    @Override
    public void processRow(Cluster cluster, IUserData row) {
        ...
    }
}

A: You cannot modify a method declaration in a derived class. You can only override a superclass method if the derived class method has the exact same method signature. You must use function overloading and make a new method processRow with the new parameter types you mentioned.

A: In my experience, you have to use the first declaration, then in the implementation, check to make sure that:
row instanceof IUserData

of course, this is checked at runtime rather than during compile, but I don't know any other way around it.  Of course, you can also just cast the row to the type IUserData, whether blindly or after checking its type (above).

A: Short answer: No.
You can create such a function, but because the signature is different, the compiler will see it as a different function.
If you think about it, what you are trying to do doesn't really make sense. Suppose you wrote a function that takes an Updater as a parameter and calls processRow on it with something that is not IUserData. At compile time, Java has no way to know whether the object passed in an Updater, UserdataUpdater, or some other subclass of Updater. So should it allow the call or not? What should the compiler do?
What you can do is inside UserdataUpdater.processRow, include code that checks the type passed in at runtime and throws an exception or does some other sort of error processing if it is not valid.

A: Assuming you have no control on the Updater class, you can't do that ... you'll have to implement that method with the exact same signature. However you can check for the type of row, inside your implementation and decide whatever processing is appropriate:
public void processRow (Cluster cluster, IAppendOnlyData row)
{
    if( row instanceof IUserData )
    {
        // your processing here
    }
    else
    {
        // Otherwise do whatever is appropriate.
    }
}


Q: Android Studio resetDrmState message on MediaPlayer release and set to null I have a media player that can play 1 of 46 sounds on button click. Instead of keeping 46 media players and stopping them all when I want to play another, I decided to keep 1 and just reuse it. My whole application works perfectly fine but in my Run box I get a resetDrmState message on every button click.
V/MediaPlayer: resetDrmState:  mDrmInfo=null mDrmProvisioningThread=null mPrepareDrmInProgress=false mActiveDrmScheme=false
    cleanDrmObj: mDrmObj=null mDrmSessionId=null

Is this a bad message?
Does anyone know a way to get rid of the message?
I use the code:
 public void onClick(View view) {
        String thisIV=view.getTag().toString();
        int resId=getResources().getIdentifier(thisIV,"raw", getPackageName());

        if(mediaPlayer!=null && mediaPlayer.isPlaying()){
            mediaPlayer.release();
            mediaPlayer=null;
        }

        mediaPlayer= MediaPlayer.create(MainActivity.this, resId);
        mediaPlayer.start();
    }

for my media player.


Q: Updating mysqli with Ajax and Jquery is not working I just want to update or edit  with Ajax. Edit or Save Button is in a  and so far everything is woking.
The Alert() function also shows variable values but the Ajax portion is not running. I am not sure why the data is not updating. Any help would be appreciated.
Question_statistics Page
include "include/connection";
while ($records=mysqli_fetch_array($query)){
    $id=$records['id'];
    $question=$records['question'];
    $question_from=$records['question_from'];
    $question_date=$records['question_date'];
    ?>
    <tr id="record-<?php  echo  $id; ?>" class="record">
        <?php echo $id; ?>

        <td class="box" id="box<?php echo $id?>">
            <span class="edit" id="<?php echo $id?>">Edit
            <span class="save" data-table="questions" id="save<?php echo $id?>">Save
            <span id="Q<?php echo $id?>"><?php echo $question; ?>

        <?php echo $question_from; ?>
        <?php echo $question_date; ?>

            <a id="<?php echo $id; ?>" class="delete" data-table="questions">

Custom javascriptfile:
$(document).ready(function() {
    //Update Question
    $('.edit').click(function(ae){
        ae.preventDefault();
        $('.edit').hide();
        var id = $(this).attr("id");
        $('#box'+id).addClass('editable');
        $('#box'+id).attr('contenteditable', 'true');
        $('#save'+id).show();
    });

    $('.save').click(function(){
        $('.save').hide();
        $('.box').removeClass('editable');
        $('.box').removeAttr('contenteditable');
        $('.edit').show();
        // var id =$(this).attr("id"); here id will show like `save+Id`
        var id= $('.edit').attr("id");
        var table = $(this).attr("data-table");
        var question=$('#Q'+id).text();

        alert(id+table+question);

        $.ajax({
            type: 'get',
            url:'include/ajaxserver.php',
            // data: variable or key : value, key:value,
            data: {
                id: id,
                edit_me: true,
                table: table,
                question: question
            },
            beforeSend: function() {
                parent.animate({'backgroundColor':'#fb6c6c'},300);
            },
            success: function(data) {
                setTimeout( function ( ) {
                    alert( 'Data has been Deleted From Database' );
                },600 );
            }
        });
    });
});/*end of the ready function*/

ajaxserver file:
include('connection');
if(isset($_GET["edit_me"]) && $_GET["edit_me"]=="true")
{
    $id = $_GET["id"];
    $table = $_GET["table"];
    $question=$_GET["question"];
    $query = "UPDATE `{$table}` SET question='$question' WHERE id='$id'";

    if (mysqli_query($con, $query)) {
        echo "";
    }
    else
      echo "";
}

A: Notice you are checking if $_GET["edit_me"] == "true" (string true) in the PHP page but that would mean that you should be sending edit_me: "true" in your ajax. Change your $_GET to:
# This will just check the key is filled
if(!empty($_GET["edit_me"]))

Then fix the SQL injection (you can Google that) and then send back instead of that javascript alert string you are doing:
die(json_encode(['success'=>(mysqli_query($con, $query))]));

This would send back to the ajax response {"success":true}if it worked. Since you are not specifically expecting json, you can parse the response:
// I changed the param here from data to response
success: function(response) {
    // Parse the response
    var data = JSON.parse(response);
    // Alert either way
    alert((data.success == true)? "Updated" : "Not Updated");
    // Do whatever this is
    setTimeout( function ( ) {
        alert( 'Data has been Deleted From Database' );
    },600 );
}


Q: lottery system pot division I making a lottery system in my web-based application, so it is in JavaScript, but my problem is more mathematical so feel free to write snippets in other language.
I want to distribute the lottery pot over winners in a natural feeling way, example:
var pot = 1000;
var tickets = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];
tickets = shuffleArray(tickets); //shuffle tickets for winners
//first half wins something (2 should be changeable)
var winners_count = Math.ceil(tickets.length / 2);

In this scenario i need a way to divide the whole pot over the 10 winners where first place gets the most and last (10th) get fewest.
for(var i=0; i<winners_count; i++){
    var ticket = tickets[i];
    //formula to determine percentage of pot to gain needed.
}

example outcome: (just to show you where it needs to go, not actual match)
1 - 22%
2 - 18%
3 - 14%
4 - 12%
5 - 10%
6 - 8%
7 - 7%
8 - 5%
9 - 3%
10 - 1%

I am quite bad at mathematics and some pointers and/or code snippets would help me a lot in solving this.
EDIT
Solution from Fabien Roualdes: http://jsfiddle.net/LB8YU/1/

A: I propose you to use an exponential distribution:
for(i=0 ; i<nrWinners ; i++){
    value = exp(-lambda*i);
    distribution[i] = value;
    sum += value;
}
for(i=0 ; i<nrWinners ; i++){
    distribution[i] /= sum;
}

Lambda is a positive parameter which will permit you to choose the shape of the distribution:

*

*If lambda is high the first winners will have a big part of the pot;

*On the contrary, the smaller lambda is, the more the distribution will aim towards a fair division of the pot.

I hope it will help you!
EDIT: When I say lambda is high, it is already high if it is equal to 1 for 5 winners.


Q: Adding controls to a from C# 2015, this.Controls.Add(bla) method not found? public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        WebBrowser wb = new WebBrowser();
        this.Controls.Add(wb);
    }
}

This results in an error:

'MainWindow' does not contain a definition for 'Controls' and no extension method accepting a first argument of type 'MainWindow' could be found

Whats wrong here?
This is a WPF Application.
I'm new to C#.
I find it on internet that to add controls to the form the function is
this.Controls.Add(fdfdf)

But here this doesn't contain Controls.

A: In WPF it should be Children. In WPF you need to add items as Childrens of layout panels like your main Grid. For example if you have a Grid set it's name to grid1 and then in the code you can:
grid1.Children.Add(fdfdf)

A: You can add a component like your WebBrowser directly to the content of the Window.
In WPF you are doing it like this:
public partial class MainWindow : Window
{
    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        WebBrowser wb = new WebBrowser();
        this.Content = wb;
    }
}

But I suggest to do this via the XAML.


Q: python - calculate the number of nodes in a Binary Tree I'm trying to write a function that uses recursion to find the number of nodes, i.e. the size of the binary tree. If the tree is empty there is no node. If it's not empty the number of nodes is 1 (the root) plus the number of nodes of the left subtree and the number of nodes of the right subtree.
I'm meant to use the binary tree class given to me to do this.
This is my Binary Tree class:
class BinaryTree:

    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None

    def insert_left(self, new_data):
        if self.left == None:
            self.left = BinaryTree(new_data)
        else:
            t = BinaryTree(new_data)
            t.left = self.left
            self.left = t

    def insert_right(self, new_data):
        if self.right == None:
            self.right = BinaryTree(new_data)
        else:
            t = BinaryTree(new_data)
            t.right = self.right
            self.right = t

    def get_left(self):
        return self.left

    def get_right(self):
        return self.right

    def set_data(self, data):
        self.data = data

    def get_data(self):
        return self.data

and this is my recursive function to calculate the size:
def size(my_tree):
    count = 0
    if my_tree.get_data() is None:
        return 0
    else:
        count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
    return count

However, when I run it with this program:
 a = BinaryTree(1)
 a.insert_left(2)
 a.insert_right(3)
 print(size(a))

I get the following error:
Original exception was:
Traceback (most recent call last):
    File "prog.python3", line 57, in <module>
        print(size(a))
    File "prog.python3", line 41, in size
        count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
    File "prog.python3", line 38, in size
        if my_tree.get_data() is None:
AttributeError: 'NoneType' object has no attribute 'get_data'

when the output should be:
3

I simply don't understand what I'm doing wrong, but I'm pretty sure it must be something to do with the if statement.

A: Just modify your if statement to
if my_tree is None:
    return 0

The error arises since you are trying to access get_data property for a NULL data object on recursive call for leaf nodes of the binary tree.
Instead what you actually need to do is return 0 when you reach a NoneType node.

A: What happens if my_tree is None? Then you can't call get_data()...
Try this
if my_tree is None:
    return 0

Worth pointing out that you don't care about the node data to find the size of the tree
The more optimal method is to not recurse, and keep the size updated as you insert/remove elements

A: Assuming you pass in a valid root object and recursion occurs as expected, then at what point can you hit upon a NoneType error? Certainly, when my_tree is None, and you try to access an attribute of None. When can my_tree be None? At the leaves. In other words, your base case is malformed.
Note that testing the return value of get_data is completely redundant here, because self.data has nothing to do with the height of the node, or the node itself.
def size(my_tree):
    if not my_tree:
        return 0

    return 1 + size(my_tree.get_left()) + size(my_tree.get_right())

Further nitpicks:

*

*You don't need else; that's implied by control flow.

*You don't need an extra variable to store the count, because you don't do anything else besides return it.

A: You are getting this error because you are calling get_data() on non-existent object. So, you are calling get_data() on a NoneType object.
def size(my_tree):
    count = 0
    if my_tree is None:
        return 0
    count += 1 + size(my_tree.get_left()) + size(my_tree.get_right())
    return count

The else clause is not needed. Another suggestion to count the binary tree nodes is to have a attribute size on the class, and increase / decrease it as items are added / removed from the tree.


Q: Restrict list of components when linking in property editor in IDE I have created a new designtime component, which contains a published property Handler of type TComponent and registered it into the Tool Palette.
When i place a component of this type on my form, the property editor of the IDE shows me the property 'Handler' with a dropdown box that allows me to set this property at design time. The dropbox shows all available TComponents on the current form.
How can I restrict the list of components that is shown here (design time) to components of a certain type or with a certain property? i.e. Components that implement a certain (set of) interfaces.
I know that you can also use interface-properties, but also encountered several posts on the internet stating that this is very unstable and raises all kinds of problems.
Is there a method I can call for each of the proposed components where I can determine if they should appear in the list at design time?
Addition after the answer of @David:
Now that I've learned that TComponentProperty is what i was looking for, I also found a related question here: How to modify TComponentProperty to show only particular items on drop down list?

A: *

*Derive a sub class of TComponentProperty.

*Override its GetValues method to apply your filter.

*Register this TComponentProperty as the property editor for your property.

Here is a very simple example:
Component
unit uComponent;

interface

uses
  System.Classes;

type
  TMyComponent = class(TComponent)
  private
    FRef: TComponent;
  published
    property Ref: TComponent read FRef write FRef;
  end;

implementation

end.

Registration
unit uRegister;

interface

uses
  System.SysUtils, System.Classes, DesignIntf, DesignEditors, uComponent;

procedure Register;

implementation

type
  TRefEditor = class(TComponentProperty)
  private
    FGetValuesProc: TGetStrProc;
    procedure FilteredGetValuesProc(const S: string);
  public
    procedure GetValues(Proc: TGetStrProc); override;
  end;

procedure TRefEditor.FilteredGetValuesProc(const S: string);
begin
  if S.StartsWith('A') then
    FGetValuesProc(S);
end;

procedure TRefEditor.GetValues(Proc: TGetStrProc);
begin
  FGetValuesProc := Proc;
  try
    inherited GetValues(FilteredGetValuesProc);
  finally
    FGetValuesProc := nil;
  end;
end;

procedure Register;
begin
  RegisterComponents('Test', [TMyComponent]);
  RegisterPropertyEditor(TypeInfo(TComponent), nil, 'Ref', TRefEditor);
end;

end.

This rather useless property editor will only offer you components whose names begin with A. Despite its complete lack of utility, this does illustrate the ability to filter that you desire. You'll likely want to call Designer.GetComponent(...) passing a component name to obtain the component instance, and implement your filtering based on the type and state of that component instance.

A: As @TLama already pointed out you need to change the tpe of handler field/property.
Now in case if you want to ba able to assign specific type of component to this field/property then set this field type to the same type of that compomnent.
But if you want to be able to assign several different component types but not all components make sure that Handler field/property type is the type of the first common ancestor class/component of your desired components that you want to be able to assign to the Handler field/property.


Q: Copying from a set of cells from one column and paste them in consecutive columns in VBA Excel Macros I have got a set of values in Range 'A' and Range 'B'. I want to compare each consecutive row of Range 'A' and when the previous row is greater than the next row ; I want to copy then set of points below the compared points and paste them in the consecutive columns. for eg. C,G,J etc... I have got the compare  part  done ..Just the arranging part is taking my time. In my case I am trying to use DO Until and For Loop. But is there any better way ... PLs Advice...
 Range("H1").Select

 Do Until Range("H1", Range("H1").End(xlDown))

 If IsEmpty(ActiveCell) Then

 ActiveCell.Offset(1, 0).Select
 j = 2

 For i = 1 To Range("H1", Range("H1").End(xlDown)).Rows.Count

 Cells(i + 1, 8).Select
 Selection.Copy
 Cells(i + 1, 11 + j).Select
 ActiveSheet.Paste

 Cells(i + 1, 9).Select
 Selection.Copy
 Cells(i + 1, 12 + j).Select
 ActiveSheet.Paste

 Next i

ActiveCell.Offset(1, 0).Select

 Else

 j = 0
 For i = 1 To Range("H1", Range("H1").End(xlDown)).Rows.Count

 Cells(i + 1, 8).Select
 Selection.Copy
 Cells(i + 1, 11 + j).Select
 ActiveSheet.Paste

 Cells(i + 1, 9).Select
 Selection.Copy
 Cells(i + 1, 12 + j).Select
 ActiveSheet.Paste

 Next i

 ActiveCell.Offset(1, 0).Select

 End If

Loop


Q: CDash build ID not set (CTest, CMake) I have a CDash configured to accept posts for automatic builds and tests. However, when any system attempts to post results to the CDash, the following error is produced. The result is that each result gets posted four times (presumably the original posting attempt plus the three retries).
Can anyone give me a hint as to what sets this mysterious build ID? I found some code that seems to produce a similar error, but still no lead on what might be happening.

Build::GetNumberOfErrors(): BuildId not set
    Build::GetNumberOfWarnings(): BuildId not set
     Submit failed, waiting 5 seconds...
     Retry submission: Attempt 1 of 3
     Server Response:

A: The buildid for CDash is computed based on the site name, the build name and the build stamp of the submission. You should have a Build.xml file in a Testing/20110311-* directory in your build tree. Open that up and see if any of those fields (near the top) is empty. If so, you need to set BUILDNAME and SITE with -D args when configuring with CMake. Or, set CTEST_BUILD_NAME and CTEST_SITE in your ctest -S script.
If that's not it, then this is a mystery. I've not seen this error occur before...


Q: How do I prompt the user to give the name for the writing and reading serialized file? I am making an attempt to prompt the user to create the name for the writing and reading serialized file. E.g. could I do the following:
System.out.print("What would you like to name your file?");
String fileName = scanner.nextLine;

try{
 ObjectOutput ostream = new ObjectOutputStream(new FileOutputStream(fileName)) // Would this create a file with the name inputted by the user? If so what would be the extension for the file?

 ostream.writeObject(//whatever I want to put in here)

 //close

//catch

try{

 ObjectInputStream = new ObjectInputStream(new FileInputStream(fileName))

//catch

A: If you want to prompt the user for something from the terminal, the easiest way is probably to use java.io.Console, in particular one of its readLine() methods:
import java.io.Console;

...

Console console = System.console();
if (console == null) {
  throw new IllegalStateException("No console to read input from!");
}

String fileName = console.readLine("What would you like to name your file? ");
// Whatever the user inputed is now in fileName

See http://docs.oracle.com/javase/7/docs/api/java/io/Console.html.


Q: Braces around Java method I just noticed recently, while coding, that surrounding code with braces without any condition (or anything else) lets the code running correctly. For example, the following snippet:
public static void main(String[] args) {
{
    System.out.println("Hello world !");
    {
        System.out.println("Hello subworld !");
        {
            System.out.println("Hello sub-subworld !");
        }
    }
}
}

Gives the following output:
Hello world !
Hello subworld !
Hello sub-subworld !

I would like to know: are there any consequences, deeper into execution, of this kind of practice ? And, is it used in any case and proven to be useful ?


Q: QGIS 3.0 Hybrid Tile Server URLs I've recently come into a new position where I'm using QGIS instead of ESRI and am learning the ropes on handling all the things ESRI comes out of the box with that QGIS doesn't.
I've found tile server URLs for OpenStreetMap and Bing Aerial, but nothing of the hybrid variation. Does anyone have information on anything like Bing or Google Hybrid tiles with worldwide/US coverage?

A: The plugin QuickMapServices gives you access to many worldwide base layers, which can be easily added to your map from a menu.
Install from the Plugins menu > Manage and install plugins > search for quickmapservices > install plugin > activate by checking the box next the plugin name.

Access the plugin through the Web menu. By default, you have access to a few reliable base layers.

At your own risk, you can also access a wide variety of "contributed" base layers, of varying reliability and accuracy. Go to Settings > More Services > Get contributed pack. In my experience, the contributed layers are accurate, but they don't all work. Some are missing tiles, while others only work at certain zoom levels.

You can also manually add any layer for which you have a URL.
See the answer provided by Matthias Kuhn to this question (scroll down, it's near the bottom of the page) for help adding an XYZ tiles layer, and some URLs.
And see the answer to this question for help adding WMS layers.


Q: Recursively reversing a string in C? I have to reverse a string in a recursive function, but I cannot use loops or strlen to find where the end of the string is. Then I have to pass the reversed string back to main and copy it to a new file. Here's what I have so far:
int reverse(char *str, char *strnew, int p)
{
    char temp=str[p];
    if(temp=='\0' || temp=='\n')
    {
            strnew=str;
            return p;
    }
    else
    {
            reverse(str++, strnew, ++p);
            p--;
            strnew[p]=str[p];
            printf("strnew: %c\n",  strnew[p]);
            return 0;
    }
}

int main(int argc, char *argv[])
{
    FILE *fp;
    char buffer[100];
    char newstr[100];
    int pointer=0;
    fp=fopen("lab8.txt", "r");
    if(fp==NULL)
    {
            printf("Error opening file\n");
            return 0;
    }
    (fgets(buffer, 100, fp));
    reverse(buffer, newstr, pointer);
    printf("newstr: %s\n", newstr);
    FILE *fp2=fopen("lab8.2.txt", "w");
    fputs(newstr, fp2);
    fclose(fp);
    fclose(fp2);

    return 0;
}

I cannot wrap my head around how to reverse the string. I've found where the null character is using p, but how do I copy the string backwards onto a new string?

A: #include <stdio.h>

int reverse(char *str, int pos){
    char ch = str[pos];
    return (ch == '\0')? 0 : ((str[pos=reverse(str, ++pos)]=ch), ++pos);
}

int main(){
    char buffer[100];

    scanf("%99[^\n]", buffer);
    reverse(buffer, 0);
    fprintf(stdout, "%s\n", buffer);
    return 0;
}

A: Since this is obviously homework, no complete solution, only ideas.
First, you don't need to limit yourself to one recursive function. You can have several, and a resursive implementation of strlen is trivial enough. my_strlen(char *p) evaluates to 0 if *p = 0, and to 1 + my_strlen(p+1) otherwise.
You can probably do it in a single recursion loop, too, but you don't have to.
One more thing: as you recurse, you can run your code both on the front end of recursion and on the back end. A recursion is like a loop; but after the nested call to self returns, you have a chance to perform another loop, this one backwards. See if you can leverage that.

A: It is quite simple.  When you enter the string, you save the character at the position you are are.  Call the method recursively more character to the right.  When you get to the end of the string, you will have N stack frames, each holding one character of an N character string.  As you return, write the characters back out, but increment the pointer as you return, so that the characters are written in the opposite order.

A: I'll try to be nice and give you a little sample code. With some explanation.
The beauty of recursion is that you don't need to know the length of the string, however the string must be null terminated. Otherwise you can add a parameter for the string length.
What you need to think is that the last input character is your first output character, therefore you can recurse all the way to the end until you hit the end of the string. As soon as you hit the end of the string you start appending the current character to the output string (initially set to nulls) and returning control to the caller which will subsequently append the previous character to the output string.
void reverse(char *input, char *output) {
    int i;
    if(*input) /* Checks if end of string */
        reverse(input+1,output); /* keep recursing */
    for(i=0;output[i];i++); /* set i to point to the location of null terminator */
    output[i]=*input; /* Append the current character */
output[i+1]=0; /* Append null terminator */
} /* end of reverse function and return control to caller */

Finally, lets test the function.
int main(argc, argv) {
    char a[]="hello world";
    char b[12]="\0";
    reverse(a,b);
    printf("The string '%s' in reverse is '%s'\n", a, b);
}

Output
The string 'hello world' in reverse is 'dlrow olleh'


Q: How to programmatically grant the "draw over other apps" permission in android? How can I programmatically grant the permission in Settings -> Apps -> Draw over other apps in Android? I want to use system alert window but unable to in Android Marshmallow without forcing the user to go through the Settings app and grant the permission first.

A: Here's the code for automatic granting the SYSTEM_ALERT_WINDOW permission to the package. To run this code, your Android application must be system (signed by platform keys).
This method is based on the following Android source code files: AppOpsManager.java and DrawOverlayDetails.java, see the method DrawOverlayDetails.setCanDrawOverlay(boolean newState).
@TargetApi(Build.VERSION_CODES.KITKAT)
public static void autoSetOverlayPermission(Context context, String packageName) {
    PackageManager packageManager = context.getPackageManager();
    int uid = 0;
    try {
        ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0);
        uid = applicationInfo.uid;
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
        return;
    }

    AppOpsManager appOpsManager = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
    final int OP_SYSTEM_ALERT_WINDOW = 24;
    try {
        Class clazz = AppOpsManager.class;
        Method method = clazz.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class);
        method.invoke(appOpsManager, OP_SYSTEM_ALERT_WINDOW, uid, packageName, AppOpsManager.MODE_ALLOWED);
        Log.d(Const.LOG_TAG, "Overlay permission granted to " + packageName);
    } catch (Exception e) {
        Log.e(Const.LOG_TAG, Log.getStackTraceString(e));
    }
}

}
The code has been tested in Headwind MDM project, it successfully grants "Draw over other apps" permission without any user consent to the Headwind Remote application (disclaimer: I'm the project owner of Headwind MDM and Headwind Remote), when Headwind MDM application is signed by platform keys. The code has been tested on Android 10 (LineageOS 17).

A: You can check and ask for overlay permission to draw over other apps using this
if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 0);
}

A: if (!Settings.canDrawOverlays(this)) {
    Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
    Uri.parse("package:" + getPackageName()));
    startActivityForResult(intent, 0);
}

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>

A: Check this question and the answer:
SYSTEM_ALERT_WINDOW - How to get this permission automatically on Android 6.0 and targetSdkVersion 23
"Every app that requests the SYSTEM_ALERT_WINDOW permission and that is installed through the Play Store (version 6.0.5 or higher is required), will have granted the permission automatically."


Q: Django - assign m2m relationship in admin In the app I'm building some users have the role "Coder" and are assigned to "Assignments".
What I can't seem to get working is the process of an Admin assigning Coders to Assignments.
Here is the Model-Code I have so far (probably totally wrong):
class Coder(models.Model):
"""Every user can be a coder. Coders are assigned to Assignments"""
user = models.OneToOneField(User)

class Admin:
    list_display = ('',)
    search_fields = ('',)

def __unicode__(self):
    return u"Coders"

class Assignment(models.Model):
"""(Assignment description)"""
title = models.CharField(blank=True, max_length=100)
start_year = models.IntegerField(blank=True, null=True)
end_year = models.IntegerField(blank=True, null=True)
country = models.IntegerField(blank=True, null=True)
coders = models.ManyToManyField(Coder)

class Admin:
    list_display = ('',)
    search_fields = ('',)

def __unicode__(self):
    return u"Assignment"

And this is the admin-code:
class AssignmentCoderInline(admin.StackedInline):
model = Assignment.coders.through
can_delete = False
verbose_name_plural = 'coder'

class AssignmentAdmin(admin.ModelAdmin):
fieldsets = [
    ('Assignment', {'fields': ['title', 'start_year', 'end_year']})
]
inlines = (AssignmentCoderInline,)

class CoderInline(admin.StackedInline):
model = Coder
can_delete = False
verbose_name_plural = 'coder'

Now, when i'm in the admin, I want to create an assignment and add coders to it.
Yet all I see when trying to do so is this:

How can I add one coder/user to an assignment, so I can later show him in a view all the assignments he has?
This is probably a really dumb question, but please answer anyways, I greatly appreciate any help :)

A: If I'm not mistaken, it looks like you want to call a coder to a view, and then show all the assignments for an a user.
First, I might start by assigning a related_name to the coder and assignment models relationships with each other, so you can easily reference them later.
class Assignment(models.Model):
    coders = models.ManyToManyField(Coder, related_name='assignments')

class Coder(models.Model):
    user = models.OneToOneField(User, related_name="coder")

I'd then reference the user in a template as such using the one to one relationship:
    {% for assignment in user.coder.assignments.all %}

Also, looks like the problem is how you've got yout models setup. After reviewing the django.db.models.base for the "models.Model" class and "ModelBase" class, it looks like there is no "Admin" subclass. You'll probably want to remove those to start with.
Next, the __unicode__ field shows the default visible value which represents the object on the screen. In this case, you've forced it to be "Coders". If you had 5 coders to an assignment, you'd see "Coders, Coders, Coders, Coders, Coders" instead of "admin, user1, bob22, harry8, stadm1in", etc. Let's override the unicode to show something more meaningful. Since the coders field only has the user field, let's reference that by self.user.username. We'll change Assignment()'s unicode to self.title as well.
ModelForm doesn't have an 'Admin' subclass either, so let's remove that.
MODELS:

class Coder(models.Model):
    """Every user can be a coder. Coders are assigned to Assignments"""
    user = models.OneToOneField(User, related_name='coder')

    def __unicode__(self):
        return self.user.username

class Assignment(models.Model):
    """(Assignment description)"""
    title = models.CharField(blank=True, max_length=100)
    start_year = models.IntegerField(blank=True, null=True)
    end_year = models.IntegerField(blank=True, null=True)
    country = models.IntegerField(blank=True, null=True)
    coders = models.ManyToManyField(Coder, related_name='assignments')

    def __unicode__(self):
        return self.title

ADMIN:

class AssignmentCoderInline(admin.StackedInline):
    model = Assignment.coders.through
    can_delete = False
 #   verbose_name_plural = 'coder'

class AssignmentAdmin(admin.ModelAdmin):
    fieldsets = [
        ('Assignment', {'fields': ['title', 'start_year', 'end_year']})
    ]
    inlines = (AssignmentCoderInline,)


Q: Using JSP to paint a part of page other wise painted by Servlet I am updating an age old application that paints its page using a Servlet. I want to add something to that page and really want to stop adding to that Servlet file.
Is there a way I could paint a part of a page using JSP and all other using Servlet.

A: Yes of course, you can use the
`<jsp:include page="content.jsp">`  or
`<%@include file="content.jsp"%>`
If your content is static(copy and paste), you can use `<%@include file="content.jsp"%>`
The `<%@include file="content.jsp">` directive is similiar to "#include" in C programming, including the all contents of the included file and then compiling it like it is part of the including file. Also the included file can be any type (including HTML or text).


Q: Websocket connection error on Stack Overflow Using Chrome, I am having this error when I refresh a page on Stack Overflow and open the developer tool:

WebSocket connection to 'ws://sockets.ny.stackexchange.com/' failed: Unexpected response code: 502 full.js?v=f9e9cb812ede:13

PS. Also, the copy/pasting feature does not work when you try to Ctrl + V to paste a print screen.
Chrome version: 29.0.1547.62 m
OS: Windows 7


Q: Starting and stopping Apache Camel routes from admin UI I have a Apache Camel context which is part of a large Spring application. The application has a web based admin UI. I'd like to be able to stop/start/suspend/resume the camel routes from within this UI. How can I achieve this?
Currently my Camel context is defined in a Spring context file and autostarts when the Spring application is deployed. My routes are defined in Java classes which extend SpringRouteBuilder.
I have:
camel-context.xml:
<beans>

    <!--bootstrap camel context-->
    <camelContext xmlns="http://camel.apache.org/schema/spring">
        <package>com.package</package>
    </camelContext>

</beans>

which is imported in the main Spring context. I then have classes which extend SpringRouteBuilder in com.package
Is there a better way of doing this so that I can programatically control the Camel context when there is an event in the UI?

A: You can also do like we do in hawtio (http://hawt.io/) where we use REST calls to remote manage Camel applications, so we can control routes, see statistic, view routes, and much more. All this is made easier by using an excellent library called jolokia (http://jolokia.org/) that makes JMX exposed as REST services. Each JMX operation/attribute is easily callable as an URI template over REST. And data is in json format.
That what you can build UI consoles that just use REST for communication, and are not tied into the Java or JMX world etc.
Also the Java API on CamelContext allows you to control routes. And there is also the control-bus EIP that has more details: http://camel.apache.org/controlbus


Q: SSL Working fine how can I add in http to https redirection? Hi I'm having major problems with a server, SSL works perfectly WHEN connecting with HTTPS://..., I need to set up redirection from http to https.
This is my ssl.conf, Centos 6, with one IP address. SSL Cert set up with SANs. Would rather not use .htaccess.
Listen 172.21.11.48:443

NameVirtualHost 172.21.11.48:443

LoadModule ssl_module   modules/mod_ssl.so
SSLEngine on
SSLSessionCache         shmcb:/var/cache/httpd/mod_ssl/ssl_scache(512000)
SSLCertificateFile /etc/pki/tls/certs/aether.example.com.crt
SSLCertificateKeyFile /etc/pki/tls/private/aether.example.com-2048.key
SSLCACertificateFile /etc/pki/tls/certs/exampleca.crt

<VirtualHost 172.21.11.48:443>
  SSLEngine on
  ServerAlias      "webmail.example.com"
  DocumentRoot    "/var/www/html/roundcubemail"
  SSLCertificateFile /etc/pki/tls/certs/aether.example.com.crt
  SSLCertificateKeyFile /etc/pki/tls/private/aether.example.com-2048.key
  SSLCACertificateFile /etc/pki/tls/certs/exampleca.crt
</VirtualHost>

<VirtualHost 172.21.11.48:443>
  SSLEngine on
  ServerAlias      "cloud.example.com"
  DocumentRoot    "/var/www/html/owncloud"
  SSLCertificateFile /etc/pki/tls/certs/aether.example.com.crt
  SSLCertificateKeyFile /etc/pki/tls/private/aether.example.com-2048.key
  SSLCACertificateFile /etc/pki/tls/certs/exampleca.crt
</VirtualHost>

When connecting on http://webmail.example.com it errors with "Your browser sent a request that this server could not understand. Reason: You're speaking plain HTTP to an SSL-enabled server port". When I add another vhost on port 80 Apache fails to start. Any help would be gratefully received.
Steve

A: Remove the SSLEngine on in the top of your config - if you configure that outside of your virtual hosts, you're turning it on for every virtual host on the server.
To set up redirection to https, you'll want something like this in your port 80 virtual host:
Redirect / https://webmail.example.com/


Q: Detect activity level of microphone in flex I have to detect avtivityLevel of microphone in Flex. I am using the activityLevel property of Microphone class but as I found out it always return -1 even if I have done Microphone.getMicrophone().
To detect activity level we have to set microphone.setLoopback = true;
Does anybody know how to do this without using loop back as I do not want to hear my sound back just monitor the activity level
Thanks

A: The microphone won't show any activity until it is attached to a NetStream connection. You can use a MockNetStream to fake the connection using OSMF - see my answer here.


Q: php docker how to use file_get_contents to fetch self domain's result I have a project need to server migration, the new server deployed by docker. but in docker, the file_get_contents() cannot fetch the result from self domain. and I can't use others way (for example reqire_once) to load this file ( this project is too old and code is... you know ).
code:
$json = file_get_content("http://this.site.com/xxx/yyy/get_result.php?params=xxx&params2=yyy")

If I use it, will get a warning connect refuese, if I replace the domain to http://127.0.0.1 or http://localhost, will get the same warning, or replace to http://nginx ( nginx is another container's name ) will get content, but not my site's content ( it will get contents the same by using 127.0.0.1 in the broswer, not using http://this.site.com )
So it

A: Your code is running with a docker on another instance so is 127.0.0.1 address is different from your computer's address.
You must enter the external IP address of the container

A: Try using host.docker.internal...


Q: автоматизация платежей android планируем доску обьявлений для не очень большего города.
с реализацией то справляемся хотя и мы начинающие.
Но с монетизацией затрудняемся.
Первый вопрос как можно монетизировать?
Второй вопрос как можно автоматизировать платежи VIP обьявлений?
Всем кто обратит внимание спасибо!

A: Привет. Вопрос слишком общий.Но отвечу в целом .

*

*(Монетизация)Для начала если есть аудитория то можно добавить за счет
введения платных услуг, показа рекламы, размещения ссылок и т.п

*-(Автоматизировать)Ясный пень это делать в ручную вы не будете ,думаю нужен сервак где будет сервис которуму идет запрос на обьявление и по
определенным критериям он сам знает какой у него приоритет в показе
.Насамом деле это очень легко.


Q: Keep selected row in table highlighted during fireTableDataChanged is there chance to keep the selected row in a JTable higlithed druing fireTableDataChanged?
Thank you


Q: Prism 7 throws and exception when working with nested views I posted similar question few months ago Working with nested views using Prism with IsNavigationTarget which can return false, I'm still not sure what is the proper way to do it.
Imagine you have a view A, in this view A you have declared a region A, then you injected a view B into this region A. Similarly, in View B you have registered region B, and then you injected a view C into this region B. As it shown on the following picture:

In the ViewModelA for ViewA, I have a method SetUpSubViews() where I call:
_regionManager.RequestNavigate("regionA", "ViewB", NavigationCallback);

ViewModelB for View B implements INavigationAware. So that in OnNavigatedTo() method I call:
_regionManager.RequestNavigate("regionB", "ViewC", NavigationCallback);

ViewModelC for View C implements INavigationAware too.
Now, I have in both ViewModelB and ViewModelC in IsNavigationTarget() method:
public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return false;
    }

It means I want to create new view everytime this view is navigated.
Both ViewB and ViewC implement IRegionMemberLifetime interface, where I set:
#region IRegionMemberLifetime

public bool KeepAlive => false;

#endregion

It means that I don't want to reuse view and I want it to be disposed.
And regions in the view are declared like this:
<ContentControl prism:RegionManager.RegionName="{x:Static localRegions:LocalRegions.RegionB}" />

Now, first time when I call SetUpSubViews() method on ViewModelA all is good. Second time when I call it I see the exception:

Region with the given name is already registered
...

What I need is to have a way to recreate view<->viewmodel pair from scratch everytime when I need. It seems when view is disposed, prism doesn't remove region that was declared in removed view. Question to community and prism developers, how to do it in proper way?
The current solution doesn't make happy, here is what I do:
Step 1 - I set in ViewModelB and ViewModelC in INavigationAware part
    public bool IsNavigationTarget(NavigationContext navigationContext)
    {
        return true;
    }

that signals to prism to do not create new views and probably it also means that if any region is found in the view to do not register it in the region manager.
Step 2 - When i need to inject view to region, i remove manually old view and create new one. So my SetUpSubViews() method looks like this:
protected void SetUpSubViews(){
            //get region by name
            var region = _regionManager.Regions["regionA"];
            // push to remove all views from the region
            region.RemoveAll();
            // navigate to view
           _regionManager.RequestNavigate("regionA", "ViewB", NavigationCallback);}

Similarly I have to remove ViewC from region regionB on ViewB. (here is region.RemoveAll() is a key line.)
Step3 - I don't implement IRegionMemberLifetime interface on viewB and viewC.
It works, but it doesn't look correct.
P.S. I also tried scoped manager, but i don't know how to propagate new created scoped manager to the viewmodels, cause they are created automatically, and if i resolve it via constructor I get main global manager instead of scoped.
Thanks.

A: This is quite a troublesome problem. I recommend videos from Brian Lagunas himself where he provides a solution and explanation. For example this one.
https://app.pluralsight.com/library/courses/prism-problems-solutions/table-of-contents
If you can watch it. If not I will try to explain.
The problem I believe is that IRegionManager from the container is a singleton and whenever you use it it is the same instance, so when you are trying to inject a region in an already injected region it will not work and you need to have a separate RegionManager for nested views.
This should fix it.
Create two interfaces
public interface ICreateRegionManagerScope
{
    bool CreateRegionManagerScope { get; }
}
public interface IRegionManagerAware
{
    IRegionManager RegionManager { get; set; }
}

Create a RegionManagerAwareBehaviour
public class RegionManagerAwareBehaviour : RegionBehavior
{
    public const string BehaviorKey = "RegionManagerAwareBehavior";

    protected override void OnAttach()
    {
        Region.Views.CollectionChanged += Views_CollectionChanged;
    }

    void Views_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach (var item in e.NewItems)
            {
                IRegionManager regionManager = Region.RegionManager;

                // If the view was created with a scoped region manager, the behavior uses that region manager instead.
                if (item is FrameworkElement element)
                {
                    if (element.GetValue(RegionManager.RegionManagerProperty) is IRegionManager scopedRegionManager)
                    {
                        regionManager = scopedRegionManager;
                    }
                }

                InvokeOnRegionManagerAwareElement(item, x => x.RegionManager = regionManager);
            }
        }
        else if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            foreach (var item in e.OldItems)
            {
                InvokeOnRegionManagerAwareElement(item, x => x.RegionManager = null);
            }
        }
    }

    private static void InvokeOnRegionManagerAwareElement(object item, Action<IRegionManagerAware> invocation)
    {
        if (item is IRegionManagerAware regionManagerAwareItem)
        {
            invocation(regionManagerAwareItem);
        }

        if (item is FrameworkElement frameworkElement)
        {
            if (frameworkElement.DataContext is IRegionManagerAware regionManagerAwareDataContext)
            {
                // If a view doesn't have a data context (view model) it will inherit the data context from the parent view.
                // The following check is done to avoid setting the RegionManager property in the view model of the parent view by mistake.
                if (frameworkElement.Parent is FrameworkElement frameworkElementParent)
                {
                    if (frameworkElementParent.DataContext is IRegionManagerAware regionManagerAwareDataContextParent)
                    {
                        if (regionManagerAwareDataContext == regionManagerAwareDataContextParent)
                        {
                            // If all of the previous conditions are true, it means that this view doesn't have a view model
                            // and is using the view model of its visual parent.
                            return;
                        }
                    }
                }

                invocation(regionManagerAwareDataContext);
            }
        }
    }
}

Create ScopedRegionNavigationContentLoader
public class ScopedRegionNavigationContentLoader : IRegionNavigationContentLoader
{
    private readonly IServiceLocator serviceLocator;

    /// <summary>
    /// Initializes a new instance of the <see cref="RegionNavigationContentLoader"/> class with a service locator.
    /// </summary>
    /// <param name="serviceLocator">The service locator.</param>
    public ScopedRegionNavigationContentLoader(IServiceLocator serviceLocator)
    {
        this.serviceLocator = serviceLocator;
    }

    /// <summary>
    /// Gets the view to which the navigation request represented by <paramref name="navigationContext"/> applies.
    /// </summary>
    /// <param name="region">The region.</param>
    /// <param name="navigationContext">The context representing the navigation request.</param>
    /// <returns>
    /// The view to be the target of the navigation request.
    /// </returns>
    /// <remarks>
    /// If none of the views in the region can be the target of the navigation request, a new view
    /// is created and added to the region.
    /// </remarks>
    /// <exception cref="ArgumentException">when a new view cannot be created for the navigation request.</exception>
    public object LoadContent(IRegion region, NavigationContext navigationContext)
    {
        if (region == null) throw new ArgumentNullException("region");
        if (navigationContext == null) throw new ArgumentNullException("navigationContext");

        string candidateTargetContract = this.GetContractFromNavigationContext(navigationContext);

        var candidates = this.GetCandidatesFromRegion(region, candidateTargetContract);

        var acceptingCandidates =
            candidates.Where(
                v =>
                {
                    var navigationAware = v as INavigationAware;
                    if (navigationAware != null && !navigationAware.IsNavigationTarget(navigationContext))
                    {
                        return false;
                    }

                    var frameworkElement = v as FrameworkElement;
                    if (frameworkElement == null)
                    {
                        return true;
                    }

                    navigationAware = frameworkElement.DataContext as INavigationAware;
                    return navigationAware == null || navigationAware.IsNavigationTarget(navigationContext);
                });

        var view = acceptingCandidates.FirstOrDefault();

        if (view != null)
        {
            return view;
        }

        view = this.CreateNewRegionItem(candidateTargetContract);

        region.Add(view, null, CreateRegionManagerScope(view));

        return view;
    }

    private bool CreateRegionManagerScope(object view)
    {
        bool createRegionManagerScope = false;

        if (view is ICreateRegionManagerScope viewHasScopedRegions)
            createRegionManagerScope = viewHasScopedRegions.CreateRegionManagerScope;

        return createRegionManagerScope;
    }

    /// <summary>
    /// Provides a new item for the region based on the supplied candidate target contract name.
    /// </summary>
    /// <param name="candidateTargetContract">The target contract to build.</param>
    /// <returns>An instance of an item to put into the <see cref="IRegion"/>.</returns>
    protected virtual object CreateNewRegionItem(string candidateTargetContract)
    {
        object newRegionItem;
        try
        {
            newRegionItem = this.serviceLocator.GetInstance<object>(candidateTargetContract);
        }
        catch (ActivationException e)
        {
            throw new InvalidOperationException(
                string.Format(CultureInfo.CurrentCulture, "Cannot create navigation target", candidateTargetContract),
                e);
        }
        return newRegionItem;
    }

    /// <summary>
    /// Returns the candidate TargetContract based on the <see cref="NavigationContext"/>.
    /// </summary>
    /// <param name="navigationContext">The navigation contract.</param>
    /// <returns>The candidate contract to seek within the <see cref="IRegion"/> and to use, if not found, when resolving from the container.</returns>
    protected virtual string GetContractFromNavigationContext(NavigationContext navigationContext)
    {
        if (navigationContext == null) throw new ArgumentNullException(nameof(navigationContext));

        var candidateTargetContract = UriParsingHelper.GetAbsolutePath(navigationContext.Uri);
        candidateTargetContract = candidateTargetContract.TrimStart('/');
        return candidateTargetContract;
    }

    /// <summary>
    /// Returns the set of candidates that may satisfiy this navigation request.
    /// </summary>
    /// <param name="region">The region containing items that may satisfy the navigation request.</param>
    /// <param name="candidateNavigationContract">The candidate navigation target as determined by <see cref="GetContractFromNavigationContext"/></param>
    /// <returns>An enumerable of candidate objects from the <see cref="IRegion"/></returns>
    protected virtual IEnumerable<object> GetCandidatesFromRegion(IRegion region, string candidateNavigationContract)
    {
        if (region == null) throw new ArgumentNullException(nameof(region));
        return region.Views.Where(v =>
            string.Equals(v.GetType().Name, candidateNavigationContract, StringComparison.Ordinal) ||
            string.Equals(v.GetType().FullName, candidateNavigationContract, StringComparison.Ordinal));
    }
}

In your App.xaml
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
 containerRegistry.RegisterSingleton<IRegionNavigationContentLoader,ScopedRegionNavigationContentLoader>();

}

protected override void ConfigureDefaultRegionBehaviors(IRegionBehaviorFactory regionBehaviors)
    {
       base.ConfigureDefaultRegionBehaviors(regionBehaviors);

       regionBehaviors.AddIfMissing(RegionManagerAwareBehaviour.BehaviorKey, typeof(RegionManagerAwareBehaviour));
    }

Coming to the finish.
Now in your ViewModelB implement IRegionManagerAware and have it as a normal property
public IRegionManager RegionManager { get; set; }

Then at your ViewB implement ICreateRegionManagerScope and have it as a get property
public bool CreateRegionManagerScope => true;

Now it should work.
Again I truly recommend the videos at Pluralsight from Brian on Prism. He has a couple of videos that help a lot when you are starting with a Prism.


Q: CSRF PHP Prevention Mechanism I have read many articles about CSRF, almost all of them have the same solution which is hidden tokens, so i wrote a code to prevent CSRF and i tried hacking my own page afterwards but it didn't work, i would like to know if my code is CSRF bulletproof, and if there is anyway around it.
i have four pages that has forms in them so in each page i would write the following:
            if (isset($_POST['submit'])){

            // Check for CSRF token
            if ($_SESSION['token'] === $_POST['token']){

                // write to db

            }else{
                 // CSRF attack has been detected
                 die("CSRF :
1: $_SESSION[token]
 2: $_POST[token]");

            }

        }else{
            // assign CSRF prevention token
            $form_token = md5((rand(1,89412) * 256 / 4).$date.time());
            $_SESSION['token'] = $form_token;
        }
        ?>
        <form action='' method='post'>
        <input type='hidden' name='token' value='<?echo $form_token;?>'>

would this method be enough to stop attackers from using CSRF on my website ?
Thanks alot.

A: I'll show you my code for CSRF prevention:
config.php
Configuration file should be auto-loaded in every page using require or include functions.
Best practice would be to write a configuration class (I'll just write down functions in order to simplify my code).
session_start();

if(empty($_SESSION['CSRF'])){
        $_SESSION['CSRF'] = secureRandomToken();
    }

post.php
This is just an example. In every "post" page you should check if CSRF token is set. Please submit your forms with POST method! I'd also recommend you to take a look at Slim Framework or  Laravel Lumen, they provide an excellent routing system which is gonna let you to accept POST requests only on your "post.php" page very easily (they also will automatically add a CSRF token in every form).
if (!empty($_POST['CSRF'])) {
    if (!hash_equals($_SESSION['CSRF'], $_POST['CSRF'])) {
        die('CSRF detected.');
    }
}else{
    die('CSRF detected.');
}

view.php
Now you just have to put an hidden input with your CSRF session value in it.
<input type="hidden" name="CSRF" value="<?= $_SESSION['CSRF'] ?>">

I hope that this quick explanation may help you :)


Q: youku search JS API in english I need the youku (China youtube) API in English or an explanation how to use it.
This is the code from youtube I want to write with youku:
url: 'https://www.googleapis.com/youtube/v3/search',
data: {
       'part': 'snippet',
       'q': this.searchBox.val(),
       'type': 'video',
       'key': '***key***'
       },

Thank you!
Edit:
This topic was for everyone who wants to work with youku API.
I edited my question and I provided the correct answer.
You have to work with translator (no English version) and this is the correct path:
http://doc.open.youku.com/?docid=318
Please ready the Developer agreement as well:
http://doc.open.youku.com/?docid=312
Good luck.

A: EDIT: I found the correct link, and you can use the browser to translate to english.  http://doc.open.youku.com/
The closest thing I can find to help you out this this thread, which contains a link that appears to go to Youku API documentation. I cannot get that link to open however. I hope this helps.