text:
Q: Showing that $B_j$ is a cauchy sequence with respect to the operator norm Given A $\in$ $L( \mathbb{R}^n ) $ , show that $B_j$ is a cauchy sequence with respect to the operator norm where $$B_j = \sum_{r=0}^{j} \frac{A^r}{r!} $$
So far I have gotten that $|| B_m - B_n|| = || \displaystyle\sum_{r=n+1}^{m} \frac{A^r}{r!}||$ $$ \leq \sum_{r=n+1}^{m} \frac{1}{r!} ||A||^r $$
I am confused where to go from here as most examples include the fact that $||A|| \leq 1$ and/or don't include $r!$ in $B_j$

A: You can further continue from your work with
$$\|B_m - B_n\| \le \sum_{r=n+1}^\infty \frac{\|A\|^r}{r!}.$$
The right-hand side converges to zero as $n \to \infty$ because the series $\sum_{r=0}^\infty \frac{\|A\|^r}{r!} = e^{\|A\|}$ is convergent. Thus you have shown $(B_n)$ is Cauchy.


text:
Q: Static Padding Between CSS Flex Items I am trying to create a flexible layout in CSS that will wrap according to the client's resolution.
For example, on an ipad in landscape (1024px wide), i would like to display the following:

But on a playbook in portrait (600px wide), i would like to display the following:

I have almost everything working except the 20px margins. I cannot seem to figure out how to specify the margins for wrapped elements.
Here is my code:
HTML:

Box 1

Box 2

CSS:
.box-row-fluid {
    display: -webkit-flex;
    -webkit-flex-flow: row wrap;
}

.box-row-fluid > .col {
    -webkit-flex: 1 400px;
    background: #fff;
}

Code assumes that the browser is a valid webkit browser.
I would appreciate some help. Thank you for your time.

A: You can certainly do it like this My Fiddle (Edited background color for margin visibility)
CSS
.col:nth-child(1) {
   margin-bottom: 20px;
}

For adding a margin between 2 div horizontally you can use @media query for particular resolutions and add margin-right: 20px; for the other one
Explanation: Use :nth-child(1) because you are using class="col" for both

A: Why don't you include twitter bootstrap?
It would work with this to work then.

        Content box 1

        Content box 1

The only thing you need to include is the "grid-system" very small and works great!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I change Vuetify's primary text color? In a few places, vuetify sets text color to the "primary color" defined in its theme (eg. hilighting selected drop down menus). With my company's colors, this looks ugly. How can I set this to be different?
From what I can tell, this comes from these css rules:
.v-application.primary--text {
    color: #0064a2 !important;
    caret-color: #0064a2 !important;
}

When I change those, I can make the text color look nice. Unfortunately, they're generated by vuetify and marked as !important, so I can't seem to change them outside of the browser inspector.
I can add something like 'primary--text': 'color: #FF00FF' to the style theme, but that changes the background color, not the text color.
Here's a codepen example
I could use vuetify's themes exclusively for text, and set the rest of the element colors manually, but this doesn't seem to be their intended use. What should I do to change the text color?

A: You can add a class to the app and create a more-specific CSS rule like so (this example doesn't actually run here, but you can copy it over to your codepen):

new Vue({
  el: '#app',
  vuetify: new Vuetify({
    theme: {
      dark: true,
      themes: {
        dark: {

          // Color is applied to selected drop down item
          primary: '#0064A2',

          // Uncomment this to make things worse
          // 'primary--text': '#FF00FF'
        }
      }
    }
  }),
})
.my-app.v-application .primary--text {
    color: white !important;
}
<div id="app">
  <v-app class="my-app">
    <!--Click the dropdown to see ugly colors-->
    <v-select :items="[undefined]"/>
  </v-app>
</div>

A: Was having the same issue and Roy's answer guided me to this solution:
.my-app.v-application .primary--text {
    color: inherit !important;
}

This way, you aren't screwing up styling for other items that are using the primary color.


text:
Q: Joomla article text truncating in category list I am having an issue with Joomla whereas the text for articles being displayed in a category blog or category list is being cut off.
I would like to show articles on a page with all the text being shown and not truncated.
Here is a picture of the issue. As you can see the first article is being truncated whereas the second and third are fine as they are shorter than length.

I have tried amending the 'read-more' settings, changed the intro text size and several other options and just can't seem to sort this issue. I have also looked in the default templates for the content articles to change the size manualy but can't see where I can do this.
Is anybody able to help with this issue?
Thanks!

A: *

*Click Content->Categories

*Click Options (on Categories Page)

*Click on the Blog/Featured Layouts

*Change the "# Leading Articles" count from 1 to 10 or higher

*Change the "# Intro Articles" count to 0


text:
Q: Implementing a Generic List in Java In an effort to understand Generics in Java (and how to use them), I am trying to implement a list structure using them but have hit a wall.
Scenario:
Suppose there is some classes (we'll call them ClassA, ClassB, and ClassC) which all extend ClassBase. ClassBase is abstract, and simply contains an ID code with appropriate getters and setters. The subclasses add additional attributes, but those aren't important.
The list is designed to be able to hold a number of the above sub-classes, and manipulate the list using the common ID attribute. The list needs to be growable, and each list will only contain one type of sub-class (so a list of ClassA, ClassB, or ClassC. No mixed combinations of those).
Attempt 1:
I set up my List class like so:
ClassList<T extends ClassBase>

I then declare an array of elements as "private T list[]", and write the remainder of the class. The signatures for the element getters and setters are as follows, since those might be important:
public T get(int index)
public void set(int index, T item)

Everything appears to be good, except when I go to compile it complains about every instance where I try to recreate the underlying array (in order to shrink/grow it).
.\test\ListClass.java:10: error: generic array creation
        list = new T[0];
               ^

So after some thought and reading the error makes sense, as the compiler doesn't know what constructors are going to be available (at least that's how I understand it), so it doesn't appear that this way will work.
Attempt 2:
I keep the same class declaration, but change the internal array to "private ClassBase list[]", and then adapt my code accordingly. The main change is casting from ClassBase to T and back when necessary. So the getter for instance looks like this:
public T get(int index)
{
    return (T)(list[index]);
}

So now my code compiles and executes, but every instance where I have done the above casting now throws the infamous unchecked warning:
.\test\ListClass.java:16: warning: [unchecked] unchecked cast
        return (T)(list[index]);
                  ^

I can see why the warning is appearing, but at the same time the ListClass controls all means of accessing and manipulating the list, so I can guarantee that only elements of type T are placed in there.
Problem:
I suppose I could suppress the warnings. But I am of the belief that they are there for a reason and would prefer to get rid of them the proper way. The problem is I can't work out what the 'proper' way is (or whether infact suppressing the error is the proper way in this case).
So that's my question. What is wrong with my design, and how do I fix it?
Thanks in advance.
Note:
Before anyone tells me to use one of the existing generics and stop reinventing the wheel, that's not the point. My aim isn't to recreate a replacement for the generic lists, it is to understand generics, and a list like above is about the best example I can think of which clearly shows how they work.

A: The unchecked cast warning is one of the most problematic, annoying, and ultimately useless warnings issued by java.  I say "ultimately useless" instead of just plain "useless" because it is not entirely without merit, it is good to know that you have an iffy conversion somewhere, but it just so turns out that if you do any work whatsoever with generics in java, you will want to add @SuppressWarnings("unchecked") as a macro to your keyboard, that's how often you will have to be suppressing this warning.
Essentially, the value of the unchecked warning is that all your iffy conversions will be easily identifiable in your source code because of the @SuppressWarnings("unchecked") statements attached to them.
So, there is nothing wrong with suppressing the unchecked warnings, as long as you know what you are doing.  If you later come across a class cast exception at runtime, you will know that the cause of the problem is probably in the nearest @SuppressWarnings("unchecked") statement.
Just be sure whenever possible to suppress unchecked warnings at the statement level, instead of at the function or at the class level. For some weird reason, java will not allow this:
@SuppressWarnings("unchecked")
return (T)x;

so this might tempt you to suppress the warning at the function level and be done with it.  However, this will work:
@SuppressWarnings("unchecked")
T temp = (T)x;
return temp;

This way, the warning is localized to the exact statement that contains the iffy conversion, so you know precisely where every single iffy conversion is.  If you suppress at the function or at the class level, then iffy conversions could be anywhere, you would not know.
That having been said, another very good option that you have is to abandon the idea of creating and manipulating your own array of generic objects, and have your home-grown list class contain Java's ArrayList<T> instead.  This class exists precisely in order to encapsulate generic arrays, and as Michael Borgwardt has already stated, if you look at its source code, you will see that it contains an array of java.lang.Object, and that it is choke full of @SuppressWarnings("unchecked") clauses.  The benefit of using it is that it has been thoroughly tested, so all these conversions are known to be good, so you can't go wrong with it.

A: The only working solution is to suppress the warnings. That's what the existing generic collections also do.
So it doesn't mean there's anything wrong with your design - if there is anything wrong, it's with the design of Java generics (which had to make some compromises to achieve downwards compatibility).

A: It is a sort of catch 22, I agree.  However if you know that only instances of type T are added to the list, then you can surpress the warning without repercussions.  The compiler isn't intelligent enough to derive this information on its own.
However, also know that should you create another method that allows the insertion of instances of type ClassBase, the compiler will let you do it, and the warning that you surpressed would be warning you exactly of this type of problem and will cause a ClassCastException for types that are not T, so be mindful of this fact!


text:
Q: unknown RT error message I'm trying to debug a script that's trying to talk to RT (Request Tracker) and I'm getting the following output:
RT/3.6.6 409 Syntax Error

# Syntax Error

>>ARRAY(0x2b3495f37750)

I have no idea what this error means in the context of RT given the astounding lack of detail making it difficult to debug.  Here's the associated code for a little context, it's a script trying to create a ticket.
import requests

def combDicts(dicts):
    out = {}
    for d in dicts:
        out.update(d)
    return out

operPath = 'ticket/new'
credentials = {'user': 'myuser', 'pass': 'mypassword'}
content = {
    'content': {
        'id': 'ticket/new',
        'Subject': 'Python Script Test',
        'Queue': 'General - unassigned',
    }
}
r = requests.post('https://rt.hdms.com/REST/1.0/' + operPath, params=combDicts((credentials, content)), verify = False)
print r.text

If I comment out all but the Queue line of the content dict the error changes to:
RT/3.6.6 409 Syntax Error

# Syntax Error

>> Queue

The crux of my question is this: Does anyone know what this error means or know where I can find documentation on what all the RT errors are and what could cause them?

A: You'll find much more information in the logs on the RT server itself, especially if you up the log level to debug. You might have better luck using one of the python libraries available for calling RT. However, the version of RT you're running is fairly old, released in Jan. 2008. You may have trouble using current libraries with an old version of RT.


text:
Q: Nested React Router V6 Wildcard issue Backstory: Looking to setup nested routes that match on a wildcard for my /items, /item, /service, /services routes.
Issue: Routes are not matching correctly when using wildcard on react-router-dom V6.
Console Warnings:

You rendered descendant <Routes> (or called useRoutes()) at "/"
(under <Route path="/">) but the parent route path has no trailing
"*". This means if you navigate deeper, the parent won't match anymore
and therefore the child routes will never render.
Please change the parent <Route path="/"> to <Route path="*">.

Code example:
ParentNavigation.jsx
const ParentNavigation: React.FC<> = (props) => {

    const defaultRoutes = [
        { path: '*', element: <Navigate to="/404" /> },
        { path: '/', element: <Home />, index: true },
        { path: '/product/:id/*', element: <ProductPage /> },
        { path: '/products/*', element: <ProductsPage /> },
        { path: '/item/:id/*', element: <ItemPage /> },
        { path: '/items/*', element: <ItemsPage /> },
        { path: '/service/:id/*', element: <ServicePage /> },
        { path: '/services/*', element: <ServicesPage /> },
        { path: '/404', element: <ErrorPage /> }
    ];

    const mainRoutes = {
        path: '/',
        element: <App />,
        children: [...defaultRoutes, ...routes]
    };

    const routing = useRoutes([mainRoutes]);

    return routing;
};

NestedComponent.jsx
const SidePanelRouter = (props) => {
    let location = useLocation();
    const isOpen = location.pathname.includes('/recommendations');
    return isOpen && <SidePanel>
        <>
            <Routes>
                <Route path="/*/recommendations" element={<Recommendations />} />
                <Route path="/*/recommendations/edit" element={<RecommendationEdit />} />
                <Route path="/*/recommendations/list" element={<RecommendationList />} />
            </Routes>
        </>
    </SidePanel>;
};


text:
Q: Spark streaming maxRate is violated sometimes I have a simple Spark Streaming process (1.6.1) which receives data from Azure Event Hub. I am experimenting with back pressure and maxRate settings. This is my configuration:
spark.streaming.backpressure.enabled = true
spark.streaming.backpressure.pid.minRate = 900
spark.streaming.receiver.maxRate = 1000

I use two receivers, therefor per microbatch I would expect 2000 messages (in total). Most of the time this works fine (the total event count is below or equal the maxRate value). However sometimes I have spikes which violate the maxRate value.
My test case is as follows:
- send 10k events to azure event hub
- mock job/cluster downtime (no streaming job is running) 60sec delay
- start streaming job
- process events and assert events number smaller or equal to 2000

In that test I can observe that the total number of events sometime is higher than 2000, for example: 2075, 2530, 2040. It is not significantly higher and the processing is not time consuming however I would still expect the total number of events per microbatch to obey the maxRate value. Furthermore sometime the total number of events is smaller than backpressure.pid.minRate, for example: 811, 631.
Am I doing something wrong?


text:
Q: crash during protocol buffers initialization The following crash observed with my application using protocol buffers
0x00000000 in ?? ()
0x08055f43 in google::protobuf::DescriptorPool::InternalAddGeneratedFile (
encoded_file_descriptor=0xf64, size=3940) at once.h:115
0x08072b7a in google::protobuf::protobuf_AddDesc_google_2fprotobuf_2fdescrip
tor_2eproto () at google/protobuf/descriptor.pb.cc:557

A: Met the exact same crash as you described. The reason is mixed Release verion of libprotobuf.lib with Debug runtime under VC 2008. Further discussion in http://code.google.com/p/protobuf/issues/detail?id=184 .

A: Yesterday i'v met same problem.
Why it happend:
I had two .proto files with same relative path/name in different libraries (different packages):
lib1/proto/config.proto, lib2/proto/config.proto
The solution is obvious - put your .proto files in different directories and/or have unique .proto filenames.
PS: i know it's four year old question, but I hope it help to someone else.


text:
Q: SQL 2008 Set variable select statement errors Having a problem with variables in a stored procedure.
I keep getting errors:
Msg 156, Level 15, State 1, Procedure SP_ProjectData, Line 6
Incorrect syntax near the keyword 'SELECT'.
Msg 137, Level 15, State 1, Procedure SP_ProjectData, Line 6
Must declare the scalar variable "@CurrentVersion".

The second variable (@CurrentVersion) is the problem one. I initially created the procedure without that one and it was fine. Now I need to update it but it just will not accept the second variable that I am trying to set its value using a select statement.
I have been round and round using posts on here and all sorts of other sites trying "Set", "Select" playing around with the formatting along the way but have come up with nothing.
This is the complete procedure, any help greatly appreciated as ever.
  USE [ic_intranet]
    GO
    /****** Object:  StoredProcedure [dbo].[SP_ProjectData]    Script Date: 07/04/2016 12:29:06 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    ALTER PROCEDURE [dbo].[SP_ProjectData]
        @ProjectRef int,
        @CurrentVersion decimal(4, 2)

        SELECT @CurrentVersion = VersionNumber FROM t_ProjectEquipmentVersions WHERE CurrentVersion = 'true' and JobNumber = @ProjectRef

    AS

    SELECT
    t_Projects.JobNumber,
    t_Projects.JobName,
    t_Projects.ProjectType,
    t_Projects.ProjectStatus,
    t_Projects.JobCode,
    t_Projects.TargetCompleteDate,
    t_Projects.ActualFinishDate,
    t_Projects.LocationCountry,
    t_Projects.LocationTown,
    t_Projects.SoldDate,
    (SELECT SUM(ProjectGBPCost) FROM dbo.t_ProjectEquipment WHERE (JobNumber = @ProjectRef)) AS TotalValueBuy,
    (SELECT SUM(ProjectGBPRetail) FROM dbo.t_ProjectEquipment WHERE (JobNumber = @ProjectRef)) AS TotalValueSell,
    (SELECT COUNT(Ordered) FROM dbo.t_ProjectEquipment WHERE (Ordered = '1' and JobNumber = @ProjectRef) GROUP BY Ordered) AS OrderedItems,
    (SELECT SUM(ProjectGBPCost) FROM dbo.t_ProjectEquipment WHERE (Ordered = '1' and JobNumber = @ProjectRef)) AS OrderedValueBuy,
    (SELECT SUM(ProjectGBPRetail) FROM dbo.t_ProjectEquipment WHERE (Ordered = '1' and JobNumber = @ProjectRef)) AS OrderedValueSell,
    (SELECT COUNT(Ordered) FROM dbo.t_ProjectEquipment WHERE (Ordered = '0' and JobNumber = @ProjectRef) GROUP BY Ordered) AS NotOrderedItems,
    (SELECT SUM(ProjectGBPCost) FROM dbo.t_ProjectEquipment WHERE (Ordered = '0' and JobNumber = @ProjectRef)) AS NotOrderedValueBuy,
    (SELECT SUM(ProjectGBPRetail) FROM dbo.t_ProjectEquipment WHERE (Ordered = '0' and JobNumber = @ProjectRef)) AS NotOrderedValueSell,
    t_EmployeeProjectManager.Firstname AS ProjectManagerFirstname,
    t_EmployeeProjectManager.Surname AS ProjectManagerSurname,
    t_EmployeeLeadEngineer.Firstname AS LeadEngineerFirstname,
    t_EmployeeLeadEngineer.Surname AS LeadEngineerSurname,
    t_EmployeeSalesRep.Firstname AS SalesRepFirstname,
    t_EmployeeSalesRep.Surname AS SalesRepSurname,
    t_EmployeeDesigner.Firstname AS DesignerFirstname,
    t_EmployeeDesigner.Surname AS DesignerSurname
    FROM t_Projects
    LEFT JOIN t_Employee AS t_EmployeeProjectManager ON t_Projects.ProjectManager = t_EmployeeProjectManager.ID
    LEFT JOIN t_Employee AS t_EmployeeLeadEngineer ON t_Projects.LeadEngineer = t_EmployeeLeadEngineer.ID
    LEFT JOIN t_Employee AS t_EmployeeSalesRep ON t_Projects.SalesRep = t_EmployeeSalesRep.ID
    LEFT JOIN t_Employee AS t_EmployeeDesigner ON t_Projects.Designer = t_EmployeeDesigner.ID
    WHERE JobNumber = @ProjectRef

A: At first glance,
Write the Select Statement after the AS statement,
USE [ic_intranet]
    GO
    /****** Object:  StoredProcedure [dbo].[SP_ProjectData]    Script Date: 07/04/2016 12:29:06 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO

    ALTER PROCEDURE [dbo].[SP_ProjectData]
        @ProjectRef int,
        @CurrentVersion decimal(4, 2)

    AS

        SELECT @CurrentVersion = VersionNumber FROM t_ProjectEquipmentVersions WHERE CurrentVersion = 'true' and JobNumber = @ProjectRef

    SELECT
    t_Projects.JobNumber,
    t_Projects.JobName,
    t_Projects.ProjectType,
    t_Projects.ProjectStatus,
    t_Projects.JobCode,
    t_Projects.TargetCompleteDate,
    t_Projects.ActualFinishDate,
    t_Projects.LocationCountry,
    t_Projects.LocationTown,
    t_Projects.SoldDate,
    (SELECT SUM(ProjectGBPCost) FROM dbo.t_ProjectEquipment WHERE (JobNumber = @ProjectRef)) AS TotalValueBuy,
    (SELECT SUM(ProjectGBPRetail) FROM dbo.t_ProjectEquipment WHERE (JobNumber = @ProjectRef)) AS TotalValueSell,
    (SELECT COUNT(Ordered) FROM dbo.t_ProjectEquipment WHERE (Ordered = '1' and JobNumber = @ProjectRef) GROUP BY Ordered) AS OrderedItems,
    (SELECT SUM(ProjectGBPCost) FROM dbo.t_ProjectEquipment WHERE (Ordered = '1' and JobNumber = @ProjectRef)) AS OrderedValueBuy,
    (SELECT SUM(ProjectGBPRetail) FROM dbo.t_ProjectEquipment WHERE (Ordered = '1' and JobNumber = @ProjectRef)) AS OrderedValueSell,
    (SELECT COUNT(Ordered) FROM dbo.t_ProjectEquipment WHERE (Ordered = '0' and JobNumber = @ProjectRef) GROUP BY Ordered) AS NotOrderedItems,
    (SELECT SUM(ProjectGBPCost) FROM dbo.t_ProjectEquipment WHERE (Ordered = '0' and JobNumber = @ProjectRef)) AS NotOrderedValueBuy,
    (SELECT SUM(ProjectGBPRetail) FROM dbo.t_ProjectEquipment WHERE (Ordered = '0' and JobNumber = @ProjectRef)) AS NotOrderedValueSell,
    t_EmployeeProjectManager.Firstname AS ProjectManagerFirstname,
    t_EmployeeProjectManager.Surname AS ProjectManagerSurname,
    t_EmployeeLeadEngineer.Firstname AS LeadEngineerFirstname,
    t_EmployeeLeadEngineer.Surname AS LeadEngineerSurname,
    t_EmployeeSalesRep.Firstname AS SalesRepFirstname,
    t_EmployeeSalesRep.Surname AS SalesRepSurname,
    t_EmployeeDesigner.Firstname AS DesignerFirstname,
    t_EmployeeDesigner.Surname AS DesignerSurname
    FROM t_Projects
    LEFT JOIN t_Employee AS t_EmployeeProjectManager ON t_Projects.ProjectManager = t_EmployeeProjectManager.ID
    LEFT JOIN t_Employee AS t_EmployeeLeadEngineer ON t_Projects.LeadEngineer = t_EmployeeLeadEngineer.ID
    LEFT JOIN t_Employee AS t_EmployeeSalesRep ON t_Projects.SalesRep = t_EmployeeSalesRep.ID
    LEFT JOIN t_Employee AS t_EmployeeDesigner ON t_Projects.Designer = t_EmployeeDesigner.ID
    WHERE JobNumber = @ProjectRef


text:
Q: vaadin grid inline number format I am using
    NumberFormat format = DecimalFormat.getNumberInstance(Locale.GERMAN);
    format.setGroupingUsed(true);

    NumberRenderer numPointCommaRenderer = new NumberRenderer(format);
    pnGrid.getColumn("amount").setRenderer(numPointCommaRenderer);

in order to display in a vaadin grid the number "1.234,56"  but when i enter in the inline mode the number is changing with the default locale "1,234.56".
I don't want to change the default locale (English) also i don't to alter the locale of the grid.
only to alter the inline edit of the number to "1,234.56".
Any suggestions
Elias


text:
Q: Proper way to indicate code change in lstlisting [Since the question was not clear]
I have a piece of program code I would like to describe in my thesis. My problem is that the part I would like to explain is surrounded by simple code pieces not worth to describe. Now I would like to ask, if there is a possibility to have jumps in the line numbers. Further, I would like to ask if someone has experience with indicating that I left out parts of the code because they are not relevant.
\noindent
\begin{minipage}{\linewidth}
\begin{lstlisting}[caption=Function, label={lst:example}, firstnumber=1]
int complicated_function(int b){
    //I do a lot here..

    if(a < b){
       return a;
    }else{
       return b;
    }
    if(b == 0){
        printf("Error");  //Not really relevant, just error handling. How can I leave it out?
    }
return EXIT_SUCCESS;
}
\end{lstlisting}
\end{minipage}`

Thanks!

A: If you want only some lines to be discused in your paper you can easy split the listing in for example three parts, using option linerange={1-3} for the first 3 lines. If you want the real line numbers in your listing use for example option firstnumber=10 to start with line number 10.
Here comes the MWE:
\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.c}
int complicated_function(int b){
    //I do a lot here..

    if(a < b){
       return a;
    }else{
       return b;
    }
    if(b == 0){
        printf("Error");  //Not really relevant, just error handling. How can I leave it out?
    }
return EXIT_SUCCESS;
}
\end{filecontents*}

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\lstset{
  language=c,
  basicstyle=\footnotesize\ttfamily,
  tabsize=2,
  frame=single,
  numbers=left,
  numberstyle=\tiny
}

\begin{document}

We start with
\lstinputlisting[%
  caption={Function}
 ,label={lst:example}
 ,linerange={1-1}
]{\jobname.c}

Then you will find
\lstinputlisting[%
  caption={Function, Part 2}
 ,label={lst:example2}
 ,linerange={4-8}
]{\jobname.c}

And closing
\lstinputlisting[%
  caption={Function, Part 3}
 ,label={lst:example3}
 ,linerange={10-12}
 ,firstnumber=10
]{\jobname.c}

\end{document}

I used package filecontents to have one file with the program code to be discussed.


text:
Q: Projection of trace operator I want to ask if the trace operator for sobolev spaces ($\gamma$) and the projection operator related to a basis commute.
So let $u\in H^2(\Omega)$ where $\Omega$ is assumed to have $C^\infty$ boundary. The boundary condition is just to gurantee sufficient regularity. The trace operator is defined as a map
$$\gamma: H^2(\Omega)\rightarrow H^1(\partial\Omega)$$
Let $\lbrace \psi_n\rbrace_{n\in\mathbb{N}}$ be a basis for $H^2(\Omega)$. Then the projection operator ($P_M$) is defined as
$$P_Mu=\sum_{j=-M}^M c_j\psi_j.$$
Now for $v\in L^2(\Omega)$ the following is given,
$$\int_{\partial\Omega}\gamma u\gamma v=\int_\Omega f v.$$
My question is this: is the following statement correct?
$$P_M(\int_{\partial\Omega}\gamma u\gamma v)=P_M(\int_\Omega f v)\tag{**}\\\int_{\partial\Omega}\gamma (P_Mu)\gamma (P_Mv)=\int_\Omega f (P_M)v),$$
If this is incorrect can some one please help in providing details what (**) should be equal to. My eventual goal is to find $\int_{\partial\Omega}\gamma (P_Mu)\gamma (P_{M^\bot} v)$.
Thanks for any help.


text:
Q: Silverlight datagrid cell value depending on another cell value? I have a datagrid which is bound to a table. I have a field nemed Typ in the datagrid which is not bound to any field. I need to display "bag" or "bulk" in the Typ field depending on there is a "B" at the end of the ProductCode field.
<sdk:DataGrid AutoGenerateColumns="False" HorizontalAlignment="Center" Margin="77,42,91,323" Name="dgScripts" Width="577" SelectionChanged="dgScripts_SelectionChanged">
        <sdk:DataGrid.Columns>
            <sdk:DataGridTextColumn Binding="{Binding ProductCode}" Header="Prod. Code" Width="80" />
        <sdk:DataGridTextColumn Header="Type" Width="50" />
            <sdk:DataGridTextColumn Binding="{Binding MedNo}" Header="Med. Code" Width="100" />
        </sdk:DataGrid.Columns>
    </sdk:DataGrid>

How can I do this?

A: You can do this by these steps:

*

*"Type" column -> templated column

*"Type" column binding set to ProductCode

*Than use Image in "Type" columns template. This image source property should use binding with a valueconverter.

*This converter should deside whether to return "bag" or "bulk" imagesource..


text:
Q: Pycharm Not Stepping into Function I'm attempting to step through some Python code in Pycharm
checkdata = cache.get_doc_store().get_all_documents(doc_type='test'})
However, I can't seem to get Pycharm to step into this particular function. If I run it in the expression evaluator, the code executes and I get a return value, but if I try to run it in the standard debugger, Pycharm won't step into the function and I don't get a return value. Has anyone ever seen this before?

A: So this one was actually related to generator functions. The return value I was getting was a generator, which I confused for the list generator [x for x in func_call]. When we "called" the function, we simply got a generator back, but the code in the function body is not executed until we call next(), send(), etc. Which is why we couldn't step into it in Pycharm. This blog post explains generators in much better detail https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/


text:
Q: Continuity of potential function at an interior point Suppose $\Omega \subset \mathbb{R}^3$ is closed, bounded, with smooth boundary and the density $\rho: \Omega \to \mathbb{R}$ is continuous.  The potential function is
$$\phi(x) = \int_\Omega \frac{\rho(x')}{|x - x'|} dx',$$
I already showed it continuous for $x \notin \Omega$ and am trying to show it continuous for $x \in \Omega$.
My effort: I take a ball $B_\delta(x_0)$ around a fixed point $x_0$ with $|x-x_0| < \delta$ and look at
$$|\phi(x) - \phi(x_0)| \leq \left|\int_{\Omega- B_\delta(x_0)}\rho(x') \left(\frac{1}{|x-x'|} - \frac{1}{|x_0-x'|}\right) dx'\right|+ \left|\int_{ B_\delta(x_0)}\frac{\rho(x') }{|x_0-x'|} dx' \right| + \left|\int_{ B_\delta(x_0)} \frac{\rho(x')}{|x-x'|} dx' \right|$$
Since the integrand in the first integral is continuous there exists $\delta_0$ such that if $|x - x_0| < \delta_0$ then
$$\left|\int_{\Omega- B_\delta(x_0)}\rho(x') \left(\frac{1}{|x-x'|} - \frac{1}{|x_0-x'|}\right) dx'\right| < \frac{\epsilon}{3}$$
Also convergence of the potential integral means if $\delta$ is small enough then
$$\left|\int_{ B_\delta(x_0)}\frac{\rho(x') }{|x_0-x'|} dx' \right| < \frac{\epsilon}{3}$$
My question is how to show the third integral can be made $< \frac{\epsilon}{3}$ since $B_\delta(x_0)$ is not centered at $x$.

A: The Absolute continuity of the Lebesgue integral can be used here. Since the function $\rho(x)/|x-x_0|$ is integrable on the ball $B(x_0, 1)$, it follows that for every $\epsilon$ there exists $\delta>0$ such that if $E\subset B(x_0, 1)$ has measure less than $\delta$, then
$$
\int_E \frac{|\rho(x)|}{|x'-x_0|} dx' < \epsilon
$$
This argument works for both 2nd and 3rd integrals, they don't have to be treated separately.


text:
Q: Can I update an attached object using a detached but equal object? I retrieve movie data from an external API. In a first phase I will scrape each movie and insert it into my own database. In a second phase I will periodically update my database by using the API's "Changes" API which I can query to see what movies have had their information changed.
My ORM layer is Entity-Framework. The Movie class looks like this:
class Movie
{
    public virtual ICollection<Language> SpokenLanguages { get; set; }
    public virtual ICollection<Genre> Genres { get; set; }
    public virtual ICollection<Keyword> Keywords { get; set; }
}

The problem arises when I have a movie that needs to be updated: my database will think of the object being tracked and the new one that I receive from the update API call as different objects, disregarding .Equals().
This causes a problem because when I now try to update the database with the updated movie, it will insert it instead of updating the existing Movie.
I had this issue before with the languages and my solution was to search for the attached language objects, detach them from the context, move their PK to the updated object and attach that to the context. When SaveChanges() is now executed, it will essentially replace it.
This is a rather smelly approach because if I continue this approach to my Movie object, it means I'll have to detach the movie, the languages, the genres and the keywords, look up each one in the database, transfer their IDs and insert the new objects.
Is there a way to do this more elegantly? Ideally I just want to pass in the updated movie to the context and have that select the correct movie to update based on the Equals() method, update all its fields and for each complex object: use the existing record again based on its own Equals() method and insert if it doesn't exist yet.
I can skip the detaching/attaching by providing .Update() methods on each complex object which I can use in combination of retrieving all the attached objects but this will still require me to retrieve every single existing object to then update it.

A: I didn't find what I was hoping for but I did find an improvement over the existing select-detach-update-attach sequence.
The extension method AddOrUpdate(this DbSet) allows you to do exactly what I want to do: Insert if it's not there and update if it found an existing value. I didn't realize using this sooner since I've really only seen it be used in the seed() method in combination with Migrations. If there is any reason I shouldn't use this, let me know.
Something useful to note: There is an overload available which allows you to specifically select how equality should be determined. Here I could have used my TMDbId but I instead opted to simply disregard my own ID altogether and instead use a PK on TMDbId combined with DatabaseGeneratedOption.None. I use this approach on each subcollection as well, where appropriate.
Interesting part of the source:
internalSet.InternalContext.Owner.Entry(existing).CurrentValues.SetValues(entity);

which is how the data is actually updated under the hood.
All that is left is calling AddOrUpdate on each object that I want to be affected by this:
public void InsertOrUpdate(Movie movie)
{
    _context.Movies.AddOrUpdate(movie);
    _context.Languages.AddOrUpdate(movie.SpokenLanguages.ToArray());
    // Other objects/collections
    _context.SaveChanges();
}

It isn't as clean as I hoped since I have to manually specify each piece of my object that needs to be updated but it's about as close as it will get.
Related reading: https://stackoverflow.com/questions/15336248/entity-framework-5-updating-a-record

Update:
It turns out my tests weren't rigorous enough. After using this technique I noticed that while the new language was added, it wasn't connected to the movie. in the many-to-many table. This is a known but seemingly low-priority issue and hasn't been fixed as far as I know.
In the end I decided to go for the approach where I have Update(T) methods on each type and follow this sequence of events:

*

*Loop over collections in new object

*For each entry in each collection, look it up in the database

*If it exists, use the Update() method to update it with the new values

*If it doesn't exist, add it to the appropriate DbSet

*Return the attached objects and replace the collections in the root object with the collections of the attached objects

*Find and update the root object

It's a lot of manual work and it's ugly so it'll go through a few more refactorings but now my tests indicate it should work for more rigorous scenarios.

After cleaning it up further I now use this method:
private IEnumerable<T> InsertOrUpdate<T, TKey>(IEnumerable<T> entities, Func<T, TKey> idExpression) where T : class
{
    foreach (var entity in entities)
    {
        var existingEntity = _context.Set<T>().Find(idExpression(entity));
        if (existingEntity != null)
        {
            _context.Entry(existingEntity).CurrentValues.SetValues(entity);
            yield return existingEntity;
        }
        else
        {
            _context.Set<T>().Add(entity);
            yield return entity;
        }
    }
    _context.SaveChanges();
}

This allows me to call it like this and insert/update the underlying collections:
movie.Genres = new List<Genre>(InsertOrUpdate(movie.Genres, x => x.TmdbId));

Notice how I reassign the retrieved value to the original root object: now it is connected to each attached object. Updating the root object (the movie) is done the same way:
var localMovie = _context.Movies.SingleOrDefault(x => x.TmdbId == movie.TmdbId);
if (localMovie == null)
{
    _context.Movies.Add(movie);
}
else
{
    _context.Entry(localMovie).CurrentValues.SetValues(movie);
}

A: Since you are dealing with different fields id and tmbid, i suggest that updating the API to make a single and separate index of all the info like genres,languages,keywords etc... And then make a call to index and check for info rather than gathering the whole info about specific object in your Movie class.


text:
Q: .htaccess Deny from  rule being ignored Ubuntu 10.04.4 LTS
Apache 2.2.14
ISPConfig 3.0.4.2

A client of ours has an old web server that keeps crashing from what appears to be malicious bots/spiders that are probably spoofing their user agents.  I've tried just about every htaccess configuration that I can think of to try and stop these from crawling the site, but to no avail.
At this point, I'm trying to block individual IPs via .htaccess but nothing seems to work.
I have AllowOveride set to 'All' in the vhost config file:
<Directory /var/www/<this_website>
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

I have the following mods enabled:
ls -x /etc/apache2/mods-enabled/
actions.conf     actions.load        alias.conf            alias.load       auth_basic.load   auth_digest.load
authn_file.load  authz_default.load  authz_groupfile.load  authz_host.load  authz_user.load   autoindex.conf
autoindex.load   cgi.load            dav_fs.conf           dav_fs.load      dav.load          deflate.conf
deflate.load     dir.conf            dir.load              env.load         expires.load      fcgid.conf
fcgid.load       include.load        mime.conf             mime.load        negotiation.conf  negotiation.load
php5.conf        php5.load           reqtimeout.conf       reqtimeout.load  rewrite.load      ruby.load
setenvif.conf    setenvif.load       ssl.conf              ssl.load         status.conf       status.load
suexec.load      suphp.conf          suphp.load

And a snippit of the .htaccess file in the webroot:
...
order allow,deny
Allow from all
Deny from 180.76.6.45
...

I've verified that the .htaccess file is being read by adding a "Deny from All" at the bottom of the blocklist.  Upon hitting the home page with the browser, I get an Apache "Forbidden" page as would be expected.  However, while watching the access logs, I'm still seeing the following long after the .htaccess was written...
180.76.6.45 - - [15/Oct/2014:19:22:24 +0000] "GET /legacy HTTP/1.1" 403 0 "-" "Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)"

The same holds true for every other IP on the list.  Why are my "Deny from IP" directives being ignored?

A: Your IP block is working ;-)
Apache access log reports page access successes and failures.  A failure is NOT an error.  An error is when Apache cannot successfully carry out a directive, load a module, or some such error.
The return code that follows the 'request path protocol' string "GET /legacy HTTP/1.1", is 403 - which means 'forbidden', in other words, access was denied.  I don't know your log format so I cannot be certain, but the value after the '403' is probably the number of bytes returned, which is (as it should be) zero.


text:
Q: prompt cl commands from a program I am trying to design a screen that will present to the user, a list if options to execute CL commands such as WRKSBSD, WRKJOBD etc. I had assumed that executing the command from within the program would display the command screen the same way it would have, had the user pressed F4 to prompt the command parameters. But as I found out, executing the command from within a CL program without the mandatory parameters passed in results in an error. Is there any way to display the command prompt screen while executing it within a program?

A: Put a question mark in front of the command name and it will prompt.
There are also ways of making it prompt only individual parameters, but sounds like the single ? up front would do the job here.


text:
Q: How do I get compiled python(with cxFreeze) to get the current working directory as the directory where the executable is in? I am working on a mac and I am writing a game in python and pygame that needs some sound files to be present in the same directory where the source code is. The thing is it works when I run the source code through the python interpreter. It doesn't work when I try to run the executable that has been compiled by cxFreeze. I have searched the internet for solutions but found nothing.
When python is interpreted the cwd would be the directory where the source code is in. When it is compiled with cxFreeze and ran through the terminal, the cwd would change to my home directory. This messes things up because I want to make this game portable and I need the sound files to be in the same folder as the executable.
import os

# Load the sound files.
CWDPATH = os.getcwd()
BEEP1 = pygame.mixer.Sound(os.path.join(CWDPATH, 'beep1.wav'))
BEEP2 = pygame.mixer.Sound(os.path.join(CWDPATH, 'beep2.wav'))
BEEP3 = pygame.mixer.Sound(os.path.join(CWDPATH, 'beep3.wav'))
BEEP4 = pygame.mixer.Sound(os.path.join(CWDPATH, 'beep4.wav'))

This part of code is what's causing the problem. It runs smoothly when interpreted, but doesn't work when compiled with cxFreeze because os.getcwd() evaluates to the home directory. I have tried putting 'os' in 'packages' option in the cxFreeze script as well. It doesn't work and I have worked on this hours without a solution. How can I get this to work?

A: You can use sys.argv. The first element of the command line arguments is always the program itself:
import os
import sys

CWDPATH = os.path.abspath(os.path.dirname(sys.argv[0]))

A: Try using
os.path.abspath(__file__)

this would return the absolute path of the script being executed, since  you have the audio files in the same path,it should not be an issue to access them


text:
Q: Closure of a set in metric space is compact I'm trying to prove that if $X$ is a metric space, then for a set $A\subset X$, the closure $\bar A$ is compact iff for every sequence $(x_n)_{n=1}^\infty\subset A$ there exists a subsequence $(x_{n_k})_{k=1}^\infty$ that converges to some $x\in X$.
The forward direction is pretty straightforward as a particular case of the definition of compactness by B-W property.
For the reverse, let $a\equiv(x_n)_{n=1}^\infty\subset \bar A$ be some sequence. Then, if $a$ has any subsequence in $A$ we are done by assumption. Otherwise, there are at most finitely many points in $a$ that are in $A$. So there exists some subsequence which resides entirely in $\bar A \backslash A$, and also for some $N\in \mathbb N$ the $N$-tail of $a$ is in $\bar A\backslash A$.
But I don't see where this gets me. What guarantees that I can come up with a convergent subsequence? The closure of a set contains all its limit points, but why shouldn't I be able to choose a non-convergent sequence this subset? Or in $\bar A$ in general?
Other approaches such as finite open covers or being a closed subset of a compact set don't seem to be relevant here.
Thanks!

A: PART 1. Let $\bar A$ be compact and let $(x_n)_{n\geq 0}$ be  a sequence in $A.$
Let $C_0$ be a finite cover of $\bar A$ by open balls of $X$ of radius $1.$ Let $\beta_0\in C_0$ such that $\{n:x_n\in \beta_0\}$ is infinite. Let $\gamma_0=\bar {\beta_0}\cap \bar A$ .
Now recursively  suppose that $\gamma_m$ is a compact subset of $\bar A$ and that $\{n:x_n\in \gamma_m\}$ is infinite. Let $C_{m+1}$ be a finite cover of  $\gamma_m$ by open balls of $X$ of radius $2^{-(m+1)}$ and let $\beta_{m+1}\in C_{m+1}$ such that $\{n:x_n\in \beta_{m+1}\}$ is infinite. And let $\gamma_{m+1}=\bar \beta_{m+1}\cap \gamma_m.$
Now we may take a strictly increasing $f:\mathbb N_0\to \mathbb N_0$ such that $x_{f(n)}\in \gamma_n$ for every  $n.$ Now $d(x_{f(n)},x_{f(n')})<2^{-n}$ when $n<n'$, so the sequence $(x_{f(n)})_{n\geq 0}$ is a Cauchy sequence in the closed set $\gamma_0$ , so it converges to a limit point $x$.
PART 2.(Converse). Let $\bar A$ be non-compact. Let $C$ be an open cover of $\bar A$ with no finite subcover.
CASE 1.  $C$ has no countable subcover.
For each $p\in \bar A$ take $q_p\in \mathbb Q^+$ and $c_p\in C$ such that $B(p,q_p)\subset c_p.$  For $q\in \mathbb Q^+$ let $$S(q)=\{p\in \bar A: q_p=q\}.$$        Suppose that for every $q\in \mathbb Q^+$ there is a finite $T(q)\subset S(q)$ such that $\cup_{p\in T(q)}B(p,q)\supset S(q).$ Then $\cup_{q\in \mathbb Q^+}\{c_p:p\in T(q)\}$ is a countable sub-cover of $C$, contrary to hypothesis.
Therefore there exists $q_0\in \mathbb Q^+$ such that  no finite subset of $\{B(p,q_0):p\in S(q_0)\}$ covers $S(q).$
So take $p_1\in S(q_0)$ and take $p_{n+1}\in S(q_0)$ \ $\cup_{j\leq n}B(p_j,q_0).$ We now have $d(p_n,p_m)\geq q_0$ whenever $n\ne m$.
Finally take $x_n\in A$ such that $d(x_n,p_n)<q_0/4.$ Then $(x_n)_n$ is a sequence in $A$ with $d(x_n,x_m)\geq q_0/2$ whenever $n\ne m$, so it has no convergent subsequence.
CASE 2. $C$ has a countable subcover. Let $\{c_n:n\in \mathbb N\}$ be a countable subcover of $C.$  Since $C$ has no finite subcover, let $$x_n\in \bar A \  \cup_{j<n}c_j.$$ Suppose $(x_n)_n$ had a  subsequence $(x_{f(n)})_n$  converging to $x$ (with $f :\mathbb N\to \mathbb N$ strictly increasing).
We have $x\in \bar A$ so $x\in c_{n_0}$ for some $n_0.$
But then $B(x,r)\subset c_{n_0}$ for some $r>0,$ and for all but finitely many $n$ we have $x_{f(n)}\in B(x,r)$ (because $(x_{f(n)})_n$ converges to $x$).... So there exists $n$ such that $f(n)>n_0$ and $x_{f(n)}\in c_{n_0}$, contrary to $x_{f(n)}\not \in \cup_{j<f(n)}c_j.$
Therefore $(x_n)_n$ has no convergent subsequence. Finally let $y_n\in A$ with $d(x_n,y_n)<2^{-n}.$ Then $(y_n)_n$ has no convergent subsequences for if $(y_{f(n)})_n$ converged to $y$ then $(x_{f(n)})_n$ would also converge to $y$.

A: Another approach is the following: let $(x_n)_n$ be a sequence in $\bar{A}$. Then for every $n\in\mathbb{N}$, choose $y_n\in A$ such that $d(x_n,y_n)<1/n$. Then by hypothesis there is subsequence $(y_{n_k})_k$ such that $y_{n_k}\to y\in \bar{A}$. Then it's easy to show that $x_{n_k}\to y$ also, so $\bar{A}$ is compact.

A: This is a proof using the ideas of @MathNewbie and @GregMartin.
We will use the following theorem (Barry Simon, Real Analysis, Theorem 2.3.6)  (Gerald Folland, Real Analysis, comment on Theorem 4.29)

Theorem: Let $X$ be a metric space. Then, the following are equivalent:

*

*$X$ is compact

*$X$ is sequentially compact (i.e. every sequence has a convergent subsequence)

Then the question can be rephrase as follows.
$X$ is a metric space, then for a set $A\subset X$, the closure $\bar A$ is sequentially compact iff for every sequence $(x_n)_{n=1}^\infty\subset A$ there exists a subsequence $(x_{n_k})_{k=1}^\infty$ that converges to some $x\in X$.

*

*($\Rightarrow$) Let $A \subset X$ and $\{x_n\}_{n = 1}^{\infty} \subset A$.
Then, $\{x_n\}_{n = 1}^{\infty} \subset \overline{A}$ and $\overline{A}$ is sequentially compact so there exists a convergent subsequence that converges in $\overline{A} \subset X$.

*($\Leftarrow$) Let $\{x_n\}_{n = 1}^{\infty} \subset \overline{A}$.
Then, for all $n \in \mathbb{N}$, since $X$ is a metric space and $x_n \in \overline{A}$, there exist $\{y_{nk}\}_{k = 1}^{\infty} \subset A$ such that $d(y_{nk}, x_n) < \frac{1}{k}$.
By hypothesis, the sequence $\{y_{nn}\}_{n = 1}^{\infty}$ has convergent subsequence, say $\{y_{n_j n_j}\}_{j = 1}^\infty$ that converges to $y_\infty \in \overline{A} \subset X$.

Let's prove that $\{x_{n_j}\}_{j = 1}^{\infty}$ converges to $y_\infty$.
Indeed, let $\varepsilon > 0$.
Let $N_1 \in \mathbb{N}$ such that $d(y_{n_j n_j}, y_\infty) < \frac{\varepsilon}{2}$ for all $j > N_1$.
Let $N_2  \in \mathbb{N}$ such that $n_j > \left\lceil \frac{1}{\varepsilon} \right\rceil$ so $d(y_{n_j n_j}, x_{n_j}) < \frac{\varepsilon}{2}$ for all $j > N_2$.
Let $N = \max\{N_1, N_2\}$, then
$$
   d(x_{n_j}, y_\infty) \le \underbrace{d(x_{n_j}, y_{n_j n_j})}_{<\frac{\varepsilon}{2}} + \underbrace{d(y_{n_j n_j}, y_\infty)}_{\frac{\varepsilon}{2}} < \varepsilon
$$
for all $j > N$.


text:
Q: Clarification about the toString method within an ADT class This is the modified toString function within the Complex ADT class that i'm trying to implement (My doubt is only regarding this function so I havent included the private variables declared before and the other functions) :
class ComplexCart implements Complex{
  public String toString(){
    if(image == 0) return (real + "");
  }
}

Why can't we write the following?
if(imag == 0) return(real);

Why do we need to add the additional  ""  ?

A: since the return type is String, and real is integer type. alternatively you can use real.toString()

A:  public String toString(){
    if(image == 0) return (real + "");
  }

In the above code if real  is not of type String  it's compile time error.
if it is of type String.No errorrs occures.
To make real as string you are writing real + "".
Then , Immediate question is Then how it's working with + ""  ??
Here the Docs of String

The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuilder(or StringBuffer) class and its append method. String conversions are implemented through the method toString, defined by Object and inherited by all classes in Java.

As a side note:
concatenating with String is a bad idea.There are some identical and better ways to do it.
1)Integer.toString(intval);
2)String.valueOf(intval);

A: It's because you have to return a String from toString(), and presumably real is not a String. real + "" performs string concatenation (converting real to a String and concatenating it with the empty string; see JLS §15.18.1) and results in a String, which is why you can validly return it.
Note that you should consider using something like Integer.toString(real) over real + "" (see Integer.toString()).

A: Since real is int type where as toString() method expects String to return.So you need add "";
+ is String concatenation operator here.


text:
Q: cmake mutliple targets - one header only target and another an executable Based on this stackoverflow answer to a similar question (Cmake include header only target from header only target), I am creating a header only library and trying to use it in an executable.
My folder structure is below:
├── CMakeLists.txt   // root folder CMake file
├── srcs             // this is the hdr only library
│   ├── src1.hpp
│   ├── CMakeLists.txt
│   ├── src2.hpp
│   └── src3.hpp
│   └── ...
└── test             // this is the executable project
    ├── CMakeLists.txt
    └── main.cpp

Root level CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
project (MyProj CXX)

add_subdirectory(srcs)
add_subdirectory(test)

src level CMakeLists.txt (for header only library)
add_library(MyLib INTERFACE)
target_sources(MyLib  INTERFACE
  "${CMAKE_CURRENT_SOURCE_DIR}/src1.hpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/src2.hpp"
  "${CMAKE_CURRENT_SOURCE_DIR}/src3.hpp"
  )
target_include_directories(MyLib
  INTERFACE ${CMAKE_CURRENT_BINARY_DIR})
add_subdirectory(plugins)

CMake file for executable test project
add_executable(MyTest main.cpp)

target_sources(MyTest
    PRIVATE main.cpp
)

target_include_directories(MyTest PUBLIC
  $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}>)

target_link_libraries(MyTest PUBLIC MyLib)

Though this configures cmake without warnings/error, running the make fails, indicating that the executable project is unable to find the header file(s) from library.

/.../nettu2/test/main.cpp:6:10: fatal error: src1.hpp: No such
  file or directory  #include "src1.hpp"
            ^~~~~~~~~~~~~~~~ compilation terminated. test/CMakeFiles/MyTest.dir/build.make:62: recipe for target
  'test/CMakeFiles/MyTest.dir/main.cpp.o' failed make[2]: *
  [test/CMakeFiles/MyTest.dir/main.cpp.o] Error 1
  CMakeFiles/Makefile2:126: recipe for target
  'test/CMakeFiles/MyTest.dir/all' failed make[1]: *
  [test/CMakeFiles/MyTest.dir/all] Error 2 Makefile:129: recipe for
  target 'all' failed make: *** [all] Error 2

I am sure that I am missing some crucial but trivial thing here, but yet unable to figure out, what is going wrong here.  How can I get this build working?

A: You have a minor mistake in this line:
target_include_directories(MyLib
  INTERFACE ${CMAKE_CURRENT_BINARY_DIR})

The include directory you specify for MyLib expands to the build directory corresponding to srcs, i.e. it results in an invocation like
clang++ /path/to/build/test/test.cpp -I /path/to/build/srcs ...

but you want to pass the actual source directory to the preprocessor. To fix this, try
target_include_directories(MyLib
   INTERFACE ${CMAKE_CURRENT_SOURCE_DIR})


text:
Q: Sql server suddenly stopped recognizing my new columns I'm working on a stored procedure in SQL SERVER 2012.
Suddenly, my stored procedure can't compile.
it says invalid column name on every column I try to add.
But I can run queries and the columns are there
SELECT FirstName FROM dbo.Contacts

Also, I made no change to the code.

*

*I tried to reboot

*I recreated the columns

*I refreshed the intelliSense cache
No luck...
here's a part of the code
DECLARE curContact Cursor

FOR SELECT dbo.Contacts.ContactID, dbo.Contacts.FirstName, dbo.Contacts.MiddleName, dbo.Contacts.LastName, dbo.Contacts.ContactName FROM dbo.Contacts
FOR UPDATE OF  dbo.Contacts.FirstName, dbo.Contacts.MiddleName, dbo.Contacts.LastName
OPEN curContact

here's the table structure
CREATE TABLE [dbo].[Contacts](
    [ContactID] [int] NOT NULL,
    [MillID] [int] NULL,
    [ClientID] [int] NULL,
    [FirstName] [nvarchar](64) NULL,
    [MiddleName] [nvarchar](64) NULL,
    [LastName] [nvarchar](64) NULL,
    [Gender] [bit] NULL,
    [ContactName] [nvarchar](50) NULL,
    [ContactTitle] [nvarchar](50) NULL,
    [ContactPhoneNo] [nvarchar](50) NULL,
    [ContactPhoneExt] [nvarchar](50) NULL,
    [ContactFaxNo] [nvarchar](50) NULL,
    [ContactEmail] [nvarchar](50) NULL,
    [Comment] [nvarchar](max) NULL,
    [CreatedBy] [nvarchar](50) NULL,
    [CreatedDate] [datetime] NULL,
    [ModifiedBy] [nvarchar](50) NULL,
    [ModifiedDate] [datetime] NULL,
    [ContactCellNo] [nvarchar](50) NULL,
    [ContactPageNo] [nvarchar](50) NULL,
    [ContactHomeNo] [nvarchar](50) NULL,
    [ContactOtherNo] [nvarchar](50) NULL,
    [Language] [nvarchar](15) NULL,
    [CalendarQuantityEnglish] [smallint] NULL,
    [CalendarQuantityFrench] [smallint] NULL,
    [CalendarKeepBy] [nvarchar](50) NULL,
    [CalendarComment] [nvarchar](250) NULL,
    [OtherQuantityEnglish] [smallint] NULL,
    [OtherQuantityFrench] [smallint] NULL,
    [OtherKeepBy] [nvarchar](50) NULL,
    [OtherComment] [nvarchar](250) NULL,
    [Validated] [date] NULL,
    [ValidedByWho] [nvarchar](64) NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

Any idea?

A: You need to refresh SSMS Intellisense Cache (CTRL + SHIFT + R or Edit -> Intellisense -> Refresh Local Cache).


text:
Q: How to change text after button click using Bloc flutter So I'm learning basics of bloc and I wanted to know how to change a text using a button without setstate(), this whole time ive been using setstate but I would like to know how to change a text after a button click using bloc, state, event.
This is what I have so far
Main.dart
    void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
        providers: [
          BlocProvider(
            create: (_) => SecscreenBloc(),
          ),

        ],
        child: MaterialApp(
            onGenerateRoute: Routes().onGenerateRoute,
            title: 'Flutter Demo',
            theme: ThemeData(
              primarySwatch: Colors.blue,
            ),
            home: SecScreen()),
      );
  }
}

SecScreen.dart
class SecScreen extends StatefulWidget {
  const SecScreen({Key? key}) : super(key: key);

  @override
  State<SecScreen> createState() => _SecScreenState();
}

class _SecScreenState extends State<SecScreen> {
  var numm = 1;
  @override
  Widget build(BuildContext context) {
    return BlocProvider(
      create: (context) => SecscreenBloc()..add(LoadSecscreenEvent(numm)),
      child: Scaffold(
        appBar: AppBar(
          title: Text("Bloc Increment"),
        ),
        body: BlocBuilder<SecscreenBloc,SecscreenState>(
          builder: (context,state){
            if(state is SecScreenLoadedState){
              return Column(
                children: [
                  Text("Activity:   ${state.number}"),
                  SizedBox(height: 30),
                  ElevatedButton(
                    onPressed: () => BlocProvider.of<SecscreenBloc>(context).add(LoadSecscreenEvent(
                      numm
                    )),
                    child: Icon(Icons.add),
                  ),
                ],
              );
            }
            return Container(
              color: Colors.red,
            );
          }
        ),
      ),
    );
  }
}

SecScreen_event.dart
abstract class SecscreenEvent extends Equatable {
  const SecscreenEvent();
}
class LoadSecscreenEvent extends SecscreenEvent{
  final int number;

  LoadSecscreenEvent(this.number);
  @override
  List<Object?> get props => [number];
}

SecScreen_state.dart
        part of 'secscreen_bloc.dart';

abstract class SecscreenState extends Equatable {
  const SecscreenState();
}

class SecscreenInitial extends SecscreenState {
  @override
  List<Object> get props => [];
}

class SecScreenLoadedState extends SecscreenState{

  final int number;
  SecScreenLoadedState(this.number);

  @override
  List<Object?> get props => [number];
}

secscreen_bloc.dart
class SecscreenBloc extends Bloc<SecscreenEvent, SecscreenState> {
  SecscreenBloc() : super(SecscreenInitial()) {
    on<LoadSecscreenEvent>((event, emit) {
      if (event is LoadSecscreenEvent){
        emit(SecScreenLoadedState(event.number + 1));
      }
    });
  }
}

I've been stuck at this for an embarssingly long time, would appreciate some help!

A: actually it is changed every time you press but every time the value gone to the bloc 1 and back 2 so you did not see the effection
just change the following line
onPressed: () => BlocProvider.of<SecscreenBloc>(context).add(LoadSecscreenEvent(
                  numm
                )),

to this one :
 onPressed: () => BlocProvider.of<SecscreenBloc>(context)
                  .add(LoadSecscreenEvent(state.number)),


text:
Q: How to make a simple magnifier in C# I followed the following in post on"Creating a screen magnifier".
Therefore I have this code.
It is not copy & pasted from the post. I have also added a timer so the form is not blank.
However I have found some problems.

*

*It doesn't zoom in very much. I would like to have a larger zoom. An adjustable zoom setting will be optimal, but I can make that myself if I know how to zoom in more.

*The center of the form is not always the tip of the cursor like I want it would be. Is there anyway I can Fix this?

Here is the code I have got now.
Graphics g;
Bitmap bmp;
private void Timer1_Tick(object sender, EventArgs e)
{
    bmp = new Bitmap(250, 200);
    g = this.CreateGraphics();
    g = Graphics.FromImage(bmp);
    g.CopyFromScreen(MousePosition.X , MousePosition.Y , 0, 0, new Size(300, 300));
    pictureBox1.Image = bmp;
}

The results seem to be exactly the same to this software that I found during my research.the link, It takes you to a Japanese webpage.

A: You're going to have to play around with the various numbers in the example in order to see what effect they have on the output. It'll help to turn them into variables so you can play with them more easily. Here is a good start, no promises that it works, but it'll give you a good place to start experimenting until you get what you want.
Graphics g;
Bitmap bmp;
private void Timer1_Tick(object sender, EventArgs e)
{
    var endWidth = 300;
    var endHeight = 300;

    var scaleFactor = 2; //perhaps get this value from a const, or an on screen slider

    var startWidth = endWidth / scaleFactor;
    var startHeight = endHeight / scaleFactor;

    bmp = new Bitmap(startWidth, startHeight);

    g = this.CreateGraphics();
    g = Graphics.FromImage(bmp);

    var xPos = Math.Max(0, MousePosition.X - (startWidth/2)); // divide by two in order to center
    var yPos = Math.Max(0, MousePosition.Y - (startHeight/2));

    g.CopyFromScreen(xPos, yPos, 0, 0, new Size(endWidth, endWidth));
    pictureBox1.Image = bmp;
}


text:
Q: Python Numpy Matrix Apply Element Row Column Entry Wise Function I want to apply a function on every (i,j) entry of a NumPy matrix. But I want to use the values i and j. As an example, given vectors A and B, and an abstract function f, I want to do the following:
for i in range(I):
    for j in range(J):
        M[i,j] = f(A[i],B[j])

Instead of the above can i do something like the following:
g = lambda (i,j): f(A[i],B[j])
apply(M, g)

Just trying to vectorize the for loops.
Thanks!

A: It depends on the function
f = lambda x, y: x ** 2 + y

np.random.seed([3,1415])
A = np.random.rand(10)
B = np.random.rand(10)
M = np.empty_like(A)
M.fill(np.nan)

slc = np.array([3, 5, 6, 7])

Then doing what you proposed
M[slc] = f(A[slc], B[slc])

M

array([        nan,         nan,         nan,  1.14332569,         nan,
        0.11791531,  0.86916307,  0.86854943,         nan,         nan])


text:
Q: wooden, golden, oaken - Genitive? A few nouns can be transformed into an adjective meaning "made of that noun (also: being like that noun)" by adding -en.

golden, wooden, oaken, stonen

*

*Are those remnants of an old noun inflection of the Genitive case?

*If so are there other remnants of that?

*Would it be possible to interpret "the maiden gown" as such a Genitive?

A: In most cases, they are not.  English has at least a half-dozen completely different -en suffixes.
The one you are thinking of is the one that the OED says is

added to noun-stems to form adjs. with sense 'pertaining to, of the nature of'.
  In Teut. the adjs. so formed chiefly indicate the material of which a thing is composed. Of the many words of this formation which existed in OE. scarcely any survive in mod. use; but the suffix was extensively applied in ME. to form new derivatives. Some of these took the place of OE. words, from which they formally differ only by the absence of umlaut; compare OE. gylden with mod.Eng. golden, OE. stǽnen (early ME. stenen) with ME. and dial. stonen, made of stone. From 16th c. onwards there has been in literary English a growing tendency to discard these adjs. for the attrib. use of the sb., as in 'a gold watch'; hence many of them have become wholly obs., and others (as golden, silvern) are seldom used except metaphorically, or with rhetorical emphasis. It is only in a few cases (e.g. wooden, woollen, earthen, wheaten) that these words are still familiarly used in their lit. sense.

However, there are quite a few other -en suffixes, none of which are really productive any longer:

*

*Create diminutives like chicken, kitten, maiden.

*Create feminines like vixen.

*Create plurals like oxen, brethren, children, kine.

*Create verbs from adjectives, like darken, deepen, harden, madden, moisten, widen.  This one is moderately productive insofar as words like lengthen, strengthen, hearten are of relatively recent vintage.

*Create past participles like broken, spoken, sunken.


text:
Q: How do I write from my fastcgi client to IIS express? I have C# code that works fine using a socket. Now I'm trying to get it to work with IIS express and it appears to only support named pipes. After some time googling the only answer I found was read the data via stdin. That works. I thought writing to stdout would be how to communicate but it doesn't appear to work. In C# it doesn't appear I can write to stdin so I'm pretty confused at why IIS doesn't seem to receive my data.

Judging from this page it appears I can write to stdin which is a bit hard to believe
HRESULT SendReceive( bool fSend, PBYTE pBuffer, DWORD dwSize )
{
    BOOL fRet  = FALSE;
    DWORD dwLastError = 0;
    DWORD nNumberOfBytesRead = 0;

    if( fSend == TRUE )
    {
        fRet = WriteFile( hStdin, pBuffer, dwSize, &nNumberOfBytesRead, NULL );
    }
    else
    {
        fRet = ReadFile( hStdin, pBuffer, dwSize, &nNumberOfBytesRead, NULL );
    }

    if(!fRet)
    {
        dwLastError = GetLastError();
    }

    return HRESULT_FROM_WIN32( dwLastError );
}


text:
Q: Azure Devops BUild scripts Are Restore Build and Test Required In Azure Devops for a .Net core application.
I have three steps
dotnet restore
dotnet build
dotnet test

But if I simply run dotnet test that forces a restore and build. Is there any reason to have the first two steps?

A: You can use them as follows:
dotnet restore
dotnet build --no-restore
dotnet test --no-build

In this way, you will speed up your build as it can use result of the previous command.
This is default behavior so you don't need to always run all commands to run dotent test for instance. It is convinient and still possible to opt-out from thah behavior.


text:
Q: Action bar not showing text and icons on pre Lollipop devices So my app is almost done. I have Xperia Z1 which runs Android Lollipop and everything looks fine on it.
Today I sent APK file to my friend who have Xperia T which runs on Android 4.3
He said that everything runs perfect, except actionbar is not showing text or icons. It shows text and icons only on activities that have ListViews.
I don't even know what code to past here.. So if anyone could help I would be thankfull. And please write down what code do you want me to copy.
This is how activites look like:
public class BlaBlaBla extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_programi_specijalizacija_ruke);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

and styles
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="elevation">0dp</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

    </style>

    <style name="NavigationDrawerStyle">
        <item name="android:textSize">14sp</item><!-- text size in menu-->
        <item name="android:background">#f2f2f2</item>
        <item name="android:listPreferredItemHeightSmall">36dp</item><!-- item size in menu-->
    </style>

    <style name="AppTheme.BrandedLaunch" parent="AppTheme">
        <item name="android:windowBackground">@drawable/branded_logo</item>
    </style>

    <style name="Theme.MyApp.ActionBar" parent="style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="elevation">0dp</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="elevation">0dp</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
        <item name="elevation">0dp</item>
        <item name="android:windowContentOverlay">@null</item>
        />
    </style>

    <style name="FullscreenTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
    </style>

    <style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
        <item name="android:background">@color/black_overlay</item>
    </style>

</resources>

styles v21
<resources>>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="android:elevation">0dp</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
    </style>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

        <item name="elevation">0dp</item>

        <item name="android:windowContentOverlay">@null</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:navigationBarColor">@color/black</item>

    </style>
</resources>

styles v19
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="elevation">0dp</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>

    </style>

    <style name="NavigationDrawerStyle">
        <item name="android:textSize">14sp</item><!-- text size in menu-->
        <item name="android:background">#f2f2f2</item>
        <item name="android:listPreferredItemHeightSmall">36dp</item><!-- item size in menu-->
    </style>

    <style name="AppTheme.BrandedLaunch" parent="AppTheme">
        <item name="android:windowBackground">@drawable/branded_logo</item>
    </style>

    <style name="Theme.MyApp.ActionBar" parent="style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
        <item name="elevation">0dp</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar">
        <item name="elevation">0dp</item>
        <item name="android:windowContentOverlay">@null</item>
    </style>

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light">
        <item name="elevation">0dp</item>
        <item name="android:windowContentOverlay">@null</item>
        />
    </style>

    <style name="FullscreenTheme" parent="AppTheme">
        <item name="android:actionBarStyle">@style/FullscreenActionBarStyle</item>
        <item name="android:windowActionBarOverlay">true</item>
        <item name="android:windowBackground">@null</item>
        <item name="metaButtonBarStyle">?android:attr/buttonBarStyle</item>
        <item name="metaButtonBarButtonStyle">?android:attr/buttonBarButtonStyle</item>
    </style>

    <style name="FullscreenActionBarStyle" parent="Widget.AppCompat.ActionBar">
        <item name="android:background">@color/black_overlay</item>
    </style>

</resources>

And in AndroidManifest all activities have this:
 android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />


text:
Q: visual c++ an unhandled exception of type 'System.IndexOutOfRangeException' occurred I am trying to transform my C# implementation of Levenstein algorithm into Visual C++ and I am facing this error message
An unhandled exception of type 'System.IndexOutOfRangeException' occurred

The original fully working C# code is
public static int Compute(string s, string t)
{
    int n = s.Length;
    int m = t.Length;
    int[,] d = new int[n + 1, m + 1];

    // Step 1
    if (n == 0)
    {
        return m;
    }

    if (m == 0)
    {
        return n;
    }

    // Step 2
    for (int i = 0; i <= n; d[i, 0] = i++)
    {
    }

    for (int j = 0; j <= m; d[0, j] = j++)
    {
    }

    // Step 3
    for (int i = 1; i <= n; i++)
    {
        //Step 4
        for (int j = 1; j <= m; j++)
        {
            // Step 5
            int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

            // Step 6
            d[i, j] = Math.Min(
                Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
                d[i - 1, j - 1] + cost);
        }
    }
    // Step 7
    return d[n, m];
}

Visual C++ code that produces IndexOutOfRangeException is this
int Compute(String^ s, String^ t)
{
    int n = s->Length;
    int m = t->Length;

    array<int,2>^ d = gcnew array<int,2>(n+1 , m+1); //int[,] d = new int[n + 1, m + 1];

    // Step 1
    if (n == 0)
    {
       return m;
    }

    if (m == 0)
    {
        return n;
    }

    // Step 2
    for (int i = 0; i <= n; d[i, 0] = i++)
    {
    }

    for (int j = 0; j <= m; d[0, j] = j++)
    {
    }

    // Step 3
    for (int i = 1; i <= n; i++)
    {
        //Step 4
        for (int j = 1; j <= m; j++)
        {
        // Step 5
        int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

        // Step 6
        d[i, j] = Math::Min(
            Math::Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
            d[i - 1, j - 1] + cost);
        }
    }
    // Step 7
    return d[n, m];
}

Is there anything wrong with my array declaration in Visual C++?

A: This exception occurs because of accessing the index more than its limit.
e.g. limit is n and you are using n+1 th element of an array.
check the value of i and j does it exceeds or and m+1  print the values of i and j so that you can find in which iteration the value exceeds limit.

A: I soved it , I used vectors instead or array
my 2D array implementation was not corrected , here is the correct implementation in visual C++
        int Lev(String^ s, String^ t)
    {
        int n = s->Length;
        int m = t->Length;

        vector<vector<int> > d(n+1,vector<int>(m+1));
        // Step 1
        if (n == 0)
        {
            return m;
        }

        if (m == 0)
        {
            return n;
        }

        // Step 2
        for (int i = 0; i <= n; d[i][0] = i++)
        {
        }

        for (int j = 0; j <= m; d[0][j] = j++)
        {
        }

        // Step 3
        for (int i = 1; i <= n; i++)
        {
            //Step 4
            for (int j = 1; j <= m; j++)
            {
            // Step 5
            int cost = (t[j - 1] == s[i - 1]) ? 0 : 1;

            // Step 6
            d[i][j] = Math::Min(
                Math::Min(d[i - 1][j] + 1, d[i][j - 1] + 1),
                d[i - 1][j - 1] + cost);
            }
        }
        // Step 7

        return d[n][m];
        }


text:
Q: How to make objects look like they're coming towards you when I place them in stationary postions? Or have ball land on moving platform? I'm trying to create a ball hop game where the ball has to jump from one platform to another. However, I'm struggling with having the ball land on the platform and I think it might be because the platform itself is moving rather than the camera/background. Does anyone know a way I could move the camera, or a solution to the ball landing on the platform even if the platform is moving?
This is my code now.

let gravity = 1.5;
class Ball{
  constructor(){
    this.x = 0;
    this.y= 200;
    this.d = 30;
    // constant velocity of the ball
    this.v = 0.001;
    this.xg = 0;
    this.yg = 0;
  }

  draw() {
    // stroke(0, 255, 255);
    ellipse(this.x, this.y, this.d);
  }

  update() {
    this.draw();
    this.y += this.yg;
    // ensures that ball doesnt go past screen
    if (this.y + this.d + this.yg <= windowHeight) {
      this.yg += gravity;
    }
  }
}
class Platform{
  constructor({x,y}){
    this.x = x;
    this.y= y;
    this.w = 30;
    this.h = 30;
    this.s = 1;
  }

  draw(){
    push();
    rectMode(CENTER);
    rotateX(1.45);
    rect(this.x,this.y,this.w,this.h);
    pop();

  }

  move(){
    this.y = this.y + this.s
    this.s = this.s + 0.0001
  }
}

let ball;
let plat;
let scrollOffset = 0;
function setup(){
  createCanvas(710, 400, WEBGL);

  ball = new Ball();

  plat = [
    (new Platform({x:0,y:200})),
    (new Platform({x:50,y:100})),
    (new Platform({x:0,y:0})),
    (new Platform({x:-50,y:-100})),
    (new Platform({x:0,y:-200})),
     ];
}

function draw(){
  background(255);

  ball.update();
  plat.forEach((plat) => {
    plat.draw();
    plat.move();
  });

  plat.forEach((plat) => {
      if (
        ball.y + ball.d <= plat.y &&
        ball.y + ball.d + ball.yg >= plat.y &&
        ball.x + ball.d >= plat.x &&
        ball.x <= plat.x + plat.w
      ) {
        ball.yg = 0;
      }
    });

}

function keyPressed() {
  if (keyCode === UP_ARROW) {
    ball.yg -= 20;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.5.0/p5.min.js"></script>


text:
Q: Symbolizing File Geodatabase feature class with Layer File created from AutoCAD drawing? I received an autocad drawing file which I converted into feature classes with the CAD to Geodatabase tool.
I would like to symbolize the exported data in ArcMap the same way it was symbolized in the input drawing file I received.
I visualized the drawing file in ArcMap and saved the "Drawing layers" Layer files as per usual but I am unable to import this symbology into the exported layer properties.
When I import the saved layer files, the resulting "Import Symbology Matching Dialog" correctly matches all 3 fields (Linetype, Colo, LineWt) but clicking OK doesn't do anything - dialog disappears and symbology remains unchanged.
Alternatively, when I load the layer file itself, it is linked with the DWG and source can only be changed for the CAD Feature Class type.
How can i symbolize my exported data the same way as the original DWG is shown in ArcMap.


text:
Q: Linear Algebra Done Right solution problem Could you please explain me more step by step the solution to problem 5 in the link? I cannot understand the logic flow behind it. For example, why for $(a1, a2,\dots, a_m)$ there is $a_i \ne 0$ and not $a_1 = 1$ as stated in the problem?
Thank you for help.

A: You want to show that $a_1$ can be made to either one or zero be picking the right base, besides other stuff.
If all $a_i=0$, you are done.
If there is one $a_i\neq 0$, you can use the base transformation shown in the proof to create a new base with $(a_1,a_2,a_3,...) = (1,0,0,...)$.


text:
Q: Color thresholding of red rimmed traffic signs I want to detect all red color rimmed traffic signs (Triangular and Circular). The algorithm has to be efficient and robust to work in real world situations, so i decided to use HSV space since it is light invariant.
I came across this question of detecting red objects and the answer was to use this value ranges for HSV: The code is in C++:
inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);

Mat1b mask = mask1 | mask2;

Since I am using Java's  OpenCV I tried that, but I found out it is not possible to do a Bitwise OR Operation.
So I tried to implement it manually instead of using OpenCV. I also tried same red color value ranges that is provided and sadly the results were horrible:
Here is my code
Mat hsv = new Mat();
Mat rgb = Highgui.imread(scene, Highgui.CV_LOAD_IMAGE_COLOR);
Imgproc.cvtColor(rgb, hsv, Imgproc.COLOR_RGB2HSV);
Mat thresh = new Mat(hsv.size(), CvType.CV_8UC1);

for(int x=0;x<hsv.rows();x++){
    for(int y=0;y<hsv.cols();y++)
    {
        double[] data = hsv.get(x,y);

        double H = data[0];
        double S = data[1];
        double V = data[2];
        if((( 0.0>=H && H<=10.0) && (70.0>=S && S<=255.0) && (50.0>=V && V<=255.0)) || (( 170.0>=H && H<=180.0) && (70.0>=S && S<=255.0) && (50.0>=V && V<=255.0)) ) {

            thresh.put(x,y, 255);
        }
        else
        {
            thresh.put(x,y, 0);
        }
    }
}

Here is the results before and after thresholding

Can someone provide me with right values?

A: The crucial mistake is right in the beginning:
Mat rgb = Highgui.imread(scene, Highgui.CV_LOAD_IMAGE_COLOR);
Imgproc.cvtColor(rgb, hsv, Imgproc.COLOR_RGB2HSV);

The OpenCV C++ API reference is generally the most complete and detailed, so it never hurts to refer to it. If you look at cv::imread you will notice the following note:

In the case of color images, the decoded images will have the channels stored in B G R order.

However, in your code you treat the image as RGB, i.e. swapping blue and red. This is fatal for your algorithm -- you're looking for red things, but anything that was red is actually blue.
The fix is simple -- rename rgb to bgr (to avoid misleading variable names) and change the conversion code to Imgproc.COLOR_BGR2HSV.
I believe your earlier problems with bitwise_or were just another symptom of this mistake. (I don't really see a reason why it wouldn't work).
See the following example (using OpenCV 3.4.0):
import org.opencv.core.Mat;
import org.opencv.core.Scalar;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.Core;

public class test
{
    public static void main(String[] args)
    {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);

        Mat image = Imgcodecs.imread("test.jpg", Imgcodecs.CV_LOAD_IMAGE_COLOR);
        if ((image == null) || image.empty()) {
            System.out.println("Failed to load input image.");
            System.exit(-1);
        }

        Mat image_hsv = new Mat();
        Imgproc.cvtColor(image, image_hsv, Imgproc.COLOR_BGR2HSV);

        Mat mask1 = new Mat();
        Mat mask2 = new Mat();
        Core.inRange(image_hsv, new Scalar(0, 70, 50), new Scalar(10, 255, 255), mask1);
        Core.inRange(image_hsv, new Scalar(170, 70, 50), new Scalar(180, 255, 255), mask2);

        Mat mask_combined = new Mat();
        Core.bitwise_or(mask1, mask2, mask_combined);

        Mat image_masked = new Mat();
        Core.bitwise_and(image, image, image_masked, mask_combined);

        Imgcodecs.imwrite("test-mask.jpg", mask_combined);
        Imgcodecs.imwrite("test-masked.jpg", image_masked);

        System.out.println("Done!");
    }
}

Which produces the following combined mask from your sample input image:

If we use this mask on the original image, we can see we really do get the red bits:

A: I have learned OpenCV for C++/Python, and I'm learning OpenCV for Java these days, and find this question is a good practice for pixel loop.
I'm use OpenCV 4.0.0-pre, so some functions maybe in other modules/packages/headers...

As @Dan Mašek Suggests, you should convert the image using COLOR_BGR2HSV. Except this, I also find that you have wrote the wrong hsv ranges.
For this code in C++:
inRange(hsv, Scalar(0, 70, 50), Scalar(10, 255, 255), mask1);
inRange(hsv, Scalar(170, 70, 50), Scalar(180, 255, 255), mask2);

Mat1b mask = mask1 | mask2;

Your range condition in Java:
(( 0.0>=H && H<=10.0) && (70.0>=S && S<=255.0) && (50.0>=V && V<=255.0)) ||
(( 170.0>=H && H<=180.0) && (70.0>=S && S<=255.0) && (50.0>=V && V<=255.0))

It should be:
(( 0.0<=H && H<=10.0) && (70.0<=S && S<=255.0) && (50.0<=V && V<=255.0)) ||
(( 170.0<=H && H<=180.0) && (70.0<=S && S<=255.0) && (50.0<=V && V<=255.0))

Or this:
///!(1) Create mask by loop with condition
(( 0.0<=H && H<=10.0) || ( 170.0<=H && H<=180.0)) && (70.0<=S && S<=255.0) && (50.0<=V && V<=255.0)

Or this:
///!(2) Create mask by calling API
Mat mask1 = new Mat();
Mat mask2 = new Mat();
Core.inRange(hsv, new Scalar(0, 70, 50), new Scalar(10, 255, 255), mask1);
Core.inRange(hsv, new Scalar(170, 70, 50), new Scalar(180, 255, 255), mask2);

Mat mask= new Mat();
Core.bitwise_or(mask1, mask2, mask);

In Java:
//! 2018.05.08 18:50:59 CST
//! 2018.05.08 20:53:48 CST
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;
import org.opencv.core.*;
import java.util.*;

public class test
{
    public static void main(String[] args)
    {
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
        Mat img = Imgcodecs.imread("test.jpg", Imgcodecs.CV_LOAD_IMAGE_COLOR);
        if ((img == null) || img.empty()) {
            System.out.println("Failed to load input img.");
            System.exit(-1);

        }
        Mat hsv = new Mat();
        Imgproc.cvtColor(img, hsv, Imgproc.COLOR_BGR2HSV);

        ///! (1) Create the mask by loop
        Mat mask = new Mat(hsv.size(), CvType.CV_8UC1, new Scalar(0,0,0));
        for(int i=0;i<hsv.rows();++i){
            for(int j=0;j<hsv.cols();++j){
                double[] data = hsv.get(i,j);
                double H = data[0];
                double S = data[1];
                double V = data[2];
                //mask[np.where(((h<10) | ((h>=170) & (h<=180)) ) & ((s>=70) & (s<=255)) & ((v>=50) & (v<=255)) )] = 255
                if((( 0.0<=H && H<=10.0) || ( 170.0<=H && H<=180.0)) && (70.0<=S && S<=255.0) && (50.0<=V && V<=255.0)) {
                    mask.put(i,j, 255);
                }
            }
        }

        ///!(2) Create mask by calling API
        Mat mask1 = new Mat();
        Mat mask2 = new Mat();
        Core.inRange(hsv, new Scalar(0, 70, 50), new Scalar(10, 255, 255), mask1);
        Core.inRange(hsv, new Scalar(170, 70, 50), new Scalar(180, 255, 255), mask2);

        Mat mask_combined = new Mat();
        Core.bitwise_or(mask1, mask2, mask_combined);

        ///! Get the masked
        Mat masked = new Mat();
        Core.bitwise_and(img, img, masked, mask);
        //Core.bitwise_and(img, img, masked, mask_combined);

        Imgcodecs.imwrite("test_mask.jpg", mask);
        Imgcodecs.imwrite("test_masked.jpg", masked);
    }
}

In Python, it can be wrote as:
import cv2
import numpy as np

img = cv2.imread("test.jpg")
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h,s,v = cv2.split(hsv)

## (1) by hand
mask = np.zeros_like(s)
mask[np.where(((h<10) | ((h>=170) & (h<=180)) ) & ((s>=70) & (s<=255)) & ((v>=50) & (v<=255)) )] = 255

## (2) call api
mask1 = cv2.inRange(hsv, (0, 70, 50), (10, 255, 255))
mask2 = cv2.inRange(hsv, (170, 70, 50), (180, 255, 255))
mask = cv2.bitwise_or(mask1, mask2)

masked = cv2.bitwise_and(img, img, mask=mask)

Here is my result:


text:
Q: Unable to move to required screen using react-navigation? I want to move to a different screen when I have some AsyncStorage item for authFlow but when I am going to the next screen and construction is calling out the function it is not moving to the next screen.
I tried to use the basic method this.props.navigation.navigate('navigator_name'), but i think it's not moving as blank screen is appearing.
App.js
------
import React from 'react';
import { StyleSheet, View, Text } from 'react-native';

import { createSwitchNavigator, createAppContainer, } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';

import AuthLoadingScreen from './screens/auth-loading-screen';
import WelcomeScreen from './screens/welcomeScreen';
import AppHomeScreen from './screens/app-home-screen';

const AuthStackNavigator = createStackNavigator({
  welcome: WelcomeScreen
})

// export default
const TestContainer = createAppContainer(createSwitchNavigator({
    AuthLoading: AuthLoadingScreen,
    Auth: AuthStackNavigator,
    App: AppHomeScreen,
  },
  {
    initialRouteName: 'AuthLoading',
  }
))

export default class App extends React.Component {
  constructor () {
    super()
    this.state = {
      loggedIn: 'false',
    }
  }

  render() {
    return(
      <View style={styles.container}>
        <TestContainer />
      </View>
    )
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

auth-loading-screen
-------------------
import React, { Component } from 'react';
import { View, Text, StyleSheet, ActivityIndicator, AsyncStorage } from 'react-native';

export default class AuthLoadingScreen extends Component {

    constructor (props) {
        super(props);
        console.log('calling _loadApp')
        this._loadApp();
    }

    _loadApp = async() => {
        const userToken = await AsyncStorage.getItem('userToken');
        console.log('getting value of token ', userToken, JSON.stringify(this.props.navigation.actions))
        this.props.navigation.navigate(userToken ? 'App' : 'Auth')
    }

   render() {
        return (
            <View style={styles.container}>
                <ActivityIndicator />
            </View>
        )
    }
}

const styles = StyleSheet.create ({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
})

welcomeScreen
-------------
import React, { Component } from 'react';
import { View, Text, StyleSheet, Button} from 'react-native';

export default class WelcomeScreen extends Component {
    constructor (props) {
        super(props);
    }
   render() {
        return (
            <View style={styles.container}>
                <Text>Welcome</Text>
            </View>
        )
    }
}

const styles = StyleSheet.create ({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'center'
    }
})

The screen should directly move to the welcomeScreen as item is not set through AsynStorage

A: Your function is asynchronous. However, the constructor cannot execute the asynchronous function. Therefore, you should change the position of executing the function.
  async componentDidMount() {
    await this._loadApp();
  }


text:
Q: rsync with ssh without using credentials stored in ~/.ssh/config I have a script that transfers files. Everytime I run it It needs to connect to a different host. That's why I'm adding the host as parameter.
The script is executed as: ./transfer.sh <hostname>
#!/bin/bash -evx

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user \
${1}"

files=(
  file1
  file2
)

files="${files[@]}"

# this works
$SSH

# this does not work
rsync -avzh --stats --progress $files -e $SSH:/home/ec2-user/

# also this does not work
rsync -avzh --stats --progress $files -e $SSH ec2-user@$1:/home/ec2-user/

I can properly connect with the ssh connection stored in $SSH, but the rsync connection attempts fails because of the wrong key:
Permission denied (publickey).
rsync: connection unexpectedly closed (0 bytes received so far) [sender]
rsync error: unexplained error (code 255) at io.c(226) [sender=3.1.2]

What would be the correct syntax for the rsync connection?

A: Write set -x before the rsync line and watch how the arguments are expanded. I believe it will be wrong.
You need to enclose the ssh command with arguments (without hostname) into the quotes, otherwise the arguments will get passed to the rsync command and not to the ssh.

A: My solution after Jakuje pointed me in the right direction:
#!/bin/bash -evx

host=$1

SSH="ssh \
-o UseRoaming=no \
-o UserKnownHostsFile=/dev/null \
-o StrictHostKeyChecking=no \
-i ~/.ssh/privateKey.pem \
-l ec2-user"

files=(
  file1
  file2
)

files="${files[@]}"

# transfer all in one rsync connection
rsync -avzh --stats --progress $files -e "$SSH" $host:/home/ec2-user/

# launch setup script
$SSH $host ./setup.sh


text:
Q:  not found, use_modulers flipper Swift pod `FirebaseCoreInternal` depends upon `GoogleUtilities`, hermes.h not found provided solution but this doesn't worked and the error: these error arises first I have attached some images of the error I searched for but cannot find any right answer. If I solve one issue then other is raised so that's why I am here to ask this question.

require_relative '../node_modules/react-native/scripts/react_native_pods'
require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules'

platform :ios, '12.4'
install! 'cocoapods', :deterministic_uuids => false

target 'FBStorage' do
  config = use_native_modules!

  pod 'Firebase', :modular_headers => true
  pod 'FirebaseCore', :modular_headers => true
  pod 'GoogleUtilities', :modular_headers => true
  $RNFirebaseAsStaticFramework = true

  # Flags change depending on the env values.
  flags = get_default_flags()

  use_react_native!(
    :path => config[:reactNativePath],
    # Hermes is now enabled by default. Disable by setting this flag to false.
    # Upcoming versions of React Native may rely on get_default_flags(), but
    # we make it explicit here to aid in the React Native upgrade process.
    :hermes_enabled => true,
    :fabric_enabled => flags[:fabric_enabled],
    # Enables Flipper.
    #
    # Note that if you have use_frameworks! enabled, Flipper will not work and
    # you should disable the next line.
    :flipper_configuration => FlipperConfiguration.enabled,
    # An absolute path to your application root.
    :app_path => "#{Pod::Config.instance.installation_root}/.."
  )

  target 'FBStorageTests' do
    inherit! :complete
    # Pods for testing
  end

  post_install do |installer|
    react_native_post_install(
      installer,
      # Set `mac_catalyst_enabled` to `true` in order to apply patches
      # necessary for Mac Catalyst builds
      :mac_catalyst_enabled => false
    )
    __apply_Xcode_12_5_M1_post_install_workaround(installer)
  end
end

sometimes I get an error like this : 'GoogleUtilities/GULUserDefaults.h' file not found

I am using React-Native: 0.70
the latest version of react native.
I got the the error when I installed firebase storage. but now I have checked new project that even does not work with simply adding firebase through Yarn.


text:
Q: Git pre-receive hook When you enable pre-receive hook for git repository:

It takes no arguments, but for each ref to be updated it receives on standard input a line of the format:
< old-value > SP < new-value > SP < ref-name > LF
where < old-value > is the old object name stored in the ref, < new-value > is the new object name to be stored in the ref and  is the full name of the ref. When creating a new ref, < old-value > is 40 0.

Does anyone can explain me how do I examine all the files that will be changed in the repository if i allow this commit?
I'd like to run that files through some scripts to check syntax and so on.
Thanks.

A: Oddly, I had some code laying around from a git -> Wordpress utility that might help.  The following will give you a list of all files changed in the receive, as well as their contents. No guarantees, may have bugs, may not be the most efficient way to do it, blah blah blah.  Some of this code is based off stuff in gitshelve, which is a really great thing to look at for generic git manipulation.
import sys
import os
import subprocess

def git(args, **kwargs):
    environ = os.environ.copy()
    if 'repo' in kwargs:
        environ['GIT_DIR'] = kwargs['repo']
    if 'work' in kwargs:
        environ['GIT_WORK_TREE'] = kwargs['work']
    proc = subprocess.Popen(args, stdout=subprocess.PIPE, env=environ)
    return proc.communicate()

def get_changed_files(base, commit, **kw):
    (results, code) = git(('git', 'diff', '--numstat', "%s..%s" % (base, commit)), **kw)
    lines = results.split('\n')[:-1]
    return map(lambda x: x.split('\t')[2], lines)

def get_new_file(filename, commit):
    (results, code) = git(('git', 'show', '%s:%s' % (commit, filename)))
    return results

repo = os.getcwd()
basedir = os.path.join(repo, "..")

line = sys.stdin.read()
(base, commit, ref) = line.strip().split()
modified = get_changed_files(base, commit)

for fname in modified:
    print "=====", fname
    print get_new_file(fname, commit)

A: I just did this.  Here's the basic flow I used.
In your pre-receive hook, read each line from stdin, which (as you mentioned) look like this:
oldref newref refname

*

*For each (oldref, newref) pair you need to list all the commits:
git show --format=format:%H --quiet oldref..newref

*for each commit you need to list all the files:
git diff --name-only commit^..commit

*to examine a file, use git show:
git show commit:filepath

do whatever checking of file contents here.  If you want to notify the user of an issue, write to stderr

*after iterating all the refs, commits and files exit nonzero to reject the push, or zero to allow it
Note that this approach walks all the commits in order, so if a file is modified in several commits each version will get examined.  If you wanted to only view each file in a push once, traverse the commits in reverse order instead, and just don't examine a given file twice.  I recommend the first approach however so that all versions of pushed files are examined.

A: If you want to know the whether permissions of the files are changed in the local repository before pushing to remote repository, run git ls-tree -r commit, where commit is the SHA commit value of the local repository.
This command gives a list of files with their permissions, which can be parsed to check if the permission of a file is changed before pushing.