text:
Q: d3:Adding Axis like a Box I have d3 graph with xaxis and Y axis.I want to add axis to the top and right to make it look like a box.
Something like This.

A: You could go through this article for adding multiple axes. You should create new axis generators and give the orient as 'right' and top and call them finally.
http://www.d3noob.org/2013/01/using-multiple-axes-for-d3js-graph.html
EDIT:
I have made a simple line chart with your requirements. Have a look at https://jsfiddle.net/j0kaLf59/
Also as mentioned in the comments, you could just add two line elements. Have a look at this fiddle https://jsfiddle.net/a6o2hkfq/
Reference:

*

*Create a D3 axis without tick labels

*http://www.tutorialsteacher.com/d3js/create-svg-elements-in-d3js


text:
Q: PHP URL /?val=something I was messing around on WolframAlpha.com today and noticed that you start out on the wolframalpha.com/index.html page then when you hit enter you get redirected to wolframalpha.com/input/?i=YourSearch
I know how to set this up, <form action="newpage.php" method="GET" /> but with the project I'm working on, it would be cool if I could redirect to example.com/?val=something instead of example.com/newpage.php?val=something Is it possible to redirect to a file but have the page name hidden like WA has? Would this be a job for .htacess?
EDIT:
I need to direct from index.php to pages/file.php without "file.php" showing up in the url of the browser. So if I were to say:
<form action="pages/file.php" method="GET">
    <input type="text" name="foo" />
</form>

Then if would direct me to example.com/?foo=blah instead of example.com/pages/file.php?foo=blah

A: If index.php is the script loaded if you access www.example.com/, having a form on this page with <form action=""> will do this.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Umbraco Application BeginRequest never fired I want to fire the BeginRequest event in Umbraco but it doesn't work. The rest of the code works just fine.
public class ApplicationEventHandler : IApplicationEventHandler
{
    public void OnApplicationStarting(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { }

    public void OnApplicationInitialized(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) { }

    public void OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
    {
        umbracoApplication.BeginRequest += umbracoApplication_BeginRequest;

        BundleConfig.RegisterBundles(BundleTable.Bundles);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    }

    void umbracoApplication_BeginRequest(object sender, EventArgs e)
    {
        // Create HttpApplication and HttpContext objects to access
        // request and response properties.
        UmbracoApplicationBase application = (UmbracoApplicationBase)sender;
        HttpContext context = application.Context;

        if (context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME] == null)
        {
            context.Response.Cookies.Add(new HttpCookie(Const.LANGUAGE_COOKIE_NAME, Thread.CurrentThread.CurrentUICulture.Name));
            return;
        }

        //cookie exists already
        else
        {
            //if no 404
            if (UmbracoContext.Current.PublishedContentRequest != null && !UmbracoContext.Current.PublishedContentRequest.Is404)
            {
                //cookie value different than the current thread: user switched language.
                if (context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME].Value != Thread.CurrentThread.CurrentUICulture.Name)
                {
                    //we set the cookie
                    context.Response.Cookies[Const.LANGUAGE_COOKIE_NAME].Value = Thread.CurrentThread.CurrentUICulture.Name;
                }
            }
        }
    }
}

Do you have any idea why it is not working ?
I am using umbraco 7, local IIS (not express) and I can't log messages inside the function umbracoApplication_BeginRequest.

A: This is how I was able to attach to BeginRequest in an Umbraco 7.1.2 instance.  First create a new class that inherits from UmbracoApplication (see sample below), then update your global.asax to inherit from your new class.
public class MyUmbracoApplication : Umbraco.Web.UmbracoApplication
{
    private void Application_BeginRequest(object sender, EventArgs e)
    {
        /*  Your code here */
    }
}

A: According to this, you should be implementing ApplicationEventHandler, not IApplicationEventHandler, in v6.1.0 and forwards: https://our.umbraco.org/documentation/Reference/Events/application-startup

A: First, you should create a HttpModel class that inherit System.Web.IHttpModule interface
public class HttpModule : IHttpModule
{
    void IHttpModule.Init(HttpApplication context)
    {
        context.BeginRequest += ContextBeginRequest;
    }

    private void ContextBeginRequest(object sender, EventArgs e)
    {
        HttpApplication app = sender as HttpApplication;

        if (app != null)
        {
            //do stuff
        }
    }

    void IHttpModule.Dispose()
    {
        // Nothing to dispose;
    }
}

Then, in your web.config
<system.webServer><modules runAllManagedModulesForAllRequests="true">
  <remove name="DoStuff" />
  <add name="DoStuff" type="YourNameSpace.HttpModule, YourAssembly" /></modules></system.webServer>


text:
Q: Poisson Model Interrupted Time Series Analysis I've run an Interrupted Time Series Analysis on count data, fitting a Poisson Model as below:
glm(`Subject Total` ~ Quarter + int2 + time_since_intervention2 , df, family = "poisson")

This is intended to show the change in number of application received and needs to be interpretable as such. The plot shows a diminishing trend in the [longer] pre-intervention period with a level change and potentially slight trend change.
The output summary from the model is:
Call:
glm(formula = `Subject Total` ~ Quarter + int2 + time_since_intervention2,
    family = "poisson", data = df)

Deviance Residuals:
     Min        1Q    Median        3Q       Max
-1.72350  -0.67721   0.06528   0.68167   1.35607

Coefficients:
                          Estimate Std. Error z value Pr(>|z|)
(Intercept)               3.681163   0.088844  41.434   <2e-16 ***
Quarter                  -0.028692   0.009733  -2.948   0.0032 **
int2                     -0.164817   0.202510  -0.814   0.4157
time_since_intervention2 -0.024379   0.038969  -0.626   0.5316

I can't really present the ITS outcomes as above as I need to make such more interpretable and intended to do so by just using exp() on the coefficients. However, whilst exp(Intercept) does reflect the plotted value - the others do not. I am sure this is due to my lack of understanding of the Poisson model, but could do with some advice/help as to how to derive a more usable figure??

For example int2 equates to the level change in the post-intervention period.
Under the summary output it is -0.164817. Exp(int2) = 0.8480492.
However, the "real difference" between the fitted value and relevant counterfactual = -4.2 applications.
Whilst I can report said level change in an interpratble way the trend is much more problemtaic.
Anyone have any ideas/is it just me not really understanding the Poisson model.
Thanks

A: I think that your problem is in the interpretation of the coefficients. This type of display shows coefficients that represents differences from the intercept associated with differences of predictors from their reference values.
In a Poisson model with a log link, the intercept and coefficients are in units of log of mean expected counts. You need to add/subtract the contributions from the predictor coefficients to the intercept in that scale before you exponentiate.
For example, $\exp(3.681163) \approx 39.7$ counts for the intercept at reference values of other predictors. For the difference associated with int2 with other predictors at reference values, you calculate $\exp(3.681163-0.164817) \approx 33.7$ counts, a difference of 6 counts.
This type of work can be simplified by specifying a set of predictor values of interest to post-modeling analysis software like the emmeans package in R. That can provide estimates in the original count units along with confidence intervals and tests of significance between scenarios.
Reporting model coefficients
Reporting coefficients in the way displayed in the question, with coefficients representing changes in logs of counts associated with the predictors, is standard for Poisson models. If you exponentiate the coefficients as you propose, what you get are multiplicative factors acting on the number of counts.
The model that you show fits:
$$\log(\bar T) = \beta_0  + \beta_1 Q + \beta_2 \text{int2} + \beta_3 \text{tsi2}$$
Where $\bar T$ is the mean "Subject total", $Q$ is "Quarter," and $\text{tsi2}$ is "time_since_intervention2." As noted above, you need to add up all the terms on the right side before you exponentiate to get the estimate of mean "Subject total" $\bar T$. If you do that, you get the following product:
$$\bar T = \exp(\beta_0)  \exp(\beta_1 Q) \exp( \beta_2 \text{int2}) \exp (\beta_3 \text{tsi2})$$
Thus the coefficient $\beta_2$ is the multiplicative factor for "Subject total" counts associated with $\text{int2}$, other things being equal. The coefficient is not itself on a count scale. It's not clear that exponentiating the coefficients will make them any more interpretable.
For a Poisson model, I thus don't see any advantage to going beyond the log-scale coefficients. If you nevertheless want to report exponentiated coefficients, you need to make it clear that the exponentiated coefficients represent represent multiplicative associations with counts. You also need to report corresponding confidence intervals. For 95% confidence intervals of a coefficient with value $\beta$, you report $\exp(\beta \pm 1.96 \text{SE}_{\beta})$, where $\text{SE}_{\beta}$ is the standard error in the original scale. Those will be asymmetric about $\exp(\beta)$.


text:
Q: How to upload CSV to wordpress custom table How to upload CSV data to wordpress custom table wp_sonali_data. Bellow is the code what I'm trying. But no luck please help
Here is my custom table column
id
brcode
brname
dist

Here is my uploader
   <form method="post" action="">

Choose your CSV file

<input type="file" name="file" />
<input type="submit" name="submit" value="submit"/>

</form>

<?php

    //Upload CSV File
    if (isset($_POST['submit'])) {

    global $wordpress,$wpdb;
        $datafile= $_FILES['file']['tmp_name'];
        $file=$upload_dir['basedir'].'/'.$_FILES['file']['name'];
        $fileurl=$upload_dir['baseurl'].'/'.$_FILES['file']['name'];
        if (!move_uploaded_file($_FILES['file']['tmp_name'],$file)){
            print_r('Failed to move uploaded file.');
            }
        $sql="
        LOAD DATA LOCAL INFILE '".$fileurl."' INTO TABLE wp_sonali_data
        FIELDS TERMINATED BY ','
        LINES TERMINATED BY '\r\n'
        (id,brcode,brname,dist);
        ";
        $query = $wpdb->query($sql);
}

Error
Output: 'Failed to move uploaded file.'

A: LOAD DATA INFILE "$_FILES['upload_csv']['tmp_name']"
INTO TABLE wp_sonali_data
FIELDS TERMINATED BY ',' ENCLOSED BY '"'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
("id", "brname", "brcode", "dist")


text:
Q: Anti-derivative of $\frac{\exp(x)-1}{x}$ I am looking for the antiderivative of $$\frac{\exp(x)-1}{x}$$ I showed that it is equivalent to calculate $$\sum_{n=1}^{\infty}\frac1n \frac{x^n}{n!}$$ but I can't find both of the solutions. If someone could help me I would very appreciate it. Thanks!

A: As long as you cannot use the exponential integral function, leave it as you wrote
$$\int\frac{e^x-1}{x}\,dx=\sum_{n=1}^{\infty}\frac1n \frac{x^n}{n!}>\sum_{n=1}^{\infty}\frac1{n+1} \frac{x^n}{n!}=\frac 1x\sum_{n=1}^{\infty} \frac{x^{n+1}}{(n+1)!}=\frac{e^x-x-1}x$$


text:
Q: ListView get_context_data question about Django.
Would like to ask you guys if it's possible to use get_context_data in ListView?
I am interested in using the following template tags in my ListView:
{% if liked %}

{% else %}

{% endif %}

This works in my DetailView but I can't figure out how to implement it in ListView maybe you guys can help me?
This is my views.py
class PostList(generic.ListView):

    model = Post
    queryset = Post.objects.order_by('-created_on')
    template_name = 'blog/blog.html'

class PostDetail(generic.DetailView):

    model = Post
    template_name = 'blog/post_detail.html'

    def get_context_data(self, **kwargs):
        context = super(PostDetail, self).get_context_data(**kwargs)
        context['comments'] = self.object.comments.order_by('-created_on')
        context['liked'] = self.object.likes.filter(id=self.request.user.id).exists()
        return context

I'm testing get_context_data i ListView but can't get it to work.
I get the following message: This is the response error : AttributeError at /blog/ 'PostList' object has no attribute 'object'
Please need help :)


text:
Q: Error Parsing JPQL on EclipseLink (Hermes Parser) I'm having a hard time trying to solve an issue using JPQL.
I'm working to fix some performance issues on a system and I don't have too much space to change the structure of the project (DB tables and/or Entities).
There is a problem of Select N+1 on the code because this system is doing an extensive use of Native Queries. So I decided to pick the worst queries and try to convert them to JPQL.
I'm not sure yet if this is the best solution for the scenario above.
Original Native Query:
SELECT is.*
FROM (SELECT id_map, id_spot,
      json_array_elements(id_itineraries)::text::integer AS itinerary
      FROM itinerary_spot WHERE id_map=?) tmp
JOIN itinerary_spot is ON tmp.id_spot=is.id_spot AND tmp.id_map=is.id_map
WHERE tmp.itinerary=?

This query is working OK, but it's not making the JOIN with entity Spot to avoid the Select N+1.
At this point I have thought about 2 different alternatives:

*

*Improving the Native SQL Query adding the JOIN to Spot table and then using a @SqlResultSetMapping to fill up the Entities (Itinerary and Spot).

*Converting the Query to a JPQL and let the EclipseLink 2.6 do its magic.

I don't feel confident enough to use the 1st solution because it would involve some messy code to iterate on the result and fill up the Entities.
So I decided to give a shot on the 2nd option. I converted the Native query to
Full Query:
SELECT is FROM ItinerarySpot is,
                (SELECT cs.itinerarySpotPK.idMap,
                        cs.itinerarySpotPK.idSpot,
                        SQL('json_array_elements(id_itineraries)::text::integer') AS itinerary
                 FROM ItinerarySpot cs
                 WHERE cs.itinerarySpotPK.idMap = :idMap
                ) x
WHERE x.idSpot = is.itinerarySpotPK.idSpot
  AND x.idMap = is.itinerarySpotPK.idMap
  AND x.itinerary = :idItinerary

List<ItinerarySpot> fullJPQLResult = baseDAO.runQuery( ItinerarySpot.class, fullJPQL, params );

The problem is, I'm getting an error from EclipseLink (HermesParser) that is not helping me to identify what is wrong with my JPQL:
Exception Message:
An exception occurred while creating a query in EntityManager: Exception Description: Internal problem encountered while compiling [<my-query-above>]. Internal Exception: java.lang.NullPointerException

Exception Stacktrace:
[org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1616),
        org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1636),
        com.mycompany.dao.BaseDAO.runQuery(BaseDAO.java:781),
        com.mycompany.bo.impl.retail.ItinerarySpotBO.findItinerarySpots(ItinerarySpotBO.java:357),
        com.mycompany.bo.impl.retail.ItineraryBO.buildItineraryFull(ItineraryBO.java:316),
        com.mycompany.bo.impl.retail.ItineraryBO.buildItineraryStatus(ItineraryBO.java:366),
        com.mycompany.bo.impl.retail.ItineraryBO.listItineraries(ItineraryBO.java:518),
        com.mycompany.bo.impl.retail.SpotBO.buildSpotActivities(SpotBO.java:520),
        com.mycompany.bo.impl.retail.SpotBO.buildSpotActivities(SpotBO.java:473),
        com.mycompany.action.retail.ActivityAction.recommendedActivities(ActivityAction.java:149),
        sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method),
        sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57),
        sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43),
        java.lang.reflect.Method.invoke(Method.java:606),
        com.mycompany.service.ActionInvoker.invokeAction(ActionInvoker.java:128),
        com.mycompany.service.JSONService.service(JSONService.java:101),
        javax.servlet.http.HttpServlet.service(HttpServlet.java:729),
                ...
                ...
        java.lang.Thread.run(Thread.java:745)]

When I remove 'AND x.itinerary = :idItinerary' from the Full JPQL does work (it does compile and execute).
Any help to identify the issue is welcome. I'm also opened to try another approach to solve the Select N+1.


text:
Q: How to Install Ubuntu on my lenovo which has four partitions I own a Lenovo Y580 Ideapad and in the process of installing Ubuntu through a USB I cannot install alongside windows as it already has four partitions:

*

*/dev/sda1 (Windows 7 Loader) ntfs (Size 209MB Used 70MB)

*/dev/sda2 (Windows 7 Loader) ntfs (Size 451577 Used Unknown)

*/dev/sda3 ntfs (Size 27346MB Used 4114MB)

*/dev/sda4 (Windows Recovery Environment Loader) ntfs (Size 20972MB Used 13354MB)
If possible should I delete one of these partitions to make room for Ubuntu?
How would I go about deleting it? and how would it change my computers performance in any way? Thanks in advance to any who may answer.

A: We need more information on how your hard drive is configure, GPT or MBR partition table? Total size of hard drive?
Assuming its MBR, that will only allow for 4 primary partitions. So you would have to delete a 2 primary partitions and resize 1 for Ubuntu. Then in the other partition create an extended partition with a logical partition so you can add other logical partitions if you need them.
Your partition table would look something like:
Primary 1 - sda1 (ntfs - Windows)
Primary 2 - sda2 (ntfs - Windows)
Primary 3 - sda3 (ext4 - Ubuntu)
Primary 4 - (if needed)

Extended Partition:
    Logical - sda4 (Linux Swap)
    Logical - sda5 (if needed)

This is if your hard drive is configured for MBR and if you hard drive has space for a 2nd OS. In the end you'll probably have to delete partitions to make room. Good luck.


text:
Q: Order By LPAD Issue Currently I'm trying to take a list of values from my table and order them alphanumerically so they appear from number to letters. For example I have this data set
3
8
56
70
90
AK
CN
PP
PQ
W3
0.5
0.6
0.8
040
070
1.2
1.5
1.6
100
150
187
2.8
250
3.0
6.3
800
8mm

And I want it to print 0.5 first and then W3 last. I am using an Lpad to grab the data, but it displays like shown above, with no ordering. Is there a way I can sort these alphanumerically in Oracle SQL?
(The SQL statement)
SELECT *
FROM data_table
ORDER BY LPAD(parameter_type, 10) ASC
OFFSET 0 ROWS FETCH NEXT 1000 ROWS ONLY;

A: MySQL - Try converting to decimal and checking for value greater than zero -
SELECT *
FROM data_table
ORDER BY IF(
    CONVERT(parameter_type, DECIMAL(6, 2)) > 0,
    CONVERT(parameter_type, DECIMAL(6, 2)),
    99999
) ASC, parameter_type ASC;

Oracle - If you are using Oracle you will need to use CASE as it does not have an IF() function.  Also, you cannot use CAST as it is not as forgiving as in MySQL.
SELECT *
FROM data_table
ORDER BY
  CASE WHEN REGEXP_INSTR(parameter_type, '^[0-9]') > 0 THEN TO_NUMBER(REGEXP_REPLACE(parameter_type, '[^0-9\.]', '')) END ASC, parameter_type ASC

This checks to see if the first character is [0-9] and if so removes everything apart from [0-9.] and converts it to a number. db<>fiddle

A: MySQL
Perhaps like this:
SELECT val,
       val REGEXP '^[a-zA-Z]',
       CAST(val AS DECIMAL(14,4))
FROM mytesting
ORDER BY CASE WHEN val REGEXP '^[a-zA-Z]' >= 1 THEN 1 ELSE 0 END ASC,
         CAST(val AS DECIMAL(5,2)) ASC;

First, I use CASE expression REGEXP to check whether the leading value is alphabet or number; if the value starts with alphabet, I assign to 1 if not I'll assign it to 0 so it'll be on the top of an ascending order. Then I add a second order where I change the val datatype to decimal using CAST. I put both operation in SELECT to see what the value it return after the filtering. Since the purpose they're in SELECT is for viewing purpose only, you can remove them from the final query so like this should work:
SELECT val
FROM mytesting
ORDER BY CASE WHEN val REGEXP '^[a-zA-Z]' >= 1 THEN 1 ELSE 0 END ASC,
         CAST(val AS DECIMAL(5,2)) ASC;

Alternatively, if you found those values to be useful and you want to use them, you can simplify the query to something like this:
SELECT val,
       CASE WHEN val REGEXP '^[a-zA-Z]' >= 1 THEN 1 ELSE 0 END AS val_check,
       CAST(val AS DECIMAL(14,4)) AS val_convert
FROM mytesting
ORDER BY val_check ASC,
         val_convert ASC;

Demo fiddle
Well, as you may already guess, the answer above was for MySQL and posted before the tag change. Unfortunately, Oracle is not my daily database however in the spirit of not trying to post a wrong answer, I did this:
SELECT val,
       CASE WHEN REGEXP_LIKE(val,'^[0-9]')
                   THEN CAST(REGEXP_REPLACE(val,'[a-zA-Z]','')+0 AS DEC(5,2))
              WHEN REGEXP_REPLACE(val,'[^a-zA-Z]','') IS NULL
                   THEN CAST(val AS DEC(5,2))
              ELSE 9000*9000 END AS val_check
       FROM mytesting
ORDER BY CASE WHEN REGEXP_LIKE(val,'^[0-9]')
                   THEN CAST(REGEXP_REPLACE(val,'[a-zA-Z]','')+0 AS DEC(5,2))
              WHEN REGEXP_REPLACE(val,'[^a-zA-Z]','') IS NULL
                   THEN CAST(val AS DEC(5,2))
              ELSE 9000*9000 END,
              val;

With the intention of trying to emulate the same idea as the MySQL suggested solution above.
Demo fiddle


text:
Q: Address of a pointer to an array on the heap I am trying to store an array of characters on the heap.
The following code works
char *array[3];
*array = new char;

And also the following
char *array[3];
array[0] = new char;

But not the following
char *array[3];
array = new char;

I viewed the contents of *array, array[0] and array. The first and second do not contain valid pointer addresses after assigning using new but the third one does.
So what makes the third one not work? How do the other two work while they just seem to store some unknown symbols (such as $,%,-) rather than the actual address of the pointer?

A: Perhaps it will help to elaborate what a char *array[3] is. This is an array of three pointers, which point to characters. That is, array[0], array[1], and array[2] are each pointers to a character. So, *array and array[0] are fine places (and in fact the same place) to store a pointer to a character, but array isn't even a pointer, it is an array, so trying to store a pointer there doesn't make sense.
If you want to store characters in the heap (using a c-style array of characters), you should just do char *array; and then initialize it as array = new char[3];
However, since you are using C++, it is recommended you either use std::string if you are trying to store a string, or std::vector if you want a list of single characters.


text:
Q: Poincaré duality with boundary conditions If $M$ is a compact oriented manifold with boundary then by Poincaré duality the cohomology of $\Omega(M)$ (de Rham cohomology of $M$) is dual to the cohomology of $\Omega_0(M)$, where $\Omega_0(M)$ denotes differential forms vanishing on $\partial M$. This question is about a generalization of this fact to more complicated boundary conditions.
Suppose $M$ is a compact oriented $C^\infty$ manifold with corners. Its boundary is decomposed (by the corners) to faces (of dimension $\dim M -1$).
Let $V$ be a finite-dimensional vector space, and let us choose for every face $F\subset\partial M$ a subspace $V_F\subset V$. Let us consider the complex (of $V$-valued differential forms with boundary conditions given by $V_F$'s)
$$\Omega(M)_{V,\{V_F\}}=
\{\alpha\in\Omega(M)\otimes V;\quad \alpha|_F\in\Omega(F)\otimes V_F\text{ for all faces }F\}\subset\Omega(M)\otimes V.$$
The "naive dual" of $\Omega(M)_{V,\{V_F\}}$ is $\Omega(M)_{V^*,\{\text{ann} V_F\}}$ with the pairing given by integration over $M$ ($\text{ann} V_F\subset V^*$ denotes the annihilator of $V_F$).
Is there a condition under which the pairing between the cohomologies of $\Omega(M)_{V,\{V_F\}}$ and of $\Omega(M)_{V^*,\{\text{ann} V_F\}}$ is perfect? What is the reason for the fact that the pairing is not always perfect?
Some remarks:

*

*The "dual complex" $\Omega(M)_{V^*,\{\text{ann} V_F\}}$ can be described as
$$\{\alpha\in\Omega(M)\otimes V^*;\quad \int_M\langle\alpha\wedge d\beta\rangle=
  (-1)^{\deg\alpha +1}\int_M\langle d\alpha\wedge \beta\rangle\quad \forall\beta\in \Omega(M)_{V,\{V_F\}} \}.$$

*If $V_F=0$ for all $F$'s then we get the standard Poincaré duality for manifolds with boundary.

*It is possible that manifolds with corners is not the right picture; the question might be about any "reasonable" division of $\partial M$ into "faces" (of dimension $\dim\partial M$).

A: An example where the duality fails is when $M^n$ is the closed unit ball $B^3 \subset \mathbb{R}^3$, and its boundary $S^2$ is divided into four quarters by 2 great circles. If $V = \mathbb{R}$, $V_F = V$ for 2 opposite quarters $F$ and $V_F = 0$ for the other two, then $H^1_{V, \{ V_F \}}(M) = 0$ while $H^2_{V^*, \{\text{ann} V_F\}} \cong \mathbb{R}$ (essentially, they are $H^1_c$ and $H^2_c$, respectively, of the product of an open 2-disc and a closed interval).
In a sense, the reason that the duality fails is that near the intersection of the two great circles, the set of boundary points where the forms are allowed to be non-zero is disconnected, and that no matter how small a neighbourhood we choose in $B^3$ for the intersection point, its cohomology will therefore not be entirely elementary. This can be prevented by demanding that every point in $\partial M$ has an "elementary" neighbourhood $U \cong \mathbb{H}^{n}$ such that

*

*the subdivision of $\partial U$ into faces is diffeomorphic to a complete fan (a subdivision of $\mathbb{R}^{n-1}$ into simplicial cones),

*$V$ has a basis $\{e_i\}$ such that for each face $F$ meeting $U$,
$V_F$ is spanned by a subset,

*for each $e_i$, the interior in $U$ of the union of the faces $F$ such that $e_i \not\in V_F$ is connected.

Essentially, 1. says that the subdivision of $\partial M$ is sensible, 3. prevents situations like in the example above, and 2. makes sure we can state 3. sensibly when $\dim V > 1$ (see example in Trial's comment below).
I think that if $M^n$ is oriented with boundary and possesses such "elementary" neighbourhoods, then
$$H^k_{V, \{V_F\}}(M) \cong H^{n-k}_{c, V^*, \{ \text{ann} V_F\}}(M)^*$$
where the subscript $c$ indicates the cohomology of a complex with compact supports. It should be possible to prove this using induction on a good cover (and the duality between the Mayer-Vietoris sequences for normal and compactly supported de Rham cohomology) like for standard Poincaré duality, provided that the statement is true for open subsets $U \subset M$ diffeomorphic to $\mathbb{R}^n$ and for the "elementary" neighbourhoods.
For $U \cong \mathbb{R}^n$ this is just usual Poincaré duality tensored with $V$. For an "elementary" neighbourhood  $U$,
$$H^k_{V, \{V_F\}}(U) = \bigoplus_i H^{k}_{V_i, \{V_F \cap V_i\}}(U) $$
$$H^k_{c, V^*, \{\text{ann} V_F\}}(U) = \bigoplus_i H^{k}_{c, V_i^*, \{\text{ann} (V_F \cap V_i) \}}(U), $$
where $V_i$ is the span of the element $e_i$ of the basis from condition 2.
The terms on the right hand side all vanish, except that if $e_i \in V_F$ for all $F$ meeting $\partial U$ then $H^0_{V_i, \{V_F \cap V_i\}} \cong V_i$ and $H^{n}_{c, V_i^*, \{\text{ann} (V_F \cap V_i)\}}(U) \cong V_i^*$
(3. is used to show that $H^{n-1}_{c, V_i^*, \{\text{ann} (V_F \cap V_i)\}}(U) = 0$). So the duality holds for the "elementary" neighbourhoods.


text:
Q: Showing an error while using XMLWorkerHelper I am trying to convert HTML data to PDF. For that I have used xmlworker-5.5.6.jar.
But while executing code its showing an error of missing resources.
Can anybody please help.
Thanks in Advance.
Here is My Code
Document document = new Document(PageSize.LETTER);
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(new File(filepathpdf)));
document.open();
document.addAuthor("ME");
document.addCreator("ME");
document.addSubject("Thanks for your support");
document.addCreationDate();
document.addTitle("Please read this");
XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
String str = sb.toString().substring(sb.indexOf("<html"),sb.length());
System.out.println(str);
worker.parseXHtml(pdfWriter, document, new StringReader(str));
document.close();
System.out.println("Done.");

And here is my error :

08-24 12:28:42.079 14077-15044/com.abc.abc E/AndroidRuntime: FATAL
  EXCEPTION: AsyncTask #5
                                                                    Process: com.abc.abc, PID: 14077
                                                                    java.lang.RuntimeException: An error occurred while executing
  doInBackground()
                                                                        at android.os.AsyncTask$3.done(AsyncTask.java:309)
                                                                        at
  java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
                                                                        at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
                                                                        at java.util.concurrent.FutureTask.run(FutureTask.java:242)
                                                                        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                        at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                        at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                        at java.lang.Thread.run(Thread.java:818)
                                                                     Caused by: java.lang.ExceptionInInitializerError
                                                                        at
  com.itextpdf.tool.xml.net.FileRetrieveImpl.processFromHref(FileRetrieveImpl.java:170)
                                                                        at
  com.itextpdf.tool.xml.css.StyleAttrCSSResolver.addCssFile(StyleAttrCSSResolver.java:404)
                                                                        at com.itextpdf.tool.xml.html.head.Link.start(Link.java:80)
                                                                        at
  com.itextpdf.tool.xml.html.AbstractTagProcessor.startElement(AbstractTagProcessor.java:131)
                                                                        at
  com.itextpdf.tool.xml.pipeline.html.HtmlPipeline.open(HtmlPipeline.java:105)
                                                                        at com.itextpdf.tool.xml.XMLWorker.startElement(XMLWorker.java:103)
                                                                        at
  com.itextpdf.tool.xml.parser.XMLParser.startElement(XMLParser.java:372)
                                                                        at
  com.itextpdf.tool.xml.parser.state.SelfClosingTagState.process(SelfClosingTagState.java:71)
                                                                        at
  com.itextpdf.tool.xml.parser.XMLParser.parseWithReader(XMLParser.java:237)
                                                                        at com.itextpdf.tool.xml.parser.XMLParser.parse(XMLParser.java:215)
                                                                        at
  com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:174)
                                                                        at
  com.abc.abc.SearchDetailsActivity$DownloadFileAsync.doInBackground(SearchDetailsActivity.java:2316)
                                                                        at
  com.abc.abc.SearchDetailsActivity$DownloadFileAsync.doInBackground(SearchDetailsActivity.java:2177)
                                                                        at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                        at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                        at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                        at java.lang.Thread.run(Thread.java:818)
                                                                     Caused by: java.util.MissingResourceException: Can't find resource for
  bundle 'errors/errors_en_GB', key ''
                                                                        at
  java.util.ResourceBundle.missingResourceException(ResourceBundle.java:238)
                                                                        at java.util.ResourceBundle.getBundle(ResourceBundle.java:230)
                                                                        at java.util.ResourceBundle.getBundle(ResourceBundle.java:159)
                                                                        at
  com.itextpdf.tool.xml.exceptions.LocaleMessages.(LocaleMessages.java:99)
                                                                        at
  com.itextpdf.tool.xml.exceptions.LocaleMessages.(LocaleMessages.java:84)
                                                                        at
  com.itextpdf.tool.xml.net.FileRetrieveImpl.processFromHref(FileRetrieveImpl.java:170)
                                                                        at
  com.itextpdf.tool.xml.css.StyleAttrCSSResolver.addCssFile(StyleAttrCSSResolver.java:404)
                                                                        at com.itextpdf.tool.xml.html.head.Link.start(Link.java:80)
                                                                        at
  com.itextpdf.tool.xml.html.AbstractTagProcessor.startElement(AbstractTagProcessor.java:131)
                                                                        at
  com.itextpdf.tool.xml.pipeline.html.HtmlPipeline.open(HtmlPipeline.java:105)
                                                                        at com.itextpdf.tool.xml.XMLWorker.startElement(XMLWorker.java:103)
                                                                        at
  com.itextpdf.tool.xml.parser.XMLParser.startElement(XMLParser.java:372)
                                                                        at
  com.itextpdf.tool.xml.parser.state.SelfClosingTagState.process(SelfClosingTagState.java:71)
                                                                        at
  com.itextpdf.tool.xml.parser.XMLParser.parseWithReader(XMLParser.java:237)
                                                                        at com.itextpdf.tool.xml.parser.XMLParser.parse(XMLParser.java:215)
                                                                        at
  com.itextpdf.tool.xml.XMLWorkerHelper.parseXHtml(XMLWorkerHelper.java:174)
                                                                        at
  com.abc.abc.SearchDetailsActivity$DownloadFileAsync.doInBackground(SearchDetailsActivity.java:2316)
                                                                        at
  com.abc.abc.SearchDetailsActivity$DownloadFileAsync.doInBackground(SearchDetailsActivity.java:2177)
                                                                        at android.os.AsyncTask$2.call(AsyncTask.java:295)
                                                                        at java.util.concurrent.FutureTask.run(FutureTask.java:237)
                                                                        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
                                                                        at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
                                                                        at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
                                                                        at java.lang.Thread.run(Thread.java:818)


text:
Q: MATLAB: Plotting different numerical approximation in one plot I have the following matlab code for approximating a differential equation via the Euler-method:
% Eulermethod

a=0;
b=0.6;
Steps=6;
dt=(b-a)/Steps;
x=zeros(Steps+1,1);

x(1,1)=1;
y=zeros(Steps+1,1);

for i=1:Steps
    x(i+1,1)=x(i,1)+dt*(x(i,1)*x(i,1)+1);
end
plot(x)

I want to be able to plot the solution plot for several different values of Steps in one plot and have the x-axis go from 0 to 0.6 instead of from for example 1 to 100 000 etc. Can this be done?

A: If you use the hold on command this will allow you achieve multiple plots on the same figure. Similarly, if you separate your data into x and y vectors, you can plot them against eachother by passing 2 vectors to plot instead of just one. For example
figure
hold on
for i=1:m
    x = [];
    y = [];
    %% code to populate your vectors
    plot(x,y)
end

You should now see all your plots simultanesously on the same figure. If you want x to be composed of n equally spaced elements between 0 and 0.6, you could use the linspace command:
 x = linspace(0.0,0.6,n);

In order to distinguish your plots, you can pass an extra paramter to the function .For example
 plot(x,y,'r+')

will plot the data as a series of red + symbols.

A: Plot can take more arguments: plot(x_axis,values,  modifiers);
If x-axis is a vector of M elements, values can be a matrix of MxN elements, each of which are drawn with a separate color.


text:
Q: Getting asynchronous view data on button click using spring mvc I am making a web application using spring mvc but I am stuck here. I have a page login.jsp inside WEB-INF folder and I have three types of query string associated with this view.

"login.fin?cmdAction=selectLogin" -> this will display two
  buttons->Admin Login and Trainee Login.

On click of admin Login button the page should go to "login.fin?cmdAction=adminLogin" which will display page for login of admin.
and on click of Trainee login button it should go to "login.fin?cmdAction=traineeLogin" which will display Trainee Login Page.
This is my loginController:
package com.finlogic.loginapps.login.apps;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

public class LoginController extends MultiActionController {

public ModelAndView selectLogin(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("title", "Select Login");
        return modelAndView;
    }
public ModelAndView adminLogin(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("title", "Admin");
        return modelAndView;
    }
    public ModelAndView traineeLogin(HttpServletRequest request, HttpServletResponse response)
    {
        ModelAndView modelAndView = new ModelAndView("login");
        modelAndView.addObject("title", "Trainee");
        return modelAndView;
    }

}

This is my login.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title>${title} Login Page</title>
    <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">


text:
Q: How to run an external PHP script silently within a PHP script? For example:
Content of server-a.com/test.php:
echo 'hello world one';

// now I need to call server-b.com/test.php here silently
// without interfering with user experience

echo 'hello world two';

Content of server-b.com/test.php:
mail($foo, $bar, $qux); header('location: http://google.com');

Now running server-a.com/test.php should output hello world one hello world two. And it should not redirect to google.com even though server-b.com/test.php was called successfully.

A: You can use file_get_contents()
file_get_contents("server-b.com/test.php");

or Curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "server-b.com/test.php");
curl_setopt($ch, CURLOPT_HEADER, TRUE);
curl_setopt($ch, CURLOPT_NOBODY, TRUE); // remove body
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_exec($ch);

A: use this function file_get_contents():
file_get_contents("server-b.com/test.php");

A: You can use Symfony2's Process component for that.
Example:
use Symfony\Component\Process\PhpProcess;

$process = new PhpProcess(<<<EOF
    <?php echo 'Hello World'; ?>
EOF
);
$process->run();

A: You can remove the location header with header_remove. After you include server-b.com/test.php just call
header_remove('Location');


text:
Q: firebase__WEBPACK_IMPORTED_MODULE_3___default.a.auth.onAuthStateChanged is not a function I'm working on stripe extension but when i pass the uid it gives me error "firebase__WEBPACK_IMPORTED_MODULE_3___default.a.auth.onAuthStateChanged is not a function"...So any suggestion how can i fix this error??
Here is my code :
import {loadStripe} from '@stripe/stripe-js';
import firebase from 'firebase';

const firestore = firebase.firestore();

firebase.auth().onAuthStateChanged((user) => {
  if(user) {
console.log(user.uid) ;
}
});

export async function createCheckoutSession(uid){
  firebase.auth.onAuthStateChanged((user) => {
    if (user){
      const checkoutSessionRef =  firestore
        .collection('customers')
        .doc(user.uid)
        .collection('checkout_sessions')
        .add({
          price: 'price id',
          success_url: window.location.origin,
          cancel_url: window.location.origin,
      });
// Wait for the CheckoutSession to get attached by the extension
    checkoutSessionRef.onSnapshot((snap) => {
      const { error, sessionId } = snap.data();
      if (error) {
    // Show an error to your customer and
    // inspect your Cloud Function logs in the Firebase console.
      alert(`An error occured: ${error.message}`);
    }
    if (sessionId) {
    // We have a session, let's redirect to Checkout
    // Init Stripe
    const stripe =   loadStripe('pk_test_1234');
    stripe.redirectToCheckout({ sessionId });
    }
  });
  }
}
  )}

Any suggestion How can i fix this error???

A: The onAuthStateChanged function from firebase would work only in client side. Here from my understanding, you are trying to check whether the user has logged in or logged out, but have invoked the onAuthStateChanged listener in backend itself.
Thus move the logic or onAuthStateChanged logic to front-end code. If you actually want to use a logic to check whether user has logged in or not via backend itself, then you might have to resort to cloud functions and handle it using firebase adming SDK.
Also the loadStripe promise should be handled at the top of the file inorder to avoid recreating the Stripe object on every invocation.


text:
Q: junit как протестировать Filter? Есть фильтр который добавляет хедер ко всем запросам
    @Component("xForwardedForAppenderFilter")
    public class XForwardedForAppenderFilter extends OncePerRequestFilter {

      private static final String CLIENT_IP_HEADER = "X-Forwarded-For";
      private static final String FAKE_CLIENT_IP = "11.22.33.44";

      @Override
      protected void doFilterInternal(@NonNull HttpServletRequest httpServletRequest, @NonNull HttpServletResponse httpServletResponse,
          @NonNull FilterChain filterChain) throws ServletException, IOException
      {
        HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(httpServletRequest) {
          @Override
          public String getHeader(String name) {
            if (CLIENT_IP_HEADER.equals(name) && StringUtils.isBlank(super.getHeader(name)))
              return FAKE_CLIENT_IP;
            return super.getHeader(name);
          }

          @Override
          public Enumeration<String> getHeaders(String name) {
            if (CLIENT_IP_HEADER.equals(name) && !super.getHeaders(name).hasMoreElements())
              return Collections.enumeration(Collections.singleton(FAKE_CLIENT_IP));
            return super.getHeaders(name);
          }
        };
        filterChain.doFilter(requestWrapper, httpServletResponse);
      }

Написал следующий тест, но при вызове getHeader фильтр не срабатывает.
@RunWith(MockitoJUnitRunner.class)
public class XForwardedForAppenderFilterTest {
    private static final String CLIENT_IP_HEADER = "X-Forwarded-For";
    private static final String FAKE_CLIENT_IP = "11.22.33.44";

    @InjectMocks
    private XForwardedForAppenderFilter xForwardedForAppenderFilter;

    @Test
    public void doFilterInternal() throws ServletException, IOException {
        MockHttpServletRequest httpServletRequest = new MockHttpServletRequest();
        MockHttpServletResponse httpServletResponse = new MockHttpServletResponse();
        httpServletRequest.addHeader("test","12345");
        MockFilterChain filterChain = new MockFilterChain();
        xForwardedForAppenderFilter.doFilterInternal(httpServletRequest, httpServletResponse, filterChain);
        Assert.assertTrue(httpServletRequest.getHeader(CLIENT_IP_HEADER).equals(FAKE_CLIENT_IP));
        Assert.assertTrue(httpServletRequest.getHeaders(CLIENT_IP_HEADER).nextElement().equals(FAKE_CLIENT_IP));
    }
}

Как заставить фильтр запускаться в тесте?

A: Вы проверяете не тот объект request.
Фильтр у вас берет входящий request, заворачивает его в обертку, в которой дополнительный функционал, и вызывает следующий фильтр в цепочке уже с оберткой.
Так вот, вы в тесте проверяете входящий request (он у вас хранится в httpServletRequest), а нужно проверять, тот, который передается по цепочке дальше. Для этого у вас есть MockFilterChain, который как раз и нужен, чтоб сохранить этот новый request, чтоб его можно было проверить:
MockFilterChain filterChain = new MockFilterChain();
xForwardedForAppenderFilter.doFilterInternal(
     httpServletRequest, httpServletResponse, filterChain);

ServletRequest request = filterChain.getRequest();
Assert.assertTrue(request.getHeader(CLIENT_IP_HEADER).equals(FAKE_CLIENT_IP));
Assert.assertTrue(request.getHeaders(CLIENT_IP_HEADER).nextElement().equals(FAKE_CLIENT_IP));

И еще, не используйте assertTrue для проверки равенства. При неравенстве, ошибка не покажет значений. Используйте assertEquals:
Assert.assertEquals(request.getHeader(CLIENT_IP_HEADER), FAKE_CLIENT_IP);


text:
Q: Why are there disabled buttons in HighStock Range Selector? I am having an issue with rangeSelector in HighCharts/HighStocks. For some reason,  selections are disables. My question is this, how can I make sure that all range selection buttons are active since data is available for a specific range. Here is a  example.     link
$(function() {

    var seriesOptions = [], seriesCounter = 0, names = ['t1'];
    function createChart() {
        $('#container').highcharts('StockChart', {
            loading: {
                style: {
                    backgroundColor: 'silver'
                },
                labelStyle: {
                    color: 'white'
                }
            },

            rangeSelector : {
                selected : 1
            },

            yAxis : {
                            plotLines : [ {
                    value : 0,
                    width : 2,
                    color : 'silver'
                } ]
            },

            plotOptions : {
            },

            tooltip : {
                valueDecimals : 2
            },
            series : seriesOptions
        });
    }

$.each(names, function(i, name) {

$.getJSON('https://dl.dropboxusercontent.com/u/34899000/data.json?dt=' + name.toLowerCase(), function(
                data) {

            seriesOptions[i] = {
                name : name,
                data : data

            };
            seriesCounter += 1;

            if (seriesCounter === names.length) {
                createChart();
            }
        });
    });
});

A: You must enable the range selector buttons, so in your case you must add an attribute allButtonsEnabled and set it to true
rangeSelector: {
    allButtonsEnabled: true,
    selected: 1
},

See documentation
http://api.highcharts.com/highstock#rangeSelector

allButtonsEnabled: Boolean
  Since 2.0.3
Whether to enable all buttons from the start. By default buttons are
  only enabled if the corresponding time range exists on the X axis, but
  enabling all buttons allows for dynamically loading different time
  ranges. Defaults to false.

In your fiddle enabling all buttons doesn't do anything since the time axis is 1 month which is the minimum range.


text:
Q: Filling a DataSet or a DataTable from a LINQ query result set How do you expose a LINQ query as an ASMX web service?

Usually, from the business tier, I can return a typed DataSet or a DataTable which can be serialized for transport over ASMX.
How can I do the same for a LINQ query?
Is there a way to populate a typed DataSet or a DataTable via a LINQ query?
public static MyDataTable CallMySproc()
{
    string conn = "...";

    MyDatabaseDataContext db = new MyDatabaseDataContext(conn);
    MyDataTable dt = new MyDataTable();

    // execute a sproc via LINQ
    var query = from dr
                in db.MySproc().AsEnumerable
                select dr;

    // copy LINQ query resultset into a DataTable -this does not work !
    dt = query.CopyToDataTable();

    return dt;
}

How could I put the result set of a LINQ query into a DataSet or a DataTable?

Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service?

A: As mentioned in the question, IEnumerable has a CopyToDataTable method:
IEnumerable<DataRow> query =
    from order in orders.AsEnumerable()
    where order.Field<DateTime>("OrderDate") > new DateTime(2001, 8, 1)
    select order;

// Create a table from the query.
DataTable boundTable = query.CopyToDataTable<DataRow>();

Why won't that work for you?

A: If you use IEnumerable as the return type, it will return your query variable directly.
MyDataContext db = new MyDataContext();
IEnumerable<DataRow> query =
    (from order in db.Orders.AsEnumerable()
        select new
        {
            order.Property,
            order.Property2
        })
    as IEnumerable<DataRow>;
return query.CopyToDataTable<DataRow>();

A: To perform this query against a DataContext class, you'll need to do the following:
MyDataContext db = new MyDataContext();
IEnumerable<DataRow> query =
    (from order in db.Orders.AsEnumerable()
        select new
        {
            order.Property,
            order.Property2
        })
    as IEnumerable<DataRow>;
return query.CopyToDataTable<DataRow>();

Without the as IEnumerable<DataRow>; you will see the following compilation error:

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable' to 'System.Collections.Generic.IEnumerable'. An explicit conversion exists (are you missing a cast?)

A: Make a set of Data Transfer Objects, a couple of mappers, and return that via the .asmx.
You should never expose the database objects directly, as a change in the procedure schema will propagate to the web service consumer without you noticing it.

A: For the sake of completeness, these solutions do not work for EF Core (at least not for EF Core 2.2). Casting to IEnumerable<DataRow>, as suggested in the other answers here, fails. Implementing this class and extension methods worked for me https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/implement-copytodatatable-where-type-not-a-datarow.
Why it's not built into EF Core, I have not idea.

A: If you use a return type of IEnumerable, you can return your query variable directly.

A: Create a class object and return a list(T) of the query.


text:
Q: saving checkmark accessory value in nsuserdefaults and then retreving them hi
i am trying to save state of ticked row in nsuserdefaults.Some how i am getting error
:setObject undeclared.
my code is as:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{

    UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath];

    NSInteger newRow = [indexPath row];
    NSInteger oldRow = (lastIndexPath != nil) ? [lastIndexPath row] : -1;

    if(newRow != oldRow)
    {
        newCell.accessoryType = UITableViewCellAccessoryCheckmark;
        UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath];
        oldCell.accessoryType = UITableViewCellAccessoryNone;
        lastIndexPath = indexPath;
    }
    NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
    prefs = [setObject:lastIndexPath forKey:@"lastIndexPath"];

}

also i am trying to fetch row state in viewdidload method(should i fetch here?in view did load).my code is as:
- (void)viewDidLoad {
menuList=[[NSMutableArray alloc] initWithObjects:
          [NSArray arrayWithObjects:@"LOCATION1",nil],
          [NSArray arrayWithObjects:@"LOCATION2",nil],
          [NSArray arrayWithObjects:@"LOCATION3",nil],
          [NSArray arrayWithObjects:@"LOCATION4",nil],
          [NSArray arrayWithObjects:@"LOCATION5",nil],
          [NSArray arrayWithObjects:@"LOCATION6",nil],
          [NSArray arrayWithObjects:@"LOCATION7",nil],
          nil];

[self.navigationController setNavigationBarHidden:NO];
self.navigationController.navigationBar.tintColor=[UIColor blackColor];
self.navigationController.navigationBar.barStyle=UIBarStyleBlackTranslucent;
self.title=@"Location Selection";
[table reloadData];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
if([[prefs objectForKey:@"lastIndexPath"] compare: indexPath]== NSOrderedSame){
    cell.AccessoryType = UITableViewCellAccessoryCheckMark;
}
[super viewDidLoad];
}

and getting errors: indexPath Undeclared and cell undeclared.
i am getting why these errors are coming coz both of them(indexpath and cell) are not in scope,then where to place this code(nsuserdefaults data retriving code).Please guide my.
Thanks!

A: Try replacing this:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
prefs = [setObject:lastIndexPath forKey:@"lastIndexPath"];

With this:
[[NSUserDefaults standardUserDefaults] setObject:lastIndexPath forKey:@"lastIndexPath"];

Your error is because you are invoking  setObject:forKey: without specifying that your prefs object is calling it. So the compilor is not identifying it as a valid message. You are also trying to assing that messages output to your prefs object, which is not correct.
This said,  I am pretty sure you cant store an NSIndexPath inside of a plist directly, you would either have to store as an NSNumber, NSString, or NSData.
This would look like this:
[[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithInt:lastIndexPath.row] forKey:@"lastIndexPath"];


text:
Q: sql query for the following statement? My table 'Customer' contains customerid , firstname, lastname, company,city,state,country, email, invoicetotal
Question: For countries that have at least two customers using yahoo as email provider, display the name alongside the revenue
My solution:
select county,sum(invoiceTotal)from customer where email like '%yahoo%'
group by Country,Email having Count(Country)>2

I am unable to get proper result the no of rows displayed in my output are different from the number of rows in expected output,Can any1 tell me where have i gone wrong???

A: You are grouping by email as well - just group by Country and you should be fine
select
    county,
    sum(invoiceTotal)
from customer
where email like '%yahoo%'
group by Country
having Count(Country)>2

A: You can't group by email, since that's unique. Fortunately, you don't have to.

A: select
    county,
    sum(invoiceTotal)
from customer
where email like '%yahoo%'
group by Country
having Count(Country)>=2

Because the statement say at least then you need put >=.


text:
Q: Next 13+ check mobile device Next js ile proje geliştiriyorum. burada eğer mobile cihaz ise bir component render etmek istiyorum. ama bu isMobileDevice değerini jsx içerisinde kullanırsam aşadıdaki hataları alıyorum.
import useTranslation from "next-translate/useTranslation";
import isMobile from "ismobilejs";
import DefaultLayout from "../../components/core/Layouts/Default";
import { MouseIcon, ScrollDownWrapper, ScrollText, SearchBoxWrapper, SliderWrapper, Wrapper } from "./style";
import MainSlider from "../../components/common/MainSlider";
import SearchBox from "../../components/common/SearchBox";

const HomeScreen = () => {
    const { t } = useTranslation("home");
    const isMobileDevice = isMobile()?.any;

    return (
        <DefaultLayout>
            <Wrapper>
                <SearchBoxWrapper>
                    <SearchBox />
                    {isMobileDevice && (
                        <ScrollDownWrapper>
                            <MouseIcon />
                            <ScrollText>{t("scrollDown")}</ScrollText>
                        </ScrollDownWrapper>
                    )}
                </SearchBoxWrapper>
                <SliderWrapper>
                    <MainSlider />
                </SliderWrapper>
            </Wrapper>
        </DefaultLayout>
    );
};

export default HomeScreen;

I want to render the project on client side using "use client" because isMobijeJs needs window object but it doesn't work.
Can you help me?


text:
Q: Adjusting just the year of some data in R I have a dataframe with 730 observations and one of the columns is a date column, all of the dates are supposed to be 2007 and I realise that a few seem to have been mistakenly entered as 2006. is there a way I can use R to select the 2005's and change them to 2008 without affecting the month and the day?
it is in date format in r and looks like this.
2005-05-21

Edit:
this is the output you asked for:
structure(c(13604, 13604, 13604, 13604, 13604, 13604, 13604,
13604, 13604, 13604, 13604, 13604, 13604, 13604, 13604, 13604,
13604, 13604, 13604, 13604, 13597, 13597, 13597, 13597, 13597,
13597, 13597, 13597, 13597, 13597, 13598, 13598, 13598, 13598,
13598, 13598, 13598, 13598, 13598, 13598, 13607, 13607, 13607,
13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607,
13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607,
13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607,
13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607, 13607,
13607, 13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608,
13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608,
13608, 13608, 13608, 13598, 13598, 13598, 13598, 13598, 13598,
13598, 13598, 13598, 13598, 13598, 13598, 13598, 13598, 13598,
13598, 13598, 13598, 13598, 13598, 13597, 13597, 13597, 13597,
13597, 13597, 13597, 13597, 13597, 13597, 13597, 13597, 13597,
13597, 13597, 13597, 13597, 13597, 13597, 13597, 13605, 13605,
13605, 13605, 13605, 13605, 13605, 13605, 13605, 13605, 13605,
13605, 13605, 13605, 13605, 13605, 13605, 13605, 13605, 13605,
13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608,
13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608, 13608,
13608, 13608, 13244, 13244, 13244, 13244, 13244, 13244, 13244,
13244, 13244, 13244, 13244, 13244, 13244, 13244, 13244, 13244,
13244, 13244, 13244, 13244, 13600, 13600, 13600, 13600, 13600,
13600, 13600, 13600, 13600, 13600, 13600, 13600, 13600, 13600,
13600, 13600, 13600, 13600, 13600, 13600, 13613, 13613, 13613,
13613, 13613, 13613, 13613, 13613, 13613, 13613, 13613, 13613,
13613, 13613, 13613, 13613, 13613, 13613, 13613, 13613, 13613,
13610, 13610, 13610, 13610, 13610, 13610, 13610, 13610, 13610,
13610, 13610, 13610, 13610, 13610, 13610, 13610, 13610, 13610,
13610, 13610, 13610, 13616, 13616, 13616, 13616, 13616, 13616,
13616, 13616, 13616, 13616, 13616, 13616, 13616, 13616, 13616,
13616, 13616, 13616, 13616, 13616, 13616, 13616, 13616, 13616,
13616, 13616, 13616, 13616, 13616, 13616, 13616, 13616, 13616,
13616, 13616, 13616, 13616, 13616, 13616, 13616, 13618, 13618,
13618, 13618, 13618, 13618, 13618, 13618, 13618, 13618, 13618,
13618, 13618, 13618, 13618, 13618, 13618, 13618, 13618, 13618,
13621, 13621, 13621, 13621, 13621, 13621, 13621, 13621, 13621,
13621, 13621, 13621, 13621, 13621, 13621, 13621, 13621, 13621,
13621, 13621, 13622, 13622, 13622, 13622, 13622, 13622, 13622,
13622, 13622, 13622, 13622, 13622, 13622, 13622, 13622, 13622,
13622, 13622, 13622, 13622, 13620, 13620, 13620, 13620, 13620,
13620, 13620, 13620, 13620, 13620, 13620, 13620, 13620, 13620,
13620, 13620, 13620, 13620, 13620, 13620, 13622, 13622, 13622,
13622, 13622, 13622, 13622, 13622, 13622, 13622, 13622, 13622,
13622, 13622, 13622, 13622, 13622, 13622, 13622, 13622, 13622,
13622, 13622, 13623, 13623, 13623, 13623, 13623, 13623, 13623,
13623, 13623, 13623, 13623, 13623, 13623, 13623, 13623, 13623,
13623, 13623, 13623, 13623, 13623, 14080, 14080, 14080, 14080,
14080, 14080, 14080, 14080, 14080, 14080, 14080, 14080, 14080,
14080, 14080, 14080, 14080, 14080, 14080, 14080, 14080, 14081,
14082, 14083, 14084, 14085, 14086, 14087, 14088, 14089, 14090,
14091, 14092, 14093, 14094, 14095, 14096, 14097, 14098, 14099,
14100, 14101, 14102, 14103), class = "Date")sked for

A: If you want to keep it as a date format you can do the following with lubridate
library(lubridate)

year(yourDF$date)[year(yourDF$date)==2005] <- 2008

Here's an example....
df <- data.frame(date =Sys.Date() - 1:4, Col2 = 1:4)

df
        date Col2
1 2016-04-20    1
2 2016-04-19    2
3 2016-04-18    3
4 2016-04-17    4

# In my example i'll change the year from 2016 to 2008

year(df$date)[year(df$date)==2016] <- 2008

df
        date Col2
1 2008-04-20    1
2 2008-04-19    2
3 2008-04-18    3
4 2008-04-17    4

A: assuming your date is
x <- as.Date('2005/01/01')

you can try
d <- as.POSIXlt(x)
d$year <- d$year+3
result <- as.Date(d)

result should be:
[1] "2008-01-01"

A: if you are reading the dates as character,
you can simply use a regular expression.
The idea is the following:
gsub("^2005", "2008","2005-05-21")

#output
[1] "2008-05-21"

NB: "^2005": if the string starts with "2005"
Let's assume an extract from your data:
data <- structure(c(13604, 13604, 13604, 13604, 13604, 13604, 13604), class = "Date")

#check
data
[1] "2007-04-01" "2007-04-01" "2007-04-01" "2007-04-01" "2007-04-01" "2007-04-01" "2007-04-01"

#substitution, with class conversion
data2 <- as.Date(gsub("^2007", "2008", data))

#output
data2

[1] "2008-04-01" "2008-04-01" "2008-04-01" "2008-04-01" "2008-04-01" "2008-04-01" "2008-04-01"

#check
class(data2)
[1] "Date"


text:
Q: iOS: have a clean code, use static class or singleton I'm developing a game and inside I have a class called StageViewController.
I noticed that code inside is becoming very very long and dull.
In this class I have controller about gesture, position, animation and it's not easy use static class or singleton class to clean this class.
Is a possible solution to use others viewcontrollers inside this StageViewController to simplify the code?
Example: If in my game I should make an entry of an object that I should color, can I use another viewcontroller (with another class) to make my code inside StageViewController more simplify?
If you have any suggestion for me or link to read you can make me happy ;-)

A: Typically this indicates that you're storing model information in the view controller. The view controller should only keep track of how to display information. You should move the actual state of the game into model classes. These model classes inherit from NSObject, they are not view controllers.
In a well designed model-view-controller system, you should be able to run your entire game without knowing what the display looks like. Your model should be able to take inputs, update the game state, and provide outputs, regardless of how or whether that information is actually displayed. This kind of thinking improves reusability, and also reduces the complexity of your view controllers.


text:
Q: Redux | Can't get an Axios response to dispatch to the reducer I'm setting up redux in my React Native app and am struggling to get my response to dispatch to the reducer. I have confirmed that I am getting the response properly with the dispatch so the backend is working properly. I posted a lot of code below because I'm a bit lost, but my top three issues are:

*

*I'm not connecting my component to the store properly

*I didn't create the store correctly

*authAction.js may be wrong altogether

Here's my code:
1)
In case I didn't connect right, this is how I connected it at the bottom of the component that uses the function:
export default connect(null, { signup })(ApprovedScreen)

2) store.js
import thunk from 'redux-thunk';
import rootReducer from './reducers';

const inititalState = {};

const store = createStore(
        rootReducer,
        inititalState,
        applyMiddleware(thunk))

export default store;

3) authAction.js
import axios from 'axios'
import { LOG_IN } from './types'

export const signup = ({email, password}) => dispatch => {
    axios.post('myapi.com/signup', {email, password})
    .then(response =>dispatch({
        type:LOG_IN,
        payload: response.data.token
    }))
    .catch(error => {
        console.log(error)
    })
}

reducers/index.js (apparently this is automatically called rootReducer in the store)
import { combineReducers } from 'redux'
import { authReducer } from './authReducer'

export default combineReducers({
    auth: authReducer
})

authReducer.js
import { LOG_IN } from '../actions/types'

export const authReducer = (state = {loggedIn: null}, action) => {
    switch (action.type) {
        case LOG_IN:
            console.log('the login reducer was activated!')
            return {loggedIn: action.payload}
        default:
            return {...state}
    }
}

from my App.js file
const App = createAppContainer(switchNavigator);

  export default () =>{
    return (
      <Provider store={store}>
        <App />
      </Provider>
    )
  }

some relevant code from the file (Screen.js) where I call signup()
import React, {useState} from 'react'
import { connect } from 'react-redux'
import { StyleSheet, View, Text, TextInput, Image, TouchableOpacity } from 'react-native';
import { signup } from '../../actions/authAction'

const Screen = () => {
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')

  return (
    <View>
        <TextInput
            value={email}
            onChangeText={text=>setEmail(text)}
            placeholder='Email'
            autoCapitalize='none'
            autoCorrect={false}
            textContentType='emailAddress'
            keyboardType='email-address'
        />
        <TextInput
            value={password}
            onChangeText={text=>setPassword(text)}
            placeholder='Password'
            autoCapitalize='none'
            textContentType='newPassword'
            secureTextEntry={true}
        />
        <TouchableOpacity style={styles.submitButton} onPress={()=>signup({email, password})}>
          <Text style={styles.submitButtonText}>Create An Account</Text>
      </TouchableOpacity>
    </View>
  )
}

export default connect(null, { signup })(Screen)


text:
Q: I cant install pyttsx3 So I'm trying to install pyttsx3 and it says it is downloaded but when I go to import it says there is no module
C:\Users\gabri>pip install pyttsx3
Requirement already satisfied: pyttsx3 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (2.90)
Requirement already satisfied: pywin32 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from pyttsx3) (301)
Requirement already satisfied: comtypes in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from pyttsx3) (1.1.10)
Requirement already satisfied: pypiwin32 in c:\users\gabri\appdata\local\programs\python\python39\lib\site-packages (from pyttsx3) (223)

Here is the code
import pyttsx
calc = pyttsx3.init()
calc.say("Hi")
calc.runAndWait

here is the output
Traceback (most recent call last):
  File "C:\Users\gabri\Downloads\vc calculator.py", line 1, in <module>
    import pyttsx3
ModuleNotFoundError: No module named 'pyttsx3'


text:
Q: Domain of operator Let be $\lambda\in C^{*}$. Consider the following operator:
$ T_{\lambda}=-\Delta_{R^{2}}++\frac{\lambda^{2} }{4} (x^{2}+y^{2})+i\lambda N$,
where
$N=(x \frac{d }{dy} -y \frac{d }{dx})$      ,
with domain $D=\{u\in L^{2}(R^{2}), T_{\lambda}\in L^{2}(R^{2})\}$
I want  to prove $D=\{u\in L^{2}(R^{2}):   \Delta_{R^{2}}u\in L^{2}(R^{2}),(x^{2}+y^{2})u\in L^{2}(R^{2}),N u\in L^{2}(R^{2}) \}$
Would you know some litterature reference for this problem that I could read ?
Thanks!


text:
Q: Is there an adapter to connect a Macbook Pro to a DVI splitter? I don't think any of the previous questions on this topic cover this particular nuance, but please edify me if I'm mistaken.
I have a Macbook Pro 15" (the model that was released around March 2011) with Thunderbolt port. My office has two Dell monitors joined with a DVI splitter (which were originally connected to a Dell desktop). I have a Thunderbolt to DVI adapter that I was hoping to connect to the DVI splitter. However, the connector on the end of the splitter is different from the connector for a single-monitor DVI cable, so I can't plug the output of the splitter into the DVI end of the Thunderbolt-to-DVI adapter.
Does this mean I need either (1) an adapter to connect a "standard" DVI connector to a "splitter" DVI connector, or (2) a thunderbolt adapter that will plug directly into a splitter DVI connector? If so, do either of these items exist or am I out of luck?

A: There are many types of DVI adapter, I could type a load of stuff or just point you at Wikipedia.
The key point is that there is no such thing as a DVI adapter.  It's just a generic term that covers the overall outline of the cable end, but what you really have is either a DVI-I or DVI-D adapter, in either Single or Dual link capability.  Or it may be a DVI-A.  Or there are others...!
It's possible that your splitter cable must be of the dual link types, characterised by the longer horizontal bar pin, and your Thunderbolt adapter may or may not be.  Shouldn't matter which type, either I (Integrated with analogue signal in the pins above/below the horizontal bar in addition to digital) or D (Digital only) as I imagine you are not subsequently adapting them down to DSUB further down the line, the only thing that matters is if they are both dual link.
So it looks like you need a Thunderbolt/MiniDisplayPort to DVI Dual link - the official apple one is the digital only one without the analogue pins (DVI-D Dual Link), and thus should work, if you are worrying that you do not have the same pinout (i.e. you have DVI-I Dual Link on your splitter, and it looks as though the analogue ones have nothing to connect to) then don't worry, it won't need them.

EDIT - Additional Info
After the comments, I have decided that you have a DMS-59 connector that looks like this:

So what you really need is a MiniDisplay > DMS-59 adapter, and my google-fu suggests that this is not looking like a possibility, I think you would be better served abandoning this cable, and looking for a total replacement, Mini Display Port > 2 x DVI (Single is fine, I or D if you have 2 ports).  This may also be a pain to find, and you may end up needing a MDP/Thunderbolt to Dual Link DVI, followed by a Dual Link DVI > 2 X Single Link DVI splitter cable!

A: Zotac announced a displayport to dual-hdmi adapter (I think a dual DVI version was also announcted) that you could possibly use with a HDMI-DVI adpater.  However, I'm not clear if this is actually available for sale yet.


text:
Q: how to add space to the string in bash, and make it look like a table output? data:
place|place_loc|CATA|CATB|CATA1|CATB1
AAAAA|AAAAA_AAA|1234|123|12|1234

expected output:
place_loc| AAAAA_AAA
|CATA: 1234   CATA1:12
|CATB: 123    CATB1:1234

Current bash script:
cat info.txt | tr '\t' '|' | tail -n+2 | awk 'BEGIN{FS="|";OFS="|"} {
{printf "place_loc|%11s\n",$2}
{if ($2!="#N/A" && $2!="")
{printf "|CATA:%6s         CATA1:%7s\n",$3,$5}
{printf "|CATB:%6s          CATB1:%12s\n",$4,$6}
}'

Since the input need to concern the string length from 1-10, like CATA: 0123456789, but once i add a longer string for CATA, CATA1 will move backward.
Or can I awk the info.txt to make it looks like:
place|place_loc|CATA|CATB|CATA1|CATB1
AAAAA|AAAAA_AAA|1234     |123       |12        |1234
edit the input file add $3,$4,$5,$6 space until reach length=10
Any suggestion?

A: It can all be done in awk with two rules. You can handle outputting the first part of the heading in the second rule, saving all fields in the array a[], and then the second rule will output the needed elements of a[] and the current fields in the format you specify. For example:
Set '|' as the field separator wtih -F'|', and
awk -F'|' '
    FNR > 1 {                                           # record (line) > 1
        if (FNR == 2)                                   # if line is 2
            print "| " $2                               # finish heading row
        for (i=3;i<=NF;i+=2)                            # loop from 3rd field by 2
            printf (i==3?"|":"\t") "%s: %s ",a[i],$i    # output info
        for (i=4;i<=NF;i+=2)                            # loop from 4th field by 2
            printf (i==4?"\n|":"\t") "%s: %s ",a[i],$i  # output info
        print ""                                        # tidy up with newline
        delete a                                        # clear the array
        for (i=1; i<=NF; i++)                           # fill array with current fields
            a[i]=$i
        next                                            # skip to next line
    }
    {
        printf "%s", $2                                 # output 1st part of heading
        for (i=1; i<=NF; i++)                           # fill array with current fields
            a[i]=$i
    }
' file

The order of execution is a bit backwards. The rule handling the first line is actually the last rule above between the bottom {...} the top rule handles the second line on.
Example Use/Output
With your input in the file named file, you can just select-copy the above and middle-mouse paste into an xterm with the current directory containing file to test, e.g.:
awk -F'|' '
>     FNR > 1 {                                           # record (line) > 1
>         if (FNR == 2)                                   # if line is 2
>             print "| " $2                               # finish heading row
>         for (i=3;i<=NF;i+=2)                            # loop from 3rd field by 2
>             printf (i==3?"|":"\t") "%s: %s ",a[i],$i    # output info
>         for (i=4;i<=NF;i+=2)                            # loop from 4th field by 2
>             printf (i==4?"\n|":"\t") "%s: %s ",a[i],$i  # output info
>         print ""                                        # tidy up with newline
>         delete a                                        # clear the array
>         for (i=1; i<=NF; i++)                           # fill array with current fields
>             a[i]=$i
>         next                                            # skip to next line
>     }
>     {
>         printf "%s", $2                                 # output 1st part of heading
>         for (i=1; i<=NF; i++)                           # fill array with current fields
>             a[i]=$i
>     }
> ' file
place_loc| AAAAA_AAA
|CATA: 1234     CATA1: 12
|CATB: 123      CATB1: 1234

The output above is:
place_loc| AAAAA_AAA
|CATA: 1234     CATA1: 12
|CATB: 123      CATB1: 1234


text:
Q: how to replace a single newline with a double newline in google docs My question is simple, what do I enter into find-and-replace on google docs so that I can replace a single newline with a double newline so that there is an empty space between my paragraphs? I already know that I can search \n with regular expressions on, but how can I set it to replace it with two?

A: Sadly, you can't do that in search and replace UI.
I'd recommend using Apps Script and using this code.
Code:
function addAdditionalNewLine() {
  DocumentApp.getActiveDocument()
    .getBody()
    .getParagraphs()
    .forEach(function (paragraph){
      paragraph.appendText("\n");
    });
}

function onOpen() {
  var ui = DocumentApp.getUi();
  // Or DocumentApp or FormApp.
  ui.createMenu('Custom Menu')
    .addItem('Add New Lines', 'addAdditionalNewLine')
    .addToUi();
}

Note:

*

*What the code does is add a new line every end of every paragraph.

*Additionally, I added a custom menu whenever the document is refreshed/opened (You may need to refresh the document after saving the script):

*Please make sure to have the necessary permissions first on the editor by running the function addAdditionalNewLine manually.

Sample:

Output (after running clicking "Add New Lines" menu):


text:
Q: SAP Web Service from .NET via WCF I'm trying to consume a SAP Web Service from .NET via WCF. I've generated the proxy and I have configured the app.config file.
Here is my test code:
WebServiceSAP.ZTEST_RFCClient myWCFService = new WebServiceSAP.ZTEST_RFCClient("MyEndPoint");

myWCFService.ClientCredentials.UserName.UserName = "<UserName>";
myWCFService.ClientCredentials.UserName.Password = "<Password>";

WebServiceSAP.ZTestRfc parameter = new WebServiceSAP.ZTestRfc();
parameter.TestInput = "This is a simple test";

WebServiceSAP.ZTestRfcResponse response = myWCFService.ZTestRfc(parameter);

Console.WriteLine(reponse.TestOutput);
Console.ReadLine();

The ZTestRFC SAP method is a very simple function that accepts an input string, and outputs: "Result: <the input string>"
When I call ZTestRFC method, I got a null value in variable response. But SOAP messages seem to be fine.
SOAP Request
<MessageLogTraceRecord>
<HttpRequest xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
<Method>POST</Method>
<QueryString></QueryString>
<WebHeaders>
<VsDebuggerCausalityData>uIDPoxJmI5NcDatNiPM/wFAr52kAAAAAtqHAVnNWjEeMpMExOyr/vN7OXwCJZltNnikldpg5migACQAA</VsDebuggerCausalityData>
</WebHeaders>
</HttpRequest>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header>
<Action s:mustUnderstand="1" xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">urn:sap-com:document:sap:soap:functions:mc-style:ZTEST_RFC:ZTestRfcRequest</Action>
</s:Header>
<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<ZTestRfc xmlns="urn:sap-com:document:sap:soap:functions:mc-style">
<TestInput xmlns="">This is a simple test</TestInput>
</ZTestRfc>
</s:Body>
</s:Envelope>
</MessageLogTraceRecord>

SOAP Response
<MessageLogTraceRecord>
<HttpResponse xmlns="http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace">
<StatusCode>OK</StatusCode>
<StatusDescription>OK</StatusDescription>
<WebHeaders>
<Content-Length>359</Content-Length>
<Content-Type>text/xml; charset=utf-8</Content-Type>
<Set-Cookie>MYSAPSSO2=AjExMDABAAxQMDEwMDA1MSAgICACAAMwNDADAAhEMTEgICAgIAQADDIwMTAxMTEwMTIwOQUABAAAAAgGAAFYCQABU%2f8A9jCB8wYJKoZIhvcNAQcCoIHlMIHiAgEBMQswCQYFKw4DAhoFADALBgkqhkiG9w0BBwExgcIwgb8CAQEwEzAOMQwwCgYDVQQDEwNQMTECAQAwCQYFKw4DAhoFAKBdMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTEwMTExMDEyMDk0OFowIwYJKoZIhvcNAQkEMRYEFJC%2fNFLVBnu1ZAodWTlPApEs8sApMAkGByqGSM44BAMEMDAuAhUBS844BOB%2f8NgEGuepMgLaKbVEGGUCFQFLs6HiI%21BWT1MejMqvABd3%2fJFVMw%3d%3d; path=/; domain=.<domain ... ></Set-Cookie>
<Server>SAP NetWeaver Application Server / ABAP 700</Server>
</WebHeaders>
</HttpResponse>
<SOAP-ENV:Envelope xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<s:Header xmlns:s="http://schemas.xmlsoap.org/soap/envelope/"></s:Header>
<SOAP-ENV:Body>
<rfc:ZTestRfcResult xmlns:rfc="urn:sap-com:document:sap:soap:functions:mc-style">
<TestOutput xmlns="">Result:</TestOutput>
</rfc:ZTestRfcResult>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</MessageLogTraceRecord>

I don't know what could be happening. Any ideas?
Thanks in advance

A: Offhand, it looks like when you created the proxy (BTW, what technique did you use to do that?), SAP told .NET that the parameter and the response would be in some namespace, but that you're sending the parameter in the empty namespace (""). That may be why the SAP service is returning "Result:". You may be getting a null response because your proxy may be expecting the TestOutput element to be in a different namespace.
Look at the generated proxy classes and see what namespaces are expected.


text:
Q: Setting connection and read timeout for sockets in python thrift client I am executing the following code for establishing a thrift server using the official thrift library of python.
    `transport = TSocket.TSocket(self.__host, self.__port)`
    `transport.setTimeout(2000)`

Would this set a sum total of connect timeout and read timeout to 2 seconds or is it simple the connect timeout. If so, how do I set the read timeout and vice versa.

A: The settimeout affects separately each operation: for example send, recv and connect operations.
It looks like you cannot set the read timeout differently from the connect timeout.
Also the timeout is for each operation so if you do a connect and then a read, you will have 2 + 2 seconds max possible time.
See this which is the method that the thrift TSocket uses:
socket.settimeout(...)


text:
Q: How do I prevent ImageMagick convert from scaling images *up*? I'm using ImageMagick's convert tool to generate image thumbnails for a web application. I'm using notation like so: 600x600>
The images are indeed scaled to 600px wide/tall (depending on the longer side) and proportions are properly maintained, however images less than 600px in either direction are scaled up — this behavior is not desired. Is there a way to prevent convert from scaling images up if the destination dimensions both exceed the original image size?

A: convert input.png -resize 600x600\> output.png does indeed work on my installation of ImageMagick.  I would double check that the > is being escaped properly and that my version of ImageMagick is recent.

A: Look at the  widthxheight> syntax

widthxheight>   Change as per
  widthxheight but only if an image
  dimension exceeds a specified
  dimension.

Examples:
[/tmp]# identify -format "%wx%h"  test.gif
172x66
[/tmp]# convert test.gif -resize '1000x1000>' test2.gif && identify -format "%wx%h"  test2.gif
172x66
[/tmp]# convert test.gif -resize '10x10>' test3.gif && identify -format "%wx%h"  test3.gif
10x4
[/tmp]# convert test.gif -resize '100x100>' test4.gif && identify -format "%wx%h"  test4.gif
100x38


text:
Q: Programatic referencing of literals and object properties I have advice that this might work for programmatically filling a set of literals from a set of object properties:-
For i As Integer = 1 To noOfTexts
  Dim ctl As Literal = DirectCast(FindControl("help" & i), Literal)
  If ctl IsNot Nothing Then
 ctl.Text = pageData.help(i).trim()
 ctl.Visible = True
  End If
Next

However, the line: ctl.Text = pageData.help(i).trim() fails because it's not understood that pageData.help(i) should translate to pageData.help1, pageData.help2, etc.
Is there some syntax that would achieve this in VS2010 Asp.net VB?

A: You can reference properties dynamically using reflection...
 Dim PageDataType As Type = GetType(pageData)
 Dim PropertyName As String = "help" & i
 Dim Property As PropertyInfo = PageDataType.GetProperty(PropertyName)
 Dim PropertyValue As String

 If Property IsNot Nothing
     PropertyValue = Property.GetValue(pageData, Nothing)
 End If

Note: Reflection in .NET is slower than direct access, but not enough to make its use impractical


text:
Q: Android Gallery - Replace Bitmap in ImageView after scrolling stopped I've programmed a zoomable gallery with several images.

*

*The images can be zoomed.

*Zoomed images can be dragged.

*If the image is not zoomed, the gallery can be scrolled.

The layout consists of a LinearLayout with a TextView (the name of the gallery) and the Gallery itself.
An item in the gallery consists of a RelativeLayout containing a FrameLayout with the ImageView in it (I read I need the FrameLayout for zooming) and a TextView to show the zoom state of the image.
I've used a custom View.OnTouchListener to implement the zooming.
Now I was trying to replace the image in the ImageView after the gallery has stopped scrolling with a high res picture so the user can zoom in much better/further.
I did this with the OnItemSelectedListener and setCallbackDuringFling to false.
Even this works fine if you fling the screen fast.
But if you keep your finger on the display and move it slowly to the edge, the OnItemSelectedListener is fired before the next item reached the center and the scrolling animation stops. Instead the gallery jumps like it looses touch contact and centers the next item in the gallery immediately. Also the OnItemSelectedListener is called more than once on the same item when moving the finger slowly (I avoid this problem by saving the position of the last selected item).
So (long story short) I was looking for a callback/listener to the "scrolling/snap-to-grid" effect of the Gallery. I also tried an AnimationListener, but the gallery returns null when i call getAnimation on it.
I'm desperate here... can anyone help?

A: Problem solved: I'm now using the android.support.v4.view.ViewPager with the custom callbacks in the OnPageChangeListener:

*

*onPageSelected

*onPageScrollStateChanged

*onPageScrolled

A: I recommend a slight change to your method. For your Gallery, override onScroll(MotionEvent, MotionEvent, float, float) and onFling(MotionEvent, MotionEvent, float, float) have them return their super but on MotionEvent.ACTION_DOWN || MotionEvent.ACTION_UP set a moving flag to true || false respectively.
Now in the BaseAdapter for your Gallery in the getView(int, View, ViewGroup) method when you are returning your image view return the low res ImageView if the moving flag is true else return the high res.


text:
Q: How to change the type of a parent class' property in a child class? I have a parent class as follows:
public class ParentClass {
  protected List<String> property = null;
  public ParentClass() {
    this.property = new LinkedList<String>();
  }
    //property gets populated here
  public boolean parentClassFunc(String where){
    assert property != null;
    for(String it : property)
        {
            if(where.equals(it))return true;
        }
        return false ;
  }
}

And I want to speed up this Class by extending it and making some changes, one change includes changing the type of property from LinkedList to HashSet to take advantage of O(1) .contains on that type.
This is what the ChildClass would look like:
public class ChildClass extends ParentClass {

  //make property a HashSet instead of LinkedList

  @Override
  public boolean parentClassFunc(String where){
    assert property != null;
    return property.contains(where);
  }
}

How can I change the property type in a ChildClass in Java?

A: You can provide a constructor overload for the child to specify its own collection type:
public class ParentClass {
  protected Collection<String> property = null;

  public ParentClass() {
    this(new LinkedList<>());
  }

  protected ParentClass(Collection<String> property) {
    this.property = property;
  }
}

public class ChildClass extends ParentClass {
  public ChildClass() {
    super(new HashSet<>());
  }
}


text:
Q: How to catch all errors from browserify? I use the following gulp task
const gulp          = require('gulp');
const browserify    = require('browserify');
const watchify      = require('watchify');
const source        = require('vinyl-source-stream');
const gutil         = require('gulp-util');

gulp.task('watchify', () => {

    var bundler = watchify(browserify('./test/app.js', {
            debug: true,
            fullPaths: true,
            paths: ['./src'],
            cache: {},
            packageCache: {}
        }))
    .on('update', bundle)
    .on('error', (error) => { gutil.log('[error]', error); });

    function bundle(){
        return bundler
            .bundle()
            .pipe(source('bundle.js'))
            .pipe(gulp.dest('./test/'));
    }

    return bundle();

});

But today the browserify process hung without sending the error event, after hours of trail and error I found out it was because of something like this:
aFunction(argA, , argC);

(some work-in-progress code where I missed an argument in a function call)
My question is, how can I listen to these kind of errors more easily?
I could of course lint the files first but i'd also like to know if it's possible within browserify.

A: It looks like this unmerged pull request for watchify might have fixed your problem - it appears that errors don't get caught properly in the gulp-watchify module so you never get to see them.
You might have more success using the official Gulp recipe for Browserify and Watchify which doesn't use the gulp-watchify module.

It appears that the issue is that Gulp is never informed of the error when it occurs. Try using this error handling code:
(error) => {
    gutil.log('[error]', error);
    this.emit('end');
}


text:
Q: Error when using two any functions in if condition this is a very simple(may be silly) question.But I have been trying for an hour on this.Here is a invalid syntax statement i get ,when I use two if conditions with any function.Here is the statement I used.
if any(table in sentence for table in (alias_dict["tables"].strip('][').split(', ')))==False and if any(column in sentence for column in (alias_dict["columns"].strip('][').split(', ')))==True:
    print("Hii success")

But I am getting the error:

if any(table in sentence for table in
(alias_dict["tables"].strip('][').split(', ')))==False and if
any(column in sentence for column in
(alias_dict["columns"].strip('][').split(', ')))==True:
^ SyntaxError: invalid syntax

Error (^) is shown near 'and'. I tried giving "&&" as well. I also tried giving paranthesis for whole any() as well.But it doesnt seem to work out.I know it might be a silly blunder from my part.Still Any help appreciated.

A: The syntax is if thing and otherthing, not if thing and if otherthing.
Comparing to False is also slightly weird. Try this instead.
if not any(
        table in sentence for table in alias_dict["tables"].strip('][').split(', ')
      ) and any(
        column in sentence for column in alias_dict["columns"].strip('][').split(', ')):
    print("Hii success")

A: You don't need to give another if in the same if statement!
if any(table in sentence for table in (alias_dict["tables"].strip('][').split(', ')))==False
Your complete code will be:
if any(table in sentence for table in (alias_dict["tables"].strip('][').split(', ')))==False and any(column in sentence for column in (alias_dict["columns"].strip('][').split(', ')))==True:
    print("Hii success")

and if you even want to use another if statement, then use elif in the next condition


text:
Q: Find the parameters of this distribution and the probability The mean weight of a leopard is 190kg. We look at the leopards in the Zoo and assume their weight to be normally distributed. We know that 5% of all leopards weigh more than 220kg.
(a) Determine the parameters µ and σ for this distribution.
(b) What is the probability that a randomly chosen leopard weighs between 160kg and 190kg
So lets say that W= weight in kg, E[W]=190kg
a)$0.95=P[W \le 220]= P[\frac{W-190}{\sigma \le \frac{30}{\sigma}}]=\phi \frac{30}{\sigma}≈ 1.64$
b)$P[160 ≤ G ≤ 190] = P[G ≤ 190]−P[G ≤ 160] = Φ(0/σ)−Φ(30/σ) ≈ Φ(2.87)−Φ(2.05)≈ 0.018$
Is this correct? I was unsure on how to calculate this. Are the values right?

A: For $(a)$ we have
$$\begin{align*}
\mathsf P(W\gt220)
&=1-\mathsf P(W<220)\\\\
&=1-\Phi\left(\frac{30}{\sigma}\right)\\\\
&=0.05
\end{align*}$$
We have then that $\Phi\left(\frac{30}{\sigma}\right)=0.95$ which occurs when $$\frac{30}{\sigma}=1.645\Rightarrow \sigma\approx18.24$$
More accurately than a standard normal table,  R statistical software gives
> qnorm(.95)
[1] 1.644854

> 30/qnorm(.95)
[1] 18.2387

You now have the ingredients to solve for $(b)$ except you should have
$$\begin{align*}
\mathsf P(160<W<190)
&=\mathsf P(W<190)-\mathsf P(W<160)\\\\
&=\Phi\left(\frac{0}{18.24}\right)-\Phi\left(\frac{-30}{18.24}\right)\\\\
&\approx0.45
\end{align*}$$
Alternatively, you can note that we are given that $5$% of leopards weigh more that $220$ so by symmetry, $5$% of leopards weigh less than $160$ giving $$0.5-0.05=0.45$$

A: You can calculate b) without resorting to normal table look up.
Due to symmetry of the normal curve around its mean
$$
P(\mu-a < W < \mu) = P(\mu< W < \mu + a) = 0.5 - P(W > \mu+a) = 0.45
$$
here $a=30$.


text:
Q: Circular traversing in jQuery? Is there any way to traverse the DOM in a circle? Like, when you get to the end of the list, it loops back around to the beginning?
Here's an example, which does not work, but will hopefully illustrate the effect I would like to achieve:

$('li.four').next().addClass('one');

A: There's nothing built in, but you can trivially write your own method;
jQuery.fn.nextOrFirst = function (selector) {
    var next = this.next.apply(this, arguments);

    if (!next.length) {
        var siblings = this.siblings();

        if (selector) {
            siblings = siblings.filter(selector);
        }

        next = siblings.first();
    }

    return next;
};

Then use like (http://jsfiddle.net/sszRN/);
$('li.four').nextOrFirst().addClass('one');

A: I sometimes use
var $next = $( $(this).next()[0] || $(this).prevAll().addBack()[0] );

yeah, crazy :D

A: Not exactly sure what you're asking or trying to achieve here but if you merely want to add a class to the first element you can do this
Traverse the dom to find the parent element
Find the first child of that element - like this
$('li.four').parent().find(">:first-child").addClass('one');


text:
Q: array.push is not working titanium appecelrator I am not able to submit/post my data when I am trying to add a specific entry using the push method.
I have the following code
var args = arguments[0] || {};
var TF;
var TA;
var basicSwitch;
var caViewBoolean;
var bounded_field;
var caViewDistance;
var commentTA;
var pinTF;
var newTF = [];
var issueTABoolean;
var correctTABoolean;
var issueTADistance;
var correctTADistance;
var mFields = [];
var isRequire = [];
var bounded_lblTitle = [];
var postButton;

$.scrView.customName = "New Entry";

if (args.fromLog == "Yes") {
    Alloy.Globals.logViews.push($.scrView);
    Alloy.Globals.logScrollableView.views = Alloy.Globals.logViews;
    Alloy.Globals.logScrollableView.scrollToView($.scrView);
} else {
    Alloy.Globals.locationViews.push($.scrView);
    Alloy.Globals.locationScrollableView.views = Alloy.Globals.locationViews;
    Alloy.Globals.locationScrollableView.scrollToView($.scrView);
}

//Click event of New Entry button
function onbtnClick() {

    if (OS_ANDROID) {
        Alloy.Globals.buttonClickEffect(postButton);
    }

    var mFields = [];

    //Create data which will be used to create new entry
    if (TF) {
        var tf_dict = {
            "id": TF._id,
            "value": TF.value
        };
        mFields.push(tf_dict);
    }

    if (TA) {
        var ta_dict = {
            "id": TA._id,
            "value": TA.value
        };
        mFields.push(ta_dict);
    }
    var boolean_dict = [i];
    for (var k = 0; k < yesnobasicswitch.length; k++) {
        if (yesnobasicswitch[i]) {
            if (yesnobasicswitch[i].value) {
                boolean_dict[i] = {
                    "id": yesnobasicswitch[i]._id,
                    "value": yesnobasicswitch[i].value,
                    "ca": {
                        "problem": issuetextarea[i].value,
                        "solution": correctivetextarea[i].value
                    }
                };
            } else {
                boolean_dict[i] = {
                    "id": yesnobasicswitch[i]._id,
                    "value": yesnobasicswitch[i].value
                };
            }

            mFields.push(boolean_dict[i]);
        }
    }
}

I am not sure If the code is enough to make people understand what I am trying to do. The code has been written by someone else and it is just a part of it.


text:
Q: How to implement pop-up notification in Xamarin.Android I am trying to implement pop up notification in Xamarin.Android mvvmcross project, all my notifications are invoked through viewModels , I have a notification service that i inject as a dependency both in the PLC and the Droid project , i'd like to use the same notification service to invoke a pop up.
I want the pop up to be like a crouton (https://github.com/slown1/Xamarin.Crouton).
any ideas?

A: You could try userdialogs which is a great plugin for popups!
If you want to use Crouton you probably need to create an interface for it which you implement independently for the different platforms. How to do that can be found in the MvvmCross wiki